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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
RansomNote.kt | ncschroeder | 604,822,497 | false | {"Kotlin": 19399} | /*
https://leetcode.com/problems/ransom-note/
Given two strings `ransomNote` and `magazine`, return `true` if `ransomNote` can be constructed by using the letters from `magazine` and `false` otherwise.
Each letter in `magazine` can only be used once in `ransomNote`.
*/
// Original solution with eager searching of the magazine
fun canConstruct(ransomNote: String, magazine: String): Boolean {
// Let magazineCharCounts be a map where the keys are the letters in magazine and the values are the counts
// for how many times that letter appears in magazine
val magazineCharCounts = mutableMapOf<Char, Int>()
for (c in magazine) {
magazineCharCounts[c] = (magazineCharCounts[c] ?: 0) + 1
}
for (c in ransomNote) {
when (val charCount: Int? = magazineCharCounts[c]) {
null -> return false
1 -> magazineCharCounts.remove(c)
else -> magazineCharCounts[c] = charCount - 1
}
}
return true
}
// Solution with lazy searching of the magazine
fun canConstruct(ransomNote: String, magazine: String): Boolean {
val magazineCharCounts = mutableMapOf<Char, Int>()
var searchIndex = 0
for (c in ransomNote) {
when (val charCount: Int? = magazineCharCounts[c]) {
null -> {
if (searchIndex > magazine.lastIndex) {
return false
}
while (true) {
val curChar = magazine[searchIndex]
if (curChar == c) {
searchIndex++
break
}
if (searchIndex == magazine.lastIndex) {
return false
}
magazineCharCounts[curChar] = (magazineCharCounts[curChar] ?: 0) + 1
searchIndex++
}
}
1 -> magazineCharCounts.remove(c)
else -> magazineCharCounts[c] = charCount - 1
}
}
return true
} | 0 | Kotlin | 0 | 0 | c77d0c8bb0595e61960193fc9b0c7a31952e8e48 | 2,085 | Coding-Challenges | MIT License |
src/main/kotlin/com/github/vqvu/eulerproject/Problem49.kt | vqvu | 57,861,531 | false | null | package com.github.vqvu.eulerproject
import java.util.ArrayList
import java.util.Arrays
import java.util.HashMap
import java.util.SortedSet
import java.util.TreeSet
/**
* @author victor
*/
fun main(args: Array<String>) {
val primePermutations: MutableMap<String, SortedSet<Int>> = HashMap()
for (prime in computePrimes(9999).map(Long::toInt)) {
if (prime > 1000) {
val key = sortChars(prime.toString())
var permutations = primePermutations[key]
if (permutations == null) {
permutations = TreeSet()
primePermutations[key] = permutations
}
permutations.add(prime)
}
}
for (permutations in primePermutations.values) {
if (permutations.size < 3) {
continue
}
val permList = ArrayList(permutations)
for (i in 0..permList.size - 3) {
for (j in i + 1..permList.size - 2) {
for (k in j + 1..permList.size - 1) {
val first = permList[i]
val second = permList[j]
val third = permList[k]
if (second - first == third - second) {
println(listOf(first, second, third))
}
}
}
}
}
}
fun sortChars(str: String): String {
val chars = str.toCharArray()
Arrays.sort(chars)
return String(chars)
}
| 0 | Kotlin | 0 | 0 | 1163894f462045060eda763b3040c0bbb1a68e30 | 1,455 | euler-project | MIT License |
src/Day02.kt | StrixG | 572,554,618 | false | {"Kotlin": 2622} | fun main() {
fun part1(input: List<String>): Int {
var score = 0
for (line in input) {
val (enemyMove, move) = line.let { it[0] - 'A' to it[2] - 'X' }
val outcome = ((move - enemyMove).mod(3) + 1) % 3
score += move + 1 + outcome * 3
}
return score
}
fun part2(input: List<String>): Int {
var score = 0
for (line in input) {
val (enemyMove, strategy) = line.let { it[0] - 'A' to it[2] - 'X' }
val move = (enemyMove + strategy - 1).mod(3)
score += move + 1 + strategy * 3
}
return score
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 85f2f28197ad54d8c4344470f0ba80307b068680 | 885 | advent-of-code-2022 | Apache License 2.0 |
src/main/java/challenges/cracking_coding_interview/trees_graphs/first_common_ancestor/QuestionD.kt | ShabanKamell | 342,007,920 | false | null | package challenges.cracking_coding_interview.trees_graphs.first_common_ancestor
import challenges.util.TreeNode
/**
* Design an algorithm and write code to find the first common ancestor of two nodes in a binary tree.
* Avoid storing additional nodes in a data structure.
* NOTE: This is not necessarily a binary search tree.
*/
object QuestionD {
fun commonAncestor(root: TreeNode?, p: TreeNode, q: TreeNode): TreeNode? {
return if (!covers(root, p) || !covers(root, q)) { // Error check - one node is not in tree
null
} else ancestorHelper(root, p, q)
}
private fun ancestorHelper(root: TreeNode?, p: TreeNode, q: TreeNode): TreeNode? {
if (root == null || root == p || root == q) {
return root
}
val pIsOnLeft = covers(root.left, p)
val qIsOnLeft = covers(root.left, q)
if (pIsOnLeft != qIsOnLeft) { // Nodes are on different side
return root
}
val childSide: TreeNode? = if (pIsOnLeft) root.left else root.right
return ancestorHelper(childSide, p, q)
}
private fun covers(root: TreeNode?, p: TreeNode): Boolean {
if (root == null) return false
return if (root == p) true else covers(root.left, p) || covers(root.right, p)
}
@JvmStatic
fun main(args: Array<String>) {
val array = intArrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val root: TreeNode = TreeNode.createMinimalBST(array) ?: return
val n3: TreeNode = root.find(1)!!
val n7: TreeNode = root.find(7)!!
val ancestor: TreeNode? = commonAncestor(root, n3, n7)
println(ancestor?.data)
}
} | 0 | Kotlin | 0 | 0 | ee06bebe0d3a7cd411d9ec7b7e317b48fe8c6d70 | 1,667 | CodingChallenges | Apache License 2.0 |
src/Day03.kt | xNakero | 572,621,673 | false | {"Kotlin": 23869} | class Day03 {
fun part1() = readInput("day03")
.map { it.chunked(it.length / 2) }
.map { rucksack -> rucksack.map { it.chunked(1) } }
.flatMap { it[0].intersect(it[1].toSet()) }
.map { it.toCharArray()[0] }
.sumOf { priority(it) }
fun part2() = readInput("day03")
.chunked(3)
.flatMap {
it[0].toCharArray()
.intersect(it[1].toSet())
.intersect(it[2].toSet())
}
.sumOf { priority(it) }
private fun priority(character: Char) =
when {
character.isUpperCase() -> character.code - 38
else -> character.code - 96
}
}
fun main() {
val day3 = Day03()
println(day3.part1())
println(day3.part2())
} | 0 | Kotlin | 0 | 0 | c3eff4f4c52ded907f2af6352dd7b3532a2da8c5 | 772 | advent-of-code-2022 | Apache License 2.0 |
2023/11/Solution.kt | AdrianMiozga | 588,519,359 | false | {"Kotlin": 110785, "Python": 11275, "Assembly": 3369, "C": 2378, "Pawn": 1390, "Dart": 732} | import java.io.File
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
private const val FILENAME = "2023/11/input.txt"
fun main() {
partOne()
partTwo()
}
private fun partOne() {
calculate(2)
}
private fun partTwo() {
calculate(1_000_000)
}
private fun calculate(expandAmount: Int) {
val file =
File(FILENAME).readLines().map { it.toMutableList() }.toMutableList()
val expandRows = mutableListOf<Int>()
for ((index, line) in file.withIndex()) {
if (line.all { it == '.' }) {
expandRows.add(index)
}
}
val expandColumns = mutableListOf<Int>()
for (column in 0 until file[0].size) {
var all = true
for (row in 0 until file.size) {
if (file[row][column] != '.') {
all = false
break
}
}
if (all) {
expandColumns.add(column)
}
}
val galaxies = mutableListOf<Pair<Int, Int>>()
for ((indexRow, row) in file.withIndex()) {
for ((columnRow, element) in row.withIndex()) {
if (element == '#') {
galaxies.add(Pair(indexRow, columnRow))
}
}
}
var result = 0L
for (i in 0 until galaxies.size) {
for (j in i + 1 until galaxies.size) {
val minX = min(galaxies[i].first, galaxies[j].first)
val maxX = max(galaxies[i].first, galaxies[j].first)
val minY = min(galaxies[i].second, galaxies[j].second)
val maxY = max(galaxies[i].second, galaxies[j].second)
val new = Pair(maxX - minX, maxY - minY)
var count = 0
for (element in expandRows) {
if (element in (minX + 1) until maxX) {
count++
}
}
for (element in expandColumns) {
if (element in (minY + 1) until maxY) {
count++
}
}
result += (new.first + new.second + (count * expandAmount) - count)
}
}
println(result)
}
| 0 | Kotlin | 0 | 0 | c9cba875089d8d4fb145932c45c2d487ccc7e8e5 | 2,111 | Advent-of-Code | MIT License |
src/main/MyMath.kt | nibarius | 154,152,607 | false | {"Kotlin": 963896} | import java.math.BigInteger
object MyMath {
// Based on
// https://en.wikipedia.org/wiki/Modular_multiplicative_inverse#Applications
// https://sv.wikipedia.org/wiki/Kinesiska_restklassatsen
// https://rosettacode.org/wiki/Chinese_remainder_theorem
// Use BigInteger to be able to calculate big numbers and to get modInverse for free.
private fun chineseRemainder(pairs: Collection<Pair<BigInteger, BigInteger>>): BigInteger {
val prod = pairs.fold(1.toBigInteger()) { acc, i -> acc * i.first }
var sum = 0.toBigInteger()
for ((ni, ai) in pairs) {
val p = prod / ni
sum += ai * p.modInverse(ni) * p
}
return sum % prod
}
/**
* The chinese remainder theorem can be used to find the solution to for example the system:
* x === 0 (mod 17) (x mod 17 = 0)
* x === 11 (mod 13) (x mod 13 = 11)
* x === 16 (mod 19) (x mod 19 = 16)
* chineseRemainder([(17, 0), (13, 11), (19, 16)]) == 3417 ==> x = 3417
*
* @param pairs a collection of pairs where first is the modulus and second is the remainder.
*/
fun chineseRemainder(pairs: Collection<Pair<Int, Int>>): Long {
return chineseRemainder(pairs.map { it.first.toBigInteger() to it.second.toBigInteger() }).toLong()
}
/**
* Calculates the least common multiple of a collection of ints.
*/
fun lcm(numbers: Collection<Int>): Long {
return numbers.fold(1.toBigInteger()) { acc, i -> lcm(acc, i.toBigInteger()) }.toLong()
}
// Based on https://www.baeldung.com/java-least-common-multiple#lcm-biginteger
private fun lcm(n1: BigInteger, n2: BigInteger): BigInteger {
return (n1 * n2).abs() / n1.gcd(n2)
}
} | 0 | Kotlin | 0 | 6 | f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22 | 1,754 | aoc | MIT License |
src/main/kotlin/day2/Day2.kt | Wicked7000 | 573,552,409 | false | {"Kotlin": 106288} | package day2
import Day
import checkWithMessage
import parserCombinators.*
import readInput
import readInputString
import runTimedPart
import kotlin.sequences.sequenceOf
@Suppress("unused")
class Day2(): Day() {
private val winningMatchUps = mapOf(
Action.SCISSORS to Action.ROCK,
Action.PAPER to Action.SCISSORS,
Action.ROCK to Action.PAPER
)
private val losingMatchUps = mapOf(
Action.ROCK to Action.SCISSORS,
Action.SCISSORS to Action.PAPER,
Action.PAPER to Action.ROCK
)
enum class MatchUpResult(val action: Char) {
WIN('Z'),
LOSE('X'),
DRAW('Y');
companion object {
fun getEnum(value: String): MatchUpResult {
if(value.length > 1){
throw Error("Supplied string is too long $value")
}
val character = value[0]
for(result in MatchUpResult.values()){
if(result.action == character){
return result
}
}
throw Error("Could not match supplied character $value")
}
}
}
enum class Action(val action: Char, val altAction: Char, val score: Int) {
ROCK('A', 'X', 1),
PAPER('B', 'Y', 2),
SCISSORS('C', 'Z', 3);
companion object: ParsableEnum<Action> {
fun getEnum(value: String): Action {
if(value.length > 1){
throw Error("Supplied string is too long $value")
}
val character = value[0]
for(action in Action.values()){
if(action.action == character || action.altAction == character){
return action
}
}
throw Error("Could not match supplied character $value")
}
override fun toMap(): Map<String, Action> {
val firstMap = enumValues<Action>().associateBy { ""+it.action }
val secondMap = enumValues<Action>().associateBy { ""+it.altAction }
return firstMap + secondMap
}
}
}
private fun getMatchUpResult(matchUp: MatchUp): MatchUpResult {
return if(matchUp.opponentAction == matchUp.strategyAction){
MatchUpResult.DRAW
} else if(winningMatchUps[matchUp.opponentAction] == matchUp.strategyAction){
MatchUpResult.WIN
} else {
MatchUpResult.LOSE
}
}
data class MatchUp(val opponentAction: Action, val strategyAction: Action)
private fun actionPairToString(first: Action, second: Action): String {
return "$first-$second";
}
private fun tallyScoreForMatchUps(input: List<MatchUp>): Int {
var totalScore = 0
for(matchUp in input){
val result = getMatchUpResult(matchUp)
if(result == MatchUpResult.WIN){
totalScore += 6
} else if(result == MatchUpResult.DRAW){
totalScore += 3
}
totalScore += matchUp.strategyAction.score;
}
return totalScore;
}
private fun parseInput(input: String): List<MatchUp> {
val parseTree = parseTillEnd(toClass(parserCombinators.sequenceOf(enum(Action), space(), enum(Action), optional(newLine())), MatchUp::class))
val result = parseTree(BaseParser(input))
if(result.hasError){
throw Error(result.error)
}
@Suppress("UNCHECKED_CAST")
return result.results.toList() as List<MatchUp>
}
private fun parseInputP2(input: String): List<MatchUp> {
val parseTree = parseTillEnd(toClass(parserCombinators.sequenceOf(enum(Action), space(), strategyAction(), optional(newLine())), MatchUp::class))
val result = parseTree(BaseParser(input))
if(result.hasError){
throw Error(result.error)
}
@Suppress("UNCHECKED_CAST")
return result.results.toList() as List<MatchUp>
}
private fun strategyAction(): ParserFn {
return newParser({ parser ->
val newParser = anyLetter()(parser)
newParser.lastParserName = "strategyAction(${newParser.lastParserName})"
if(newParser.hasError){
return@newParser newParser
}
val enumResult = newParser.popLast()
val opponentAction = newParser.popLast()
if(opponentAction !is Action){
newParser.error = "Expected result of type Action but got: ${opponentAction::class.simpleName}"
return@newParser newParser
}
val newResult = when (MatchUpResult.getEnum(""+enumResult as Char)) {
MatchUpResult.DRAW -> {
opponentAction
}
MatchUpResult.WIN -> {
winningMatchUps[opponentAction]!!
}
MatchUpResult.LOSE -> {
losingMatchUps[opponentAction]!!
}
}
newParser.results.add(opponentAction)
newParser.results.add(newResult)
return@newParser newParser
}, "strategyAction(?)")
}
private fun part1(input: String): Int {
val parsedInput = parseInput(input)
return tallyScoreForMatchUps(parsedInput);
}
private fun part2(input: String): Int {
val parsedInput = parseInputP2(input)
return tallyScoreForMatchUps(parsedInput);
}
override fun run(){
val testData = readInputString(2,"test")
val inputData = readInputString(2, "input")
val testResult1 = part1(testData)
checkWithMessage(testResult1, 15)
runTimedPart(1, { part1(it) }, inputData)
val testResult2 = part2(testData)
checkWithMessage(testResult2, 12)
runTimedPart(2, { part2(it) }, inputData)
}
}
| 0 | Kotlin | 0 | 0 | 7919a8ad105f3b9b3a9fed048915b662d3cf482d | 6,184 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/days/Day08.kt | TheMrMilchmann | 725,205,189 | false | {"Kotlin": 61669} | /*
* Copyright (c) 2023 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package days
import utils.*
fun main() {
val (instructions, mappings) = readInput().let { lines ->
val instructions = lines.first()
val mappings = lines.drop(2).associate { line ->
val targets = line.substringAfter('(').removeSuffix(")").split(", ").let { it[0] to it[1] }
line.substringBefore(' ') to targets
}
instructions to mappings
}
fun findRequiredSteps(start: String, isDest: (String) -> Boolean): Long {
var step = 0L
var pos = start
val instructionsItr = iterator {
while (true) {
yieldAll(instructions.asIterable())
}
}
while (!isDest(pos)) {
pos = when (val instruction = instructionsItr.next()) {
'L' -> mappings[pos]!!.first
'R' -> mappings[pos]!!.second
else -> error("Unexpected instruction: $instruction")
}
step++
}
return step
}
tailrec fun gcd(x: Long, y: Long): Long =
if (y == 0L) x else gcd(y, x % y)
fun lcm(x: Long, y: Long): Long =
if (x == 0L || y == 0L) 0 else (x * y) / gcd(x, y)
fun solve(
isStart: (String) -> Boolean,
isDest: (String) -> Boolean
): Long =
mappings.mapNotNull { (k, _) -> if (isStart(k)) k else null }
.map { findRequiredSteps(it, isDest) }
.reduce(::lcm)
println("Part 1: ${solve(isStart = { it == "AAA" }, isDest = { it == "ZZZ" })}")
println("Part 2: ${solve(isStart = { it.endsWith('A') }, isDest = { it.endsWith('Z') })}")
} | 0 | Kotlin | 0 | 1 | f94ff8a4c9fefb71e3ea183dbc3a1d41e6503152 | 2,746 | AdventOfCode2023 | MIT License |
codeforces/round631/c.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package codeforces.round631
private fun solve(): String {
val (h, g) = readInts()
val a = (listOf(0) + readInts()).toIntArray()
val bottomLevel = 1 shl (h - 1)
tailrec fun siftDown(i: Int, act: Boolean): Int {
val j = if (i >= bottomLevel) 0 else if (a[2 * i] >= a[2 * i + 1]) 2 * i else 2 * i + 1
if (act) a[i] = a[j]
return if (a[j] == 0) i else siftDown(j, act)
}
val toLeave = 1 shl g
val ans = mutableListOf<Int>()
for (i in 1 until toLeave) {
while (siftDown(i, false) >= toLeave) {
ans.add(i)
siftDown(i, true)
}
}
return "${a.fold(0L, Long::plus)}\n${ans.joinToString(" ")}"
}
fun main() = println(List(readInt()) { solve() }.joinToString("\n"))
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 866 | competitions | The Unlicense |
2020/kotlin/day-4/main.kt | waikontse | 330,900,073 | false | null | import util.FileUtils
val fileUtils = FileUtils("input.txt")
fun main() {
val allPassports: List<String> = combineLines(fileUtils.lines)
println ("number of passport lines: " + allPassports.size)
val validPassportCount = allPassports.map(::splitPassportFields)
.filter(::isValidPassport)
.count()
val verifiedPassportCount = allPassports.map(::splitPassportFields)
.filter(::isValidPassport)
.filter(::isVerifiedPassport)
.count()
println ("Day-4 challenge 1: $validPassportCount")
println ("Day-4 challenge 2: $verifiedPassportCount")
}
fun combineLines(lines: List<String>): List<String> {
val combinedLines: MutableList<String> = ArrayList()
val passportLine: MutableList<String> = ArrayList()
lines.forEach{ line ->
if (line.isBlank()) {
val combinedPassportLine = passportLine.joinToString(" ")
combinedLines.add(combinedPassportLine);
passportLine.clear()
} else {
passportLine.add(line);
}
}
val combinedPassportLine = passportLine.joinToString(" ")
combinedLines.add(combinedPassportLine);
passportLine.clear()
return combinedLines;
}
fun splitPassportFields(passport: String): Map<String, String> {
return passport.split(" ")
.associate {
it.split(":").let { (key, value) -> key to value }
}
}
fun isValidPassport(mappedPassportFields: Map<String, String>): Boolean {
if (mappedPassportFields.size == 8) {
return true;
}
return isFromNorthPole(mappedPassportFields);
}
fun isFromNorthPole(mappedPassportFields: Map<String, String>): Boolean {
if (mappedPassportFields.size == 7 && !mappedPassportFields.containsKey("cid")) {
return true;
}
return false
}
fun isVerifiedPassport(mappedPassportFields: Map<String, String>): Boolean {
return verifyBirthYear(mappedPassportFields.get("byr")) &&
verifyIssueYear(mappedPassportFields.get("iyr")) &&
verifyExpirationYear(mappedPassportFields.get("eyr")) &&
verifyHeight(mappedPassportFields.get("hgt")) &&
verifyHairColor(mappedPassportFields.get("hcl")) &&
verifyEyeColor(mappedPassportFields.get("ecl")) &&
verifyPassportId(mappedPassportFields.get("pid"))
}
fun verifyValue(value: Int, validRegion: Pair<Int, Int>): Boolean {
return value >= validRegion.first && value <= validRegion.second
}
fun String.isNullOrBlank(value: String?): Boolean {
return value == null || value.isBlank()
}
fun verifyBirthYear(byr: String?): Boolean {
if (byr.isNullOrBlank()) {
return false
}
return verifyValue(byr.toInt(), Pair(1920, 2002));
}
fun verifyIssueYear(iyr: String?): Boolean {
if (iyr.isNullOrBlank()) {
return false
}
return verifyValue(iyr.toInt(), Pair(2010, 2020));
}
fun verifyExpirationYear(eyr: String?): Boolean {
if (eyr.isNullOrBlank()) {
return false;
}
return verifyValue(eyr.toInt(), Pair(2020, 2030))
}
fun verifyHeight(hgt: String?): Boolean {
if (hgt.isNullOrBlank()) {
return false
}
if (hgt.endsWith("cm")) {
return verifyValue(hgt.dropLast(2).toInt(), Pair(150, 193))
}
if (hgt.endsWith("in")) {
return verifyValue(hgt.dropLast(2).toInt(), Pair(59, 76))
}
return false
}
fun verifyHairColor(hcl: String?): Boolean {
if (hcl.isNullOrBlank()) {
return false
}
val regexp = """#[0-9a-f]{6,6}""".toRegex()
return regexp.matches(hcl)
}
fun verifyEyeColor(ecl: String?): Boolean {
if (ecl.isNullOrBlank()) {
return false
}
return ecl.equals("amb") || ecl.equals("blu") || ecl.equals("brn") || ecl.equals("gry")
|| ecl.equals("grn") || ecl.equals("hzl") || ecl.equals("oth")
}
fun verifyPassportId(pid: String?): Boolean {
if (pid.isNullOrBlank()) {
return false
}
return pid.length == 9 && pid.toIntOrNull() != null
}
| 0 | Kotlin | 0 | 0 | abeb945e74536763a6c72cebb2b27f1d3a0e0ab5 | 4,082 | advent-of-code | Creative Commons Zero v1.0 Universal |
src/Day01/Day01.kt | SelenaChen123 | 573,253,480 | false | {"Kotlin": 14884} | import java.io.File
fun main() {
fun part1(input: List<String>): Int {
var globalMax = 0
var localMax = 0
for (line in input) {
if (line != "") {
localMax = localMax + line.toInt()
} else {
if (localMax.compareTo(globalMax) > 0) {
globalMax = localMax
}
localMax = 0
}
}
return globalMax
}
fun part2(input: List<String>): Int {
var max = ArrayList<Int>()
var localMax = 0
for (index in 0..input.size - 1) {
if (input[index] != "") {
localMax = localMax + input[index].toInt()
} else {
max.add(localMax)
if (index != input.size - 1) {
localMax = 0
}
}
}
max.add(localMax)
max.sort()
return max[max.size - 1] + max[max.size - 2] + max[max.size - 3]
}
val testInput = File("input", "Day01_test.txt").readLines()
val input = File("input", "Day01.txt").readLines()
val part1TestOutput = part1(testInput)
check(part1TestOutput == 24000)
println(part1(input))
val part2TestOutput = part2(testInput)
check(part2TestOutput == 45000)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 551af4f0efe11744f918d1ff5bb2259e34c5ecd3 | 1,344 | AdventOfCode2022 | Apache License 2.0 |
src/main/kotlin/g2101_2200/s2162_minimum_cost_to_set_cooking_time/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2101_2200.s2162_minimum_cost_to_set_cooking_time
// #Medium #Math #Enumeration #2023_06_26_Time_134_ms_(100.00%)_Space_32.8_MB_(100.00%)
class Solution {
fun minCostSetTime(startAt: Int, moveCost: Int, pushCost: Int, targetSeconds: Int): Int {
val mins = targetSeconds / 60
val secs = targetSeconds % 60
return Math.min(
cost(mins, secs, startAt, moveCost, pushCost),
cost(mins - 1, secs + 60, startAt, moveCost, pushCost)
)
}
private fun cost(mins: Int, secs: Int, startAt: Int, moveCost: Int, pushCost: Int): Int {
if (mins > 99 || secs > 99 || mins < 0 || secs < 0) {
return Int.MAX_VALUE
}
val s = Integer.toString(mins * 100 + secs)
var curr = (startAt + '0'.code).toChar()
var res = 0
for (i in 0 until s.length) {
if (s[i] == curr) {
res += pushCost
} else {
res += pushCost + moveCost
curr = s[i]
}
}
return res
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,068 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/g0601_0700/s0654_maximum_binary_tree/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g0601_0700.s0654_maximum_binary_tree
// #Medium #Array #Tree #Binary_Tree #Stack #Monotonic_Stack #Divide_and_Conquer
// #2023_02_13_Time_271_ms_(90.00%)_Space_37.8_MB_(95.00%)
import com_github_leetcode.TreeNode
/*
* Example:
* var ti = TreeNode(5)
* var v = ti.`val`
* Definition for a binary tree node.
* class TreeNode(var `val`: Int) {
* var left: TreeNode? = null
* var right: TreeNode? = null
* }
*/
class Solution {
fun constructMaximumBinaryTree(nums: IntArray): TreeNode? {
return mbt(nums, 0, nums.size - 1)
}
private fun mbt(nums: IntArray, l: Int, r: Int): TreeNode? {
if (l > r || l >= nums.size || r < 0) {
return null
}
if (l == r) {
return TreeNode(nums[r])
}
var max = Int.MIN_VALUE
var maxidx = 0
for (i in l..r) {
if (nums[i] > max) {
max = nums[i]
maxidx = i
}
}
val root = TreeNode(max)
root.left = mbt(nums, l, maxidx - 1)
root.right = mbt(nums, maxidx + 1, r)
return root
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,129 | LeetCode-in-Kotlin | MIT License |
src/Day01.kt | Jintin | 573,640,224 | false | {"Kotlin": 30591} | import java.lang.Integer.max
fun main() {
fun part1(input: List<String>): Int {
var max = 0
input.map {
it.toIntOrNull() ?: 0
}.reduce { acc, i ->
if (i == 0) {
max = max(max, acc)
0
} else {
acc + i
}
}
return max
}
fun part2(input: List<String>): Int {
val list = mutableListOf<Int>()
input.map {
it.toIntOrNull() ?: 0
}.toMutableList().also {
it.add(0)
}.reduce { acc, i ->
if (i == 0) {
list.add(acc)
0
} else {
acc + i
}
}
list.sortDescending()
return list.take(3).sum()
}
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 2 | 4aa00f0d258d55600a623f0118979a25d76b3ecb | 886 | AdventCode2022 | Apache License 2.0 |
src/main/kotlin/se/saidaspen/aoc/aoc2022/Day20.kt | saidaspen | 354,930,478 | false | {"Kotlin": 301372, "CSS": 530} | package se.saidaspen.aoc.aoc2022
import se.saidaspen.aoc.util.*
fun main() = Day20.run()
object Day20 : Day(2022, 20) {
override fun part1() = solve(1, 1)
override fun part2() = solve(811589153, 10)
private fun solve(key: Long, times: Int): Long {
// Changes 1, 2, 3 to (0, 1), (1, 2), (2, 3) to keep the original positions while moving things around
val wPos = longs(input).withIndex().map { P(it.index, it.value * key) }.toMutableList()
repeat(times) {
for (i in 0 until wPos.size) {
// Idx is the current index, elem.first is the original index, elem.second is the value
val (currIdx, elem) = wPos.withIndex().first { it.value.first == i }
wPos.removeAt(currIdx)
// FYI: Size has decreased by one, as we removed a value.
val newIdx = (currIdx + elem.second).mod(wPos.size)
wPos.add(newIdx, elem)
}
}
val indexOfZero = wPos.indexOfFirst { it.second == 0L }
return listOf(1000, 2000, 3000).sumOf { wPos[(indexOfZero + it).mod(wPos.size)].second }
}
}
| 0 | Kotlin | 0 | 1 | be120257fbce5eda9b51d3d7b63b121824c6e877 | 1,140 | adventofkotlin | MIT License |
kotlin/368.Largest Divisible Subset(最大整除子集).kt | learningtheory | 141,790,045 | false | {"Python": 4025652, "C++": 1999023, "Java": 1995266, "JavaScript": 1990554, "C": 1979022, "Ruby": 1970980, "Scala": 1925110, "Kotlin": 1917691, "Go": 1898079, "Swift": 1827809, "HTML": 124958, "Shell": 7944} | /**
<p>
Given a set of <b>distinct</b> positive integers, find the largest subset such that every pair (S<sub>i</sub>, S<sub>j</sub>) of elements in this subset satisfies: S<sub>i</sub> % S<sub>j</sub> = 0 or S<sub>j</sub> % S<sub>i</sub> = 0.
</p>
<p>If there are multiple solutions, return any subset is fine.
</p>
<p><b>Example 1:</b>
<pre>
nums: [1,2,3]
Result: [1,2] (of course, [1,3] will also be ok)
</pre>
</p>
<p><b>Example 2:</b>
<pre>
nums: [1,2,4,8]
Result: [1,2,4,8]
</pre>
</p>
<p><b>Credits:</b><br />Special thanks to <a href="https://leetcode.com/stomach_ache">@Stomach_ache</a> for adding this problem and creating all test cases.</p><p>给出一个由<strong>无重复的</strong>正整数组成的集合, 找出其中最大的整除子集, 子集中任意一对 (S<sub>i</sub>, S<sub>j</sub>) 都要满足: S<sub>i</sub> % S<sub>j</sub> = 0 或 S<sub>j</sub> % S<sub>i</sub> = 0。</p>
<p>如果有多个目标子集,返回其中任何一个均可。</p>
<p><strong>示例 1:</strong></p>
<pre>
集合: [1,2,3]
结果: [1,2] (当然, [1,3] 也正确)
</pre>
<p><strong> 示例 2:</strong></p>
<pre>
集合: [1,2,4,8]
结果: [1,2,4,8]
</pre>
<p><strong>致谢:</strong><br />
特别感谢 <a href="https://leetcode.com/stomach_ache">@Stomach_ache</a> 添加这道题并创建所有测试用例。</p>
<p>给出一个由<strong>无重复的</strong>正整数组成的集合, 找出其中最大的整除子集, 子集中任意一对 (S<sub>i</sub>, S<sub>j</sub>) 都要满足: S<sub>i</sub> % S<sub>j</sub> = 0 或 S<sub>j</sub> % S<sub>i</sub> = 0。</p>
<p>如果有多个目标子集,返回其中任何一个均可。</p>
<p><strong>示例 1:</strong></p>
<pre>
集合: [1,2,3]
结果: [1,2] (当然, [1,3] 也正确)
</pre>
<p><strong> 示例 2:</strong></p>
<pre>
集合: [1,2,4,8]
结果: [1,2,4,8]
</pre>
<p><strong>致谢:</strong><br />
特别感谢 <a href="https://leetcode.com/stomach_ache">@Stomach_ache</a> 添加这道题并创建所有测试用例。</p>
**/
class Solution {
fun largestDivisibleSubset(nums: IntArray): List<Int> {
}
} | 0 | Python | 1 | 3 | 6731e128be0fd3c0bdfe885c1a409ac54b929597 | 2,149 | leetcode | MIT License |
src/main/kotlin/nl/jackploeg/aoc/_2022/calendar/day21/Day21.kt | jackploeg | 736,755,380 | false | {"Kotlin": 318734} | package nl.jackploeg.aoc._2022.calendar.day21
import nl.jackploeg.aoc.generators.InputGenerator.InputGeneratorFactory
import nl.jackploeg.aoc.utilities.readStringFile
import javax.inject.Inject
import kotlin.math.abs
class Day21 @Inject constructor(
private val generatorFactory: InputGeneratorFactory,
) {
// get root monkey number
fun partOne(fileName: String): Long? {
val monkeys = readStringFile(fileName).map { mapMonkey(it) }.associate { it.name to it }
val rootMonkey = monkeys.get("root")
while (rootMonkey!!.number == null) {
for (monkey in monkeys.values.filter { it.number == null }) {
val monkey1 = monkeys.get(monkey.monkey1)
val monkey2 = monkeys.get(monkey.monkey2)
if (monkey1!!.number != null && monkey2!!.number != null) {
when (monkey.operation) {
Operation.PLUS -> monkey.number = monkey1.number?.plus(monkey2.number!!)
Operation.MINUS -> monkey.number = monkey1.number?.minus(monkey2.number!!)
Operation.MULTIPLY -> monkey.number = monkey1.number?.times(monkey2.number!!)
Operation.DIVIDE -> monkey.number = monkey1.number?.div(monkey2.number!!)
else -> {}
}
}
}
}
return rootMonkey.number
}
fun partTwo(fileName: String): Long = generatorFactory.forFile(fileName).readAs(::monkeyJob) { input ->
val monkeyJobs = mutableMapOf<String, MonkeyJob>()
input.forEach { monkeyJobs[it.name] = it }
var max = Long.MAX_VALUE
var min = 0L
var answer: PartTwoResult? = null
while (answer == null) {
val mid = max - (max - min) / 2
val results = listOf(min, mid, max).map { yellValue ->
//print("Yell: $yellValue: ")
monkeyJobs[HUMAN_NAME] = MonkeyJob.YellNumber(HUMAN_NAME, yellValue.toDouble())
(monkeyJobs[ROOT_NAME] as MonkeyJob.ResultOperation).let { resultOp ->
val xx = monkeyJobs[resultOp.first]!!.getData(monkeyJobs)
val yy = monkeyJobs[resultOp.second]!!.getData(monkeyJobs)
//println("distance: ${abs(xx - yy)}")
PartTwoResult(yellValue, abs(xx - yy))
}
}.sortedBy { it.distanceFromAnswer }
val maybeResult = results.firstOrNull { it.distanceFromAnswer == 0.0 }
if (maybeResult != null) {
answer = maybeResult
} else {
val bestTwo = results.take(2)
min = kotlin.math.min(bestTwo.first().yellNumber, bestTwo.last().yellNumber)
max = kotlin.math.max(bestTwo.first().yellNumber, bestTwo.last().yellNumber)
}
}
answer.yellNumber
}
private fun monkeyJob(line: String): MonkeyJob {
val mainParts = line.split(": ")
val monkeyName = mainParts[0]
val remainingParts = mainParts[1].split(" ")
return if (remainingParts.size == 3) {
val firstMonkey = remainingParts[0]
val secondMonkey = remainingParts[2]
val operation: (Double, Double) -> Double = when (remainingParts[1]) {
"+" -> Double::plus
"*" -> Double::times
"-" -> Double::minus
"/" -> Double::div
else -> throw IllegalArgumentException("Unknown operation ${remainingParts[1]}")
}
MonkeyJob.ResultOperation(monkeyName, firstMonkey, secondMonkey, operation)
} else {
MonkeyJob.YellNumber(monkeyName, remainingParts[0].toDouble())
}
}
sealed class MonkeyJob(val name: String) {
abstract fun getData(monkeyJobs: MutableMap<String, MonkeyJob>): Double
class YellNumber(name: String, val number: Double) : MonkeyJob(name) {
override fun getData(monkeyJobs: MutableMap<String, MonkeyJob>): Double = number
}
class ResultOperation(
name: String,
val first: String,
val second: String,
val operation: (Double, Double) -> Double
) : MonkeyJob(name) {
override fun getData(monkeyJobs: MutableMap<String, MonkeyJob>): Double = operation(
monkeyJobs[first]!!.getData(monkeyJobs),
monkeyJobs[second]!!.getData(monkeyJobs)
)
}
}
data class PartTwoResult(val yellNumber: Long, val distanceFromAnswer: Double)
fun mapMonkey(line: String): Monkey {
val parts = line.split(" ")
if (parts.size == 2) {
return Monkey(parts[0].dropLast(1), parts[1].toLong())
} else {
return Monkey(parts[0].dropLast(1), null, Operation.from(parts[2][0]), parts[1], parts[3])
}
}
enum class Operation {
PLUS, MINUS, MULTIPLY, DIVIDE;
companion object {
fun from(char: Char): Operation {
return when (char) {
'+' -> PLUS
'-' -> MINUS
'*' -> MULTIPLY
'/' -> DIVIDE
else -> throw RuntimeException()
}
}
}
}
data class Monkey(
val name: String,
var number: Long?,
var operation: Operation? = null,
val monkey1: String? = null,
val monkey2: String? = null
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Monkey
if (name != other.name) return false
return true
}
override fun hashCode(): Int {
return name.hashCode()
}
}
companion object {
private const val HUMAN_NAME = "humn"
private const val ROOT_NAME = "root"
}
}
| 0 | Kotlin | 0 | 0 | f2b873b6cf24bf95a4ba3d0e4f6e007b96423b76 | 6,043 | advent-of-code | MIT License |
src/main/kotlin/g1401_1500/s1439_find_the_kth_smallest_sum_of_a_matrix_with_sorted_rows/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1401_1500.s1439_find_the_kth_smallest_sum_of_a_matrix_with_sorted_rows
// #Hard #Array #Binary_Search #Matrix #Heap_Priority_Queue
// #2023_06_07_Time_225_ms_(100.00%)_Space_38.5_MB_(100.00%)
import java.util.Objects
import java.util.TreeSet
@Suppress("kotlin:S6510")
class Solution {
fun kthSmallest(mat: Array<IntArray>, k: Int): Int {
val treeSet = TreeSet(
Comparator { o1: IntArray, o2: IntArray ->
if (o1[0] != o2[0]) {
return@Comparator o1[0] - o2[0]
} else {
for (i in 1 until o1.size) {
if (o1[i] != o2[i]) {
return@Comparator o1[i] - o2[i]
}
}
return@Comparator 0
}
}
)
val m = mat.size
val n = mat[0].size
var sum = 0
val entry = IntArray(m + 1)
for (ints in mat) {
sum += ints[0]
}
entry[0] = sum
treeSet.add(entry)
var count = 0
while (count < k) {
val curr: IntArray = treeSet.pollFirst() as IntArray
count++
if (count == k) {
return Objects.requireNonNull(curr)[0]
}
for (i in 0 until m) {
val next = Objects.requireNonNull(curr).copyOf(curr.size)
if (curr[i + 1] + 1 < n) {
next[0] -= mat[i][curr[i + 1]]
next[0] += mat[i][curr[i + 1] + 1]
next[i + 1]++
treeSet.add(next)
}
}
}
return -1
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,696 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/g2501_2600/s2532_time_to_cross_a_bridge/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2501_2600.s2532_time_to_cross_a_bridge
// #Hard #Array #Heap_Priority_Queue #Simulation
// #2023_07_04_Time_420_ms_(100.00%)_Space_47.1_MB_(50.00%)
import java.util.PriorityQueue
@Suppress("NAME_SHADOWING")
class Solution {
fun findCrossingTime(n: Int, k: Int, time: Array<IntArray>): Int {
// create 2 PQ
var n = n
val leftBridgePQ = PriorityQueue { a: IntArray, b: IntArray -> if (a[1] == b[1]) b[0] - a[0] else b[1] - a[1] }
val rightBridgePQ = PriorityQueue { a: IntArray, b: IntArray -> if (a[1] == b[1]) b[0] - a[0] else b[1] - a[1] }
val leftWHPQ = PriorityQueue { a: IntArray, b: IntArray -> a[1].compareTo(b[1]) }
val rightWHPQ = PriorityQueue { a: IntArray, b: IntArray -> a[1].compareTo(b[1]) }
for (i in 0 until k) {
val efficiency = time[i][0] + time[i][2]
leftBridgePQ.offer(intArrayOf(i, efficiency))
}
var duration = 0
while (n > 0 || rightBridgePQ.isNotEmpty() || rightWHPQ.isNotEmpty()) {
while (leftWHPQ.isNotEmpty() && leftWHPQ.peek()[1] <= duration) {
val id = leftWHPQ.poll()[0]
val e = time[id][0] + time[id][2]
leftBridgePQ.offer(intArrayOf(id, e))
}
while (rightWHPQ.isNotEmpty() && rightWHPQ.peek()[1] <= duration) {
val id = rightWHPQ.poll()[0]
val e = time[id][0] + time[id][2]
rightBridgePQ.offer(intArrayOf(id, e))
}
if (rightBridgePQ.isNotEmpty()) {
val id = rightBridgePQ.poll()[0]
duration += time[id][2]
leftWHPQ.offer(intArrayOf(id, duration + time[id][3]))
} else if (leftBridgePQ.isNotEmpty() && n > 0) {
val id = leftBridgePQ.poll()[0]
duration += time[id][0]
rightWHPQ.offer(intArrayOf(id, duration + time[id][1]))
--n
} else {
// update duration
var left = Int.MAX_VALUE
if (leftWHPQ.isNotEmpty() && n > 0) {
left = leftWHPQ.peek()[1]
}
var right = Int.MAX_VALUE
if (rightWHPQ.isNotEmpty()) {
right = rightWHPQ.peek()[1]
}
duration = Math.min(left, right)
}
}
return duration
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 2,432 | LeetCode-in-Kotlin | MIT License |
17.kts | pin2t | 725,922,444 | false | {"Kotlin": 48856, "Go": 48364, "Shell": 54} | import java.util.*
val grid = System.`in`.bufferedReader().lines().map { it.map { (it - '0') }.toList() }.toList()
val up = Pair(0, -1); val right = Pair(1, 0); val down = Pair(0, 1); val left = Pair(-1, 0)
data class Crucible(val pos: Pair<Int, Int>, val dir: Pair<Int, Int>, val loss: Int, val straights: Int)
var res1 = 0; var res2 = 0
val queue = PriorityQueue<Crucible>(compareBy { it.loss })
queue.add(Crucible(Pair(0, 0), right, 0, 0))
val processed = HashSet<Triple<Pair<Int, Int>, Pair<Int, Int>, Int>>()
while (!queue.isEmpty()) {
val c = queue.poll()
if (c.pos == Pair(grid[0].size - 1, grid.size - 1)) { res1 = c.loss; break }
val key = Triple(c.pos, c.dir, c.straights)
if (processed.contains(key)) continue
processed.add(key)
listOf(up, right, down, left).forEach { dir ->
val np = Pair(c.pos.first + dir.first, c.pos.second + dir.second)
if (np.first >= 0 && np.second >= 0 && np.first < grid[0].size && np.second < grid.size) {
val next = Crucible(np, dir, c.loss + grid[np.second][np.first], c.straights + 1)
if (c.dir == dir) {
if (next.straights <= 3) queue.add(next)
} else {
if (c.dir == up && dir != down || c.dir == right && dir != left || c.dir == down && dir != up || c.dir == left && dir != right) {
queue.add(Crucible(next.pos, next.dir, next.loss, 1))
}
}
}
}
}
queue.clear()
queue.add(Crucible(Pair(0, 0), right, 0, 0))
processed.clear()
while (!queue.isEmpty()) {
val c = queue.poll()
if (c.pos == Pair(grid[0].size - 1, grid.size - 1)) { res2 = c.loss; break }
val key = Triple(c.pos, c.dir, c.straights)
if (processed.contains(key)) continue
processed.add(key)
listOf(up, right, down, left).forEach { dir ->
val np = Pair(c.pos.first + dir.first, c.pos.second + dir.second)
if (np.first >= 0 && np.second >= 0 && np.first < grid[0].size && np.second < grid.size) {
val next = Crucible(np, dir, c.loss + grid[np.second][np.first], c.straights + 1)
if (c.dir == dir) {
if (next.straights <= 10) queue.add(next)
} else if (c.straights >= 4) {
if (c.dir == up && dir != down || c.dir == right && dir != left || c.dir == down && dir != up || c.dir == left && dir != right) {
queue.add(Crucible(next.pos, next.dir, next.loss, 1))
}
}
}
}
}
println(listOf(res1, res2))
| 0 | Kotlin | 1 | 0 | 7575ab03cdadcd581acabd0b603a6f999119bbb6 | 2,531 | aoc2023 | MIT License |
sincmathsmp/src/commonMain/kotlin/io/github/gallvp/sincmaths/SincMatrixMaths.kt | GallVp | 353,046,891 | false | {"Kotlin": 187027, "C": 2472, "Makefile": 2334, "C++": 2258, "Ruby": 2181, "CMake": 1385, "Shell": 730} | package io.github.gallvp.sincmaths
import kotlin.math.pow
expect operator fun SincMatrix.times(rhs: SincMatrix): SincMatrix
expect operator fun SincMatrix.times(rhs: Double): SincMatrix
expect operator fun SincMatrix.plus(rhs: SincMatrix): SincMatrix
expect operator fun SincMatrix.plus(rhs: Double): SincMatrix
expect infix fun SincMatrix.elDiv(rhs: SincMatrix): SincMatrix
expect infix fun SincMatrix.elMul(rhs: SincMatrix): SincMatrix
expect fun SincMatrix.elSum(): Double
expect infix fun SincMatrix.elPow(power: Double): SincMatrix
operator fun SincMatrix.minus(rhs: SincMatrix): SincMatrix = this + (rhs * -1.0)
operator fun SincMatrix.minus(rhs: Double): SincMatrix = this + (rhs * -1.0)
operator fun SincMatrix.div(rhs: Double): SincMatrix = this * (1 / rhs)
operator fun SincMatrix.unaryMinus(): SincMatrix {
return this * -1.0
}
infix fun SincMatrix.elMul(rhs: Double): SincMatrix = this * rhs
operator fun Double.plus(rhs: SincMatrix) = rhs + this
operator fun Double.minus(rhs: SincMatrix) = -rhs + this
operator fun Double.times(rhs: SincMatrix) = rhs * this
operator fun Double.div(rhs: SincMatrix) = (SincMatrix.ones(rhs.numRows, rhs.numCols) * this) elDiv rhs
expect fun SincMatrix.floor(): SincMatrix
expect fun SincMatrix.abs(): SincMatrix
fun SincMatrix.sign(): SincMatrix {
// Octave code: floor(t./(abs(t)+1)) - floor(-t./(abs(-t)+1))
val negSelf = this * -1.0
val firstPart = (this elDiv (this.abs() + 1.0)).floor()
val secondPart = (negSelf elDiv (negSelf.abs() + 1.0)).floor()
return firstPart - secondPart
}
fun SincMatrix.sqrt(): SincMatrix = this elPow (1.0 / 2.0)
fun SincMatrix.cross(ontoVector: SincMatrix): SincMatrix {
require(
this.isVector && ontoVector.isVector &&
this.numel == 3 && ontoVector.numel == 3,
) {
"This function works only for vectors of length 3"
}
val c1 = this[2] * ontoVector[3] - this[3] * ontoVector[2]
val c2 = this[3] * ontoVector[1] - this[1] * ontoVector[3]
val c3 = this[1] * ontoVector[2] - this[2] * ontoVector[1]
return if (this.isColumn && ontoVector.isColumn) {
doubleArrayOf(c1, c2, c3).asSincMatrix(m = 3, n = 1)
} else {
doubleArrayOf(c1, c2, c3).asSincMatrix(m = 1, n = 3)
}
}
fun SincMatrix.dot(rhs: SincMatrix): SincMatrix = (this elMul rhs).sum()
fun SincMatrix.round(n: Int): SincMatrix =
map {
kotlin.math.round(it * 10.0.pow(n)) / 10.0.pow(n)
}
| 1 | Kotlin | 0 | 0 | 061bed61c37bedc6aedc2312e179d0e507683011 | 2,468 | sincmaths | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/CountingElements.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
/**
* Counting Elements
* @see <a href="https://leetcode.com/problems/counting-elements/">Source</a>
*/
fun interface CountingElements {
operator fun invoke(arr: IntArray): Int
}
/**
* Approach 1: Search with Array
* Time complexity : O(N^2)
* Space complexity : O(1)
*/
class CESearchWithArray : CountingElements {
override operator fun invoke(arr: IntArray): Int {
var count = 0
for (x in arr) {
if (x.plus(1).isInArray(arr)) {
count++
}
}
return count
}
/**
* @param arr
* Check is target in the array
*/
private fun Int.isInArray(arr: IntArray): Boolean {
for (x in arr) {
if (x == this) {
return true
}
}
return false
}
}
/**
* Approach 2: Search with HashSet
* Time complexity : O(N).
* Space complexity : O(N).
*/
class CESearchingWithHashSet : CountingElements {
override operator fun invoke(arr: IntArray): Int {
val set = arr.toHashSet()
var count = 0
for (x in arr) {
val value = x.plus(1)
if (set.contains(value)) {
count++
}
}
return count
}
}
/**
* Approach 3: Search with Sorted Array
* Time complexity : O(NlogN).
* Space complexity : varies from O(N) to O(1).
*/
class CESearchingWithSortedArray : CountingElements {
override operator fun invoke(arr: IntArray): Int {
arr.sort()
var count = 0
var runLength = 1
for (i in 1 until arr.size) {
if (arr[i - 1] != arr[i]) {
if (arr[i - 1] + 1 == arr[i]) {
count += runLength
}
runLength = 0
}
runLength++
}
return count
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,482 | kotlab | Apache License 2.0 |
src/nativeMain/kotlin/com.qiaoyuang.algorithm/round1/Questions5.kt | qiaoyuang | 100,944,213 | false | {"Kotlin": 338134} | package com.qiaoyuang.algorithm.round1
fun test5() {
val charArray0 = charArrayOf('W', 'e', ' ', 'a', 'r', 'e', ' ', 'h', 'a', 'p', 'p', 'y', '.', ' ', ' ', ' ', ' ')
charArray0.replaceChar(' ', "%20", 13)
println("Input: \"We are happy\", replace the ' ' with \"%20\"")
charArray0.forEach {
print(it)
}
println()
println("Input: \"We are happy\", replace the '&' with \"!@#\"")
charArray0.replaceChar('&', "!@#", 13)
charArray0.forEach {
print(it)
}
println()
val array1 = intArrayOf(1, 2, 3, -1, -1, -1)
val array2 = intArrayOf(4, 5, 6)
println("Input: [1, 2, 3], [4, 5, 6]")
insetArray(array1, 3, array2)
array1.forEach {
print(it)
}
println()
val array11 = intArrayOf(1, 3, 5, -1, -1, -1, -1)
val array21 = intArrayOf(2, 4, 6, 8)
println("Input: [1, 3, 5], [2, 4, 6, 8]")
insetArray(array11, 3, array21)
array11.forEach {
print(it)
}
println()
val array12 = intArrayOf(1, 3, 5)
val array22 = intArrayOf()
println("Input: [1, 3, 5], []")
insetArray(array12, 3, array22)
array12.forEach {
print(it)
}
println()
}
/**
* Questions 5-1: replace char in CharArray with another string. For example, replace the ' ' to "%20"
*/
private fun CharArray.replaceChar(char: Char, str: String, length: Int) {
var count = 0
var index = 0
while (index < length) {
val c = this[index]
if (c == char)
count++
index++
}
if (count == 0) return
var diff = (str.length - 1) * count
index = length - 1
while (index >= 0) {
val c = this[index]
var newIndex = index + diff
if (newIndex < size) {
if (c == char) {
for (i in str.lastIndex downTo 0)
this[newIndex--] = str[i]
diff -= str.length - 1
} else
this[newIndex] = c
}
index--
}
}
/**
* Questions 5-2: We have two sorted IntArray a1 and a2, the a1 have enough space to insert a2, please insert a2 to a1 and sorted.
*/
private fun insetArray(a1: IntArray, a1RealSize: Int, a2: IntArray) {
var a1Index = a1.lastIndex
var a1RealIndex = a1RealSize - 1
var a2Index = a2.lastIndex
while (a1Index >= 0) {
if (a1RealIndex < 0) {
a1[a1Index--] = a2[a2Index--]
continue
}
if (a2Index < 0) {
a1[a1Index--] = a1[a1RealIndex--]
continue
}
val a1Num = a1[a1RealIndex]
val a2Num = a2[a2Index]
if (a2Num >= a1Num) {
a1[a1Index] = a2Num
a2Index--
} else {
a1[a1Index] = a1Num
a1RealIndex--
}
a1Index--
}
} | 0 | Kotlin | 3 | 6 | 66d94b4a8fa307020d515d4d5d54a77c0bab6c4f | 2,798 | Algorithm | Apache License 2.0 |
src/Day01.kt | lmoustak | 573,003,221 | false | {"Kotlin": 25890} | import kotlin.math.max
fun main() {
fun part1(input: List<String>): Int {
var currentCalories = 0
var maxCalories = 0
input.forEach {
if (it.isBlank()) {
maxCalories = max(maxCalories, currentCalories)
currentCalories = 0
} else {
currentCalories += it.toInt()
}
}
maxCalories = max(maxCalories, currentCalories)
return maxCalories
}
fun part2(input: List<String>): Int {
var currentCalories = 0
val elves = mutableListOf<Int>()
input.forEach {
if (it.isBlank()) {
elves.add(currentCalories)
currentCalories = 0
} else {
currentCalories += it.toInt()
}
}
elves.sortDescending()
return elves[0] + elves[1] + elves[2]
}
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | bd259af405b557ab7e6c27e55d3c419c54d9d867 | 996 | aoc-2022-kotlin | Apache License 2.0 |
src/main/kotlin/kt/kotlinalgs/app/sorting/QuickSort.ws.kts | sjaindl | 384,471,324 | false | null | package kt.kotlinalgs.app.sorting
println("test")
val array1 = intArrayOf(3, 2, 1)
val array2 = intArrayOf(2000, 234, 21, 41, 1, 21, 75, 0, -4)
QuickSort().sort(array1)
QuickSort().sort(array2)
// runtime: O(N log N) best + average, O(N^2) worst case
// space: O(log N) best + average, O(N) worst case
// unstable
println(array1.map { it })
println(array2.map { it })
class QuickSort {
fun sort(array: IntArray) {
if (array.size <= 1) return
// Improvement: Randomize array (avoid worst case when array is sorted)
quickSort(array, 0, array.lastIndex)
}
// [3, 2, 1], 0, 2
private fun quickSort(array: IntArray, low: Int, high: Int) {
if (high <= low) return
val pivot = partition(array, low, high)
quickSort(array, low, pivot - 1)
quickSort(array, pivot + 1, high)
}
// [3, 2, 1], 0, 2
private fun partition(array: IntArray, low: Int, high: Int): Int {
val pivotIndex = low + (high - low) / 2 // improvement: median of 3
val pivot = array[pivotIndex] // 2
exchange(array, low, pivotIndex) // [2, 1, 3]
var left = low + 1 // 2
var right = high // 2
// pivot = 3
// [4,5,3,1,2] -> [3,5,4,1,2] --> [3,5,1,4,2]
// [2,1,10,3,4] -> [10,1,2,3,4]
while (left <= right) {
while (left < array.size && array[left] < pivot) left++
while (right >= 0 && array[right] > pivot) right--
if (left <= right) {
exchange(array, left, right)
left++
right--
}
}
exchange(array, low, right)
return right
}
private fun exchange(array: IntArray, firstIndex: Int, secondIndex: Int) {
val temp = array[firstIndex]
array[firstIndex] = array[secondIndex]
array[secondIndex] = temp
}
}
| 0 | Java | 0 | 0 | e7ae2fcd1ce8dffabecfedb893cb04ccd9bf8ba0 | 1,881 | KotlinAlgs | MIT License |
src/main/kotlin/days/Day6.kt | hughjdavey | 725,972,063 | false | {"Kotlin": 76988} | package days
class Day6 : Day(6) {
private val times = inputList.first().split(' ').filter { it.matches(Regex("\\d+")) }
private val distances = inputList.last().split(' ').filter { it.matches(Regex("\\d+")) }
override fun partOne(): Any {
val races = times.zip(distances).map { (time, distance) -> Race(time.toLong(), distance.toLong()) }
return races.map { it.winningHoldTimes().size }.fold(1) { a, e -> a * e }
}
override fun partTwo(): Any {
val time = times.joinToString("")
val distance = distances.joinToString("")
val race = Race(time.toLong(), distance.toLong())
return race.winningHoldTimes().size
}
data class Race(val time: Long, val distance: Long) {
fun winningHoldTimes(): List<Long> {
return (0..time).filter { holdTime ->
val remainingTime = time - holdTime
val boatDistance = holdTime * remainingTime
boatDistance > distance
}
}
}
}
| 0 | Kotlin | 0 | 0 | 330f13d57ef8108f5c605f54b23d04621ed2b3de | 1,025 | aoc-2023 | Creative Commons Zero v1.0 Universal |
aoc16/day_10/main.kt | viktormalik | 436,281,279 | false | {"Rust": 227300, "Go": 86273, "OCaml": 82410, "Kotlin": 78968, "Makefile": 13967, "Roff": 9981, "Shell": 2796} | import java.io.File
data class Rule(val bot_low: Int?, val out_low: Int?, val bot_high: Int?, val out_high: Int?)
fun main() {
val instructions = File("input").readLines()
val bots = mutableMapOf<Int, MutableList<Int>>()
val rules = mutableMapOf<Int, Rule>()
val outputs = mutableMapOf<Int, Int>()
for (inst in instructions) {
if (inst.startsWith("value")) {
val v = inst.split(" ")[1].toInt()
val bot = inst.split(" ")[5].toInt()
bots.getOrPut(bot) { mutableListOf() }.add(v)
} else if (inst.startsWith("bot")) {
val bot = inst.split(" ")[1].toInt()
val low = inst.split(" ")[6].toInt()
val high = inst.split(" ")[11].toInt()
val bot_low = if (inst.split(" ")[5] == "bot") low else null
val out_low = if (inst.split(" ")[5] == "output") low else null
val bot_high = if (inst.split(" ")[10] == "bot") high else null
val out_high = if (inst.split(" ")[10] == "output") high else null
rules.put(bot, Rule(bot_low, out_low, bot_high, out_high))
}
}
while (bots.filterValues { it.size == 2 }.any()) {
val bot = bots.filterValues { it.size == 2 }.keys.first()
val vals = bots.get(bot)!!
val low = vals.minOrNull()!!
val high = vals.maxOrNull()!!
if (low == 17 && high == 61) {
println("First: $bot")
}
val rule = rules.get(bot)!!
if (rule.bot_low != null)
bots.getOrPut(rule.bot_low) { mutableListOf() }.add(low)
else if (rule.out_low != null)
outputs.put(rule.out_low, low)
if (rule.bot_high != null)
bots.getOrPut(rule.bot_high) { mutableListOf() }.add(high)
else if (rule.out_high != null)
outputs.put(rule.out_high, high)
vals.clear()
}
val second = outputs.get(0)!! * outputs.get(1)!! * outputs.get(2)!!
println("Second: $second")
}
| 0 | Rust | 1 | 0 | f47ef85393d395710ce113708117fd33082bab30 | 1,996 | advent-of-code | MIT License |
src/test/kotlin/be/brammeerten/y2022/Day5Test.kt | BramMeerten | 572,879,653 | false | {"Kotlin": 170522} | package be.brammeerten.y2022
import be.brammeerten.readFile
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import java.util.*
class Day5Test {
@Test
fun `part 1`() {
val input = readFile("2022/day5/exampleInput.txt")
val stacks = readStacks(input)
val moves = readMoves(input)
moves.forEach{ it.execute(stacks)}
val result = stacks.map { it.peek() }.joinToString("")
assertEquals("CMZ", result)
}
@Test
fun `part 2`() {
val input = readFile("2022/day5/exampleInput.txt")
val stacks = readStacks(input)
val moves = readMoves(input)
moves.forEach{ it.executePart2(stacks)}
val result = stacks.map { it.peek() }.joinToString("")
assertEquals("MCD", result)
}
private fun readMoves(input: List<String>): List<Move> {
val regex = "move (\\d+) from (\\d+) to (\\d+)".toRegex()
val moves = input
.filter { it.startsWith("move") }
.map {
val matches = regex.find(it)
Move(matches!!.groupValues[1].toInt(), matches.groupValues[2].toInt(), matches.groupValues[3].toInt())
}
return moves
}
private fun readStacks(input: List<String>): List<Stack<Char>> {
val num = (input[0].length + 1) / 4
val stacks = (1..num).map { Stack<Char>() }.toList()
input
.takeWhile { !it.startsWith(" 1 2 3") }
.forEach { stacks.forEachIndexed { i, stack -> pushIfPresent(it, i, stack) } }
stacks.forEach { it.reverse() }
return stacks
}
private fun pushIfPresent(line: String, index: Int, stack: Stack<Char>) {
val i = index*4 + 1
val char = line[i]
if (char != ' ') {
stack.push(char)
}
}
class Move(val amount: Int, val from: Int, val to: Int) {
fun execute(stacks: List<Stack<Char>>) {
for (c in 1..amount) {
val elem = stacks[from-1].pop()
stacks[to-1].push(elem)
}
}
fun executePart2(stacks: List<Stack<Char>>) {
(1..amount)
.map { stacks[from-1].pop() }
.reversed()
.forEach{ stacks[to-1].push(it) }
}
}
} | 0 | Kotlin | 0 | 0 | 1defe58b8cbaaca17e41b87979c3107c3cb76de0 | 2,335 | Advent-of-Code | MIT License |
src/day12/Day12.kt | crmitchelmore | 576,065,911 | false | {"Kotlin": 115199} | package day12
import helpers.ReadFile
class Block {
var minDistanceFromOrigin = Int.MAX_VALUE
var pathOfMinDistance: List<Pair<Int, Int>> = listOf()
val isEnd: Boolean
val isStart: Boolean
val height: Int
var position: Pair<Int, Int> = Pair(0, 0)
var validEdges: List<Pair<Int, Int>> = listOf()
constructor(isEnd: Boolean, isStart: Boolean, height: String) {
this.isEnd = isEnd
this.isStart = isStart
var h = height.toCharArray().first().code - 96
if (isStart) {
h = 1
}
if (isEnd) {
h = 26
}
this.height = h
}
}
class Day12 {
val lines = ReadFile.named("src/day12/input.txt")
val linesT = listOf(
"Sabqponm",
"abcryxxl",
"accszExk",
"acctuvwj",
"abdefghi",
)
val chars = lines.map { it.split("").filter { it.isNotEmpty() }.map { char ->
Block(isEnd = char == "E", isStart = char == "S", height = char)
} }
fun pairsNextTo(pair: Pair<Int, Int>): List<Pair<Int, Int>> {
val (x, y) = pair
var pairs: MutableList<Pair<Int, Int>> = mutableListOf()
if (x != 0) {
pairs.add(Pair(x - 1, y))
}
if (x != chars[0].size - 1) {
pairs.add(Pair(x + 1, y))
}
if (y != 0) {
pairs.add(Pair(x, y - 1))
}
if (y != chars.size - 1) {
pairs.add(Pair(x, y + 1))
}
return pairs
}
fun result1() {
var S: Pair<Int, Int> = Pair(0, 0)
var E: Pair<Int, Int> = Pair(0, 0)
for (line in 0 until chars.size) {
for (char in 0 until chars[line].size) {
val currentChar = chars[line][char]
val position = Pair(char, line)
currentChar.position = position
currentChar.validEdges = pairsNextTo(position).filter {
val candidate = chars[it.second][it.first]
!candidate.isEnd && candidate.height+1 >= currentChar.height
}
if (currentChar.isEnd) {
currentChar.minDistanceFromOrigin = 0
currentChar.pathOfMinDistance = listOf(position)
E = position
}
if (currentChar.isStart) {
S = position
}
}
}
val currentLayer = listOf(chars[E.second][E.first])
breadthFirstSearch(currentLayer)
print(chars[S.second][S.first].minDistanceFromOrigin)
print(chars[S.second][S.first].pathOfMinDistance)
var min = chars[S.second][S.first]
for (line in 0 until chars.size) {
for (char in 0 until chars[line].size) {
val currentChar = chars[line][char]
if (currentChar.minDistanceFromOrigin < min.minDistanceFromOrigin && currentChar.height == 1) {
min = currentChar
}
}
}
println("min: ${min.minDistanceFromOrigin}")
}
// Sabqponm
// abcryxxl
// accszExk
// acctuvwj
// abdefghi
//
//
// v..v<<<<
// >v.vv<<^
// .>vv>E^^
// ..v>>>^^
// ..>>>>>^
fun breadthFirstSearch(currentLayer: List<Block>) {
var nextLayer = mutableListOf<Block>()
for (current in currentLayer) {
for (location in current.validEdges) {
val block = chars[location.second][location.first]
val pathIsShortestFollowable = block.minDistanceFromOrigin > current.minDistanceFromOrigin + 1
if (pathIsShortestFollowable) {
block.minDistanceFromOrigin = current.minDistanceFromOrigin + 1
block.pathOfMinDistance = current.pathOfMinDistance + block.position
if (!block.isStart) {
nextLayer.add(block)
}
}
}
}
println(nextLayer.map{it.position})
if (currentLayer.size > 0) {
breadthFirstSearch(nextLayer)
}
}
} | 0 | Kotlin | 0 | 0 | fd644d442b5ff0d2f05fbf6317c61ee9ce7b4470 | 4,132 | adventofcode2022 | MIT License |
src/day21/Code.kt | fcolasuonno | 221,697,249 | false | null | package day21
import java.io.File
fun main() {
val name = if (false) "test.txt" else "input.txt"
val dir = ::main::class.java.`package`.name
val input = File("src/$dir/$name").readLines()
val parsed = parse(input)
println("Part 1 = ${part1(parsed)}")
println("Part 2 = ${part2(parsed)}")
}
sealed class Op {
abstract fun exec(input: List<Char>): List<Char>
abstract fun reverse(input: List<Char>): List<Char>
data class Swap(val from: Int, val to: Int) : Op() {
override fun exec(input: List<Char>) = input.mapIndexed { i, c ->
when (i) {
from -> input[to]
to -> input[from]
else -> c
}
}
override fun reverse(input: List<Char>) = exec(input)
}
data class SwapLetter(val from: Char, val to: Char) : Op() {
override fun exec(input: List<Char>) = input.map { c ->
when (c) {
from -> to
to -> from
else -> c
}
}
override fun reverse(input: List<Char>) = exec(input)
}
data class Rotate(val lr: String, val amount: Int) : Op() {
override fun exec(input: List<Char>) = if (lr == "right")
input.indices.map { input[(it + input.size - amount) % input.size] }
else
input.indices.map { input[(it + amount) % input.size] }
override fun reverse(input: List<Char>) = if (lr != "right")
input.indices.map { input[(it + input.size - amount) % input.size] }
else
input.indices.map { input[(it + amount) % input.size] }
}
data class RotateIndex(val letter: Char) : Op() {
override fun exec(input: List<Char>) = input.indexOf(letter).let {
if (it >= 4) (it + 2) else (it + 1)
}.let { amount ->
input.indices.map { input[(it + input.size - amount % input.size) % input.size] }
}
override fun reverse(input: List<Char>) = input.indexOf(letter).let {
if (it == 0 || it % 2 == 1) {
1 + it / 2
} else {
(input.size - 1) * (input.size - 2 - it) / 2
}
}.let { amount ->
input.indices.map { input[(it + amount) % input.size] }
}
}
data class Reverse(val start: Int, val end: Int) : Op() {
override fun exec(input: List<Char>) = input.take(start) + input.slice(start..end).reversed() + input.drop(end + 1)
override fun reverse(input: List<Char>) = exec(input)
}
data class Move(val from: Int, val end: Int) : Op() {
override fun exec(input: List<Char>) = if (end >= from) {
input.slice((0..end) - from) + input[from] + input.drop(end + 1)
} else {
input.slice(0 until end) + input[from] + input.slice((end until input.size) - from)
}
override fun reverse(input: List<Char>) = if (from >= end) {
input.slice((0..from) - end) + input[end] + input.drop(from + 1)
} else {
input.slice(0 until from) + input[end] + input.slice((from until input.size) - end)
}
}
}
private val swapPosition = """swap position (\d+) with position (\d+)""".toRegex()
private val swapLetter = """swap letter (.) with letter (.)""".toRegex()
private val rotate = """rotate (left|right) (\d+) steps?""".toRegex()
private val rotateIndex = """rotate based on position of letter (.)""".toRegex()
private val reverse = """reverse positions (\d+) through (\d+)""".toRegex()
private val move = """move position (.) to position (.)""".toRegex()
fun parse(input: List<String>) = input.map {
swapPosition.matchEntire(it)?.destructured?.let {
val (positionFrom, positionTo) = it.toList()
Op.Swap(positionFrom.toInt(), positionTo.toInt())
} ?: swapLetter.matchEntire(it)?.destructured?.let {
val (letterFrom, letterTo) = it.toList()
Op.SwapLetter(letterFrom.single(), letterTo.single())
} ?: rotate.matchEntire(it)?.destructured?.let {
val (lr, steps) = it.toList()
Op.Rotate(lr, steps.toInt())
} ?: rotateIndex.matchEntire(it)?.destructured?.let {
val (letter) = it.toList()
Op.RotateIndex(letter.single())
} ?: reverse.matchEntire(it)?.destructured?.let {
val (start, end) = it.toList()
Op.Reverse(start.toInt(), end.toInt())
} ?: move.matchEntire(it)?.destructured?.let {
val (from, to) = it.toList()
Op.Move(from.toInt(), to.toInt())
}
}.requireNoNulls()
fun part1(input: List<Op>): Any? = input.fold("abcdefgh".toList()) { seq, op ->
op.exec(seq)
}.joinToString("")
fun part2(input: List<Op>): Any? = input.reversed().fold("fbgdceah".toList()) { seq, op ->
op.reverse(seq)
}.joinToString("") | 0 | Kotlin | 0 | 0 | 73110eb4b40f474e91e53a1569b9a24455984900 | 4,797 | AOC2016 | MIT License |
src/main/kotlin/de/huddeldaddel/euler/Problem039.kt | huddeldaddel | 171,357,298 | false | null | package de.huddeldaddel.euler
/**
* Solution for https://projecteuler.net/problem=39
*/
fun main() {
var maxCombinations = 0
var result = 0
for(p in 3..1000) {
val combinations = mutableSetOf<String>()
for(a in 1..p) {
for(b in 1..p) {
val c = calculateC(a, b)
if(c.isInt() && (p == a + b + c.toInt())) {
combinations.add(normalizeResult(a, b, c.toInt()))
}
}
}
if(combinations.size > maxCombinations) {
maxCombinations = combinations.size
result = p
}
}
println(result)
}
fun calculateC(a: Int, b: Int): Double {
return Math.sqrt((a*a).toDouble() + b*b)
}
fun Double.isInt(): Boolean {
return this.rem(1.0f) < 0.0000000000000001
}
fun normalizeResult(a: Int, b: Int, c: Int): String {
val result = StringBuilder()
listOf(a, b, c)
.sorted()
.map { i -> i.toString() }
.forEach{ s -> result.append(s).append("+")}
return result.toString().subSequence(0, result.length -1).toString()
} | 0 | Kotlin | 1 | 0 | df514adde8c62481d59e78a44060dc80703b8f9f | 1,121 | euler | MIT License |
aoc2022/day2.kt | davidfpc | 726,214,677 | false | {"Kotlin": 127212} | package aoc2022
import utils.InputRetrieval
fun main() {
Day2.execute()
}
object Day2 {
fun execute() {
val input = readInput()
println("Part 1: ${part1(input)}")
println("Part 2: ${part2(input)}")
}
/**
* Rock Paper Scissors (Part 1)
* Opponent Move:
* A - Rock
* B - Paper
* C - Scissors
* Our Move:
* X - Rock - 1pts
* Y - Paper - 2pts
* Z - Scissors - 3pts
* Outcome of the round:
* Lost - 0pts
* Draw - 3pts
* Won - 6pts
*/
private val SCORE_MAP = mapOf("A X" to 4, "A Y" to 8, "A Z" to 3, "B X" to 1, "B Y" to 5, "B Z" to 9, "C X" to 7, "C Y" to 2, "C Z" to 6)
private fun part1(input: List<String>): Int = input.sumOf { SCORE_MAP[it]!! }
/**
* Rock Paper Scissors (Part 2)
* Opponent Move:
* A - Rock
* B - Paper
* C - Scissors
* Outcome of the round:
* X - Must Lose - 0pts
* Y - Must Draw - 3pts
* Z - Must Win - 6pts
* Our Move:
* Rock - 1pts
* Paper - 2pts
* Scissors - 3pts
*/
private val SCORE_MAP_PART_2 = mapOf("A X" to 3, "A Y" to 4, "A Z" to 8, "B X" to 1, "B Y" to 5, "B Z" to 9, "C X" to 2, "C Y" to 6, "C Z" to 7)
private fun part2(input: List<String>): Int = input.sumOf { SCORE_MAP_PART_2[it]!! }
private fun readInput(): List<String> = InputRetrieval.getFile(2022, 2).readLines()
}
| 0 | Kotlin | 0 | 0 | 8dacf809ab3f6d06ed73117fde96c81b6d81464b | 1,416 | Advent-Of-Code | MIT License |
year2021/day04/part2/src/main/kotlin/com/curtislb/adventofcode/year2021/day04/part2/Year2021Day04Part2.kt | curtislb | 226,797,689 | false | {"Kotlin": 2146738} | /*
--- Part Two ---
On the other hand, it might be wise to try a different strategy: let the giant squid win.
You aren't sure how many bingo boards a giant squid could play at once, so rather than waste time
counting its arms, the safe thing to do is to figure out which board will win last and choose that
one. That way, no matter which boards it picks, it will win for sure.
In the above example, the second board is the last to win, which happens after 13 is eventually
called and its middle column is completely marked. If you were to keep playing until this point, the
second board would have a sum of unmarked numbers equal to 148 for a final score of 148 * 13 = 1924.
Figure out which board will win last. Once it wins, what would its final score be?
*/
package com.curtislb.adventofcode.year2021.day04.part2
import com.curtislb.adventofcode.common.io.forEachSection
import com.curtislb.adventofcode.common.parse.parseInts
import com.curtislb.adventofcode.year2021.day04.bingo.BingoBoard
import java.nio.file.Path
import java.nio.file.Paths
/**
* Returns the solution to the puzzle for 2021, day 4, part 2.
*
* @param inputPath The path to the input file for this puzzle.
*/
fun solve(inputPath: Path = Paths.get("..", "input", "input.txt")): Int? {
var numbers: List<Int> = emptyList()
val boards = mutableSetOf<BingoBoard>()
inputPath.toFile().forEachSection { lines ->
if (numbers.isEmpty()) {
numbers = lines.first().parseInts()
} else {
boards.add(BingoBoard(lines))
}
}
// Remove boards as they win, returning the score of the last winning board
for (number in numbers) {
val boardsToRemove = mutableSetOf<BingoBoard>()
for (board in boards) {
board.mark(number)
if (board.isWinning) {
if (boards.size == 1) {
return board.winningScore
}
boardsToRemove.add(board)
}
}
boards.removeAll(boardsToRemove)
}
// All numbers were called without the final board winning
return null
}
fun main() = when (val solution = solve()) {
null -> println("No solution found.")
else -> println(solution)
}
| 0 | Kotlin | 1 | 1 | 6b64c9eb181fab97bc518ac78e14cd586d64499e | 2,242 | AdventOfCode | MIT License |
src/main/kotlin/g0501_0600/s0516_longest_palindromic_subsequence/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g0501_0600.s0516_longest_palindromic_subsequence
// #Medium #String #Dynamic_Programming #Dynamic_Programming_I_Day_17
// #2023_01_12_Time_243_ms_(87.50%)_Space_45.8_MB_(66.67%)
class Solution {
fun longestPalindromeSubseq(s: String): Int {
if (s.isEmpty()) {
return 0
}
val dp = Array(s.length) { IntArray(s.length) }
for (jidiff in 0 until s.length) {
for (i in 0 until s.length) {
val j = i + jidiff
if (j >= s.length) {
continue
}
dp[i][j] = when (j) {
i -> 1
i + 1 -> if (s[i] == s[j]) 2 else 1
else -> if (s[i] == s[j]) 2 + dp[i + 1][j - 1] else Math.max(dp[i + 1][j], dp[i][j - 1])
}
}
}
return dp[0][s.length - 1]
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 888 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/behavioural_patterns/interpreter/Interpreter.kt | ThijsBoehme | 291,005,516 | false | {"Kotlin": 88248, "Java": 31062} | package behavioural_patterns.interpreter
import java.util.stream.Collectors
interface Element {
fun eval(): Int
}
class Integer(private val value: Int): Element {
override fun eval(): Int {
return value
}
}
class BinaryOperation: Element {
lateinit var type: Type
lateinit var left: Element
lateinit var right: Element
override fun eval(): Int {
return when (type) {
Type.ADDITION -> left.eval() + right.eval()
Type.SUBTRACTION -> left.eval() - right.eval()
}
}
enum class Type {
ADDITION, SUBTRACTION
}
}
class Token(
val type: Type,
val text: String
) {
override fun toString(): String {
return "`$text`"
}
enum class Type {
INTEGER, PLUS, MINUS, LEFTPARENTHESIS, RIGHTPARENTHESIS
}
}
fun lex(input: String): List<Token> {
val result = ArrayList<Token>()
var i = 0
while (i < input.length) {
when (input[i]) {
'+' -> result.add(Token(Token.Type.PLUS, "+"))
'-' -> result.add(Token(Token.Type.MINUS, "-"))
'(' -> result.add(Token(Token.Type.LEFTPARENTHESIS, "("))
')' -> result.add(Token(Token.Type.RIGHTPARENTHESIS, ")"))
else -> {
val builder = StringBuilder("${input[i]}")
for (j in (i + 1) until input.length) {
if (input[j].isDigit()) {
builder.append(input[j])
++i
} else {
result.add(Token(Token.Type.INTEGER, builder.toString()))
break
}
}
}
}
i++
}
return result
}
fun parse(tokens: List<Token>): Element {
val result = BinaryOperation()
var hasLeftHandSide = false
var i = 0
while (i < tokens.size) {
val token = tokens[i]
when (token.type) {
Token.Type.INTEGER -> {
val integer = Integer(token.text.toInt())
if (hasLeftHandSide) result.right = integer
else {
result.left = integer
hasLeftHandSide = true
}
}
Token.Type.PLUS -> result.type = BinaryOperation.Type.ADDITION
Token.Type.MINUS -> result.type = BinaryOperation.Type.SUBTRACTION
Token.Type.LEFTPARENTHESIS -> {
var j = i // Location of right parenthesis (assumes no nesting of parentheses)
while (j < tokens.size) {
if (tokens[j].type == Token.Type.RIGHTPARENTHESIS) break
j++
}
val subExpression = tokens.stream()
.skip((i + 1).toLong())
.limit((j - i - 1).toLong())
.collect(Collectors.toList())
val element = parse(subExpression)
if (hasLeftHandSide) result.right = element
else {
result.left = element
hasLeftHandSide = true
}
i = j
}
Token.Type.RIGHTPARENTHESIS -> {
}
}
i++
}
return result
}
fun main() {
val input = "(13+4)-(12+1)"
val tokens: List<Token> = lex(input)
println(tokens.stream().map { it.toString() }.collect(Collectors.joining("_")))
val parsed = parse(tokens)
println("$input = ${parsed.eval()}")
}
| 0 | Kotlin | 0 | 0 | 9bdb5be77dcd527493b39ad562291a4023e36a98 | 3,530 | portfolio-design-patterns-udemy | MIT License |
kork-plugins/src/main/kotlin/com/netflix/spinnaker/kork/plugins/VersionRequirementsParser.kt | clareliguori | 196,099,646 | true | {"Java": 871051, "Kotlin": 337241, "Groovy": 121638, "Shell": 2440, "JavaScript": 595, "HTML": 394} | /*
* Copyright 2020 Netflix, Inc.
*
* 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.netflix.spinnaker.kork.plugins
import com.netflix.spinnaker.kork.exceptions.UserException
import java.util.regex.Pattern
/**
* Provides utility methods for parsing version requirements values from and to [VersionRequirements].
*
* Version requirements are in the format of "{service}{operator}{version}", where:
*
* - `service` is the service name that is supported by a plugin
* - `operator` is a version constraint operator (`>`, `<`, `>=`, `<=`)
* - `version` is the service version that is being constrained
*
* TODO(jonsie): Add range constraint support (>= 1.0.0 & < 2.0.0)
*/
object VersionRequirementsParser {
private val SUPPORTS_PATTERN = Pattern.compile(
"^(?<service>[\\w\\-]+)(?<operator>[><=]{1,2})(?<version>[0-9]+\\.[0-9]+\\.[0-9]+)$")
private const val SUPPORTS_PATTERN_SERVICE_GROUP = "service"
private const val SUPPORTS_PATTERN_OPERATOR_GROUP = "operator"
private const val SUPPORTS_PATTERN_VERSION_GROUP = "version"
/**
* Parse a single version.
*/
fun parse(version: String): VersionRequirements {
return SUPPORTS_PATTERN.matcher(version)
.also {
if (!it.matches()) {
throw InvalidPluginVersionRequirementException(version)
}
}
.let {
VersionRequirements(
service = it.group(SUPPORTS_PATTERN_SERVICE_GROUP),
operator = VersionRequirementOperator.from(it.group(SUPPORTS_PATTERN_OPERATOR_GROUP)),
version = it.group(SUPPORTS_PATTERN_VERSION_GROUP)
)
}
}
/**
* Parse a list of comma-delimited versions.
*/
fun parseAll(version: String): List<VersionRequirements> =
version.split(',').map { parse(it.trim()) }
/**
* Convert a list of [VersionRequirements] into a string.
*/
fun stringify(requirements: List<VersionRequirements>): String =
requirements.joinToString(",") { it.toString() }
enum class VersionRequirementOperator(val symbol: String) {
GT(">"),
LT("<"),
GT_EQ(">="),
LT_EQ("<=");
companion object {
fun from(symbol: String): VersionRequirementOperator =
values().find { it.symbol == symbol }
?: throw IllegalVersionRequirementsOperator(symbol, values().map { it.symbol }.joinToString { "'$it'" })
}
}
data class VersionRequirements(
val service: String,
val operator: VersionRequirementOperator,
val version: String
) {
override fun toString(): String = "$service${operator.symbol}$version"
}
class InvalidPluginVersionRequirementException(version: String) : UserException(
"The provided version requirement '$version' is not valid: It must conform to '$SUPPORTS_PATTERN'"
)
class IllegalVersionRequirementsOperator(symbol: String, availableOperators: String) : UserException(
"Illegal version requirement operator '$symbol': Must be one of $availableOperators"
)
}
| 0 | Java | 1 | 2 | a2d0804caa518f9a13f750f4a49eda8ea3d349cf | 3,467 | kork | Apache License 2.0 |
src/Java/LeetcodeSolutions/src/main/java/leetcode/solutions/concrete/kotlin/Solution_125_Valid_Palindrome.kt | v43d3rm4k4r | 515,553,024 | false | {"Kotlin": 40113, "Java": 25728} | package leetcode.solutions.concrete.kotlin
import leetcode.solutions.*
import leetcode.solutions.ProblemDifficulty.*
import leetcode.solutions.validation.SolutionValidator.*
import leetcode.solutions.annotations.ProblemInputData
import leetcode.solutions.annotations.ProblemSolution
/**
* __Problem:__ A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing
* all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and
* numbers. Given a string s, return true if it is a palindrome, or false otherwise.
*
* __Constraints:__
* - 1 <= s.length <= 2 * 10^5
* - s consists only of printable ASCII characters.
*
* __Solution 1:__ Mutate string checking weather current character is letter or digit. Then using two-sided comparison
* for each character.
*
* __Time:__ O(N)
*
* __Space:__ O(N)
*
* __Solution 2:__ This solution is more efficient in terms of speed and memory. An intermediate string is not created
* here, but the passage through the given string occurs immediately. At the same time, the counters i and j are
* synchronized - as long as one of them has an invalid symbol, the other counter does not move.
*
* __Time:__ O(N)
*
* __Space:__ O(1)
*
* @see Solution_9_Palindrome_Number
* @author <NAME>
*/
class Solution_125_Valid_Palindrome : LeetcodeSolution(EASY) {
@ProblemSolution(timeComplexity = "O(N)", spaceComplexity = "O(N)")
private fun isPalindrome1(s: String): Boolean {
val filteredStr = StringBuilder()
for (i in s.indices) {
if (Character.isLetterOrDigit(s[i])) {
filteredStr.append(Character.toLowerCase(s[i]))
}
}
var i = 0
var j = filteredStr.length - 1
while (i < filteredStr.length) {
if (filteredStr[i] != filteredStr[j]) {
return false
}
++i; --j
}
return true
}
@ProblemSolution(timeComplexity = "O(N)", spaceComplexity = "O(1)")
private fun isPalindrome2(s: String): Boolean {
var i = 0
var j = s.length - 1
while (i != j + 1 && i != j) {
if (Character.isLetterOrDigit(s[i]) && Character.isLetterOrDigit(s[j])) {
if (Character.toLowerCase(s[i]) != Character.toLowerCase(s[j])) {
return false
}
++i; --j
} else if (!Character.isLetterOrDigit(s[i])) ++i else --j
}
return true
}
@ProblemInputData
override fun run() {
ASSERT_TRUE(isPalindrome1("A man, a plan, a canal: Panama"))
ASSERT_FALSE(isPalindrome1("race a car"))
ASSERT_TRUE(isPalindrome1(" "))
ASSERT_FALSE(isPalindrome1(",,,,,,,,,,,,some"))
ASSERT_TRUE(isPalindrome2("A man, a plan, a canal: Panama"))
ASSERT_FALSE(isPalindrome2("race a car"))
ASSERT_TRUE(isPalindrome2(" "))
ASSERT_FALSE(isPalindrome2(",,,,,,,,,,,,some"))
}
} | 0 | Kotlin | 0 | 1 | c5a7e389c943c85a90594315ff99e4aef87bff65 | 3,059 | LeetcodeSolutions | Apache License 2.0 |
src/chapter2/section5/ex31_Distinct.kt | w1374720640 | 265,536,015 | false | {"Kotlin": 1373556} | package chapter2.section5
import extensions.formatDouble
import extensions.formatInt
import extensions.random
import kotlin.math.pow
/**
* 不重复元素
* 编写一段程序,接受命令行参数M、N和T,然后使用正文中的代码进行T遍实验:
* 生成N个0到M-1间的int值并计算不重复值的个数。
* 令T=10,N=10³、10⁴、10⁵和10⁶以及M=N/2、N和2N
* 根据概率论,不重复值的个数应该约为M*(1-e^(-a)),其中a=N/M
* 打印一张表格来确认你的实验验证了这个公式
*
* 解:我使用的中文版题目中有两处错误
* 书中要统计重复值的个数,实际上是统计不重复值的个数,否则和公式不符
* 原书中公式1-e^(-a)还需要再乘以M才是正确答案
*/
fun ex31_Distinct(M: Int, N: Int, T: Int): Pair<Int, Double> {
var count = 0
repeat(T) {
val array = Array(N) { random(M) }
array.sort()
var diffCount = 1
for (i in 1 until array.size) {
if (array[i] != array[i - 1]) {
diffCount++
}
}
count += diffCount
}
val expect = M * (1 - Math.E.pow(N.toDouble() / M * -1))
return count / T to expect
}
fun main() {
val T = 10
var N = 1000
repeat(4) {
var M = N / 2
repeat(3) {
val result = ex31_Distinct(M, N, T)
println("N:${formatInt(N, 7)} M:${formatInt(M, 7)} count:${formatInt(result.first, 7)} expect:${formatDouble(result.second, 2, 7)}")
M *= 2
}
N *= 10
}
} | 0 | Kotlin | 1 | 6 | 879885b82ef51d58efe578c9391f04bc54c2531d | 1,568 | Algorithms-4th-Edition-in-Kotlin | MIT License |
src/commonMain/kotlin/io/github/alexandrepiveteau/graphs/algorithms/RandomWalk.kt | alexandrepiveteau | 630,931,403 | false | {"Kotlin": 132267} | package io.github.alexandrepiveteau.graphs.algorithms
import io.github.alexandrepiveteau.graphs.Successors
import io.github.alexandrepiveteau.graphs.SuccessorsWeight
import io.github.alexandrepiveteau.graphs.Vertex
import io.github.alexandrepiveteau.graphs.internal.collections.IntVector
import kotlin.contracts.contract
import kotlin.random.Random
/**
* Performs a random walk on the graph, starting from the given [from] vertex, and performs the
* given [action] on each vertex. The walk may be infinite if the graph contains cycles, and the
* walk will stop if the vertex has no successors.
*
* This method is inline, so it can be used to traverse the graph with suspending functions.
*
* ## Asymptotic complexity
* - **Time complexity**: Depends on the graph.
* - **Space complexity**: O(1).
*/
public inline fun <G> G.randomWalk(
from: Vertex,
random: Random = Random,
action: (Vertex) -> Unit,
) where G : Successors {
contract { callsInPlace(action) }
var current = index(from)
while (true) {
action(vertex(current))
val size = successorsSize(current)
if (size == 0) return
current = index(successorVertex(current, random.nextInt(size)))
}
}
/**
* Performs a random walk on the graph, starting from the given [from] vertex, and performs the
* given [action] on each vertex. The walk may be infinite if the graph contains cycles, and the
* walk will stop if the vertex has no successors. The walk will be weighted, and the probability of
* choosing a successor is proportional to the weight of the link. Negative weights are not
* supported, and will be ignored and treated as if they were 0.
*
* This method is inline, so it can be used to traverse the graph with suspending functions.
*
* ## Asymptotic complexity
* - **Time complexity**: Depends on the graph.
* - **Space complexity**: O(|D|), where |D| is the number of distinct successors for any given
* vertex.
*/
public inline fun <G> G.randomWalkWeighted(
from: Vertex,
random: Random = Random,
action: (Vertex) -> Unit,
) where G : SuccessorsWeight {
contract { callsInPlace(action) }
var current = index(from)
val vertices = IntVector()
val weights = IntVector()
while (true) {
action(vertex(current))
val size = successorsSize(current)
if (size == 0) return
vertices.clear()
weights.clear()
for (i in 0 ..< size) {
val weight = successorWeight(current, i)
if (weight <= 0) continue
vertices += index(successorVertex(current, i))
weights += weight
}
val total = weights.sum()
if (total <= 0) return // No reachable successors.
val value = random.nextInt(total)
var sum = 0
for (i in 0 ..< weights.size) {
sum += weights[i]
if (sum > value) {
current = vertices[i]
break
}
}
}
}
| 9 | Kotlin | 0 | 6 | a4fd159f094aed5b6b8920d0ceaa6a9c5fc7679f | 2,851 | kotlin-graphs | MIT License |
archive/101/solve.kt | daniellionel01 | 435,306,139 | false | null | /*
=== #101 Optimum polynomial - Project Euler ===
If we are presented with the first k terms of a sequence it is impossible to say with certainty the value of the next term, as there are infinitely many polynomial functions that can model the sequence.
As an example, let us consider the sequence of cube numbers. This is defined by the generating function, un = n3: 1, 8, 27, 64, 125, 216, ...
Suppose we were only given the first two terms of this sequence. Working on the principle that "simple is best" we should assume a linear relationship and predict the next term to be 15 (common difference 7). Even if we were presented with the first three terms, by the same principle of simplicity, a quadratic relationship should be assumed.
We shall define OP(k, n) to be the nth term of the optimum polynomial generating function for the first k terms of a sequence. It should be clear that OP(k, n) will accurately generate the terms of the sequence for n ≤ k, and potentially the first incorrect term (FIT) will be OP(k, k+1); in which case we shall call it a bad OP (BOP).
As a basis, if we were only given the first term of sequence, it would be most sensible to assume constancy; that is, for n ≥ 2, OP(1, n) = u1.
Hence we obtain the following OPs for the cubic sequence:
OP(1, n) = 1
1, 1, 1, 1, ...
OP(2, n) = 7n−6
1, 8, 15, ...
OP(3, n) = 6n2−11n+6
1, 8, 27, 58, ...
OP(4, n) = n3
1, 8, 27, 64, 125, ...
Clearly no BOPs exist for k ≥ 4.
By considering the sum of FITs generated by the BOPs (indicated in red above), we obtain 1 + 15 + 58 = 74.
Consider the following tenth degree polynomial generating function:
un = 1 − n + n2 − n3 + n4 − n5 + n6 − n7 + n8 − n9 + n10
Find the sum of FITs for the BOPs.
Difficulty rating: 35%
*/
fun solve(x: Int): Int {
return x*2;
}
fun main() {
val a = solve(10);
println("solution: $a");
} | 0 | Kotlin | 0 | 1 | 1ad6a549a0a420ac04906cfa86d99d8c612056f6 | 1,878 | euler | MIT License |
src/main/kotlin/leetcode/Problem2266.kt | fredyw | 28,460,187 | false | {"Java": 1280840, "Rust": 363472, "Kotlin": 148898, "Shell": 604} | package leetcode
/**
* https://leetcode.com/problems/count-number-of-texts/
*/
class Problem2266 {
fun countTexts(pressedKeys: String): Int {
if (pressedKeys.length == 1) {
return 1
}
var answer = 1L
var i = 0
var length = 1
val memo3 = IntArray(pressedKeys.length + 1) { -1 }
val memo4 = IntArray(pressedKeys.length + 1) { -1 }
while (i < pressedKeys.length - 1) {
if (pressedKeys[i] != pressedKeys[i + 1]) {
val numDigits = numDigits(pressedKeys[i])
answer = (answer * countTexts(
numDigits,
length,
if (numDigits == 3) memo3 else memo4
)) % 1_000_000_007
length = 1
} else {
length++
}
i++
}
val numDigits = numDigits(pressedKeys[i])
answer = (answer * countTexts(
numDigits,
length,
if (numDigits == 3) memo3 else memo4
)) % 1_000_000_007
return answer.toInt()
}
private fun numDigits(key: Char): Int {
return if (key == '7' || key == '9') 4 else 3
}
private fun countTexts(numDigits: Int, length: Int, memo: IntArray): Int {
if (length < 0) {
return 0
}
if (length == 0) {
return 1
}
if (memo[length] != -1) {
return memo[length]
}
var count = 0
for (digit in 1..numDigits) {
count = (count + countTexts(numDigits, length - digit, memo)) % 1_000_000_007
}
memo[length] = count
return count
}
}
| 0 | Java | 1 | 4 | a59d77c4fd00674426a5f4f7b9b009d9b8321d6d | 1,712 | leetcode | MIT License |
src/main/kotlin/org/jetbrains/bio/span/semisupervised/Errors.kt | JetBrains-Research | 159,559,994 | false | {"Kotlin": 330801} | package org.jetbrains.bio.span.semisupervised
import java.util.*
/**
* Simple counter of correct out of all
*/
data class ErrorRate(var total: Int = 0, var correct: Int = 0) {
fun observe(outcome: Boolean) {
total++; if (outcome) correct++
}
fun combine(other: ErrorRate) {
total += other.total; correct += other.correct
}
fun rate(): Double = 1.0 * correct / total
}
/**
* Merging map based error [LocationLabel] -> [ErrorRate]
*/
class LabelErrors(val map: MutableMap<LocationLabel, ErrorRate> = TreeMap()) :
MutableMap<LocationLabel, ErrorRate> by map {
fun error(type: Label? = null) = 1.0 - correct(type) * 1.0 / total(type)
fun correct(type: Label?) = filter(type).sumOf { (_, errRate) -> errRate.correct }
fun total(type: Label?) = filter(type).sumOf { (_, errRate) -> errRate.total }
private fun filter(type: Label?) = when (type) {
null -> map.entries
else -> map.entries.filter { (ann, _) -> ann.type == type }
}
fun combine(other: LabelErrors) {
other.map.entries.forEach {
if (it.key !in map) {
map[it.key] = ErrorRate()
}
map[it.key]?.combine(it.value)
}
}
fun observe(label: LocationLabel, outcome: Boolean) {
var ler = map[label]
if (ler == null) {
ler = ErrorRate()
map[label] = ler
}
ler.observe(outcome)
}
}
| 2 | Kotlin | 1 | 7 | fe581a3821d7bd28bafa5b8240f7a961a4c1f291 | 1,463 | span | MIT License |
src/main/kotlin/ch/heigvd/stats/ranking/KendallTau.kt | rbarazzutti | 132,765,154 | false | null | package ch.heigvd.stats.ranking
import kotlin.coroutines.experimental.buildSequence
import kotlin.math.sqrt
/**
* Rough implementation of Kendall-Tau correlation coefficient computation.
*
* This implementation:
*
* - is slow (O(n²)), thanks to efficient sorts a smarter implementation should be O(n·log(n))
* - doesn't handle cases based on non-square contingency tables (Tau-c)
* - simple and easy to understand
*
*/
interface KendallTau {
/**
* Kendall-Tau-a
*
* This variant ignores ties
*
* More details on Wikipedia (https://en.wikipedia.org/wiki/Kendall_rank_correlation_coefficient#Tau-a)
*
* @return the Tau-a value
*/
fun tauA(): Double
/**
* Kendall-Tau-b
*
* This variant supports ties
*
* More details on Wikipedia (https://en.wikipedia.org/wiki/Kendall_rank_correlation_coefficient#Tau-b)
*
* @return the Tau-b value
*/
fun tauB(): Double
companion object {
/**
* build a [KendallTau] instance with two rankings
*
* @return a new instance
*/
fun <T, U> build(a: Array<T>, b: Array<U>): KendallTau where T : Comparable<T>, U : Comparable<U> {
(a.size == b.size) || throw Exception("Arrays need to have equals sizes")
return object : KendallTau {
/**
* returns a list of available indices pairs
*
* Only pairs, st that P=(a,b) with a>b are returned in the list
*/
private fun indices() = buildSequence {
for (i in a.indices)
for (j in 0 until i)
yield(Pair(i, j))
}
/**
* pairs comparison values
*/
private val pairs: Sequence<Int> by lazy {
indices().map { a[it.first].compareTo(a[it.second]) * b[it.first].compareTo(b[it.second]) }
}
/**
* list of numbers of tied values in the i-th group of ties for the first quantity
*/
private val t by lazy {
a.indices.map { Pair(a[it], it) }.groupBy { it.first }.map { it.value.size }
}
/**
* list of numbers of tied values in the i-th group of ties for the second quantity
*/
private val u by lazy {
b.indices.map { Pair(b[it], it) }.groupBy { it.first }.map { it.value.size }
}
/**
* number of concordant pairs
*/
private val nc by lazy {
pairs.filter { it > 0 }.count()
}
/**
* number of discordant pairs
*/
private val nd by lazy {
pairs.filter { it < 0 }.count()
}
private val n0 by lazy {
a.size * (a.size - 1) / 2
}
private val n1 by lazy {
t.map { it * (it - 1) }.sum() / 2
}
private val n2 by lazy {
u.map { it * (it - 1) }.sum() / 2
}
override fun tauA() = 1.0 * (nc - nd) / n0
override fun tauB() = (nc - nd) / sqrt(1.0 * (n0 - n1) * (n0 - n2))
}
}
}
}
| 0 | Kotlin | 0 | 0 | e1945b7eb928fd204d37ae0e20926855d0197ff5 | 3,533 | kotlin-tau | MIT License |
aoc-2020/src/commonMain/kotlin/fr/outadoc/aoc/twentytwenty/Day02.kt | outadoc | 317,517,472 | false | {"Kotlin": 183714} | package fr.outadoc.aoc.twentytwenty
import fr.outadoc.aoc.scaffold.Day
import fr.outadoc.aoc.scaffold.readDayInput
class Day02 : Day<Int> {
private val input: Sequence<PasswordEntry> =
readDayInput()
.lineSequence()
.parse()
data class Policy(val first: Int, val second: Int, val letter: Char)
data class PasswordEntry(val policy: Policy, val password: String)
private fun Sequence<String>.parse(): Sequence<PasswordEntry> {
val regex = Regex("^([0-9]+)-([0-9]+) ([a-z]): ([a-z0-9]+)$")
return map { entry ->
val parsed = regex.find(entry)!!
PasswordEntry(
policy = Policy(
first = parsed.groupValues[1].toInt(),
second = parsed.groupValues[2].toInt(),
letter = parsed.groupValues[3].first()
),
password = parsed.groupValues[4]
)
}
}
override fun step1(): Int {
fun isValid(entry: PasswordEntry): Boolean {
val letterCount = entry.password.count { c -> c == entry.policy.letter }
return letterCount in entry.policy.first..entry.policy.second
}
return input.count { entry -> isValid(entry) }
}
override fun step2(): Int {
fun isValid(entry: PasswordEntry): Boolean {
val isFirstLetterOk = entry.password[entry.policy.first - 1] == entry.policy.letter
val isSecondLetterOk = entry.password[entry.policy.second - 1] == entry.policy.letter
return isFirstLetterOk xor isSecondLetterOk
}
return input.count { entry -> isValid(entry) }
}
override val expectedStep1: Int = 591
override val expectedStep2: Int = 335
}
| 0 | Kotlin | 0 | 0 | 54410a19b36056a976d48dc3392a4f099def5544 | 1,771 | adventofcode | Apache License 2.0 |
BellmanFord/bellmanford.kt | ReciHub | 150,083,876 | false | {"C++": 2125921, "Java": 329701, "Python": 261837, "C#": 119510, "C": 86966, "JavaScript": 69795, "Jupyter Notebook": 48962, "HTML": 35203, "Kotlin": 20787, "Go": 15812, "CSS": 12510, "TeX": 12253, "TypeScript": 10773, "PHP": 8809, "Swift": 7787, "Scala": 6724, "Rust": 6297, "Shell": 5562, "Ruby": 5488, "Haskell": 4927, "SCSS": 4721, "Brainfuck": 1919, "Dart": 1879, "Elixir": 1592, "MATLAB": 734, "Visual Basic .NET": 679, "R": 617, "Assembly": 616, "LOLCODE": 243, "PowerShell": 15, "Batchfile": 5} | class Edge(val source: Int, val destination: Int, val weight: Int)
class Graph(val vertices: Int, val edges: List<Edge>) {
fun bellmanFord(startVertex: Int) {
val distance = IntArray(vertices) { Int.MAX_VALUE }
distance[startVertex] = 0
for (i in 1 until vertices) {
for (edge in edges) {
if (distance[edge.source] != Int.MAX_VALUE && distance[edge.source] + edge.weight < distance[edge.destination]) {
distance[edge.destination] = distance[edge.source] + edge.weight
}
}
}
for (edge in edges) {
if (distance[edge.source] != Int.MAX_VALUE && distance[edge.source] + edge.weight < distance[edge.destination]) {
println("Graph contains a negative-weight cycle.")
return
}
}
for (i in 0 until vertices) {
println("Shortest distance from vertex $startVertex to vertex $i is ${distance[i]}")
}
}
}
fun main() {
val vertices = 5
val edges = listOf(
Edge(0, 1, -1),
Edge(0, 2, 4),
Edge(1, 2, 3),
Edge(1, 3, 2),
Edge(1, 4, 2),
Edge(3, 2, 5),
Edge(3, 1, 1),
Edge(4, 3, -3)
)
val graph = Graph(vertices, edges)
val startVertex = 0
graph.bellmanFord(startVertex)
}
| 121 | C++ | 750 | 361 | 24518dd47bd998548e3e840c27968598396d30ee | 1,365 | FunnyAlgorithms | Creative Commons Zero v1.0 Universal |
src/main/kotlin/nl/kelpin/fleur/advent2018/Day24.kt | fdlk | 159,925,533 | false | null | package nl.kelpin.fleur.advent2018
class Day24(immune: List<String>, infection: List<String>) {
companion object {
const val INFECTION = "infection"
const val IMMUNE = "immune"
const val WEAK = "weak"
val highestInitiative = compareByDescending(Group::initiative)
val mostEffectivePowerThenHighestInitiative = compareByDescending(Group::effectivePower)
.then(highestInitiative)
}
data class Susceptibility(val weakOrImmune: String, val types: List<String>) {
companion object {
fun parse(string: String): List<Susceptibility> {
return string.split("; ").filterNot(String::isBlank)
.map { it ->
val (weakOrImmune, typesString) = it
.split("to")
.map(String::trim)
val types = typesString.split(", ")
Susceptibility(weakOrImmune, types.map(String::trim))
}
}
}
}
data class Group(val side: String,
val index: Int,
val count: Int,
val hpEach: Int,
val susceptibilities: List<Susceptibility>,
val damage: Int,
val damageType: String,
val initiative: Int) {
companion object {
private val groupRE = Regex("""(\d+) units each with (\d+) hit points (?>\((.+)\))? ?with an attack that does (\d+) (\w+) damage at initiative (\d+)""")
fun parse(side: String, line: String, index: Int): Group {
val match = groupRE.matchEntire(line)
val (count, hpEach, susceptibilitiesString, damage, damageType, initiative) = match!!.destructured
val susceptibilities = Susceptibility.parse(susceptibilitiesString)
return Group(side, index, count.toInt(), hpEach.toInt(), susceptibilities, damage.toInt(), damageType, initiative.toInt())
}
}
fun getId(): String = "$side #$index"
override fun toString(): String = "${getId()} ($count left)"
fun effectivePower(): Int = count * damage
private fun isWeakTo(damageType: String): Boolean = susceptibilities.any { susceptibility ->
susceptibility.weakOrImmune == WEAK && susceptibility.types.contains(damageType)
}
private fun isImmuneTo(damageType: String): Boolean = susceptibilities.any { susceptibility ->
susceptibility.weakOrImmune == IMMUNE && susceptibility.types.contains(damageType)
}
fun attackedBy(other: Group): Group? {
val factor = when {
isImmuneTo(other.damageType) -> 0
isWeakTo(other.damageType) -> 2
else -> 1
}
val unitsLeft = count - (other.effectivePower() * factor) / hpEach
return when {
unitsLeft > 0 -> copy(count = unitsLeft)
else -> null
}
}
fun boosted(boost: Int) = copy(damage = damage + boost)
fun findTarget(targets: List<Group>): Group? =
targets.find { target -> target.isWeakTo(damageType) }
?: targets.find { target -> !target.isImmuneTo(damageType) }
}
val groups = immune.map { Group.parse(IMMUNE, it, immune.indexOf(it) + 1) } +
infection.map { Group.parse(INFECTION, it, infection.indexOf(it) + 1) }
data class State(val groups: List<Group>) {
fun targetSelection(): Map<String, Group?> {
val attackers = groups.sortedWith(mostEffectivePowerThenHighestInitiative).toMutableList()
val targets = attackers.toMutableList()
return attackers.associateBy(Group::getId) { attacker ->
val target = attacker.findTarget(targets.filter { it.side != attacker.side })
if (target != null) {
targets.remove(target)
}
target
}
}
fun done(): Boolean = groups.map { it.side }.distinct().size == 1
fun next(): State {
val selectedTargets = targetSelection()
val attackers = groups.sortedWith(highestInitiative).toMutableList()
val result = groups.toMutableList()
while (!attackers.isEmpty()) {
val attacker = attackers.removeAt(0)
val target = selectedTargets[attacker.getId()] ?: continue
val attackedTarget = target.attackedBy(attacker)
result.update(target, attackedTarget)
attackers.update(target, attackedTarget)
}
return State(result)
}
fun withImmuneBoost(boost: Int): State =
copy(groups = groups.map { if (it.side == IMMUNE) it.boosted(boost) else it })
fun count(): Int = groups.sumBy { it.count }
}
private tailrec fun battle(state: State): State =
if (state.done()) state
else {
val next = state.next()
if (next == state) next // standoff!
else battle(next)
}
fun part1(state: State = State(groups)): Int = battle(state).count()
tailrec fun part2(boost: Int): Int {
println("boost = $boost")
val result = battle(State(groups).withImmuneBoost(boost))
return if (result.groups.none { it.side == INFECTION }) result.count()
else part2(boost + 1)
}
} | 0 | Kotlin | 0 | 3 | a089dbae93ee520bf7a8861c9f90731eabd6eba3 | 5,629 | advent-2018 | MIT License |
src/commonMain/kotlin/org/jetbrains/packagesearch/packageversionutils/normalization/VersionComparatorUtil.kt | JetBrains | 498,634,573 | false | {"Kotlin": 44145} | package org.jetbrains.packagesearch.packageversionutils.normalization
import kotlin.math.sign
object VersionComparatorUtil {
private val WORDS_SPLITTER = Regex("\\d+|\\D+")
private val ZERO_PATTERN = Regex("0+")
private val DIGITS_PATTERN = Regex("\\d+")
private val DEFAULT_TOKEN_PRIORITY_PROVIDER: (String) -> Int =
{ param -> VersionTokenType.lookup(param).priority }
fun max(v1: String, v2: String) = if (compare(v1, v2) > 0) v1 else v2
fun min(v1: String, v2: String) = if (compare(v1, v2) < 0) v1 else v2
private fun String.splitVersionString(): Sequence<String> =
trim { it <= ' ' }
.splitToSequence(*"()._-;:/, +~".toCharArray(), ignoreCase = true)
.flatMap { WORDS_SPLITTER.find(it)?.groups?.mapNotNull { it?.value } ?: emptyList() }
fun compare(
v1: String,
v2: String,
tokenPriorityProvider: (String) -> Int = DEFAULT_TOKEN_PRIORITY_PROVIDER,
): Int = v1.splitVersionString()
.zip(v2.splitVersionString())
.map { (e1, e2) ->
val t1 = VersionTokenType.lookup(e1)
val res = tokenPriorityProvider(e1) - tokenPriorityProvider(e2)
when {
res.sign != 0 -> res
t1 == VersionTokenType._WORD -> e1.compareTo(e2)
t1 == VersionTokenType._DIGITS -> compareNumbers(e1, e2)
else -> 0
}
}
.firstOrNull { it != 0 }
?: 0
private fun compareNumbers(n1: String, n2: String): Int {
val (num1, num2) = Pair(n1.trimStart('0'), n2.trimStart('0'))
if (num1.isEmpty()) return if (num2.isEmpty()) 0 else -1
if (num2.isEmpty()) return 1
return compareBy<String> { it.length }.thenBy { it }.compare(num1, num2)
}
enum class VersionTokenType(val priority: Int) {
SNAP(10),
SNAPSHOT(10),
S(10),
DEV(10),
DEVELOP(10),
M(20),
BUILD(20),
MILESTONE(20),
EAP(25),
PRE(25),
PREVIEW(25),
ALPHA(30),
A(30),
BETA(40),
BETTA(40),
B(40),
RC(50),
_WS(60),
SP(70),
REL(80),
RELEASE(80),
R(80),
FINAL(80),
CANDIDATE(80),
STABLE(80),
_WORD(90),
_DIGITS(100),
BUNDLED(666),
SNAPSHOTS(10);
companion object {
fun lookup(str: String): VersionTokenType {
val trimmedStr = str.trim()
if (trimmedStr.isEmpty()) return _WS
for (token in values()) {
if (token.name[0] != '_' && token.name.equals(trimmedStr, ignoreCase = true)) {
return token
}
}
return when {
ZERO_PATTERN.matches(trimmedStr) -> _WS
DIGITS_PATTERN.matches(trimmedStr) -> _DIGITS
else -> _WORD
}
}
}
}
}
| 0 | Kotlin | 2 | 4 | 4a9cf732526a0cd177dbaadb786bd2e41903a33e | 3,032 | package-search-version-utils | Apache License 2.0 |
src/test/kotlin/year2015/Day14.kt | abelkov | 47,995,527 | false | {"Kotlin": 48425} | package year2015
import kotlin.math.max
import kotlin.test.*
class Day14 {
@Test
fun part1() {
// Vixen can fly 19 km/s for 7 seconds, but then must rest for 124 seconds.
val regex = """(\w+) can fly (\d+) km/s for (\d+) seconds, but then must rest for (\d+) seconds.""".toRegex()
var maxDistance = 0
for (line in readInput("year2015/Day14.txt").lines()) {
val matchResult = regex.matchEntire(line)
val (_, speedString, maxMoveTimeString, maxRestTimeString) = matchResult!!.groupValues.drop(1)
val speed = speedString.toInt()
val maxMoveTime = maxMoveTimeString.toInt()
val maxRestTime = maxRestTimeString.toInt()
var distance = 0
var time = 0
var moveTime = maxMoveTime
var restTime = maxRestTime
val raceTime = 2503
while (time < raceTime) {
time++
if (moveTime > 0) {
distance += speed
moveTime--
} else {
restTime--
if (restTime == 0) {
moveTime = maxMoveTime
restTime = maxRestTime
}
}
}
maxDistance = max(maxDistance, distance)
}
assertEquals(2660, maxDistance)
}
@Test
fun part2() {
data class Reindeer(
val speed: Int,
val maxMoveTime: Int,
val maxRestTime: Int,
var distance: Int = 0,
var score: Int = 0,
var moveTime: Int = maxMoveTime,
var restTime: Int = maxRestTime
) {
fun update() {
if (moveTime > 0) {
distance += speed
moveTime--
} else {
restTime--
if (restTime == 0) {
moveTime = maxMoveTime
restTime = maxRestTime
}
}
}
}
val reindeers = mutableSetOf<Reindeer>()
// Vixen can fly 19 km/s for 7 seconds, but then must rest for 124 seconds.
val regex = """(\w+) can fly (\d+) km/s for (\d+) seconds, but then must rest for (\d+) seconds.""".toRegex()
for (line in readInput("year2015/Day14.txt").lines()) {
val matchResult = regex.matchEntire(line)
val (_, speedString, maxMoveTimeString, maxRestTimeString) = matchResult!!.groupValues.drop(1)
val speed = speedString.toInt()
val maxMoveTime = maxMoveTimeString.toInt()
val maxRestTime = maxRestTimeString.toInt()
reindeers += Reindeer(speed, maxMoveTime, maxRestTime)
}
var time = 0
val raceTime = 2503
while (time < raceTime) {
time++
reindeers.forEach { it.update() }
val bestDistance = reindeers.maxOf { it.distance }
for (reindeer in reindeers) {
if (reindeer.distance == bestDistance) {
reindeer.score++
}
}
}
val bestScore = reindeers.maxOf { it.score }
assertEquals(1256, bestScore)
}
} | 0 | Kotlin | 0 | 0 | 0e4b827a742322f42c2015ae49ebc976e2ef0aa8 | 3,311 | advent-of-code | MIT License |
year2021/src/main/kotlin/net/olegg/aoc/year2021/day25/Day25.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2021.day25
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.utils.Vector2D
import net.olegg.aoc.year2021.DayOf2021
/**
* See [Year 2021, Day 25](https://adventofcode.com/2021/day/25)
*/
object Day25 : DayOf2021(25) {
override fun first(): Any? {
val map = matrix
val height = map.size
val width = map.first().size
val startEast = map.flatMapIndexed { y, row ->
row.mapIndexedNotNull { x, char ->
Vector2D(x, y).takeIf { char == '>' }
}
}.toSet()
val startSouth = map.flatMapIndexed { y, row ->
row.mapIndexedNotNull { x, char ->
Vector2D(x, y).takeIf { char == 'v' }
}
}.toSet()
return generateSequence(1) { it + 1 }
.scan(Triple(0, startEast, startSouth)) { (_, east, south), step ->
val newEast = east.map { curr ->
val new = Vector2D((curr.x + 1) % width, curr.y)
if (new !in east && new !in south) new else curr
}.toSet()
val newSouth = south.map { curr ->
val new = Vector2D(curr.x, (curr.y + 1) % height)
if (new !in newEast && new !in south) new else curr
}.toSet()
Triple(step, newEast, newSouth)
}
.zipWithNext()
.first { it.first.second == it.second.second && it.first.third == it.second.third }
.second
.first
}
}
fun main() = SomeDay.mainify(Day25)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 1,399 | adventofcode | MIT License |
src/main/kotlin/g1001_1100/s1022_sum_of_root_to_leaf_binary_numbers/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1001_1100.s1022_sum_of_root_to_leaf_binary_numbers
// #Easy #Depth_First_Search #Tree #Binary_Tree
// #2023_05_22_Time_158_ms_(88.89%)_Space_36.3_MB_(11.11%)
import com_github_leetcode.TreeNode
/*
* Example:
* var ti = TreeNode(5)
* var v = ti.`val`
* Definition for a binary tree node.
* class TreeNode(var `val`: Int) {
* var left: TreeNode? = null
* var right: TreeNode? = null
* }
*/
class Solution {
fun sumRootToLeaf(root: TreeNode?): Int {
val paths: MutableList<List<Int>> = ArrayList()
dfs(root, paths, ArrayList())
var sum = 0
for (list in paths) {
var num = 0
for (i in list) {
num = (num shl 1) + i
}
sum += num
}
return sum
}
private fun dfs(root: TreeNode?, paths: MutableList<List<Int>>, path: MutableList<Int>) {
path.add(root!!.`val`)
if (root.left != null) {
dfs(root.left!!, paths, path)
path.removeAt(path.size - 1)
}
if (root.right != null) {
dfs(root.right!!, paths, path)
path.removeAt(path.size - 1)
}
if (root.left == null && root.right == null) {
paths.add(ArrayList(path))
}
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,280 | LeetCode-in-Kotlin | MIT License |
chapter_1_arrays_and_strings/1_is_unique/solution.kt | codermrhasan | 230,264,289 | false | {"Kotlin": 6182, "Python": 6043} | /* PROBLEM
Implement an algorithm to determine if a string has all unique characters.
What if you can not use additional data structures? */
/* ALGORITHM 1 - areCharsUnique
Keep and array of 256 elements, corresponding to each ASCII character, initially set to
false. For each letter in the original string I set the corresponding element of the
array to true. If the string contains only unique characters, I must never find an element
in the control array already set tu true (this would mean that the letter has already been
found before).
Performance: O(n)
ALGORITHM 2 - areCharsUniqueSort
Not optimal.
First I sort the characters of the string in ascending order, then I scan the
sorted string and check that there must not be 2 equal consecutive characters.
Performance: O(n*logn)
ALGORITHM 3 - areCharsUniqueDoubleLoop
Not optimal.
Compare each character of the string with all subsequent characters.
Performance: O(n^2) */
val letters = Array(256) {false}
fun main() {
val myString = "claudiosn"
println("Characters are unique? -> ${areCharsUnique(myString)}")
println("Characters are unique? -> ${areCharsUniqueSort(myString)}")
println("Characters are unique? -> ${areCharsUniqueDoubleLoop(myString)}")
}
fun areCharsUnique(myString: String): Boolean {
for(character in myString) {
if(!letters[character.toInt()]) {
letters[character.toInt()] = true
} else {
return false
}
}
return true
}
fun areCharsUniqueSort(myString: String): Boolean {
if(myString.length < 2) return true
val arr = myString.toCharArray()
val myStringSorted = arr.sorted().joinToString("")
for(i in 0..myStringSorted.length - 2) {
if(myStringSorted[i] == myStringSorted[i+1]) return false
}
return true
}
fun areCharsUniqueDoubleLoop(myString: String): Boolean {
if(myString.length < 2) return true
for(i in 0..myString.length-2) {
for(j in i+1..myString.length-1) {
if(myString[i] == myString[j]) return false
}
}
return true
} | 0 | Kotlin | 0 | 0 | 3f40e94f388fc817ffe092772c8a541c3d356c46 | 2,128 | ctci-problems-and-solutions | MIT License |
lib_algorithms_sort_kotlin/src/main/java/net/chris/lib/algorithms/sort/kotlin/KTCountingSorter.kt | chrisfang6 | 105,401,243 | false | {"Java": 68669, "Kotlin": 26275, "C++": 12503, "CMake": 2182, "C": 1403} | package net.chris.lib.algorithms.sort.kotlin
/**
* Counting sort.
*
*/
abstract class KTCountingSorter : KTSorter() {
/*override fun sort(list: List<Int>?): List<Int>? {
return if (list == null) {
list
} else toList(sort(toArray(list), false))
}*/
override fun subSort(A: IntArray) {
if (A == null) {
return
}
val B = IntArray(A.size) //to store result after sorting
val k = max(A)
val C = IntArray(k + 1) // to store temp
for (i in A.indices) {
C[A[i]] = C[A[i]] + 1
}
// store the count of the item whose value less than A[i]
for (i in 1..C.size - 1) {
C[i] = C[i] + C[i - 1]
}
for (i in A.indices.reversed()) {
B[C[A[i]] - 1] = A[i]
C[A[i]] = C[A[i]] - 1
}
for (i in A.indices) {
A[i] = B[i]
}
}
private fun max(a: IntArray): Int {
var max = 0
for (i in a.indices) {
max = Math.max(max, a[i])
}
return max
}
}
| 0 | Java | 0 | 0 | 1f1c2206d5d9f0a3d6c070a7f6112f60c2714ec0 | 1,101 | sort | Apache License 2.0 |
src/main/kotlin/g0001_0100/s0010_regular_expression_matching/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g0001_0100.s0010_regular_expression_matching
// #Hard #Top_100_Liked_Questions #Top_Interview_Questions #String #Dynamic_Programming #Recursion
// #Udemy_Dynamic_Programming #Big_O_Time_O(m*n)_Space_O(m*n)
// #2023_07_03_Time_171_ms_(85.26%)_Space_34.6_MB_(94.74%)
class Solution {
fun isMatch(s: String, p: String): Boolean {
val n = s.length
val m = p.length
return solve(n - 1, m - 1, s, p)
}
private fun solve(i: Int, j: Int, s: String, p: String): Boolean {
if (j < 0) {
return i < 0
}
if (i < 0) {
return p[j] == '*' && solve(i, j - 2, s, p)
}
// simple char matching
// if s char matchs with p char or it can be '.'
if (s[i] == p[j] || p[j] == '.') {
return solve(i - 1, j - 1, s, p)
}
return if (p[j] == '*') {
// if s char matches with p char or it can be '.'
if (s[i] == p[j - 1] || p[j - 1] == '.') {
solve(i - 1, j, s, p) || solve(i, j - 2, s, p)
} else {
solve(
i,
j - 2,
s,
p
)
}
} else {
false
}
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,278 | LeetCode-in-Kotlin | MIT License |
src/chapter4/section4/CPM.kt | w1374720640 | 265,536,015 | false | {"Kotlin": 1373556} | package chapter4.section4
import edu.princeton.cs.algs4.In
import edu.princeton.cs.algs4.Queue
import extensions.formatDouble
import extensions.formatInt
/**
* 优先级限制下的并行任务调度问题的关键路径方法
*/
class CPM(private val N: Int) {
private val V = N * 2 + 2
private val s = 2 * N // 起点
private val t = 2 * N + 1 // 终点
private val digraph = EdgeWeightedDigraph(V)
private var lp: AcyclicLP? = null
constructor(input: In) : this(input.readInt()) {
input.readLine()
repeat(N) { v ->
// 使用一个或一个以上的空格做分隔符(正则匹配)
val list = input.readLine().split(Regex(" +"))
val weight = list[0].toDouble()
// 测试数据jobsPC.txt在权重和后继任务中间还有一个整数,和书中不同,忽略
val successor = ArrayList<Int>()
for (i in 2 until list.size) {
successor.add(list[i].toInt())
}
addTask(weight, v, *successor.toIntArray())
}
sort()
}
fun addTask(weight: Double, v: Int, vararg successor: Int) {
digraph.addEdge(DirectedEdge(v, v + N, weight))
digraph.addEdge(DirectedEdge(s, v, 0.0))
digraph.addEdge(DirectedEdge(v + N, t, 0.0))
successor.forEach {
digraph.addEdge(DirectedEdge(v + N, it, 0.0))
}
}
fun sort() {
lp = AcyclicLP(digraph, s)
}
/**
* 最短运行时间
*/
fun total(): Double {
return lp?.distTo(t) ?: Double.NEGATIVE_INFINITY
}
/**
* 关键路径
*/
fun criticalPath(): Iterable<Int>? {
if (total() == Double.NEGATIVE_INFINITY) return null
val queue = Queue<Int>()
lp!!.pathTo(t)!!.forEach { edge ->
if (edge.from() in 0 until N) {
queue.enqueue(edge.from())
}
}
return queue
}
override fun toString(): String {
val total = total()
if (total == Double.NEGATIVE_INFINITY) return "Error!"
val stringBuilder = StringBuilder("Start times:\n")
for (i in 0 until N) {
stringBuilder.append(formatInt(i, 4))
.append(": ")
.append(if (lp!!.distTo(i) == Double.NEGATIVE_INFINITY) "Unreachable" else formatDouble(lp!!.distTo(i), 2, 6))
.append("\n")
}
stringBuilder.append("Finish time:\n")
.append(formatDouble(total, 2))
.append("\n")
.append("criticalPath: ")
.append(criticalPath()!!.joinToString())
return stringBuilder.toString()
}
}
fun getJobsPC() = CPM(In("./data/jobsPC.txt"))
fun main() {
println(getJobsPC())
} | 0 | Kotlin | 1 | 6 | 879885b82ef51d58efe578c9391f04bc54c2531d | 2,807 | Algorithms-4th-Edition-in-Kotlin | MIT License |
src/main/kotlin/dev/claudio/adventofcode2021/Day4.kt | ClaudioConsolmagno | 434,559,159 | false | {"Kotlin": 78336} | package dev.claudio.adventofcode2021
fun main() {
Day4().main()
}
private class Day4 {
fun main() {
val inputList: List<String> = Support.readFileAsListString("day4-input.txt").filter { it != "" }
val marks: List<Int> = inputList[0].split(",").map { Integer.valueOf(it) }
var start = 1
val boards = mutableListOf<Board>()
while(start < inputList.size) {
val boardList = (0 until 5).map {
inputList[start + it].split(" ").filter { it2 -> it2 != "" }.map { it2 -> Integer.valueOf(it2) }
}
boards.add(Board(boardList))
start += 5
}
marks.forEach{ mark ->
boards.forEach{ board -> board.hit(mark) }
val winner: Board? = boards.firstOrNull { it.isWin() }
if (winner != null) {
println(winner.winLossNumbers().second.sum() * mark)
return
}
}
}
data class Board(
val board: List<List<Int>>,
private var marks: MutableList<Int> = mutableListOf(),
) {
fun hit(number: Int) {
marks.add(number)
}
fun isWin(): Boolean {
(board.indices).forEach { index ->
val horiz = board[index].all { marks.contains(it) }
val vert = board[index].indices.map { index2 ->
board[index2][index]
}.all { marks.contains(it) }
if (horiz || vert) return true
}
return false
}
fun winLossNumbers(): Pair<List<Int>, List<Int>> {
val allNumbers: List<Int> = board.flatten()
return Pair(allNumbers.filter { marks.contains(it) },
allNumbers.filterNot { marks.contains(it) })
}
}
} | 0 | Kotlin | 0 | 0 | 5f1aff1887ad0a7e5a3af9aca7793f1c719e7f1c | 1,815 | adventofcode-2021 | Apache License 2.0 |
src/main/kotlin/io/github/kmakma/adventofcode/y2020/Y2020Day20.kt | kmakma | 225,714,388 | false | null | package io.github.kmakma.adventofcode.y2020
import io.github.kmakma.adventofcode.utils.Day
import io.github.kmakma.adventofcode.utils.product
fun main() {
Y2020Day20().solveAndPrint()
}
class Y2020Day20 : Day(2020, 20, "Jurassic Jigsaw") {
private val monster = listOf(
" # ".toCharArray(),
"# ## ## ###".toCharArray(),
" # # # # # # ".toCharArray()
)
// number of lines a puzzle piece occupies in the input (1. line: id, 2-11.: 10x10 puzzle piece)
private val pieceInputSize = 11
private val nonDigit = "\\D".toRegex()
private lateinit var inputList: List<String>
override fun initializeDay() {
inputList = inputInStringLines()
}
private fun pieceBorderWithReversed(input: List<String>): Pair<Int, List<String>> {
val id = input.first().replace(nonDigit, "").toInt()
val borders = mutableListOf<String>()
val leftSb = StringBuilder()
val rightSb = StringBuilder()
for (i in 1..input.lastIndex) {
leftSb.append(input[i].first())
rightSb.append(input[i].last())
}
borders.apply {
add(input[1])
add(input[1].reversed())
add(rightSb.toString())
add(rightSb.reverse().toString())
add(input.last().reversed())
add(input.last().reversed())
add(leftSb.toString())
add(leftSb.reverse().toString())
}
return (id to borders.toList())
}
override suspend fun solveTask1(): Any? {
val puzzle = inputList
.filter { it.isNotBlank() }
.chunked(pieceInputSize)
.map { pieceBorderWithReversed(it) }
.toMap()
val corners = mutableListOf<Int>()
val matchmap = mutableMapOf<Int, Int>()
for ((id, borders) in puzzle) {
var matches = 0
for ((id2, borders2) in puzzle) {
if (id != id2 && doesMatch(borders, borders2))
matches++
}
matchmap[id] = matches
if (matches == 2) corners.add(id)
}
return corners.product()
}
private fun doesMatch(borders: List<String>, borders2: List<String>): Boolean {
borders.forEach { b1 -> if (borders2.contains(b1)) return true }
return false
}
override suspend fun solveTask2(): Any? {
val puzzle = inputList
.filter { it.isNotBlank() }
.chunked(pieceInputSize)
.map { PuzzlePiece.create(it) }
.toMutableList()
val setPuzzle = mutableListOf(puzzle.removeFirst())
setPuzzle.first().fixOrientation()
while (puzzle.size > 0) {
val matchedIndex = matchPuzzlePiece(puzzle, setPuzzle)
if (matchedIndex >= 0) {
setPuzzle.add(puzzle.removeAt(matchedIndex))
}
}
// puzzle "solved", now: find monsters
val image = setPuzzle.first().getTotalImage()
val waterPounds = image.map { line -> line.count { c -> c == '#' } }.sum()
val monsters = countMonsters(image)
return waterPounds - monsters * 15 // one monster = 15*#
}
private fun countMonsters(originalImage: List<String>): Int {
var image = originalImage
for (i in 0..3) {
findMonsters(image).let { if (it > 0) return it }
image = rotate(image)
}
image = image.reversed()
for (i in 0..3) {
findMonsters(image).let { if (it > 0) return it }
image = rotate(image)
}
return 0
}
private fun findMonsters(image: List<String>): Int {
var monsters = 0
val lastCol = image.first().length - monster.first().size
for (line in 0..(image.lastIndex - 2)) {
for (i in 0..lastCol) {
if (isMonster(image, line, i)) monsters++
}
}
return monsters
}
private fun isMonster(image: List<String>, row: Int, col: Int): Boolean {
monster.forEachIndexed { mRow, mLine ->
mLine.forEachIndexed { mCol, mChar ->
if (mChar == '#')
if (image[row + mRow][col + mCol] != '#') return false
}
}
return true
}
private fun rotate(image: List<String>): List<String> {
return mutableListOf<String>().apply {
val lastIndex = image.lastIndex
for (newRow in 0..lastIndex) {
val sb = StringBuilder()
for (i in image.indices.reversed()) {
sb.append(image[i][newRow])
}
this.add(sb.toString())
}
}
}
private fun matchPuzzlePiece(puzzle: List<PuzzlePiece>, setPuzzle: List<PuzzlePiece>): Int {
puzzle.forEachIndexed { index, piece ->
var matched = false
for (i in setPuzzle.indices) {
if (piece.matchTo(setPuzzle[i])) matched = true
}
if (matched) return index
}
return -1
}
}
private class PuzzlePiece(val id: Int, content: List<String>) {
private var fixed = false
private var content: List<String> = content
set(value) {
if (fixed) error("puzzle piece $id is fixed") else field = value
}
private val neighbours = mutableListOf<PuzzlePiece?>(null, null, null, null)
private val borders: List<String>
get() = borders(content)
fun fixOrientation() {
fixed = true
}
fun matchTo(fixedPiece: PuzzlePiece): Boolean {
val match = borderMatch(fixedPiece) ?: return false
when {
match.flipped && match.border % 2 == 0 -> verticalFlip()
match.flipped && match.border % 2 == 1 -> horizontalFlip()
}
matchOrientation(match.border, match.otherBorder)
fixOrientation()
fixedPiece.neighbours[match.otherBorder] = this
neighbours[(match.otherBorder + 2) % 4] = fixedPiece
return true
}
private fun borderMatch(other: PuzzlePiece): BorderMatch? {
val otherBorders = other.borders
borders.forEachIndexed { bIndex, border ->
otherBorders.forEachIndexed { obIndex, otherBorder ->
if (border.reversed() == otherBorder) return BorderMatch(bIndex, obIndex, false)
if (border == otherBorder) return BorderMatch(bIndex, obIndex, true)
}
}
return null
}
private fun matchOrientation(border: Int, otherBorder: Int) {
when (border) {
(otherBorder + 3) % 4 -> {
horizontalFlip()
verticalFlip()
rotate()
}
(otherBorder + 1) % 4 -> rotate()
(otherBorder + 0) % 4 -> {
horizontalFlip()
verticalFlip()
}
}
}
private fun rotate() {
val tempContent = mutableListOf<String>()
val lastIndex = content.lastIndex
for (newRow in 0..lastIndex) {
val sb = StringBuilder()
for (line in content.reversed()) {
sb.append(line[newRow])
}
tempContent.add(sb.toString())
}
content = tempContent
}
private fun horizontalFlip() {
content = content.reversed()
}
private fun verticalFlip() {
content = content.map { it.reversed() }
}
fun getTotalImage(): List<String> {
return topLeft().getImage()
}
private fun getImage(): List<String> {
return imageRow().also { rows ->
neighbours[2]?.let { lowerPiece -> rows.addAll(lowerPiece.getImage()) }
}
}
private fun imageRow(): MutableList<String> {
return coreImage().also { core ->
neighbours[1]?.let { rightPiece ->
rightPiece.imageRow().forEachIndexed { index, rightString -> core[index] += rightString }
}
}
}
private fun coreImage(): MutableList<String> {
return content.subList(1, content.lastIndex).map { it.substring(1, it.lastIndex) }.toMutableList()
}
private fun topLeft(): PuzzlePiece {
var topLeft = this
while (topLeft.neighbours[0] != null) {
topLeft = topLeft.neighbours[0]!!
}
while (topLeft.neighbours[3] != null) {
topLeft = topLeft.neighbours[3]!!
}
return topLeft
}
companion object {
private val nonDigit = "\\D".toRegex()
fun create(input: List<String>): PuzzlePiece {
val id = input.first().replace(nonDigit, "").toInt()
val content = input.mapIndexedNotNull { index, s -> if (index == 0) null else s }
return PuzzlePiece(id, content)
}
private fun borders(content: List<String>): List<String> {
val leftSb = StringBuilder()
val rightSb = StringBuilder()
for (s in content) {
leftSb.append(s.first())
rightSb.append(s.last())
}
return listOf(content.first(), rightSb.toString(), content.last().reversed(), leftSb.reverse().toString())
}
}
private data class BorderMatch(val border: Int, val otherBorder: Int, val flipped: Boolean = false)
} | 0 | Kotlin | 0 | 0 | 7e6241173959b9d838fa00f81fdeb39fdb3ef6fe | 9,402 | adventofcode-kotlin | MIT License |
src/Day11.kt | ka1eka | 574,248,838 | false | {"Kotlin": 36739} | import javax.naming.OperationNotSupportedException
data class MonkeyDefinition(
val items: List<Int>,
val operation: Char,
val operationArg: Int?,
val divider: Int,
val trueTarget: Int,
val falseTarget: Int
)
interface Monkeys<T> {
fun catch(target: Int, item: T)
}
interface SeriousMonkeys<T> : Monkeys<T> {
val dividers: Set<Int>
}
interface Monkey<T> {
var inspectionsCount: Int
fun simulateTurn()
fun catch(item: T)
}
class NormalMonkey(private val definition: MonkeyDefinition, private val monkeys: Monkeys<Long>) : Monkey<Long> {
private val items: ArrayDeque<Long> = ArrayDeque(definition.items.map { it.toLong() })
override var inspectionsCount: Int = 0
override fun simulateTurn() {
while (items.isNotEmpty()) {
val initial = items.removeFirst()
var inspected = when (definition.operation) {
'*' -> when (definition.operationArg) {
null -> initial * initial
else -> {
initial * definition.operationArg
}
}
'+' -> {
initial + definition.operationArg!!
}
else -> throw OperationNotSupportedException()
}
inspected /= 3
when (inspected % definition.divider) {
0L -> monkeys.catch(definition.trueTarget, inspected)
else -> monkeys.catch(definition.falseTarget, inspected)
}
inspectionsCount++
}
}
override fun catch(item: Long) = items.addLast(item)
}
class DivisibleLevel(initial: Int, private val divider: Int) {
private var reminder = initial % divider
fun pow2() {
reminder = reminder * reminder % divider
}
fun multiply(arg: Int) {
reminder = reminder * arg % divider
}
fun plus(arg: Int) {
reminder = (reminder + arg) % divider
}
fun isDivisible(): Boolean = reminder == 0
}
class SeriousWorryLevel(initial: Int, dividers: Set<Int>) {
private val levels = dividers.associateWith { DivisibleLevel(initial, it) }
fun pow2() = levels.values.forEach(DivisibleLevel::pow2)
fun multiply(arg: Int) = levels.values.forEach { it.multiply(arg) }
fun plus(arg: Int) = levels.values.forEach { it.plus(arg) }
fun isDivisibleBy(divider: Int) = levels[divider]!!.isDivisible()
}
class SeriousMonkey(
private val definition: MonkeyDefinition,
private val monkeys: SeriousMonkeys<SeriousWorryLevel>
) : Monkey<SeriousWorryLevel> {
private val items = ArrayDeque(definition.items.map { SeriousWorryLevel(it, monkeys.dividers) })
override var inspectionsCount: Int = 0
override fun simulateTurn() {
while (items.isNotEmpty()) {
val item = items.removeFirst()
when (definition.operation) {
'*' -> when (definition.operationArg) {
null -> item.pow2()
else -> item.multiply(definition.operationArg)
}
'+' -> item.plus(definition.operationArg!!)
}
val target = if (item.isDivisibleBy(definition.divider)) {
definition.trueTarget
} else {
definition.falseTarget
}
monkeys.catch(target, item)
inspectionsCount++
}
}
override fun catch(item: SeriousWorryLevel) = items.addLast(item)
}
fun main() {
fun parseMonkeyDefinitions(input: List<String>) = input.chunked(7) {
val items = it[1].substring(18).split(", ").map(String::toInt)
val operation = it[2][23]
val operationArg = it[2].substring(25).toIntOrNull()
val test = it[3].substring(21).toInt()
val trueTarget = it[4].substring(29).toInt()
val falseTarget = it[5].substring(30).toInt()
MonkeyDefinition(
items,
operation,
operationArg,
test,
trueTarget,
falseTarget
)
}
class MonkeyBusiness<T>(input: List<String>, block: (MonkeyDefinition, SeriousMonkeys<T>) -> Monkey<T>) :
SeriousMonkeys<T> {
private val monkeyDefinitions = parseMonkeyDefinitions(input)
override val dividers: Set<Int> = monkeyDefinitions.map { it.divider }.toSet()
private val monkeys: List<Monkey<T>> = monkeyDefinitions
.map { block(it, this) }
fun simulateRound() = monkeys.forEach(Monkey<T>::simulateTurn)
fun toInspectionsSequence(): Sequence<Int> = monkeys
.asSequence()
.map { it.inspectionsCount }
override fun catch(target: Int, item: T) {
monkeys[target].catch(item)
}
}
fun part1(input: List<String>): Long = with(MonkeyBusiness(input, ::NormalMonkey)) {
repeat(20) {
this.simulateRound()
}
this.toInspectionsSequence()
.sortedDescending()
.take(2)
.fold(1L) { acc, current -> acc * current }
}
fun part2(input: List<String>): Long = with(MonkeyBusiness(input, ::SeriousMonkey)) {
repeat(10000) {
this.simulateRound()
}
this.toInspectionsSequence()
.sortedDescending()
.take(2)
.fold(1L) { acc, current -> acc * current }
}
val testInput = readInput("Day11_test")
check(part1(testInput) == 10605L)
check(part2(testInput) == 2713310158L)
val input = readInput("Day11")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 4f7893448db92a313c48693b64b3b2998c744f3b | 5,631 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/Day01.kt | JPQuirmbach | 572,636,904 | false | {"Kotlin": 11093} | fun main() {
fun parseInput(input: String) = input.split("\n\n")
.map { elf -> elf.lines().map { it.toInt() } }
fun part1(input: String): Int {
return parseInput(input)
.maxOf { it.sum() }
}
fun part2(input: String): Int {
return parseInput(input)
.map { it.sum() }
.sortedDescending()
.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 | 829e11bd08ff7d613280108126fa6b0b61dcb819 | 692 | advent-of-code-Kotlin-2022 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/ValidAnagram.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.ALPHABET_LETTERS_COUNT
/**
* 242. Valid Anagram
* @see <a href="https://leetcode.com/problems/valid-anagram/">Source</a>
*/
fun interface ValidAnagram {
operator fun invoke(s: String, t: String): Boolean
}
class ValidAnagramHashMap : ValidAnagram {
override fun invoke(s: String, t: String): Boolean {
val sMap = HashMap<Char, Int>()
val sl: Int = s.length
val tl: Int = t.length
if (sl != tl) {
return false
}
for (i in 0 until sl) {
sMap[s[i]] = sMap.getOrDefault(s[i], 0) + 1
sMap[t[i]] = sMap.getOrDefault(t[i], 0) - 1
}
for (c in sMap.keys) {
if (sMap[c] != 0) {
return false
}
}
return true
}
}
class ValidAnagramImpl : ValidAnagram {
override fun invoke(s: String, t: String): Boolean {
val alphabet = IntArray(ALPHABET_LETTERS_COUNT)
for (i in s.indices) {
alphabet[s[i] - ALPHABET_FIRST_LETTER]++
}
for (i in t.indices) {
alphabet[t[i] - ALPHABET_FIRST_LETTER]--
if (alphabet[t[i] - ALPHABET_FIRST_LETTER] < 0) {
return false
}
}
for (i in alphabet) {
if (i != 0) {
return false
}
}
return true
}
companion object {
private const val ALPHABET_FIRST_LETTER = 'a'
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,114 | kotlab | Apache License 2.0 |
src/main/kotlin/dev/patbeagan/days/Day07.kt | patbeagan1 | 576,401,502 | false | {"Kotlin": 57404} | package dev.patbeagan.days
import java.util.*
/**
* [Day 7](https://adventofcode.com/2022/day/7)
*/
class Day07 : AdventDay<Int> {
override fun part1(input: String): Int {
val dir = parseInput(input)
val listOfDirsOfSmallSize = mutableListOf<Dir>()
dir.walk {
if (it is Dir && it.size < 100000) {
listOfDirsOfSmallSize.add(it)
}
}
return listOfDirsOfSmallSize.sumOf { it.size }
}
override fun part2(input: String): Int {
val maxSpace = 70_000_000
val updateSpace = 30_000_000
val dir = parseInput(input)
val totalSpace = dir.size
val freeSpace = maxSpace - totalSpace
val requiredSpace = updateSpace - freeSpace
val listOfDirs = mutableListOf<Dir>()
dir.walk {
if (it is Dir) {
listOfDirs.add(it)
}
}
return listOfDirs.minBy {
if (it.size < requiredSpace) Int.MAX_VALUE else it.size
}.size
}
fun parseInput(input: String): Dir {
val lines = input
.trim()
.split("\n")
val context = Context()
val commands = mutableListOf<Command>()
lines.forEach { line ->
if (Command.isCommand(line)) {
Command.fromString(context, line)
?.also { it.emit() }
?.let { commands.add(it) }
} else {
commands.last().scan(line)
}
}
context.fileSystem.prettyFormat()
return context.fileSystem
}
data class Context(
var location: Stack<Dir> = Stack()
) {
val fileSystem: Dir get() = location.first()
}
sealed class Command {
abstract val context: Context
class CommandCD(override val context: Context, val input: String) : Command() {
override fun emit() = performAction()
override fun scan(input: String) = performAction()
private fun performAction() {
val dirName = input
.split(" ")[1]
when (dirName) {
".." -> context.location.pop()
else -> {
val currentDir: Dir? = try {
context.location.peek()
} catch (e: EmptyStackException) {
null
}
val matchingDir: Dir? = currentDir
?.files
?.firstOrNull { it is Dir && it.name == dirName }
?.let { it as Dir }
val dir = matchingDir ?: Dir(name = dirName, mutableListOf())
context
.location
.push(dir)
}
}
}
}
class CommandLS(override val context: Context, val input: String) : Command() {
override fun emit() {
context.location.peek()?.files?.forEach {
when (it) {
is Dir -> println("dir ${it.name}")
is File -> println("${it.size} ${it.name}")
}
}
}
override fun scan(input: String) {
println("ls: $input")
when {
regexFile.matches(input) -> regexFile.find(input)?.groupValues
?.let { File(it[2], it[1].toInt()) }
?.let { addToFileTree(it) }
?.also { println("scanned file") }
regexDir.matches(input) -> regexDir.find(input)?.groupValues
?.let { Dir(it[1], mutableListOf()) }
?.let { addToFileTree(it) }
?.also { println("scanned dir") }
else -> Unit
}
}
private fun addToFileTree(it: INode) = context.location.peek()?.files?.add(it)
companion object {
val regexFile = "(\\d*) *([^ ]*)".toRegex()
val regexDir = "dir *([^ ]*)".toRegex()
}
}
abstract fun emit()
abstract fun scan(input: String)
companion object {
private val commandRegex = "\\$ *\\W*(.*)".toRegex()
fun isCommand(input: String) = commandRegex.matches(input)
fun fromString(context: Context, input: String) = commandRegex
.find(input)
.let { it?.groupValues?.get(1) }
?.let {
when {
it.startsWith("cd") -> CommandCD(context, it)
it.startsWith("ls") -> CommandLS(context, it)
else -> null
}
}
}
}
data class Dir(
override val name: String,
val files: MutableList<INode>
) : INode {
override val size: Int get() = files.sumOf { it.size }
fun walk(action: (INode) -> Unit) {
files.forEach {
when (it) {
is File -> action(it)
is Dir -> {
action(it)
it.walk(action)
}
}
}
}
fun prettyFormat(
indentation: Int = 0,
stringBuilder: StringBuilder = StringBuilder()
): String {
val singleIndent = " "
val indentString = buildString { repeat(indentation) { append(singleIndent) } }
return stringBuilder.apply {
stringBuilder.appendLine("${indentString}- $name (dir)")
files.forEach {
when (it) {
is Dir -> it.prettyFormat(indentation + 1, stringBuilder)
is File -> stringBuilder.appendLine("${indentString}$singleIndent- ${it.name} (file, size=${it.size})")
}
}
}.toString().trim()
}
fun prettyPrint() = println(prettyFormat())
}
data class File(
override val name: String,
override val size: Int
) : INode
sealed interface INode {
val name: String
val size: Int
}
} | 0 | Kotlin | 0 | 0 | 4e25b38226bcd0dbd9c2ea18553c876bf2ec1722 | 6,428 | AOC-2022-in-Kotlin | Apache License 2.0 |
src/Day10.kt | iProdigy | 572,297,795 | false | {"Kotlin": 33616} | import java.lang.StringBuilder
import java.util.concurrent.atomic.AtomicInteger
fun main() {
fun part1(input: List<String>): Int = AtomicInteger().apply {
run(input) { cycle, x ->
if ((cycle - 20) % 40 == 0)
this += (cycle * x)
}
}.get()
fun part2(input: List<String>) = StringBuilder().apply {
run(input) { cycle, x ->
this += when {
(cycle - 1) % 40 in x - 1..x + 1 -> '#'
else -> '.'
}
}
}.toString().chunked(40).joinToString(separator = "\n")
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day10_test")
check(part1(testInput) == 13140)
check(
part2(testInput) == """##..##..##..##..##..##..##..##..##..##..
###...###...###...###...###...###...###.
####....####....####....####....####....
#####.....#####.....#####.....#####.....
######......######......######......####
#######.......#######.......#######....."""
)
val input = readInput("Day10")
println(part1(input)) // 11720
println(part2(input)) // ERCREPCJ
}
private fun run(input: List<String>, consumer: (Int, Int) -> Unit) {
var x = 1
var cycle = 0
var next: Int? = null
val queue = input.mapTo(ArrayDeque()) { it.split(' ') }
while (queue.isNotEmpty()) {
cycle++
consumer(cycle, x)
if (next != null) {
x += next
next = null
} else {
val it = queue.removeFirst()
if ("addx" == it[0])
next = it[1].toInt()
}
}
}
| 0 | Kotlin | 0 | 1 | 784fc926735fc01f4cf18d2ec105956c50a0d663 | 1,629 | advent-of-code-2022 | Apache License 2.0 |
src/Day02.kt | samframpton | 572,917,565 | false | {"Kotlin": 6980} | fun main() {
fun part1(input: List<String>) =
input.map {
when (it) {
"A X" -> 4
"A Y" -> 8
"A Z" -> 3
"B X" -> 1
"B Y" -> 5
"B Z" -> 9
"C X" -> 7
"C Y" -> 2
"C Z" -> 6
else -> 0
}
}.sum()
fun part2(input: List<String>) =
input.map {
when (it) {
"A X" -> 3
"A Y" -> 4
"A Z" -> 8
"B X" -> 1
"B Y" -> 5
"B Z" -> 9
"C X" -> 2
"C Y" -> 6
"C Z" -> 7
else -> 0
}
}.sum()
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | e7f5220b6bd6f3c5a54396fa95f199ff3a8a24be | 864 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/solutions/day09/Day9.kt | Dr-Horv | 112,381,975 | false | null | package solutions.day09
import solutions.Solver
data class Node(val parent: Node?, val children: MutableList<Node>) {
fun addChild(child: Node) {
children.add(child)
}
}
class Day9: Solver {
override fun solve(input: List<String>, partTwo: Boolean): String {
val first = input.first()
val stream = first.toCharArray().slice(IntRange(1, first.lastIndex - 1)) // Create outmost node before loop
val iterator = stream.toCharArray().iterator()
var curr = Node(null, mutableListOf())
var garbageSum = 0
while(iterator.hasNext()) {
val c = iterator.nextChar()
if(c == '<') {
garbageSum += handleGarbage(iterator)
}
when(c) {
'{' -> curr = goDeeper(curr)
'}' -> curr = goShallower(curr)
}
}
return if(!partTwo) {
sumGroupScore(curr).toString()
} else {
garbageSum.toString()
}
}
private fun goShallower(curr: Node): Node {
if(curr.parent != null) {
return curr.parent
} else {
throw RuntimeException("Unexpected no parent")
}
}
private fun goDeeper(curr: Node): Node {
val deeperNode = Node(parent = curr, children = mutableListOf())
curr.addChild(deeperNode)
return deeperNode
}
private fun handleGarbage(iterator: CharIterator): Int {
var garbageSum = 0
while(iterator.hasNext()) {
val c = iterator.nextChar()
when(c) {
'!' -> iterator.next()
'>' -> return garbageSum
else -> garbageSum++
}
}
throw RuntimeException("Unexpected no end of garbage")
}
private fun sumGroupScore(root: Node, level: Int = 1): Int {
return level + root.children.map { sumGroupScore(it, level+1) }.sum()
}
} | 0 | Kotlin | 0 | 2 | 975695cc49f19a42c0407f41355abbfe0cb3cc59 | 1,953 | Advent-of-Code-2017 | MIT License |
src/main/kotlin/year_2022/Day14.kt | krllus | 572,617,904 | false | {"Kotlin": 97314} | package year_2022
import utils.readInput
fun main() {
fun printGrid(grid: Array<Array<String>>) {
val row = grid.size
val col = grid[0].size
for (i in 0..row) {
for (j in 0..col)
print(grid[i][j])
println()
}
}
fun part1(input: List<String>): Int {
val rows = 500
val columns = 1000
val grid = Array(rows) { _ ->
Array(columns) { _ ->
"."
}
}
val moves = arrayListOf<Pair<Int, Int>>()
for (line in input) {
val entries = line.split(" -> ")
// extract moves
for (entry in entries) {
val latlon = entry.split(",")
val lat = latlon.first().toIntOrNull() ?: error("lat not able to be parsed")
val lon = latlon.last().toIntOrNull() ?: error("lon not able to be parsed")
moves.add(Pair(lat, lon))
}
// process moves
// clear moves list
}
printGrid(grid)
return 24
}
fun part2(input: List<String>): Int {
return 0
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day14_test")
check(part1(testInput) == 24)
check(part2(testInput) == 0)
val input = readInput("Day14")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | b5280f3592ba3a0fbe04da72d4b77fcc9754597e | 1,452 | advent-of-code | Apache License 2.0 |
src/Day01.kt | Allagash | 572,736,443 | false | {"Kotlin": 101198} | import java.lang.Long.max
// Day 01, Advent of Code 2022, Calorie Counting
fun main() {
fun part1(input: List<String>): Long {
var max = -1L
var count = 0L
input.forEach {
if (it.isEmpty()) {
max = max(count ,max)
count = 0
} else {
count += it.toInt()
}
}
max = max(count ,max)
return max
}
fun part2(input: List<String>): Long {
val calCount = mutableListOf<Long>()
var count = 0L
input.forEach {
if (it.isEmpty()) {
calCount.add(count)
count = 0
} else {
count += it.toInt()
}
}
return calCount.sortedDescending().subList(0, 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 | 8d5fc0b93f6d600878ac0d47128140e70d7fc5d9 | 1,060 | AdventOfCode2022 | Apache License 2.0 |
src/main/kotlin/pl/mrugacz95/aoc/day2/day2.kt | mrugacz95 | 317,354,321 | false | null | package pl.mrugacz95.aoc.day2
import java.lang.RuntimeException
fun Boolean.toInt() = if (this) 1 else 0
data class Policy(val policy: String) {
companion object {
val regex = "(?<first>\\d+)-(?<second>\\d+) (?<char>.): (?<pass>[a-z]+)".toRegex()
}
private val groups = regex.matchEntire(policy)?.groups ?: throw RuntimeException("Regex doesn't match")
val first = groups["first"]?.value?.toInt() ?: throw RuntimeException("First field not found")
val second = groups["second"]?.value?.toInt() ?: throw RuntimeException("Second field not found")
val char = groups["char"]?.value?.get(0) ?: throw RuntimeException("Char field not found")
val pass = groups["pass"]?.value ?: throw RuntimeException("Pass field not found")
}
fun validPolicyPart1(policy: Policy): Boolean {
val count = policy.pass
.toList()
.groupingBy { it }
.eachCount()[policy.char] ?: return false
return count in policy.first..policy.second
}
fun part1(policies: List<Policy>) {
println("Answer part 1: ${policies.map { validPolicyPart1(it).toInt() }.sum()}")
}
fun validPolicyPart2(policy: Policy): Boolean {
val characters = policy.pass.toList()
return (characters[policy.first - 1] == policy.char).xor(characters[policy.second - 1] == policy.char)
}
fun part2(policies: List<Policy>) {
println("Answer part 2: ${policies.map { validPolicyPart2(it).toInt() }.sum()}")
}
fun main() {
val policies: List<Policy> = {}::class.java.getResource("/day2.in")
.readText()
.split("\n")
.map { Policy(it) }
part1(policies)
part2(policies)
} | 0 | Kotlin | 0 | 1 | a2f7674a8f81f16cd693854d9f564b52ce6aaaaf | 1,628 | advent-of-code-2020 | Do What The F*ck You Want To Public License |
src/Day08.kt | rickbijkerk | 572,911,701 | false | {"Kotlin": 31571} | fun main() {
data class Tree(val value: Int, var visible: Boolean? = null) {
// val sightLeft: Int = 0
// val sightRight: Int = 0
// val sightTop: Int = 0
// val sightBottom: Int = 0
//
// fun scenicScore(): Int {
// return sightLeft * sightRight * sightTop * sightBottom
// }
override fun toString(): String {
return "Tree(value=$value, visible=$visible)"
}
}
fun buildMap(input: List<String>): Array<Array<Tree>> {
val map = Array(input.size) { Array(input[0].length) { Tree(0, false) } }
input.mapIndexed { y, line ->
line.map { it.toString().toInt() }.mapIndexed { x, number ->
map[y][x] = Tree(number, false)
}
}
return map
}
fun printCoordinates(map: Array<Array<Tree>>, width: Int, height: Int) {
map.forEachIndexed { y, array ->
array.forEachIndexed { x, tree ->
if (tree.visible == true && x != 0 && y != 0 && x != width - 1 && y != height - 1) {
println("$y,$x(${tree.value})")
}
}
println()
}
}
fun part1(input: List<String>): Int {
val map = buildMap(input)
val height = input.size
val width = input[0].length
map.forEachIndexed { y, array ->
array.forEachIndexed { x, tree ->
if (x == 0 || x == width - 1 || y == 0 || y == height - 1) {
tree.visible = true
} else {
//visible from right
try {
var neighbourX = x + 1
var visible = true
while (visible) {
if (tree.value <= map[y][neighbourX].value) {
visible = false
}
neighbourX++
}
} catch (e: IndexOutOfBoundsException) {
tree.visible = true
}
// visible from left
try {
var neighbourX = x - 1
var visible = true
while (visible) {
if (tree.value <= map[y][neighbourX].value) {
visible = false
}
neighbourX--
}
} catch (e: IndexOutOfBoundsException) {
tree.visible = true
}
// visible from top
try {
var neighboury = y - 1
var visible = true
while (visible) {
if (tree.value <= map[neighboury][x].value) {
visible = false
}
neighboury--
}
} catch (e: IndexOutOfBoundsException) {
tree.visible = true
}
// visible from bottom
try {
var neighboury = y + 1
var visible = true
while (visible) {
if (tree.value <= map[neighboury][x].value) {
visible = false
}
neighboury++
}
} catch (e: IndexOutOfBoundsException) {
tree.visible = true
}
}
}
}
// printCoordinates(map, width, height)
return map.flatMap { it.filter { tree -> tree.visible == true } }.size
}
fun rightLineOfSight(x: Int, tree: Tree, map: Array<Array<Tree>>, y: Int): Int {
var sight = 0
try {
var neighbourX = x + 1
while (true) {
if (tree.value > map[y][neighbourX].value) {
// println("${tree.value} > ${map[y][neighbourX].value} for tree:$tree")
sight++
neighbourX++
} else {
sight+=1
break
}
}
} catch (_: IndexOutOfBoundsException) {
}
return sight
}
fun leftLineOfSight(x: Int, tree: Tree, map: Array<Array<Tree>>, y: Int): Int {
var sight = 0
try {
var neighbourX = x - 1
while (true) {
if (tree.value > map[y][neighbourX].value) {
sight++
neighbourX--
} else {
sight+=1
break
}
}
} catch (_: IndexOutOfBoundsException) {
}
return sight
}
fun topLineOfSight(x: Int, tree: Tree, map: Array<Array<Tree>>, y: Int): Int {
var sight = 0
try {
var neighboury = y - 1
while (true) {
if (tree.value > map[neighboury][x].value) {
sight++
neighboury--
} else {
sight+=1
break
}
}
} catch (_: IndexOutOfBoundsException) {
}
return sight
}
fun bottomLineOfSight(x: Int, tree: Tree, map: Array<Array<Tree>>, y: Int): Int {
var sight = 0
try {
var neighbourY = y + 1
while (true) {
if (tree.value > map[neighbourY][x].value) {
sight++
neighbourY++
} else {
sight+=1
break
}
}
} catch (_: IndexOutOfBoundsException) {
}
return sight
}
fun part2(input: List<String>): Int {
val map = buildMap(input)
var scenicHighScore = 0
map.forEachIndexed { y, array ->
array.forEachIndexed { x, tree ->
val rightView = rightLineOfSight(x, tree, map, y)
val leftView = leftLineOfSight(x, tree, map, y)
val bottomView = bottomLineOfSight(x, tree, map, y)
val topView = topLineOfSight(x, tree, map, y)
val score = rightView * leftView * topView * bottomView
if (score > scenicHighScore) {
scenicHighScore = score
println("$tree $x,$y has a new highscore of $scenicHighScore right:$rightView left:$leftView top:$topView bottom:$bottomView")
}
}
}
return scenicHighScore
}
val testInput = readInput("day08_test")
// test part1
val resultPart1 = part1(testInput)
val expectedPart1 = 21 //TODO Change me
println("Part1\nresult: $resultPart1")
println("expected:$expectedPart1 \n")
check(resultPart1 == expectedPart1)
//Check results part1
val input = readInput("day08")
println("Part1 ${part1(input)}\n\n")
// test part2
val resultPart2 = part2(testInput)
val expectedPart2 = 8 //TODO Change me
println("Part2\nresult: $resultPart2")
println("expected:$expectedPart2 \n")
check(resultPart2 == expectedPart2)
//Check results part2
println("Part2 ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 817a6348486c8865dbe2f1acf5e87e9403ef42fe | 7,571 | aoc-2022 | Apache License 2.0 |
src/day02.kts | miedzinski | 434,902,353 | false | {"Kotlin": 22560, "Shell": 113} | enum class Command { FORWARD, DOWN, UP }
val input = generateSequence(::readLine).map {
val split = it.split(" ")
val command = when (split.first()) {
"forward" -> Command.FORWARD
"down" -> Command.DOWN
"up" -> Command.UP
else -> throw IllegalArgumentException()
}
val units = split.last().toInt()
Pair(command, units)
}.toList()
fun part1(): Int {
var horizontal = 0
var depth = 0
for ((command, units) in input) {
when (command) {
Command.FORWARD -> horizontal += units
Command.DOWN -> depth += units
Command.UP -> depth -= units
}
}
return horizontal * depth
}
println("part1: ${part1()}")
fun part2(): Int {
var horizontal = 0
var depth = 0
var aim = 0
for ((command, units) in input) {
when (command) {
Command.FORWARD -> {
horizontal += units
depth += aim * units
}
Command.DOWN -> aim += units
Command.UP -> aim -= units
}
}
return horizontal * depth
}
println("part2: ${part2()}")
| 0 | Kotlin | 0 | 0 | 6f32adaba058460f1a9bb6a866ff424912aece2e | 1,138 | aoc2021 | The Unlicense |
src/main/kotlin/com/sherepenko/leetcode/challenges/ThirtyDayChallenge.kt | asherepenko | 264,648,984 | false | null | package com.sherepenko.leetcode.challenges
import com.sherepenko.leetcode.Solution
import com.sherepenko.leetcode.data.ListNode
import com.sherepenko.leetcode.data.TreeNode
import com.sherepenko.leetcode.solutions.BackspaceCompare
import com.sherepenko.leetcode.solutions.BinaryTreeDiameter
import com.sherepenko.leetcode.solutions.BinaryTreeMaxPathSum
import com.sherepenko.leetcode.solutions.BinaryTreePreorderTraversal
import com.sherepenko.leetcode.solutions.ContiguosArray
import com.sherepenko.leetcode.solutions.CountElements
import com.sherepenko.leetcode.solutions.GroupAnagrams
import com.sherepenko.leetcode.solutions.HappyNumber
import com.sherepenko.leetcode.solutions.JumpGame
import com.sherepenko.leetcode.solutions.LastStoneWeight
import com.sherepenko.leetcode.solutions.LongestCommonSubsequence
import com.sherepenko.leetcode.solutions.MaxProfitII
import com.sherepenko.leetcode.solutions.MaxSubArray
import com.sherepenko.leetcode.solutions.MaximalSquare
import com.sherepenko.leetcode.solutions.MiddleNode
import com.sherepenko.leetcode.solutions.MinPathSum
import com.sherepenko.leetcode.solutions.MoveZeroes
import com.sherepenko.leetcode.solutions.NumberOfIslands
import com.sherepenko.leetcode.solutions.ProductOfArrayExceptSelf
import com.sherepenko.leetcode.solutions.RangeBitwiseAnd
import com.sherepenko.leetcode.solutions.RotatedSortedArray
import com.sherepenko.leetcode.solutions.SingleNumber
import com.sherepenko.leetcode.solutions.StringShift
import com.sherepenko.leetcode.solutions.SubArraySum
import com.sherepenko.leetcode.solutions.ValidParenthesisString
object ThirtyDayChallenge : Solution {
private val challenges = listOf(
// Week 1
object : Solution {
private val challenges = listOf(
SingleNumber(
numbers = intArrayOf(4, 1, 2, 1, 2)
),
HappyNumber(
number = 2
),
MaxSubArray(
numbers = intArrayOf(-2, 1, -3, 4, -1, 2, 1, -5, 4)
),
MoveZeroes(
numbers = intArrayOf(0, 1, 0, 3, 12)
),
MaxProfitII(
prices = intArrayOf(7, 1, 5, 3, 6, 4)
),
GroupAnagrams(
strs = arrayOf("eat", "tea", "tan", "ate", "nat", "bat")
),
CountElements(
numbers = intArrayOf(1, 1, 3, 3, 5, 5, 7, 7)
),
BackspaceCompare(
strFirst = "ab##",
strLast = "c#d#"
)
)
override fun resolve() {
println("========== Week 1 ==========")
challenges.forEach {
it.resolve()
}
}
},
// Week 2
object : Solution {
private val challenges = listOf(
MiddleNode(
head = ListNode(1).apply {
next = ListNode(2)
next!!.next = ListNode(3)
next!!.next!!.next = ListNode(4)
next!!.next!!.next!!.next = ListNode(5)
}
),
BinaryTreeDiameter(
root = TreeNode(1).apply {
left = TreeNode(2)
left?.left = TreeNode(4)
left?.right = TreeNode(5)
right = TreeNode(3)
}
),
LastStoneWeight(
stones = intArrayOf(2, 7, 4, 1, 8, 1)
),
ContiguosArray(
numbers = intArrayOf(0, 1, 0)
),
StringShift(
str = "abcdefg",
shifts = arrayOf(
intArrayOf(1, 1),
intArrayOf(1, 1),
intArrayOf(0, 2),
intArrayOf(1, 3)
)
)
)
override fun resolve() {
println("========== Week 2 ==========")
challenges.forEach {
it.resolve()
}
}
},
// Week 3
object : Solution {
private val challenges = listOf(
ProductOfArrayExceptSelf(
numbers = intArrayOf(1, 2, 3, 4)
),
ValidParenthesisString(
str = "(*))"
),
NumberOfIslands(
grid = arrayOf(
"11000".toCharArray(),
"11000".toCharArray(),
"00100".toCharArray(),
"00011".toCharArray()
)
),
MinPathSum(
grid = arrayOf(
intArrayOf(1, 3, 1),
intArrayOf(1, 5, 1),
intArrayOf(4, 2, 1)
)
),
RotatedSortedArray(
numbers = intArrayOf(4, 5, 6, 7, 0, 1, 2),
target = 2
),
BinaryTreePreorderTraversal(
values = intArrayOf(8, 5, 1, 7, 10, 12)
)
)
override fun resolve() {
println("========== Week 3 ==========")
challenges.forEach {
it.resolve()
}
}
},
// Week 4
object : Solution {
private val challenges = listOf(
SubArraySum(
numbers = intArrayOf(1, 1, 1),
value = 2
),
RangeBitwiseAnd(
first = 5,
last = 7
),
JumpGame(
numbers = intArrayOf(3, 2, 1, 0, 4)
),
LongestCommonSubsequence(
text1 = "abcde",
text2 = "face"
),
MaximalSquare(
matrix = arrayOf(
"11100".toCharArray(),
"11100".toCharArray(),
"00100".toCharArray(),
"00011".toCharArray()
)
)
)
override fun resolve() {
println("========== Week 4 ==========")
challenges.forEach {
it.resolve()
}
}
},
// Week 5
object : Solution {
val challenges = listOf(
BinaryTreeMaxPathSum(
root = TreeNode(1).apply {
left = TreeNode(2)
left?.left = TreeNode(4)
left?.right = TreeNode(5)
right = TreeNode(3)
}
)
)
override fun resolve() {
println("========== Week 5 ==========")
challenges.forEach {
it.resolve()
}
}
}
)
override fun resolve() {
println("========== 30 D A Y C H A L L E N G E ==========")
challenges.forEach {
it.resolve()
}
}
}
| 0 | Kotlin | 0 | 0 | 49e676f13bf58f16ba093f73a52d49f2d6d5ee1c | 7,556 | leetcode | The Unlicense |
src/main/kotlin/com/ginsberg/advent2023/Day01.kt | tginsberg | 723,688,654 | false | {"Kotlin": 112398} | /*
* Copyright (c) 2023 by <NAME>
*/
/**
* Advent of Code 2023, Day 1 - Trebuchet?!
* Problem Description: http://adventofcode.com/2023/day/1
* Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2023/day1/
*/
package com.ginsberg.advent2023
class Day01(private val input: List<String>) {
private val words: Map<String, Int> = mapOf(
"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 solvePart1(): Int =
input.sumOf { calibrationValue(it) }
fun solvePart2(): Int =
input.sumOf { row ->
calibrationValue(
// Run through each character and turn it into a digit or a null,
// and then map each of them to a String. In theory, we could take
// the first and last digits from the resulting list instead of joining.
row.mapIndexedNotNull { index, c ->
// If it is a digit, take it as-is
if (c.isDigit()) c
else
// Otherwise, see if this is the start of a word and if so map to the
// digit that it represents.
row.possibleWordsAt(index).firstNotNullOfOrNull { candidate ->
words[candidate]
}
}.joinToString()
)
}
private fun calibrationValue(row: String): Int =
"${row.first { it.isDigit() }}${row.last { it.isDigit() }}".toInt()
private fun String.possibleWordsAt(startingAt: Int): List<String> =
(3..5).map { len ->
substring(startingAt, (startingAt + len).coerceAtMost(length))
}
} | 0 | Kotlin | 0 | 12 | 0d5732508025a7e340366594c879b99fe6e7cbf0 | 1,829 | advent-2023-kotlin | Apache License 2.0 |
src/main/kotlin/week4/HotAirBalloons.kt | waikontse | 572,850,856 | false | {"Kotlin": 63258} | package week4
import shared.Puzzle
import shared.ReadUtils.Companion.debug
import kotlin.math.pow
class HotAirBalloons : Puzzle(25) {
infix fun Int.pow(exponent: Int): Long = toDouble().pow(exponent).toLong()
override fun solveFirstPart(): Any {
return puzzleInput.map { toDecimal(it) }
.sum()
.also { println(it) }
.run { println(toSnafu(this)) }
}
override fun solveSecondPart(): Any {
TODO("Not yet implemented")
}
private fun toSnafu(decimal: Long): String {
return toSnafu2(decimal, listOf())
}
private tailrec fun toSnafu2(division: Long, acc: List<Int>): String {
if (division == 0L) {
return convertPentalToSnafu(acc)
}
val divisionNew = division / 5
val remainder = division % 5
return toSnafu2(divisionNew, acc.plus(remainder.toInt()))
}
private fun convertPentalToSnafu(pental: List<Int>): String {
debug("Converting pental to snafu $pental")
val snafu = mutableListOf<Char>()
var carry = 0
for (i in pental) {
val conversionResult = pentalToSnafu(i + carry)
snafu.add(conversionResult.first)
carry = conversionResult.second
debug("current snafu: $snafu i: $i carry: $carry")
}
if (carry > 0) {
snafu.add('1')
}
return snafu.joinToString("").reversed()
}
private fun toDecimal(snafu: String) =
toDecimal2(snafu.reversed(), 0, 0)
private tailrec fun toDecimal2(snafu: String, acc: Long, level: Int): Long {
if (snafu.isEmpty()) {
return acc
}
val multiplier = 5 pow level
val snafuChar = snafu.first()
debug("converting $snafu with multiplier $multiplier")
return toDecimal2(snafu.drop(1), acc.plus(multiplier * snafuToDecimal(snafuChar)), level.inc())
}
private fun snafuToDecimal(snafu: Char) =
when (snafu) {
'-' -> -1
'=' -> -2
'0' -> 0
'1' -> 1
'2' -> 2
else -> throw IllegalArgumentException()
}
private fun pentalToSnafu(pental: Int) =
when (pental) {
0 -> '0' to 0
1 -> '1' to 0
2 -> '2' to 0
3 -> '=' to 1
4 -> '-' to 1
5 -> '0' to 1
else -> throw IllegalArgumentException()
}
}
| 0 | Kotlin | 0 | 0 | 860792f79b59aedda19fb0360f9ce05a076b61fe | 2,476 | aoc-2022-in-kotllin | Creative Commons Zero v1.0 Universal |
src/day6/day6.kt | pocmo | 433,766,909 | false | {"Kotlin": 134886} | import java.io.File
fun readFishMap(): MutableMap<Int, Long> {
val fishes = File("day6.txt")
.readLines()[0]
.split(",")
.map { it.toInt() }
val map = mutableMapOf<Int, Long>()
fishes.forEach { fish ->
val count = map.getOrDefault(fish, 0)
map[fish] = count + 1
}
return map
}
fun MutableMap<Int, Long>.simulateLanternFishes() {
val reproducingFishes = get(0) ?: 0
for (i in 1 .. 8) {
val count = get(i) ?: 0
put(i - 1, count)
}
put(8, reproducingFishes)
val sixFishesCount = get(6) ?: 0
put(6, sixFishesCount + reproducingFishes)
}
fun part2() {
val map = readFishMap()
println(map)
repeat(256) {
map.simulateLanternFishes()
}
println(map)
val fishCount = map.values.sum()
println("Total fishes: $fishCount")
}
fun part1() {
val map = readFishMap()
println(map)
repeat(80) {
map.simulateLanternFishes()
}
println(map)
val fishCount = map.values.sum()
println("Total fishes: $fishCount")
}
fun main() {
part2()
} | 0 | Kotlin | 1 | 2 | 73bbb6a41229e5863e52388a19108041339a864e | 1,103 | AdventOfCode2021 | Apache License 2.0 |
day08/part1.kts | bmatcuk | 726,103,418 | false | {"Kotlin": 214659} | // --- Day 8: Haunted Wasteland ---
// You're still riding a camel across Desert Island when you spot a sandstorm
// quickly approaching. When you turn to warn the Elf, she disappears before
// your eyes! To be fair, she had just finished warning you about ghosts a few
// minutes ago.
//
// One of the camel's pouches is labeled "maps" - sure enough, it's full of
// documents (your puzzle input) about how to navigate the desert. At least,
// you're pretty sure that's what they are; one of the documents contains a
// list of left/right instructions, and the rest of the documents seem to
// describe some kind of network of labeled nodes.
//
// It seems like you're meant to use the left/right instructions to navigate
// the network. Perhaps if you have the camel follow the same instructions, you
// can escape the haunted wasteland!
//
// After examining the maps for a bit, two nodes stick out: AAA and ZZZ. You
// feel like AAA is where you are now, and you have to follow the left/right
// instructions until you reach ZZZ.
//
// This format defines each node of the network individually. For example:
//
// RL
//
// AAA = (BBB, CCC)
// BBB = (DDD, EEE)
// CCC = (ZZZ, GGG)
// DDD = (DDD, DDD)
// EEE = (EEE, EEE)
// GGG = (GGG, GGG)
// ZZZ = (ZZZ, ZZZ)
//
// Starting with AAA, you need to look up the next element based on the next
// left/right instruction in your input. In this example, start with AAA and go
// right (R) by choosing the right element of AAA, CCC. Then, L means to choose
// the left element of CCC, ZZZ. By following the left/right instructions, you
// reach ZZZ in 2 steps.
//
// Of course, you might not find ZZZ right away. If you run out of left/right
// instructions, repeat the whole sequence of instructions as necessary: RL
// really means RLRLRLRLRLRLRLRL... and so on. For example, here is a situation
// that takes 6 steps to reach ZZZ:
//
// LLR
//
// AAA = (BBB, BBB)
// BBB = (AAA, ZZZ)
// ZZZ = (ZZZ, ZZZ)
//
// Starting at AAA, follow the left/right instructions. How many steps are
// required to reach ZZZ?
import java.io.*
fun <T> Sequence<T>.repeat() = sequence { while (true) yieldAll(this@repeat) }
class Fork(val left: String, val right: String) {
fun next(turn: Char): String {
if (turn == 'L') return this.left
return this.right
}
}
val lines = File("input.txt").readLines()
val directions = lines[0]
val map = lines.drop(2).associate {
it.substring(0..2) to Fork(it.substring(7..9), it.substring(12..14))
}
var position = "AAA"
val result = directions.asSequence().repeat().takeWhile {
position = map[position]!!.next(it)
position != "ZZZ"
}.count() + 1
println(result)
| 0 | Kotlin | 0 | 0 | a01c9000fb4da1a0cd2ea1a225be28ab11849ee7 | 2,651 | adventofcode2023 | MIT License |
src/main/kotlin/g0501_0600/s0529_minesweeper/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g0501_0600.s0529_minesweeper
// #Medium #Array #Depth_First_Search #Breadth_First_Search #Matrix
// #2023_01_15_Time_243_ms_(87.50%)_Space_37_MB_(87.50%)
class Solution {
private var row = 0
private var col = 0
private fun dfs(board: Array<CharArray>, row: Int, col: Int) {
if (row < 0 || row >= this.row || col < 0 || col >= this.col) {
return
}
if (board[row][col] == 'E') {
val numOfMine = bfs(board, row, col)
if (numOfMine != 0) {
board[row][col] = (numOfMine + '0'.code).toChar()
return
} else {
board[row][col] = 'B'
}
for (i in DIRECTION) {
dfs(board, row + i[0], col + i[1])
}
}
}
private fun bfs(board: Array<CharArray>, row: Int, col: Int): Int {
var numOfMine = 0
for (i in DIRECTION) {
val newRow = row + i[0]
val newCol = col + i[1]
if (newRow >= 0 && newRow < this.row && newCol >= 0 && newCol < this.col && board[newRow][newCol] == 'M') {
numOfMine++
}
}
return numOfMine
}
fun updateBoard(board: Array<CharArray>, c: IntArray): Array<CharArray> {
if (board[c[0]][c[1]] == 'M') {
board[c[0]][c[1]] = 'X'
return board
} else {
row = board.size
col = board[0].size
dfs(board, c[0], c[1])
}
return board
}
companion object {
private val DIRECTION = arrayOf(
intArrayOf(1, 0),
intArrayOf(-1, 0),
intArrayOf(0, 1),
intArrayOf(0, -1),
intArrayOf(-1, -1),
intArrayOf(-1, 1),
intArrayOf(1, -1),
intArrayOf(1, 1)
)
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,859 | LeetCode-in-Kotlin | MIT License |
kotlin/structures/CentroidDecomposition.kt | polydisc | 281,633,906 | true | {"Java": 540473, "Kotlin": 515759, "C++": 265630, "CMake": 571} | package structures
import java.util.stream.Stream
// https://sai16vicky.wordpress.com/2014/11/01/divide-and-conquer-on-trees-centroid-decomposition/
object CentroidDecomposition {
fun calcSizes(tree: Array<List<Integer>>, size: IntArray, deleted: BooleanArray, u: Int, p: Int) {
size[u] = 1
for (v in tree[u]) {
if (v == p || deleted[v]) continue
calcSizes(tree, size, deleted, v, u)
size[u] += size[v]
}
}
fun findTreeCentroid(
tree: Array<List<Integer>>,
size: IntArray,
deleted: BooleanArray,
u: Int,
p: Int,
vertices: Int
): Int {
for (v in tree[u]) {
if (v == p || deleted[v]) continue
if (size[v] > vertices / 2) {
return findTreeCentroid(tree, size, deleted, v, u, vertices)
}
}
return u
}
// static void dfs(List<Integer>[] tree, boolean[] deleted, int u, int p) {
// for (int v : tree[u]) {
// if (v == p || deleted[v]) continue;
// dfs(tree, deleted, v, u);
// }
// }
fun decompose(tree: Array<List<Integer>>, size: IntArray, deleted: BooleanArray, u: Int, total: Int) {
calcSizes(tree, size, deleted, u, -1)
val centroid = findTreeCentroid(tree, size, deleted, u, -1, total)
deleted[centroid] = true
// process centroid vertex here
// dfs(tree, deleted, centroid, -1);
System.out.println(centroid)
for (v in tree[centroid]) {
if (deleted[v]) continue
decompose(tree, size, deleted, v, size[v])
}
}
fun centroidDecomposition(tree: Array<List<Integer>>) {
val n = tree.size
decompose(tree, IntArray(n), BooleanArray(n), 0, n)
}
// Usage example
fun main(args: Array<String?>?) {
val n = 4
val tree: Array<List<Integer>> = Stream.generate { ArrayList() }.limit(n).toArray { _Dummy_.__Array__() }
tree[3].add(0)
tree[0].add(3)
tree[3].add(1)
tree[1].add(3)
tree[3].add(2)
tree[2].add(3)
centroidDecomposition(tree)
}
}
| 1 | Java | 0 | 0 | 4566f3145be72827d72cb93abca8bfd93f1c58df | 2,207 | codelibrary | The Unlicense |
src/main/kotlin/com/danielmichalski/algorithms/data_structures/_11_graph_traversal/UndirectedGraph.kt | DanielMichalski | 288,453,885 | false | {"Kotlin": 101963, "Groovy": 19141} | package com.danielmichalski.algorithms.data_structures._11_graph_traversal
import java.util.*
import kotlin.collections.ArrayList
import kotlin.collections.HashSet
class UndirectedGraph {
private val adjacencyList: MutableList<Node> = ArrayList()
fun addVertex(vertex: String) {
val node = findNode(vertex)
if (node == null) {
val newNode = Node(vertex, mutableListOf())
this.adjacencyList.add(newNode)
}
}
fun addEdge(vertex1: String, vertex2: String) {
val node1 = findNode(vertex1)
val node2 = findNode(vertex2)
node1!!.getConnections().add(vertex2)
node2!!.getConnections().add(vertex1)
}
fun depthFirstSearchRecursive(vertex: String): MutableList<Node> {
val result: MutableList<Node> = ArrayList()
val visited: MutableSet<String> = HashSet()
val node = findNode(vertex)
fun dfs(node: Node?) {
if (node == null) {
return
}
visited.add(node.getVertex())
result.add(node)
node.getConnections()
.map { con -> findNode(con) }
.forEach { neighbour ->
if (!visited.contains(neighbour?.getVertex())) {
dfs(neighbour)
}
}
}
dfs(node)
return result
}
fun depthFirstSearchIterative(vertex: String): MutableList<Node> {
val stack = ArrayDeque<Node>()
stack.push(findNode(vertex)!!)
val result: MutableList<Node> = ArrayList()
val visited: MutableSet<String> = HashSet()
var currentVertex: Node?
visited.add(vertex)
while (stack.size > 0) {
currentVertex = stack.pop()
result.add(currentVertex)
currentVertex.getConnections()
.map { con -> findNode(con) }
.filter { neighbour -> !visited.contains(neighbour!!.getVertex()) }
.forEach { neighbour ->
visited.add(neighbour!!.getVertex())
stack.push(neighbour)
}
}
return result
}
fun breadthFirstSearch(vertex: String): MutableList<Node> {
val queue = ArrayDeque<Node>()
queue.push(findNode(vertex)!!)
val result: MutableList<Node> = ArrayList()
val visited: MutableSet<String> = HashSet()
var currentVertex: Node?
visited.add(vertex)
while (queue.size > 0) {
currentVertex = queue.pop()
result.add(currentVertex)
currentVertex.getConnections()
.map { con -> findNode(con) }
.filter { neighbour -> !visited.contains(neighbour!!.getVertex()) }
.forEach { neighbour ->
visited.add(neighbour!!.getVertex())
queue.add(neighbour)
}
}
return result
}
override fun toString(): String {
return "UndirectedGraph(adjacencyList='$adjacencyList')\n"
}
private fun findNode(vertex: String): Node? {
return adjacencyList.stream()
.filter { node -> node.getVertex() == vertex }
.findFirst()
.orElse(null)
}
}
| 0 | Kotlin | 1 | 7 | c8eb4ddefbbe3fea69a172db1beb66df8fb66850 | 3,403 | algorithms-and-data-structures-in-kotlin | MIT License |
src/main/kotlin/com/nibado/projects/advent/search/Dijkstra.kt | nielsutrecht | 47,550,570 | false | null | package com.nibado.projects.advent.search
import com.nibado.projects.advent.Point
import com.nibado.projects.advent.collect.NumberGrid
import com.nibado.projects.advent.graph.Graph
import java.util.*
object Dijkstra : GraphShortestPath, GridShortestPath {
override fun <N, E : Number> shortestPath(graph: Graph<N, E>, from: N, to: N): List<N> {
val distances = graph.nodes().associateWith { Double.POSITIVE_INFINITY }.toMutableMap()
val unvisitedSet = graph.nodes().toMutableSet()
val adjacency = mutableMapOf<N, N>()
distances[from] = 0.0
var current = from
val frontier = PriorityQueue<Pair<N, Double>> { a, b -> a.second.compareTo(b.second) }
while(unvisitedSet.isNotEmpty() && unvisitedSet.contains(to)) {
val neighbors = graph.edges(current).filter { unvisitedSet.contains(it.to.key) }
neighbors.forEach { (d, node) ->
val distance = d.toDouble()
val next = node.key
if (distances[current]!! + distance < distances[next]!!) {
distances[next] = distances[current]!! + distance
adjacency[next] = current
}
frontier.add(next to distances[next]!!)
}
unvisitedSet -= current
frontier.removeIf { it.first == current }
if (current == to) {
break
}
if (frontier.isNotEmpty()) {
current = frontier.poll().first
}
}
val path = mutableListOf(to)
while(adjacency.containsKey(path.last())) {
path += adjacency[path.last()]!!
}
return path.reversed()
}
override fun <N: Number> shortestPath(grid: NumberGrid<N>, from: Point, to: Point) : List<Point> =
shortestPath(grid.toGraph(), from, to)
} | 1 | Kotlin | 0 | 15 | b4221cdd75e07b2860abf6cdc27c165b979aa1c7 | 1,880 | adventofcode | MIT License |
src/Day03.kt | Iamlooker | 573,103,288 | false | {"Kotlin": 5744} | fun main() {
val charactersSmall = "abcdefghijklmnopqrstuvwxyz"
val charactersCaps = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
val characters = charactersSmall + charactersCaps
val range = (1..52).toList()
val priority = range.associateBy { characters[it - 1] }
fun part1(input: List<String>): Int = input.sumOf { items ->
val compartments = items.chunked(items.length / 2)
val test = compartments.first().find { firstItem ->
compartments.last().any { secondItem ->
firstItem == secondItem
}
}
test?.let { priority[it]!! } ?: 0
}
fun part2(input: List<String>): Int {
return 0
}
// val testInput = readInput("Day03_test")
// println(part1(testInput))
val input = readInput("Day03")
println(part1(input))
}
| 0 | Kotlin | 0 | 0 | 91a335428a99db2f2b1fd5c5f51a6b1e55ae2245 | 829 | aoc-2022-kotlin | Apache License 2.0 |
kotlin/1985-find-the-kth-largest-integer-in-the-array.kt | neetcode-gh | 331,360,188 | false | {"JavaScript": 473974, "Kotlin": 418778, "Java": 372274, "C++": 353616, "C": 254169, "Python": 207536, "C#": 188620, "Rust": 155910, "TypeScript": 144641, "Go": 131749, "Swift": 111061, "Ruby": 44099, "Scala": 26287, "Dart": 9750} | /*
* Using a minHeap (And BigInteger, alternativly you can compare strings too)
*/
class Solution {
fun kthLargestNumber(nums: Array<String>, k: Int): String {
val minHeap = PriorityQueue<BigInteger>{ a, b ->
if(a < b)
1
else
-1
}
nums.forEach {
minHeap.add(it.toBigInteger())
}
var kth = k
while(kth > 1) {
minHeap.poll()
kth--
}
return minHeap.poll().toString()
}
}
/*
* Using a maxHeap (And comparing strings, alternativly you can use BigInteger too)
*/
class Solution {
fun kthLargestNumber(nums: Array<String>, k: Int): String {
val minHeap = PriorityQueue<String>{ a, b ->
if(a.length > b.length)
1
else if(a.length < b.length)
-1
else {
var toReturn = 0
for(i in 0 until a.length) {
if(a[i] > b[i]) {
toReturn = 1
break
} else if(a[i] < b[i]){
toReturn = -1
break
}
}
toReturn
}
}
nums.forEach {
minHeap.add(it)
if(minHeap.size > k) minHeap.poll()
}
return minHeap.peek()
}
}
| 337 | JavaScript | 2,004 | 4,367 | 0cf38f0d05cd76f9e96f08da22e063353af86224 | 1,429 | leetcode | MIT License |
Successive_prime_differences/Kotlin/src/SuccessivePrimeDifferences.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} | private fun sieve(limit: Int): Array<Int> {
val primes = mutableListOf<Int>()
primes.add(2)
val c = BooleanArray(limit + 1) // composite = true
// no need to process even numbers > 2
var p = 3
while (true) {
val p2 = p * p
if (p2 > limit) {
break
}
var i = p2
while (i <= limit) {
c[i] = true
i += 2 * p
}
do {
p += 2
} while (c[p])
}
var i = 3
while (i <= limit) {
if (!c[i]) {
primes.add(i)
}
i += 2
}
return primes.toTypedArray()
}
private fun successivePrimes(primes: Array<Int>, diffs: Array<Int>): List<List<Int>> {
val results = mutableListOf<List<Int>>()
val dl = diffs.size
outer@ for (i in 0 until primes.size - dl) {
val group = IntArray(dl + 1)
group[0] = primes[i]
for (j in i until i + dl) {
if (primes[j + 1] - primes[j] != diffs[j - i]) {
continue@outer
}
group[j - i + 1] = primes[j + 1]
}
results.add(group.toList())
}
return results
}
fun main() {
val primes = sieve(999999)
val diffsList = arrayOf(
arrayOf(2),
arrayOf(1),
arrayOf(2, 2),
arrayOf(2, 4),
arrayOf(4, 2),
arrayOf(6, 4, 2)
)
println("For primes less than 1,000,000:-\n")
for (diffs in diffsList) {
println(" For differences of ${diffs.contentToString()} ->")
val sp = successivePrimes(primes, diffs)
if (sp.isEmpty()) {
println(" No groups found")
continue
}
println(" First group = ${sp[0].toTypedArray().contentToString()}")
println(" Last group = ${sp[sp.size - 1].toTypedArray().contentToString()}")
println(" Number found = ${sp.size}")
println()
}
}
| 0 | D | 0 | 4 | c2a9f154a5ae77eea2b34bbe5e0cc2248333e421 | 1,923 | rosetta | MIT License |
kotlin/530.Minimum Absolute Difference in BST(二叉搜索树的最小绝对差).kt | learningtheory | 141,790,045 | false | {"Python": 4025652, "C++": 1999023, "Java": 1995266, "JavaScript": 1990554, "C": 1979022, "Ruby": 1970980, "Scala": 1925110, "Kotlin": 1917691, "Go": 1898079, "Swift": 1827809, "HTML": 124958, "Shell": 7944} | /**
<p>Given a binary search tree with non-negative values, find the minimum <a href="https://en.wikipedia.org/wiki/Absolute_difference">absolute difference</a> between values of any two nodes.</p>
<p>
<b>Example:</b>
<pre>
<b>Input:</b>
1
\
3
/
2
<b>Output:</b>
1
<b>Explanation:</b>
The minimum absolute difference is 1, which is the difference between 2 and 1 (or between 2 and 3).
</pre>
</p>
<p><b>Note:</b>
There are at least two nodes in this BST.
</p><p>给定一个所有节点为非负值的二叉搜索树,求树中任意两节点的差的绝对值的最小值。</p>
<p><strong>示例 :</strong></p>
<pre>
<strong>输入:</strong>
1
\
3
/
2
<strong>输出:</strong>
1
<strong>解释:
</strong>最小绝对差为1,其中 2 和 1 的差的绝对值为 1(或者 2 和 3)。
</pre>
<p><strong>注意: </strong>树中至少有2个节点。</p>
<p>给定一个所有节点为非负值的二叉搜索树,求树中任意两节点的差的绝对值的最小值。</p>
<p><strong>示例 :</strong></p>
<pre>
<strong>输入:</strong>
1
\
3
/
2
<strong>输出:</strong>
1
<strong>解释:
</strong>最小绝对差为1,其中 2 和 1 的差的绝对值为 1(或者 2 和 3)。
</pre>
<p><strong>注意: </strong>树中至少有2个节点。</p>
**/
/**
* Definition for a binary tree node.
* class TreeNode(var `val`: Int = 0) {
* var left: TreeNode? = null
* var right: TreeNode? = null
* }
*/
class Solution {
fun getMinimumDifference(root: TreeNode?): Int {
}
} | 0 | Python | 1 | 3 | 6731e128be0fd3c0bdfe885c1a409ac54b929597 | 1,586 | leetcode | MIT License |
src/main/kotlin/com/ikueb/advent18/Day03.kt | h-j-k | 159,901,179 | false | null | package com.ikueb.advent18
import com.ikueb.advent18.model.Point
object Day03 {
private const val PATTERN = "#(\\d+) @ (\\d+),(\\d+): (\\d+)x(\\d+)"
fun getOverlappingRegions(input: List<String>) =
parseAndFindOverlappingPoints(input).second.count()
fun getNonOverlappingId(input: List<String>): Int {
val (claims, overlaps) = parseAndFindOverlappingPoints(input)
val overlappingIds = overlaps.flatMapTo(mutableSetOf()) { it.value }
return claims.find { it -> !overlappingIds.contains(it) }?.id
?: throw IllegalArgumentException("No results.")
}
private fun parseAndFindOverlappingPoints(input: List<String>) =
input.parseWith(PATTERN) { (id, x, y, xSize, ySize) ->
Claim(id.toInt(), x.toInt(), y.toInt(), xSize.toInt(), ySize.toInt())
}.let { claims -> claims to getPointCounts(claims).filterValues { it.size >= 2 } }
private fun getPointCounts(input: List<Claim>) =
input.map { claim -> claim.getPoints().associateTo(mutableMapOf()) { it to setOf(claim) } }
.reduce { a, b -> a.collate(b) { x, y -> x.plus(y) } }
private fun <K, V> MutableMap<K, V>.collate(other: Map<K, V>, reducer: (V, V) -> V) =
apply { other.forEach { merge(it.key, it.value, reducer) } }
}
private data class Claim(val id: Int, val x: Int, val y: Int, val xSize: Int, val ySize: Int) {
private fun getXRange() = x..(x + xSize - 1)
private fun getYRange() = y..(y + ySize - 1)
fun getPoints() = getXRange()
.flatMap { x -> getYRange().map { y -> Point(x, y) } }
.toSet()
} | 0 | Kotlin | 0 | 0 | f1d5c58777968e37e81e61a8ed972dc24b30ac76 | 1,656 | advent18 | Apache License 2.0 |
grow/src/main/java/com/suheng/grow/grammar/Grammar.kt | ssywbj | 189,440,773 | false | null | package com.suheng.grow.grammar
class Grammar {
private val pi = 3.14 //语句结束不用写分号
private var y: Int = 11
private val items = listOf("kiwifruit", "apple", "banana")
private val list = listOf(5, -1, 0, 9, 13)
private val map = mapOf("a" to 1, "b" to 2, "c" to 3) //to用于(key, value)映射
fun assignment() {
//val:定义只读变量且只能赋值一次
val a: Int = 1 //定义Int变量并赋值
//a = 35; error: Val cannot be reassigned
val b = 2 //定义变量并赋值,省略Int,根据数值“2”自动推断出类型
val c: Int //如果只定义变量但未赋值,不能省略类型
c = 3 //明确赋值
//var:定义可变变量
var x = 45
x = 3
println("val: a = $a, b = $b, c = $c, π = $pi, var: x = $x, ++y = ${++y}")
//字符串
val s1 = "x is $x"
x = 56
val s2 = "${s1.replace("is", "was")}, but now is $x"
println("$s1; $s2") //$变量或表示式的引用方式被称为字符串内插
}
fun sum(a: Int, b: Int): Int { //定义函数:返回值类型为Int
return a + b
}
//定义函数:表达式作为函数体,自动推断返回值类型(简写)
fun sum(a: Int, b: Int, c: Int) = a + b + c //Only expressions are allowed here
fun printUnit(a: Int, b: Int): Unit { //定义函数:返回值类型为无意义的值
println("$a + $b = ${a + b}")
}
//定义函数:返回值类型为无意义的值,Unit可省且简写,“$对象”表示对对象引用,“{}”表示对象的运算,“()”表示数值的运算
fun printUnit(a: Int, b: Int, c: Int) =
println("a, $a + $b + $c = ${a + b + c}, " + { a + b } + ", " + (a + b))
fun maxOf(a: Int, b: Float): Int { //if条件表达式
if (a > b) {
return a
} else {
return if (a > b) a else b.toInt()
}
//等价:return if (a > b) a else b.toInt()
}
fun maxOf(a: Int, b: Double): Int { //if条件表达式
return if (a > b) a else b.toInt()
}
fun maxOf(a: Int, b: Int) = if (a > b) a else b //if条件表达式
private fun parseInt(str: String): Int? { //当某个变量的值可以为null时,必须在声明处的类型后添加?来标识该引用可为空
return str.toIntOrNull() //如果str的内容不是数字返回 null
}
fun printParseInt(arg1: String, arg2: String) {
val x = parseInt(arg1)
val y = parseInt(arg2)
//println("$x * $y = ${x * y}") //直接使用'x * y'会导致编译错误,因为他们可能为null
if (x != null && y != null) { //需进行非空判断
println("$x * $y = ${x * y}") //在空检测后,x与y会自动转换为非空值(non-nullable)
} else {
println("either '$arg1' or '$arg2' is not a number")
}
}
//'is'运算符检测表达式是否为某类型的实例:如果一个不可变的局部变量或属性已经判断出为某类型,
// 那么检测后的分支中可以直接当作该类型使用,无需显式转换。
private fun getStringLength(obj: Any): Int? {
if (obj is String) {
return obj.length //'obj'在该条件分支内自动转换成String
}
return null //在离开类型检测分支后,'obj'仍然是Any类型
}
private fun getStringLen(obj: Any): Int? {
if (obj !is String) return null
return obj.length //'obj'在这一分支内自动转换成String
}
private fun getStringLen2(obj: Any): Int? {
//'obj'在'&&'的右边自动转换成String
if (obj is String && obj.length > 0) {
return obj.length
}
return null
}
fun printLength(obj: Any) {
println("'$obj' string length is ${getStringLength(obj) ?: "error, not a string"}")
}
//使用区间(range):使用in运算符来检测某个数字是否在指定区间内
fun describeIn(x: Int) {
val y = 11
if (x in 4..y + 1) { //..:闭区间运算符,包含(y+1)。闭区间,[a,b]={a<=x<=b};开区间,(a,b)={a<x<b}。
println("'..', $x in range[4, ${y + 1}]")
}
if (x in 4 until y + 1) { //until:半开区间运算符,不包含(y+1)。左闭右开区间,[a,b)={a<=x<b};左开右闭区间,(a,b]={a<x<=b}。
println("'until', $x in range(4, ${y + 1}]")
}
if (x !in 4..y + 1) {
println("$x out range(4, ${y + 1})/]")
}
}
//when表达式
fun chooseWhen(obj: Any): String =
when (obj) { //使用when进行类型判断
1 -> "One"
"Hello" -> "Greeting"
is Long -> "Long"
!is String -> "Not a string"
else -> "Unknown"
}
//for循环
fun printForAndIteration() {
for (item in items) { //集合迭代
print("$item\t")
}
println()
for (index in items.indices) { //区间迭代,list.indices:数组下标区间,items.size:数组长度
println("item at $index is ${items[index]}, items.indices = ${items.indices}, items.size = ${items.size}")
}
print("数列迭代:")
for (x in 1..9 step 3) { //数列迭代:从第一个开始,每三个输出一次(初始值为1差值为3的递增等差数列,下标从零开始)
print("$x\t")
}
println()
print("数列迭代:")
for (x in 9 downTo 0 step 4) { //数列迭代:从第一个开始,每四个输出一次(初始值为9差值为4的递减等差数列,下标从零开始)
print("$x\t")
}
println()
when {
"orange" in items -> println("juicy")
"apple" in items -> println("apple is fine too")
}
items.filter { it.startsWith("b") } //filter过滤list
.map { it.toUpperCase() }
.forEach { (println(it)) }
list.filter { x -> x > 0 } //filter过滤list
//list.filter { it > 0 } //或这样简写
}
//while循环
fun printWhile() {
var index = 0
while (index < items.size) {
println("while, item at $index is ${items[index++]}")
}
}
//创建DTOs(POJOs/POCOs):加data
data class Customer(val name: String, val email: String)
//函数的默认参数
private fun foo(a: Int = 0, b: String = "5") = a + b.toInt()
//访问或遍历map/pair,key、value可以改成任意名字
fun traversalMap() {
for ((key, value) in map) { //遍历map
print("($key, $value)\t")
}
println()
println(map["a"]) //访问map,输出单个value
println(map["b"].toString() + "\t" + map["g"]) //访问map,输出单个value
println("$map") //访问map,输出map结构{key1=value1, key2=value2, ...}
}
//If not null 缩写
fun ifNullAbbreviation() {
val x = parseInt("13")
println(x?.times(2)) //如果x为空,那么输出null;否则乘以2后输出
println(parseInt("3g")?.times(3)) //输出null
//如果x为空,那么输出null;否则判断乘以2后是否为空,空则输出null,非空则输出比较结果(等于为0,大于为1,小于为-1)
println(x?.times(2)?.compareTo(27))
}
//返回when表达式,全写
/*private fun transformWhen(a: Int): String? {
return when (a) {
1 -> "one"
2 -> "Twoqwe"
3 -> "3"
-1 -> "smaller than 0"
else -> null
}
}*/
//返回when表达式,简写
private fun transform(a: Int): String? = when (a) {
1 -> "one"
2 -> "Twoqwe"
3 -> "3"
-1 -> "smaller than 0"
else -> null
}
fun subSequence() {
//subSequence(startIndex: Int, endIndex: Int):[startIndex, endIndex),从第startIndex个开始(包括),
// 到第endIndex个结束(不包括),可能会报数组越界异常
println(transform(1)?.subSequence(1, 3)?.toString()) //one->ne
println(transform(2)?.subSequence(1, 4)?.toString()) //Twoqwe->woq
println(transform(3)?.subSequence(0, 1)?.toString()) //3->3
println(transform(-1)?.subSequence(1, 4)?.toString())
println(transform(0)?.subSequence(1, 4)?.toString())
}
fun exchangeTwoValue() {
var a = 11
var b = 22
println("before exchange: a = $a, b = $b")
a = b.also { b = a }
println("after exchange: a = $a, b = $b")
}
}
| 0 | Kotlin | 0 | 0 | da846c399e5dd3c177983755343f575e685f9735 | 8,725 | HomeShare | Apache License 2.0 |
src/Day09.kt | MarkRunWu | 573,656,261 | false | {"Kotlin": 25971} | fun main() {
data class Movement(val offsetX: Int, val offsetY: Int);
data class Position(var x: Int, var y: Int) {
fun getNextStepPosition(target: Position): Position? {
val nextX = if (kotlin.math.abs(target.x - this.x) > 1) {
this.x + if (target.x - this.x > 0) 1 else -1
} else null
val nextY = if (kotlin.math.abs(target.y - this.y) > 1) {
this.y + if (target.y - this.y > 0) 1 else -1
} else null
if (nextX != null || nextY != null) {
return Position(nextX ?: target.x, nextY ?: target.y)
}
return null
}
}
fun dumpMap(map: Array<Array<Boolean>>) {
map.map { it ->
println(it.map { v ->
if (v) "#" else "."
}.joinToString("") { it })
}
println()
}
fun parseCommands(input: List<String>): List<Movement> {
return input.map {
val commands = it.split(' ')
when (commands[0]) {
"R" -> Movement(commands[1].toInt(), 0)
"U" -> Movement(0, commands[1].toInt())
"L" -> Movement(-commands[1].toInt(), 0)
"D" -> Movement(0, -commands[1].toInt())
else -> throw IllegalStateException("unknown command: ${commands[0]}")
}
}
}
fun simulate(ropeCount: Int, headMovements: List<Movement>): List<Array<Array<Boolean>>> {
val currentRopePositions = Array(ropeCount) {
Position(0, 0)
}
val ropeMoveResults = Array(ropeCount) {
ArrayList<Position>()
}
ropeMoveResults.forEachIndexed { index, positions ->
positions.add(currentRopePositions[index].copy())
}
for (movement in headMovements) {
val xSteps = kotlin.math.abs(movement.offsetX)
val ySteps = kotlin.math.abs(movement.offsetY)
if (xSteps > 0) {
val step = if (movement.offsetX > 0) 1 else -1
for (i in 0 until xSteps) {
currentRopePositions[0].x += step
ropeMoveResults[0].add(currentRopePositions[0].copy())
for (k in 1 until ropeMoveResults.size) {
val curPos = currentRopePositions[k]
val nextPos = curPos.getNextStepPosition(currentRopePositions[k - 1])
if (nextPos != null) {
currentRopePositions[k] = nextPos.copy()
ropeMoveResults[k].add(nextPos.copy())
}
}
}
}
if (ySteps > 0) {
val step = if (movement.offsetY > 0) 1 else -1
for (i in 0 until ySteps) {
currentRopePositions[0].y += step
ropeMoveResults[0].add(currentRopePositions[0].copy())
for (k in 1 until ropeMoveResults.size) {
val curPos = currentRopePositions[k]
val nextPos = curPos.getNextStepPosition(currentRopePositions[k - 1])
if (nextPos != null) {
currentRopePositions[k] = nextPos.copy()
ropeMoveResults[k].add(nextPos.copy())
}
}
}
}
}
val maxX = ropeMoveResults.maxOf { it -> it.maxOf { it.x } }
val maxY = ropeMoveResults.maxOf { it -> it.maxOf { it.y } }
val minX = ropeMoveResults.minOf { it -> it.minOf { it.x } }
val minY = ropeMoveResults.minOf { it -> it.minOf { it.y } }
val width = maxX - minX + 1
val height = maxY - minY + 1
val ropeMovementMapList = ropeMoveResults.map {
Array(height) {
Array(width) {
false
}
}
}
for (i in ropeMoveResults.indices) {
for (pos in ropeMoveResults[i]) {
ropeMovementMapList[i][pos.y - minY][pos.x - minX] = true
}
}
return ropeMovementMapList
}
fun part1(input: List<String>): Int {
val movements = parseCommands(input)
val result = simulate(2, movements)
dumpMap(result.last())
return result.last().sumOf { it -> it.count { it } }
}
fun part2(input: List<String>): Int {
val movements = parseCommands(input)
val result = simulate(10, movements)
dumpMap(result.last())
return result.last().sumOf { it -> it.count { it } }
}
val input = readInput("Day09")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | ced885dcd6b32e8d3c89a646dbdcf50b5665ba65 | 4,785 | AOC-2022 | Apache License 2.0 |
src/main/kotlin/sorting/QuickSort.kt | Pawlllosss | 526,668,214 | false | {"Kotlin": 61939} | package sorting
class QuickSort {
fun sort(input: List<Int>): List<Int> {
val arrayToSort = ArrayList(input)
sort(arrayToSort, 0, input.size - 1)
return arrayToSort
}
private fun sort(input: MutableList<Int>, low: Int, high: Int) {
if (high > low) {
val partitionIndex = partition(input, low, high)
sort(input, low, partitionIndex - 1)
sort(input, partitionIndex + 1, high)
}
}
private fun partition(input: MutableList<Int>, low: Int, high: Int): Int {
val elementReference = input[high]
var indexLowerThanReference = low
for(i in low .. high) {
val currentElement = input[i]
if (currentElement < elementReference) {
swap(input, i, indexLowerThanReference)
indexLowerThanReference++
}
}
swap(input, indexLowerThanReference, high)
return indexLowerThanReference
}
private fun swap(
input: MutableList<Int>,
i: Int,
j: Int,
) {
val tmp = input[i]
input[i] = input[j]
input[j] = tmp
}
}
fun main() {
val listToSort = listOf(6, 4, 2, 8, 1, 13, 11)
val sortedList = QuickSort().sort(listToSort)
print(sortedList)
} | 0 | Kotlin | 0 | 0 | 94ad00ca3e3e8ab7a2cb46f8846196ae7c55c8b4 | 1,318 | Kotlin-algorithms | MIT License |
problems/2904/kotlin/Solution.kt | misut | 678,196,869 | false | {"Kotlin": 32683} | class Solution {
fun shortestBeautifulSubstring(s: String, k: Int): String {
val init = s.indexOfFirst { it == '1' }
if (init == -1) {
return ""
}
val indices = mutableListOf(init)
for (i in 1..<k) {
val idx = s.substring(indices.last() + 1).indexOfFirst { it == '1' }
if (idx == -1) {
return ""
}
indices.add(idx + indices.last() + 1)
}
println(indices)
var min = indices.first() to indices.last()
while (true) {
val idx = s.substring(indices.last() + 1).indexOfFirst { it == '1' }
if (idx == -1) {
break
}
indices.add(idx + indices.last() + 1)
indices.removeFirst()
if (min.second - min.first > indices.last() - indices.first() ||
(min.second - min.first == indices.last() - indices.first() &&
s.slice(min.first..min.second) > s.slice(indices.first()..indices.last()))
) {
min = indices.first() to indices.last()
}
}
return s.slice(min.first..min.second)
}
}
| 0 | Kotlin | 0 | 0 | 52fac3038dd29cb8eefebbf4df04ccf1dda1e332 | 1,201 | ps-leetcode | MIT License |
src/Test.kt | ilinqh | 390,190,883 | false | {"Kotlin": 382147, "Java": 32712} | import easy._2697LexicographicallySmallestPalindrome
import easy._2824CountPairsWhoseSumIsLessThanTarget
import medium._1276NumberOfBurgersWithNoWasteOfIngredients
import medium._1410HtmlEntityParser
import java.math.BigInteger
import java.security.MessageDigest
import java.util.Collections
fun printResult(solve: Any?) {
solve ?: return
when (solve) {
is ListNode -> {
solve.toArray().forEach {
print(" $it ")
}
}
is Array<*> -> {
solve.forEach {
when (it) {
is Array<*> -> {
it.forEach { i ->
print(" $i ")
}
}
is IntArray -> {
it.forEach { i ->
print(" $i ")
}
println()
}
else -> {
print(" $it ")
}
}
}
}
is IntArray -> {
solve.forEach {
print(" $it ")
}
}
else -> {
print(solve)
}
}
}
fun md5(input: String): String {
val md = MessageDigest.getInstance("MD5")
val messageDigest = md.digest(input.toByteArray())
val no = BigInteger(1, messageDigest)
var hashText = no.toString(16)
while (hashText.length < 32) {
hashText = "0$hashText"
}
return hashText
}
data class Item(
val name: String?,
val age: Int = 1,
val sex: Int = 1,
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Item
if (name != other.name) return false
return sex == other.sex
}
override fun hashCode(): Int {
var result = name?.hashCode() ?: 0
result = 31 * result + sex
return result
}
}
fun main() {
val root = TreeNode(1)
val leftNode = TreeNode(3)
val rightNode = TreeNode(2)
root.left = leftNode
leftNode.right = rightNode
val solution = _1276NumberOfBurgersWithNoWasteOfIngredients.Solution()
val firstListNode = intArrayOf(1, 4, 3, 2, 5, 2).toListNode() ?: ListNode(1)
val secondListNode = intArrayOf(1, 3, 4).toListNode() ?: ListNode(1)
val thirdListNode = intArrayOf(2, 6).toListNode() ?: ListNode(1)
// val solve = solution.threeSum(intArrayOf(-1, 0, 1, 2, -1, -4, -2, -3, 3, 0, 4))
// val solve = solution.threeSumClosest(intArrayOf(1, 1, -1, -1, 3), -1)
// val solve = solution.fourSum(intArrayOf(1, 0, -1, 0, -2, 2), 0)
// val solve = solution.searchRange(intArrayOf(1, 1, 2, 2, 9, 9, 9, 10, 11, 12), 10)
val nodeArray = Array<ListNode?>(3) {
ListNode(0)
}
nodeArray[0] = firstListNode
nodeArray[1] = secondListNode
nodeArray[2] = thirdListNode
val array = Array(1) {
IntArray(4)
}
// array[0] = intArrayOf(1, 2, 3, 4)
// array[1] = intArrayOf(5, 6, 7, 8)
// array[2] = intArrayOf(9, 10, 11, 12)
// array[3] = intArrayOf(13, 14, 15, 16)
array[0] = intArrayOf(1, 3)
// array[1] = intArrayOf(10,11,16,20)
// array[2] = intArrayOf(23,30,34,60)
// array[1] = intArrayOf(5, 6)
// array[2] = intArrayOf(1, 1)
val listNode = intArrayOf(1, 2, 3, 4, 5).toListNode()
/**
* n = 3, edges = [[0,1,100],[1,2,100],[0,2,500]]
src = 0, dst = 2, k = 1
*/
val strs: Array<String> = arrayOf<String>("eat", "tea", "tan", "ate", "nat", "bat")
// [['A','B','C','E'],['S','F','C','S'],['A','D','E','E']], word = "ABCCED"
val board =
arrayOf(
charArrayOf('A', 'B', 'C', 'E'),
charArrayOf('S', 'F', 'C', 'S'),
charArrayOf('A', 'D', 'E', 'E'),
)
val word = "ABCESCF"
val boards = arrayOf(
charArrayOf('5', '3', '.', '.', '7', '.', '.', '.', '.'),
charArrayOf('6', '.', '.', '1', '9', '5', '.', '.', '.'),
charArrayOf('.', '9', '8', '.', '.', '.', '.', '6', '.'),
charArrayOf('8', '.', '.', '.', '6', '.', '.', '.', '3'),
charArrayOf('4', '.', '.', '8', '.', '3', '.', '.', '1'),
charArrayOf('7', '.', '.', '.', '2', '.', '.', '.', '6'),
charArrayOf('.', '6', '.', '.', '.', '.', '2', '8', '.'),
charArrayOf('.', '.', '.', '4', '1', '9', '.', '.', '5'),
charArrayOf('.', '.', '.', '.', '8', '.', '.', '7', '9'),
)
val matrix = arrayOf(
intArrayOf(1, 3, 1),
intArrayOf(1, 5, 1),
intArrayOf(4, 2, 1),
// intArrayOf(0, 0, 0),
)
// val matrix = arrayOf(
// intArrayOf(1, 4, 7, 11, 15),
// intArrayOf(2, 5, 8, 12, 19),
// intArrayOf(3, 6, 9, 16, 22),
// intArrayOf(10, 13, 14, 17, 24),
// intArrayOf(18, 21, 23, 26, 30)
// )
// val circularQueue = _622DesignCircularQueue.MyCircularQueue(3) // 设置长度为 3
// circularQueue.enQueue(1) // 返回 true
// circularQueue.enQueue(2) // 返回 true
// circularQueue.enQueue(3) // 返回 true
// circularQueue.enQueue(4) // 返回 false,队列已满
// circularQueue.Rear() // 返回 3
// circularQueue.isFull() // 返回 true
// circularQueue.deQueue() // 返回 true
// circularQueue.enQueue(4) // 返回 true
// circularQueue.Rear() // 返回 4
val treeRoot = arrayListOf(1, 2, 3, 4, null).toTreeNode()
//[100,200,100],[200,50,200],[100,200,100]
// [[5,10],[2,5],[4,7],[3,9]]
// "abcde"
//["a","bb","acd","ace"]
// [[0,0],[1,1],[2,2],[3,4],[3,5],[4,4],[4,5]]
// [5,3],[4,0],[2,1]
// [9,8],[1,5],[10,12],[18,6],[2,4],[14,3]
val solve = solution.numOfBurgers(2385088, 164763
// "seven"
// listOf(-6,2,5,-2,-7,-1,3), -2
/*"x > y && x < y is always false"*/
/*arrayOf(intArrayOf(5,1,2), intArrayOf(4,0,3)*//*, intArrayOf(2, 1)*//*),
arrayOf(
intArrayOf(12,10,15),
intArrayOf(20,23,8),
intArrayOf(21,7,1),
intArrayOf(8,1,13),
intArrayOf(9,10,25),
intArrayOf(5,3,2)
)*/
)
// printResult(md5("abcdefghj123456789xiguagame"))
// val a = 1.inv()
// val a = 1 xor 2
//
// val arrayList = ArrayList<Item>()
// arrayList.add(Item("name", 1, 1))
// arrayList.add(Item("name1", 2, 2))
// arrayList.add(Item("name", 3, 1))
printResult(solve)
// val a: Int = 128
// val boxedA: Int? = a
// val anotherBoxedA: Int? = a
// print(boxedA == anotherBoxedA)
// print(boxedA === anotherBoxedA)
}
| 0 | Kotlin | 0 | 0 | 8d2060888123915d2ef2ade293e5b12c66fb3a3f | 6,667 | AlgorithmsProject | Apache License 2.0 |
src/main/kotlin/nl/jackploeg/aoc/_2023/calendar/day06/Day06.kt | jackploeg | 736,755,380 | false | {"Kotlin": 318734} | package nl.jackploeg.aoc._2023.calendar.day06
import nl.jackploeg.aoc.generators.InputGenerator.InputGeneratorFactory
import nl.jackploeg.aoc.utilities.readStringFile
import javax.inject.Inject
import kotlin.math.sqrt
class Day06 @Inject constructor(
private val generatorFactory: InputGeneratorFactory,
) {
fun countRecordOptions(raceTime: Long, record: Long): Long {
/* distance = (raceTime - push) * push => -push^2 + push*raceTime */
val (min, max) = recordBeatingTimes(raceTime, record)
return max - min + 1
}
fun recordBeatingTimes(raceTime: Long, record: Long) : Pair<Long, Long> {
val(min, max) = recordIntersectionTimes(raceTime, record)
return Pair((min + 1).toLong(), (max-0.0001).toLong())
}
fun recordIntersectionTimes(raceTime: Long, record: Long): Pair<Double, Double> {
// b^2 - 4ac, a==-1
val discriminator: Double = sqrt((raceTime * raceTime + 4 * -record).toDouble())
// (-b +/- discriminator)/2a
val i1: Double = (-raceTime + discriminator) / -2
val i2: Double = (-raceTime - discriminator) / -2
return Pair(i1, i2)
}
fun partOne(fileName: String): Long {
val whiteSpaceSplitter = "\\D+".toRegex()
val recordInfo = readStringFile(fileName)
val raceTimes = recordInfo[0].split(":")[1].trim().split(whiteSpaceSplitter).map { it.toLong() }
val records = recordInfo[1].split(":")[1].trim().split(whiteSpaceSplitter).map { it.toLong() }
return raceTimes
.mapIndexed { index, i -> countRecordOptions(i, records[index]) }
.reduce { acc, recordOptions -> acc * recordOptions }
}
fun partTwo(fileName: String): Long {
val whiteSpaceSplitter = "\\D+".toRegex()
val recordInfo = readStringFile(fileName)
val raceTime = recordInfo[0].split(":")[1].trim().replace(whiteSpaceSplitter, "").toLong()
val record = recordInfo[1].split(":")[1].trim().replace(whiteSpaceSplitter, "").toLong()
return countRecordOptions(raceTime, record)
}
}
| 0 | Kotlin | 0 | 0 | f2b873b6cf24bf95a4ba3d0e4f6e007b96423b76 | 1,970 | advent-of-code | MIT License |
src/Utils.kt | askeron | 572,955,924 | false | {"Kotlin": 24616} | import java.io.File
import java.math.BigInteger
import java.security.MessageDigest
import java.util.*
import kotlin.collections.ArrayList
import kotlin.math.sign
/**
* Reads lines from the given input txt file.
*/
fun readInput(name: String) = File("resources", "$name.txt")
.readLines()
/**
* Converts string to md5 hash.
*/
fun String.md5() = BigInteger(1, MessageDigest.getInstance("MD5").digest(toByteArray()))
.toString(16)
.padStart(32, '0')
fun <T> assertEquals(expected: T, actual: T) {
check(expected == actual) { "expected $expected but found $actual" }
}
// helpers from 2021 START
fun <T> List<T>.allDistinct() = this.size == this.distinct().size
fun <T : Comparable<T>> List<T>.isSorted() = this == this.sorted()
fun <T> List<T>.singleValue(): T {
check(size == 1) { "list has not 1 but $size items" }
return get(0)
}
fun <T> List<T>.toPair(): Pair<T, T> {
check(size == 2) { "list has not 2 but $size items" }
return get(0) to get(1)
}
infix fun <A, B, C> Pair<A, B>.toTriple(that: C): Triple<A, B, C> = Triple(first, second, that)
fun <T> T.transform(times: Int, transform: (T) -> T): T {
var result = this
repeat(times) {
result = transform.invoke(result)
}
return result
}
fun <T> List<T>.transformUntilNoChange(transform: (List<T>) -> List<T>) : List<T> =
transform.invoke(this).let {
if (it == this) {
it
} else {
it.transformUntilNoChange(transform)
}
}
fun List<String>.IntMatrixToPointMap() = charMatrixToPointMap().map { (a, b) -> a to b.digitToInt() }.toMap()
fun List<String>.charMatrixToPointMap() = flatMapIndexed { y, s ->
s.toCharArray().mapIndexed { x, c -> Point(x,y) to c }
}.toMap()
fun Int.gaussSum() = (this * (this + 1)) / 2
fun <T> List<T>.getAllDistinctCombinations(): List<List<T>> {
var result = this.map { listOf(it) }
repeat(this.size - 1) {
result = result.zipInList(this).filter { it.allDistinct() }
}
return result
}
fun <T> List<List<T>>.zipInList(list: List<T>): List<List<T>> = this.flatMap { x -> list.map { x.plus(it) } }
fun List<Int>.toIntByDigits(): Int {
assert(all { it in 0..9 })
var result = 0
forEach {
result = result * 10 + it
}
return result
}
fun <T> List<T>.nonUnique() = this.groupingBy { it }.eachCount().filter { it.value > 1 }
fun <T> MutableList<T>.removeLast(n: Int): List<T> = mutableListOf<T>()
.also { repeat(n) { _ -> it += removeLast() } }.toList().reversed()
fun <T> List<List<T>>.turnMatrix(): List<List<T>> = (0 until this[0].size).map { i -> this.map { it[i] } }
fun <K, V> Map<K, V>.inverted() = entries.associate{(k,v)-> v to k}
fun Iterable<Point>.mirror() = map { Point(it.y, it.x) }.toList()
fun Iterable<Point>.matrixString(pointChar: Char, noPointChar: Char): String =
matrixString { x, y -> if (contains(Point(x, y))) pointChar else noPointChar }
fun Iterable<Point>.matrixString(charFunction: (Int, Int) -> Char): String {
return (0..this.maxOf { it.y }).joinToString("\n") { y ->
(0..this.maxOf { it.x }).joinToString("") { x ->
charFunction.invoke(x, y).toString()
}
}
}
fun Map<Point, Int>.matrixString() = keys.matrixString { x, y -> this[Point(x,y)]!!.digitToChar()}
data class Point(val x: Int, val y: Int) {
operator fun unaryMinus() = Point(-x, -y)
operator fun plus(b: Point) = Point(x + b.x, y + b.y)
operator fun minus(b: Point) = this + (-b)
val values = listOf(x, y)
val neighboursNotDiagonal by lazy { listOf(
Point(-1,0),
Point(1,0),
Point(0,-1),
Point(0,1),
).map { this + it } }
val neighboursWithItself by lazy { listOf(
Point(-1,-1),
Point(-1,0),
Point(-1,1),
Point(0,-1),
Point(0,0),
Point(0,1),
Point(1,-1),
Point(1,0),
Point(1,1),
).map { this + it } }
val neighbours by lazy { neighboursWithItself.filterNot { it == this } }
val sign by lazy { Point(x.sign, y.sign) }
companion object {
val LEFT = Point(-1,0)
val RIGHT = Point(1,0)
val UP = Point(0,-1)
val DOWN = Point(0,1)
}
}
// helpers from 2021 END
// from 2021 Day15
fun <T> shortestPathByDijkstra(
edgesWithCosts: Set<Triple<T, T, Int>>,
start: T,
end: T,
): Pair<List<T>, Int>? {
val costsMap = mutableMapOf<T, Int>()
val previousNodeMap = mutableMapOf<T, T>()
val edgesMap = edgesWithCosts.groupBy({ it.first }) { it.second to it.third }
val queue = LinkedList<T>()
val processed = mutableSetOf<T>()
costsMap[start] = 0
queue += start
while (queue.isNotEmpty()) {
val from = queue.minByOrNull { costsMap[it] ?: Int.MAX_VALUE }!!
queue.remove(from)
processed += from
val fromCosts = costsMap[from] ?: Int.MAX_VALUE
edgesMap[from]?.forEach { edge ->
val to = edge.first
val toCosts = fromCosts + edge.second
if ((costsMap[to] ?: Int.MAX_VALUE) > toCosts) {
costsMap[to] = toCosts
previousNodeMap[to] = from
}
if (to !in processed && to !in queue) {
queue += to
}
}
}
val reversedPath = mutableListOf(end)
while (reversedPath.last() != start) {
reversedPath += previousNodeMap[reversedPath.last()] ?: return null
}
return reversedPath.toList().reversed() to costsMap[end]!!
}
// copied and then modified from takeWhile()
inline fun <T> Iterable<T>.takeWhilePlusOne(predicate: (T) -> Boolean): List<T> {
val list = ArrayList<T>()
for (item in this) {
list.add(item)
if (!predicate(item))
break
}
return list
}
fun <T> List<T>.splitInHalf(): Pair<List<T>, List<T>> {
check(size % 2 == 0) { "not an even size" }
return take(size / 2) to drop(size / 2)
}
fun <T> Iterable<T>.split(seperator: T): List<List<T>> = split { it == seperator }
fun <T> Iterable<T>.split(predicate: (T) -> Boolean): List<List<T>> {
val itemsLeft = this.toMutableList()
if (itemsLeft.isEmpty()) return emptyList()
val result = mutableListOf<List<T>>()
val currentSegment = mutableListOf<T>()
while (itemsLeft.isNotEmpty()) {
val item = itemsLeft.removeAt(0)
if (predicate.invoke(item)) {
result += currentSegment.toList()
currentSegment.clear()
} else {
currentSegment += item
}
}
result += currentSegment.toList()
return result.toList()
}
| 0 | Kotlin | 0 | 1 | 6c7cf9cf12404b8451745c1e5b2f1827264dc3b8 | 6,611 | advent-of-code-kotlin-2022 | Apache License 2.0 |
2017/src/five/CorruptionChecksumChallenge.kt | Mattias1 | 116,139,424 | false | null | package five
// Day 2
class CorruptionChecksumChallenge {
fun differenceChecksum(input: Array<String>): Int {
val numberList = this.toNumberList(input)
return numberList
.map { this.diffMaxMin(it) }
.sum()
}
private fun toNumberList(input: Array<String>): List<List<Int>> {
return input.map {
it
.split(" ")
.filter { it.isNotEmpty() }
.map { it.toInt() }
}
}
private fun diffMaxMin(numbers: List<Int>): Int {
val min: Int = numbers.min()!!
val max: Int = numbers.max()!!
return max - min
}
fun divisionChecksum(input: Array<String>): Int {
val numberList = this.toNumberList(input)
return numberList
.map { it.sortedDescending() }
.map { this.firstIntDivision(it) }
.sum()
}
private fun firstIntDivision(numbers: List<Int>): Int {
// Assumes descending sort
for (i in 0 until numbers.lastIndex) {
for (j in i + 1..numbers.lastIndex) {
val max: Int = numbers[i]
val min: Int = numbers[j]
if (max % min == 0) {
return max / min
}
}
}
throw Exception("No int division found")
}
}
| 0 | Kotlin | 0 | 0 | 6bcd889c6652681e243d493363eef1c2e57d35ef | 1,389 | advent-of-code | MIT License |
solutions/src/MaximalSquare.kt | JustAnotherSoftwareDeveloper | 139,743,481 | false | {"Kotlin": 305071, "Java": 14982} | class MaximalSquare {
/*
This was my solution. It is (m*n)^2. However, the correct solution is m*n.
I have noted that for my studies and am leaving this up as a record.
*/
fun maximalSquare(matrix: Array<CharArray>): Int {
var largest = 0
for(i in matrix.indices) {
for(j in matrix[0].indices) {
largest = maxOf(largest,maxSquareAt(Pair(i,j),matrix))
}
}
return largest
}
fun maxSquareAt(coordinates: Pair<Int,Int>, matrix: Array<CharArray>) : Int {
var largestSquare = 0
var new = mutableSetOf(coordinates)
val validRange = {pair:Pair<Int,Int> -> pair.first <= matrix.lastIndex && pair.first >= 0 && pair.second <= matrix[0].lastIndex && pair.second >= 0 }
while (new.all{ validRange(it) && matrix[it.first][it.second] == '1' }) {
largestSquare++
var nextLevel = mutableSetOf<Pair<Int,Int>>()
new.forEach {
val right = Pair(it.first+1,it.second)
val down = Pair(it.first,it.second-1)
val diag = Pair(it.first+1,it.second-1)
nextLevel.addAll(listOf(right,down,diag))
}
new = nextLevel
}
return largestSquare*largestSquare
}
} | 0 | Kotlin | 0 | 0 | fa4a9089be4af420a4ad51938a276657b2e4301f | 1,304 | leetcode-solutions | MIT License |
backend/src/main/kotlin/services/utilities/RequirementsParser.kt | Feng-12138 | 640,760,018 | false | null | package services.utilities
import java.util.concurrent.ConcurrentHashMap
class RequirementsParser {
// requirementsData example:
// ["1:CS 115,CS 135,CS 145;1:CS 136,CS 146;1:MATH 127,MATH 137,MATH 147;1:MATH 128,MATH 138,MATH 148;1:MATH 135,MATH 145;1:MATH 136,MATH 146;1:MATH 239,MATH 249;1:STAT 230,STAT 240;1:STAT 231,STAT 241;1:CS 136L;1:CS 240,CS 240E;1:CS 241,CS 241E;1:CS 245,CS 245E;1:CS 246,CS 246E;1:CS 251,CS 251E;1:CS 341;1:CS 350;3:CS 340-CS 398,CS 440-CS 489;2:CS 440-CS 489;1:CO 487,CS 440-CS 498,CS 499T,STAT 440,CS 6xx,CS 7xx"]
fun parseRequirements(requirementsData: List<String>): Requirements {
return finalizeRequirements(initialReqParse(requirementsData))
}
private fun parseBoundedRangeCourses(course: String, courses: MutableSet<Course>): Unit {
val courseRange = course.split("-")
val courseLowerBound = courseRange[0].split(" ")
val courseUpperBound = courseRange[1].split(" ")
val courseSubject = courseLowerBound[0]
val courseLowerCode = courseLowerBound[1].toInt()
val courseUpperCode = courseUpperBound[1].toInt()
// Add all possible course codes now. Invalid ones will be filter out when querying DB.
for (i in courseLowerCode..courseUpperCode) {
courses.add(
Course(
subject = courseSubject,
code = i.toString(),
)
)
}
}
// Parse a single requirement clause. Eg. requirement = "1:CS 115,CS 135,CS 145"
private fun parseSingleReqClause(requirement: String, optionalCourses: MutableSet<OptionalCourses>,
mandatoryCourses: MutableSet<Course>): Unit {
val courses = mutableSetOf<Course>()
val temp = requirement.split(":")
val nOf = temp[0]
val courseList = temp[1].split(",")
for (course in courseList) {
// Eg. CS 440-CS 489
if (course.contains("-")) {
parseBoundedRangeCourses(course, courses)
} else {
val newCourse = course.split(" ")
// Eg. CS 7xx
if (newCourse[1].contains("xx")) {
// Add all possible values of xx as course. These courses will be filtered when querying DB.
for (i in 0..9) {
courses.add(
Course(
subject = newCourse[0],
code = newCourse[1][0] + "0" + i.toString(),
)
)
}
for (i in 10..99) {
courses.add(
Course(
subject = newCourse[0],
code = newCourse[1][0] + i.toString(),
)
)
}
} else {
courses.add(
Course(
subject = newCourse[0],
code = newCourse[1],
)
)
}
}
}
if (nOf.toInt() == courses.size) {
mandatoryCourses.addAll(courses)
} else {
optionalCourses.add(
OptionalCourses(
nOf = nOf.toInt(),
courses = courses,
)
)
}
}
// Extract all courses needed based on requirement.
fun initialReqParse(requirementsData: List<String>): Requirements {
val optionalCourses = mutableSetOf<OptionalCourses>()
val mandatoryCourses = mutableSetOf<Course>()
for (requirements in requirementsData) {
val requirement = requirements.split(";")
for (r in requirement) {
parseSingleReqClause(r, optionalCourses, mandatoryCourses)
}
}
return Requirements(
optionalCourses = optionalCourses,
mandatoryCourses = mandatoryCourses,
)
}
// Finalize requirements by restraining some optional choices of courses as mandatory
private fun finalizeRequirements(requirements: Requirements): Requirements {
val optionalCoursesList = requirements.optionalCourses.toMutableList()
val mandatoryCourses = requirements.mandatoryCourses.toMutableList()
val commonTable: ConcurrentHashMap<Course, Int> = ConcurrentHashMap()
for (i in 0 until optionalCoursesList.size) {
for (j in i + 1 until optionalCoursesList.size) {
val coursesI = optionalCoursesList[i]
val coursesJ = optionalCoursesList[j]
val commonCourses = coursesJ.courses.filter { coursesI.courses.contains(it) }.toSet()
for (commonCourse in commonCourses) {
commonTable.compute(commonCourse) { _, count -> count?.plus(1) ?: 1 }
}
}
}
val remainingOptionalCourses = mutableListOf<OptionalCourses>()
for (optionalCourses in optionalCoursesList) {
var commonCourses = optionalCourses.courses.filter { it in commonTable.keys }.toSet()
if (commonCourses.size < optionalCourses.nOf) {
optionalCourses.nOf -= commonCourses.size
optionalCourses.courses.removeAll(commonCourses)
remainingOptionalCourses.add(optionalCourses)
} else {
commonCourses = commonTable.filterKeys { it in commonCourses }
.toList()
.sortedBy { (_, value) -> value }
.map { it.first }
.take(optionalCourses.nOf)
.toSet()
mandatoryCourses.addAll(commonCourses)
}
}
remainingOptionalCourses.removeIf { optionalCourses ->
mandatoryCourses.containsAll(optionalCourses.courses)
}
// add breadth and depth
mandatoryCourses.addAll(
listOf(
Course("ECON", "101"),
Course("ECON", "102"),
Course("ECON", "371"),
)
)
mandatoryCourses.addAll(
listOf(
Course("MUSIC", "116"),
Course("PHYS", "111"),
Course("CHEM", "102"),
)
)
return Requirements(
optionalCourses = remainingOptionalCourses.toMutableSet(),
mandatoryCourses = mandatoryCourses.toMutableSet(),
)
}
fun combineOptionalRequirements(
requirements: Requirements,
checkCourses: List<String>,
): CommonRequirementsData {
var commonSize = 0
if (checkCourses.isNotEmpty()) {
val iterator = requirements.optionalCourses.iterator()
while (iterator.hasNext()) {
val optionalReq = iterator.next()
val commonCourses = optionalReq.courses.filter { "${it.subject} ${it.code}" in checkCourses }
commonSize = commonCourses.size
if (commonSize >= optionalReq.nOf) {
iterator.remove()
} else {
optionalReq.nOf -= commonSize
optionalReq.courses.removeAll(commonCourses.toSet())
}
}
}
return CommonRequirementsData(
requirements = requirements,
commonSize = commonSize,
)
}
}
data class Course (
val subject: String,
val code: String,
)
data class OptionalCourses (
var nOf: Int = 1,
val courses: MutableSet<Course> = mutableSetOf(),
)
data class Requirements (
val optionalCourses: MutableSet<OptionalCourses> = mutableSetOf(),
val mandatoryCourses: MutableSet<Course> = mutableSetOf(),
)
data class CommonRequirementsData (
val requirements: Requirements,
val commonSize: Int,
) | 0 | Kotlin | 2 | 3 | f8db57b89cda6f71388cdaa0042a1c2908c86cc3 | 8,062 | LooSchedule | MIT License |
src/Day17.kt | matusekma | 572,617,724 | false | {"Kotlin": 119912, "JavaScript": 2024} | import kotlin.math.max
enum class RockType {
ROW, CROSS, COLUMN, L, SQUARE
}
data class FallResult(val rock: Rock, val isLanded: Boolean)
class Rock(val parts: List<Position>, private val type: RockType) {
fun moveRight(chamber: MutableList<MutableList<Char>>): Rock {
if (this.parts.all { chamber[0].size > it.x + 1 && chamber[it.y][it.x + 1] == '.' }) {
return Rock(this.parts.map { Position(it.x + 1, it.y) }, this.type)
}
return this
}
fun moveLeft(chamber: MutableList<MutableList<Char>>): Rock {
if (this.parts.all { it.x - 1 >= 0 && chamber[it.y][it.x - 1] == '.' }) {
return Rock(this.parts.map { Position(it.x - 1, it.y) }, this.type)
}
return this
}
fun fall(chamber: MutableList<MutableList<Char>>): FallResult {
if (this.parts.all { it.y + 1 < chamber.size && chamber[it.y + 1][it.x] == '.' }) {
return FallResult(Rock(this.parts.map { Position(it.x, it.y + 1) }, this.type), false)
}
return FallResult(this, true)
}
}
class Day17 {
val debug = false
val chamberWidth = 7
val appearDist = 3
private val chamber = MutableList<MutableList<Char>>(4) { MutableList(7) { '.' } }
private fun placeRock(currentHeight: Int, currentNumOfRocks: Long): Rock {
return when (currentNumOfRocks % 5) {
0L -> Rock((2..5).map { Position(it, chamber.size - (currentHeight + 4)) }, RockType.ROW)
1L -> Rock(
listOf(
Position(3, chamber.size - (currentHeight + 4)),
Position(2, chamber.size - (currentHeight + 5)),
Position(3, chamber.size - (currentHeight + 5)),
Position(4, chamber.size - (currentHeight + 5)),
Position(3, chamber.size - (currentHeight + 6))
), RockType.CROSS
)
2L -> Rock(
listOf(
Position(2, chamber.size - (currentHeight + 4)),
Position(3, chamber.size - (currentHeight + 4)),
Position(4, chamber.size - (currentHeight + 4)),
Position(4, chamber.size - (currentHeight + 5)),
Position(4, chamber.size - (currentHeight + 6))
), RockType.L
)
3L -> Rock((0..3).map { Position(2, chamber.size - (currentHeight + 4 + it)) }, RockType.COLUMN)
4L -> Rock(
listOf(
Position(2, chamber.size - (currentHeight + 4)),
Position(3, chamber.size - (currentHeight + 4)),
Position(2, chamber.size - (currentHeight + 5)),
Position(3, chamber.size - (currentHeight + 5)),
), RockType.SQUARE
)
else -> throw RuntimeException("Error: rock placement")
}
}
fun part1(input: List<String>, numOfRocks: Int): Int {
val directions = input[0]
var currentDir = 0
var currentNumOfRocks = 0L
var currentHeight = 0
while (currentNumOfRocks < numOfRocks) {
while (currentHeight + 4 + 4 > chamber.size) { // make chamber bigger
chamber.add(0, MutableList(7) { '.' })
}
var rock = placeRock(currentHeight, currentNumOfRocks)
// move
var isLanded = false
printChamber(rock)
while (!isLanded) {
rock = if (directions[currentDir] == '>') rock.moveRight(chamber) else rock.moveLeft(chamber)
val fallResult = rock.fall(chamber)
rock = fallResult.rock
isLanded = fallResult.isLanded
printChamber(rock)
if (currentDir + 1 == directions.length) currentDir = 0 else currentDir++
}
// finish
updateChamberWithRock(rock)
currentHeight = max(currentHeight, chamber.size - rock.parts.minOf { it.y })
currentNumOfRocks++
}
return currentHeight
}
private fun updateChamberWithRock(rock: Rock) {
for (part in rock.parts) {
chamber[part.y][part.x] = '#'
}
}
private fun printChamber(rock: Rock) {
if (!debug) return
for (i in 0 until chamber.size) {
for (j in 0 until chamber[i].size) {
val part = rock.parts.find { it.y == i && it.x == j }
if (part != null) print('@') else print(chamber[i][j])
}
println()
}
println()
}
fun part2(input: List<String>): Long {
val states = mutableMapOf<String, List<Long>>()
val directions = input[0]
var currentDir = 0
var currentNumOfRocks = 0L
var currentHeight = 0L
var additional = 0L
while (currentNumOfRocks < 1000000000000) {
while (currentHeight + 4 + 4 > chamber.size) { // make chamber bigger
chamber.add(0, MutableList(7) { '.' })
}
var rock = placeRock(currentHeight.toInt(), currentNumOfRocks)
// move
var isLanded = false
while (!isLanded) {
rock = if (directions[currentDir] == '>') rock.moveRight(chamber) else rock.moveLeft(chamber)
val fallResult = rock.fall(chamber)
rock = fallResult.rock
isLanded = fallResult.isLanded
printChamber(rock)
if (currentDir + 1 == directions.length) currentDir = 0 else currentDir++
}
// finish
updateChamberWithRock(rock)
currentHeight = max(currentHeight.toInt(), chamber.size - rock.parts.minOf { it.y }).toLong()
currentNumOfRocks++
var columnHeights = mutableListOf<Int>()
for (i in 0 until chamberWidth) {
var found = false
var j = 0
while (!found && j != chamber.size) {
if (chamber[j][i] != '.') {
found = true
} else j++
}
columnHeights.add((currentHeight - (chamber.size - j)).toInt())
}
val currentState = listOf(
currentDir,
columnHeights.joinToString(";"),
currentNumOfRocks % 5
).joinToString(";")
if (states.containsKey(currentState) && additional == 0L) { // additional not yet defined, COMPUTE REPEATING CYCLES HERE
val (previousNumOfRocks, previousHeight) = states[currentState]!!
val repeat = (1000000000000 - currentNumOfRocks) / (currentNumOfRocks - previousNumOfRocks)
currentNumOfRocks += repeat * (currentNumOfRocks-previousNumOfRocks)
additional = repeat * (currentHeight - previousHeight)
}
states[currentState] = listOf(currentNumOfRocks, currentHeight)
}
return currentHeight + additional
}
}
fun main() {
val input = readInput("input17_1")
println(Day17().part1(input, 2022))
println(Day17().part2(input))
} | 0 | Kotlin | 0 | 0 | 744392a4d262112fe2d7819ffb6d5bde70b6d16a | 7,224 | advent-of-code | Apache License 2.0 |
src/main/kotlin/nl/dirkgroot/adventofcode/year2021/Day18.kt | dirkgroot | 317,968,017 | false | {"Kotlin": 187862} | package nl.dirkgroot.adventofcode.year2021
import nl.dirkgroot.adventofcode.util.Input
import nl.dirkgroot.adventofcode.util.Puzzle
import java.util.Stack
import kotlin.IllegalStateException
import kotlin.math.max
class Day18(input: Input) : Puzzle() {
sealed interface Node {
val depth: Int
val explodes: Boolean
val mustExplode: Boolean
val splits: Boolean
val isReduced: Boolean
val magnitude: Long
fun assertDepth(d: Int)
fun increaseDepth(): Node
fun add(other: Node) = reduce(Intermediate(1, increaseDepth(), other.increaseDepth()))
data class Intermediate(override val depth: Int, var left: Node, var right: Node) : Node {
override val explodes: Boolean
get() = depth > 4 && left is Leaf && right is Leaf
override val splits = false
override val isReduced: Boolean
get() = !explodes && left.isReduced && right.isReduced
override val mustExplode: Boolean
get() = explodes || left.mustExplode || right.mustExplode
override val magnitude: Long
get() = (3L * left.magnitude) + (2L * right.magnitude)
override fun assertDepth(d: Int) {
if (depth != d) throw IllegalStateException("Invalid depth!")
left.assertDepth(d + 1)
right.assertDepth(d + 1)
}
override fun increaseDepth() = Intermediate(depth + 1, left.increaseDepth(), right.increaseDepth())
override fun toString(): String {
if (explodes)
return "$ANSI_RED[$left$ANSI_RED,$right$ANSI_RED]$ANSI_RESET"
return "[$left,$right]"
}
}
data class Leaf(override val depth: Int, var value: Int) : Node {
override val explodes = false
override val mustExplode = false
override val splits: Boolean
get() = value > 9
override val isReduced: Boolean
get() = !splits
override val magnitude: Long
get() = value.toLong()
override fun assertDepth(d: Int) {
if (depth != d) throw IllegalStateException("Invalid depth!")
}
override fun increaseDepth() = copy(depth = depth + 1)
fun split(): Intermediate {
val left = value / 2
val right = value - left
return Intermediate(depth, Leaf(depth + 1, left), Leaf(depth + 1, right))
}
override fun toString(): String {
if (splits)
return "$ANSI_GREEN$value$ANSI_RESET"
return value.toString()
}
}
}
companion object {
const val ANSI_RESET = "\u001B[0m"
const val ANSI_RED = "\u001B[31m"
const val ANSI_GREEN = "\u001B[32m"
fun parse(lines: List<String>) = lines.map { parseNumber(it) }
fun parseNumber(number: String): Node {
val stack = Stack<Node>()
var depth = 1
Regex("(\\[|]|\\d+)").findAll(number).forEach {
when (it.value) {
"[" -> depth++
"]" -> {
depth--
val right = stack.pop()
val left = stack.pop()
stack.push(Node.Intermediate(depth, left, right))
}
else -> stack.push(Node.Leaf(depth, it.value.toInt()))
}
}
return stack.single()
}
fun explode(number: Node): Node {
val nodes = allNodes(number).toList()
val explodeIndex = nodes.indexOfFirst { it.explodes }
if (explodeIndex < 0) return number
val explode = nodes[explodeIndex] as Node.Intermediate
nodes.take(explodeIndex)
.filterIsInstance<Node.Leaf>()
.lastOrNull()
?.let {
it.value += (explode.left as Node.Leaf).value
}
nodes.drop(explodeIndex)
.filterIsInstance<Node.Leaf>()
.drop(2)
.firstOrNull()
?.let {
it.value += (explode.right as Node.Leaf).value
}
nodes.filterIsInstance<Node.Intermediate>()
.first { it.left === explode || it.right === explode }
.let {
if (it.left === explode) {
it.left = Node.Leaf(it.left.depth, 0)
} else if (it.right === explode) {
it.right = Node.Leaf(it.right.depth, 0)
}
}
return number
}
fun split(number: Node): Node {
val nodes = allNodes(number)
nodes.firstOrNull { it.splits }?.let { split ->
nodes.filterIsInstance<Node.Intermediate>()
.first { it.left === split || it.right === split }
.let { splitParent ->
if (splitParent.left.splits)
splitParent.left = (splitParent.left as Node.Leaf).split()
else if (splitParent.right.splits)
splitParent.right = (splitParent.right as Node.Leaf).split()
}
}
return number
}
private fun allNodes(number: Node) = sequence {
val stack = Stack<Node>()
stack.push(number)
while (stack.isNotEmpty()) {
val node = stack.pop()
yield(node)
if (node is Node.Intermediate) {
stack.push(node.right)
stack.push(node.left)
}
}
}
fun reduce(number: Node): Node {
var count = 0
@Suppress("unused")
fun debug(n: Node) {
val nodes = allNodes(n).toList()
val firstExplode = nodes.firstOrNull { it.explodes }
val firstSplit = nodes.firstOrNull { it.splits }
println("${String.format("%03d", ++count)} $number (ex: $firstExplode | sp: $firstSplit)")
}
// debug(number)
while (!number.isReduced) {
number.assertDepth(1)
if (number.mustExplode)
explode(number)
else
split(number)
// debug(number)
}
return number
}
}
private val input by lazy { parse(input.lines()) }
override fun part1() =
input.reduce { acc, node ->
acc.add(node)
}.magnitude
override fun part2(): Any {
var largestMagnitude = 0L
input.forEach { n1 ->
input.forEach { n2 ->
if (n1 !== n2) {
val magnitude = n1.add(n2).magnitude
largestMagnitude = max(magnitude, largestMagnitude)
}
}
}
return largestMagnitude
}
} | 1 | Kotlin | 1 | 1 | ffdffedc8659aa3deea3216d6a9a1fd4e02ec128 | 7,271 | adventofcode-kotlin | MIT License |
src/main/kotlin/days/aoc2022/Day24.kt | bjdupuis | 435,570,912 | false | {"Kotlin": 537037} | package days.aoc2022
import days.Day
import util.Point2d
class Day24 : Day(2022, 24) {
lateinit var blizzardBounds: Pair<IntRange, IntRange>
override fun partOne(): Any {
return calculateFastestRoute(inputList)
}
override fun partTwo(): Any {
return calculateFastestRouteThereAndBackAndThereAgain(inputList)
}
fun calculateFastestRouteThereAndBackAndThereAgain(input: List<String>): Int {
var startingPosition = Point2d(0,0)
var endingPosition = Point2d(input[0].length - 3, input.size - 1)
blizzardBounds = Pair(0..input[0].length - 3, 1..input.size - 2)
val blizzards = mutableListOf<Blizzard>()
input.drop(1).dropLast(1).forEachIndexed { y, s ->
s.drop(1).dropLast(1).forEachIndexed { x, c ->
val point = Point2d(x, y + 1)
when (c) {
'>' -> blizzards.add(Blizzard(point, Facing.East))
'<' -> blizzards.add(Blizzard(point, Facing.West))
'^' -> blizzards.add(Blizzard(point, Facing.North))
'v' -> blizzards.add(Blizzard(point, Facing.South))
}
}
}
calculateFastestRouteTo(startingPosition, endingPosition, blizzards).let { (toGoalFirst, toGoalBlizzards) ->
calculateFastestRouteTo(endingPosition, startingPosition, toGoalBlizzards).let { (toStartSteps, toStartBlizzards) ->
calculateFastestRouteTo(startingPosition, endingPosition, toStartBlizzards).let { (toGoalSecond, _) ->
return toGoalFirst + toStartSteps + toGoalSecond
}
}
}
}
private fun calculateFastestRouteTo(startingPosition: Point2d, endingPosition: Point2d, blizzards: List<Day24.Blizzard>): Pair<Int, List<Blizzard>> {
val previousStates = mutableSetOf<PotentialMove>()
val queue = mutableListOf<PotentialMove>()
queue.add(PotentialMove(startingPosition, 0))
val blizzardStates = mutableMapOf<Int,List<Blizzard>>()
blizzardStates[0] = blizzards
while (queue.isNotEmpty()) {
val move = queue.removeFirst()
if (move !in previousStates) {
previousStates.add(move)
val nextBlizzardState = blizzardStates[move.steps + 1] ?: run {
val next = blizzardStates[move.steps]!!.map { Blizzard(it.nextPosition(), it.facing) }
blizzardStates[move.steps + 1] = next
next
}
val potentialNextMoves =
move.location.neighbors().plus(move.location).filter { it !in nextBlizzardState.map { it.currentPosition } &&
it.isInBounds(blizzardBounds.first, blizzardBounds.second) ||
it == endingPosition ||
it == startingPosition }
if (endingPosition in potentialNextMoves) {
return Pair(move.steps + 1, nextBlizzardState)
}
potentialNextMoves.forEach {
queue.add(PotentialMove(it, move.steps + 1))
}
}
}
throw IllegalStateException()
}
fun calculateFastestRoute(input: List<String>): Int {
var startingPosition = Point2d(0,0)
val endingPosition = Point2d(input[0].length - 3, input.size - 1)
blizzardBounds = Pair(0..input[0].length - 3, 1..input.size - 2)
val blizzards = mutableListOf<Blizzard>()
input.drop(1).dropLast(1).forEachIndexed { y, s ->
s.drop(1).dropLast(1).forEachIndexed { x, c ->
val point = Point2d(x, y + 1)
when (c) {
'>' -> blizzards.add(Blizzard(point, Facing.East))
'<' -> blizzards.add(Blizzard(point, Facing.West))
'^' -> blizzards.add(Blizzard(point, Facing.North))
'v' -> blizzards.add(Blizzard(point, Facing.South))
}
}
}
val previousStates = mutableSetOf<PotentialMove>()
val queue = mutableListOf<PotentialMove>()
queue.add(PotentialMove(startingPosition, 0))
val blizzardStates = mutableMapOf<Int,List<Blizzard>>()
blizzardStates[0] = blizzards
while (queue.isNotEmpty()) {
val move = queue.removeFirst()
if (move !in previousStates) {
previousStates.add(move)
val nextBlizzardState = blizzardStates[move.steps + 1] ?: run {
val next = blizzardStates[move.steps]!!.map { Blizzard(it.nextPosition(), it.facing) }
blizzardStates[move.steps + 1] = next
next
}
val potentialNextMoves =
move.location.neighbors().plus(move.location).filter { it !in nextBlizzardState.map { it.currentPosition } &&
it.isInBounds(blizzardBounds.first, blizzardBounds.second) ||
it == endingPosition ||
it == startingPosition }
if (endingPosition in potentialNextMoves) {
return move.steps + 1
}
potentialNextMoves.forEach {
queue.add(PotentialMove(it, move.steps + 1))
}
}
}
throw IllegalStateException()
}
data class PotentialMove(val location: Point2d, val steps: Int)
inner class Blizzard(val currentPosition: Point2d, val facing: Facing) {
fun nextPosition(): Point2d {
var position = currentPosition + facing.delta()
if (position.x !in blizzardBounds.first ) {
position = position.copy(x = if (facing == Facing.East) blizzardBounds.first.first else blizzardBounds.first.last)
} else if (position.y !in blizzardBounds.second) {
position = position.copy(y = if (facing == Facing.South) blizzardBounds.second.first else blizzardBounds.second.last)
}
return position
}
}
enum class Facing {
North, South, East, West;
fun delta(): Point2d {
return when (this) {
North -> Point2d(0, -1)
South -> Point2d(0, 1)
East -> Point2d(1, 0)
West -> Point2d(-1, 0)
}
}
}
}
fun Point2d.isInBounds(xRange: IntRange, yRange: IntRange): Boolean {
return x in xRange && y in yRange
} | 0 | Kotlin | 0 | 1 | c692fb71811055c79d53f9b510fe58a6153a1397 | 6,597 | Advent-Of-Code | Creative Commons Zero v1.0 Universal |
jvm-demo/src/main/java/combo/demo/models/autocomplete/AutoCompleteDataSet.kt | rasros | 148,620,275 | false | null | package combo.demo.models.autocomplete
import combo.bandit.glm.*
import combo.math.RunningVariance
import combo.math.sample
import combo.model.*
import combo.sat.optimizers.JacopSolver
import java.io.InputStreamReader
fun main() {
val a = AutoCompleteDataSet()
val lm = SGDLinearModel.Builder(a.model.problem)
.regularizationFactor(1e-2f)
.loss(HuberLoss(0.01f))
.updater(SGD(ExponentialDecay(0.001f, 1e-5f)))
.build()
repeat(1000) {
for (i in a.sites.indices)
lm.train(EffectCodedVector(a.model, a.sites[i].instance), a.scores[i], 1f)
}
lm.weights.toFloatArray().forEach { println(it) }
}
class AutoCompleteDataSet {
val model = autoCompleteModel(true)
val sites: Array<Assignment>
val scores: FloatArray
init {
val sitesLiterals = readSiteAttributes(model)
val solver = ModelOptimizer(model, JacopSolver(model.problem))
val siteScores = readScores()
scores = FloatArray(siteScores.size)
val ve = siteScores.asSequence().map { it.score.toFloat() }.sample(RunningVariance())
sites = Array(siteScores.size) {
val e = siteScores[it]
val assumptions = (sitesLiterals[e.id] ?: error("Not found ${e.id}")) + model["Person", e.person]
scores[it] = (e.score - ve.mean) / ve.variance
solver.witnessOrThrow(*assumptions)
}
}
fun printHeader() {
var result = "Score,"
for (i in 0 until model.nbrVariables) {
val variable = model.index.variable(i)
if (variable.nbrValues == 1) result += variable.name + ","
else {
val offset = if (variable.optional) {
result += variable.name + ","
1
} else 0
for (j in offset until variable.nbrValues) {
if (variable is Select) result += variable.name + "_" + variable.values[j - offset].value
else result += variable.name + "_" + (j - offset)
result += ","
}
}
}
println(result.slice(0 until result.length - 1))
}
fun printTrainingSet(effectCoding: Boolean = false) {
for (i in sites.indices)
if (effectCoding)
println("${scores[i]}," + EffectCodedVector(model, sites[i].instance).toFloatArray().joinToString(","))
else
println("${scores[i]}," + sites[i].instance.toIntArray().joinToString(","))
}
private fun readSiteAttributes(m: Model): Map<String, Array<Literal>> {
val lines = InputStreamReader(javaClass.getResourceAsStream("/combo/demo/models/ac_attributes.csv")).readLines()
val h = lines[0].split(",")
return lines.subList(1, lines.size).associate { line ->
val values = line.split(",")
val lits = ArrayList<Literal>()
for (i in 2 until h.size) {
if (model.scope.find<Variable<*, *>>(h[i]) == null) continue
val value = values[i].trim()
if (value.isEmpty() || value == "No") lits.add(!m[h[i]])
else if (value.trim() == "Yes") lits.add(m[h[i]])
else {
val v: Any = if (value.matches(Regex("[0-9]+"))) value.toInt()
else value
lits.add(m[h[i], v])
}
}
values[1] to lits.toTypedArray()
}
}
private data class Example(val id: String, val score: Int, val person: String)
private fun readScores(): List<Example> {
val lines = InputStreamReader(javaClass.getResourceAsStream("/combo/demo/models/ac_scores.csv")).readLines()
return lines.subList(1, lines.size).map { line ->
val values = line.split(",")
val id = values[0].trim()
val score = values[2].trim()
val person = values[3].trim()
Example(id, score.toInt(), person)
}
}
} | 0 | Kotlin | 1 | 2 | 2f4aab86e1b274c37d0798081bc5500d77f8cd6f | 4,052 | combo | Apache License 2.0 |
src/Day10.kt | jvmusin | 572,685,421 | false | {"Kotlin": 86453} | import kotlin.math.abs
fun main() {
fun parse(input: List<String>): List<Int> {
val seq = mutableListOf(1)
for (s in input) {
if (s.startsWith("addx ")) {
val value = s.split(" ")[1].toInt()
seq.add(seq.last())
seq.add(seq.last() + value)
} else {
seq.add(seq.last())
}
}
return seq
}
fun part1(input: List<String>): Int {
val seq = parse(input)
return listOf(20, 60, 100, 140, 180, 220).sumOf { it * seq[it - 1] }
}
fun part2(input: List<String>): Int {
val seq = parse(input)
for (i in seq.indices) {
if (i % 40 == 0) println()
print(if (abs(seq[i] - i % 40) <= 1) '#' else '.')
}
return -1
}
@Suppress("DuplicatedCode")
run {
val day = String.format("%02d", 10)
val testInput = readInput("Day${day}_test")
val input = readInput("Day$day")
println("Part 1 test - " + part1(testInput))
println("Part 1 real - " + part1(input))
println("---")
println("Part 2 test - " + part2(testInput))
println("Part 2 real - " + part2(input))
}
}
| 1 | Kotlin | 0 | 0 | 4dd83724103617aa0e77eb145744bc3e8c988959 | 1,245 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/stack/StrCal.kt | yx-z | 106,589,674 | false | null | package stack
import java.util.*
fun main(args: Array<String>) {
// parse command line calculations such as 1+2*3
// to answer -> 1+6 -> 7
// only +, -, *, /, no `.`, `^`, `(`, `)`, etc.
// assume input string is always valid and formatted (no spaces, tabs, etc.)
val test1 = "13*2+8" // = 34
val test2 = "3-12+5*9" // = 36
val test3 = "1+3*2/5-3" // = -0.8
println(test1.calc())
println(test2.calc())
println(test3.calc())
}
fun String.calc(): Double {
val numStack = Stack<Double>()
val opStack = Stack<Char>()
val numBuilder = StringBuilder()
this.forEach {
with(it) {
when {
isDigit() -> {
numBuilder.append(it)
}
// is oper
else -> {
// push math and reset
numStack.push(numBuilder.toString().toDouble())
numBuilder.setLength(0)
// calc
while (opStack.isNotEmpty() && it.getPriority() <= opStack.peek().getPriority()) {
numStack.push(opStack.pop().calc(numStack.pop(), numStack.pop()))
}
opStack.push(it)
}
}
}
}
numStack.push(numBuilder.toString().toDouble())
while (opStack.isNotEmpty()) {
numStack.push(opStack.pop().calc(numStack.pop(), numStack.pop()))
}
return numStack.pop()
}
fun Char.getPriority() = when (this) {
'+' -> 0
'-' -> 0
'*' -> 1
'/' -> 1
else -> -1
}
fun Char.calc(a: Double, b: Double) = when (this) {
'+' -> b + a
'-' -> b - a
'*' -> b * a
'/' -> b / a
else -> 0.0
}
| 0 | Kotlin | 0 | 1 | 15494d3dba5e5aa825ffa760107d60c297fb5206 | 1,416 | AlgoKt | MIT License |
Kotlin/SelectionSort.kt | shauryam-exe | 412,424,939 | true | {"Java": 54671, "C++": 46151, "C": 27439, "Python": 27284, "JavaScript": 19473, "Kotlin": 14848, "C#": 5916, "Go": 4305} | fun main(args: Array<String>) {
//Input the array in the format num1 num2 num3 num4 etc
print("Enter the elements for the Array: ")
var inputArray = readLine()!!.trim().split(" ").map { it -> it.toInt() }.toIntArray()
var sortedArray = selectionSort(inputArray)
println(sortedArray.contentToString())
}
fun selectionSort(arr: IntArray): IntArray {
for (i in arr.lastIndex downTo 0) {
var max = arr[0]
var maxIndex = 0
for (j in 0..i) {
if (arr[maxIndex]<arr[j])
maxIndex = j
}
val temp = arr[maxIndex]
arr[maxIndex] = arr[i]
arr[i] = temp
}
return arr
}
//Sample
//Input: Enter the elements for the Array: 64 23 -12 -5 0 2 89 20 100 32 650 -230 130
//Output: [-230, -12, -5, 0, 2, 20, 23, 32, 64, 89, 100, 130, 650]
//Time Complexity: Worst Case: O(n^2) Best Case: O(n^2)
//Space Complexity: O(1)
| 0 | Java | 0 | 0 | 3a247451ade57138c3255dbbd27bfb0610f9f02e | 924 | DS-Algo-Zone | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.