path
stringlengths
5
169
owner
stringlengths
2
34
repo_id
int64
1.49M
755M
is_fork
bool
2 classes
languages_distribution
stringlengths
16
1.68k
content
stringlengths
446
72k
issues
float64
0
1.84k
main_language
stringclasses
37 values
forks
int64
0
5.77k
stars
int64
0
46.8k
commit_sha
stringlengths
40
40
size
int64
446
72.6k
name
stringlengths
2
64
license
stringclasses
15 values
src/main/kotlin/io/github/kmakma/adventofcode/y2020/Y2020Day16.kt
kmakma
225,714,388
false
null
package io.github.kmakma.adventofcode.y2020 import io.github.kmakma.adventofcode.utils.Day fun main() { Y2020Day16().solveAndPrint() } class Y2020Day16 : Day(2020, 16, "Ticket Translation") { private lateinit var inputLines: List<String> override fun initializeDay() { inputLines = inputInStringLines() } override suspend fun solveTask1(): Any? { val ticketRules = TicketRules() var ruleLines = true var ticketLines = false var errorRate = 0 for (line in inputLines) { if (ruleLines && line.isBlank()) { ruleLines = false } else if (ruleLines) { ticketRules.addRule(line) } else if (ticketLines) { errorRate += ticketRules.errorRate(line) } else if (line.contains("nearby tickets:")) { ticketLines = true } } return errorRate } override suspend fun solveTask2(): Any? { val ticketRules = TicketRules() var ruleLines = true var ticketLines = false var myTicketLine = false val tickets = mutableListOf<Ticket>() var myTicket = Ticket(listOf()) for (line in inputLines) { when { ruleLines && line.isBlank() -> ruleLines = false ticketLines && line.isBlank() -> ticketLines = false myTicketLine && line.isBlank() -> myTicketLine = false ruleLines -> ticketRules.addRule(line) ticketLines -> if (ticketRules.isValidAtAll(line)) tickets.add(Ticket.create(line)) myTicketLine -> myTicket = Ticket.create(line) line.contains("nearby tickets:") -> ticketLines = true line.contains("your ticket:") -> myTicketLine = true } } var departureCheck = 1L ticketRules.orderRules(tickets).forEach { (rule, index) -> if (rule.contains("departure")) departureCheck *= myTicket[index] } return departureCheck } } class TicketRules { private val rulesList = mutableListOf<IntRange>() private val rulesMap = mutableMapOf<String, Pair<IntRange, IntRange>>() fun addRule(line: String) { val (field, firstStart, firstEnd, scndStart, scndEnd) = line.split(": ", "-", " or ") val firstRange = IntRange(firstStart.toInt(), firstEnd.toInt()) val scndRange = IntRange(scndStart.toInt(), scndEnd.toInt()) rulesList.add(firstRange) rulesList.add(scndRange) rulesMap[field] = Pair(firstRange, scndRange) } fun errorRate(line: String): Int { var errorRate = 0 line.split(",").map { it.toInt() }.forEach { value -> if (notValidAtAll(value)) { errorRate += value } } return errorRate } private fun notValidAtAll(value: Int): Boolean { for (rule in rulesList) { if (value in rule) return false } return true } fun isValidAtAll(line: String): Boolean { line.split(",").map { it.toInt() }.forEach { value -> if (notValidAtAll(value)) return false } return true } fun orderRules(tickets: List<Ticket>): Map<String, Int> { val matchingRules = mutableMapOf<Int, MutableSet<String>>() for (i in tickets.first().indices) { val matches = mutableSetOf<String>().apply { addAll(rulesMap.keys) } for (ticket in tickets) { rulesMap.forEach { (name, ranges) -> val ticketValue = ticket[i] if (ticketValue !in ranges.first && ticketValue !in ranges.second) matches.remove(name) } } matchingRules[i] = matches } val orderedRules = mutableMapOf<String, Int>() while (orderedRules.size < rulesMap.size) { for (entry in matchingRules) { if (entry.value.size == 1) { val value = entry.value.first() orderedRules[value] = entry.key matchingRules.values.forEach { set -> set.remove(value) } break } } } return orderedRules } } class Ticket(val values: List<Int>) { val indices = values.indices operator fun get(i: Int): Int { return values[i] } companion object { fun create(line: String) = Ticket(line.split(",").map { it.toInt() }) } }
0
Kotlin
0
0
7e6241173959b9d838fa00f81fdeb39fdb3ef6fe
4,563
adventofcode-kotlin
MIT License
kotlin/numbertheory/PrimesAndDivisors.kt
polydisc
281,633,906
true
{"Java": 540473, "Kotlin": 515759, "C++": 265630, "CMake": 571}
package numbertheory import java.util.Arrays object PrimesAndDivisors { // Generates prime numbers up to n in O(n*log(log(n))) time fun generatePrimes(n: Int): IntArray { val prime = BooleanArray(n + 1) Arrays.fill(prime, 2, n + 1, true) run { var i = 2 while (i * i <= n) { if (prime[i]) { var j = i * i while (j <= n) { prime[j] = false j += i } } i++ } } val primes = IntArray(n + 1) var cnt = 0 for (i in prime.indices) if (prime[i]) primes[cnt++] = i return Arrays.copyOf(primes, cnt) } // Generates prime numbers up to n in O(n) time fun generatePrimesLinearTime(n: Int): IntArray { val lp = IntArray(n + 1) val primes = IntArray(n + 1) var cnt = 0 for (i in 2..n) { if (lp[i] == 0) { lp[i] = i primes[cnt++] = i } var j = 0 while (j < cnt && primes[j] <= lp[i] && i * primes[j] <= n) { lp[i * primes[j]] = primes[j] ++j } } return Arrays.copyOf(primes, cnt) } fun isPrime(n: Long): Boolean { if (n <= 1) return false var i: Long = 2 while (i * i <= n) { if (n % i == 0L) return false i++ } return true } fun numberOfPrimeDivisors(n: Int): IntArray { val divisors = IntArray(n + 1) Arrays.fill(divisors, 2, n + 1, 1) var i = 2 while (i * i <= n) { if (divisors[i] == 1) { var j = i while (j * i <= n) { divisors[i * j] = divisors[j] + 1 j++ } } ++i } return divisors } // Generates minimum prime divisor of all numbers up to n in O(n) time fun generateMinDivisors(n: Int): IntArray { val lp = IntArray(n + 1) lp[1] = 1 val primes = IntArray(n + 1) var cnt = 0 for (i in 2..n) { if (lp[i] == 0) { lp[i] = i primes[cnt++] = i } var j = 0 while (j < cnt && primes[j] <= lp[i] && i * primes[j] <= n) { lp[i * primes[j]] = primes[j] ++j } } return lp } // Generates prime divisor of all numbers up to n fun generateDivisors(n: Int): IntArray { val divisors: IntArray = IntStream.range(0, n + 1).toArray() var i = 2 while (i * i <= n) { if (divisors[i] == i) { var j = i * i while (j <= n) { divisors[j] = i j += i } } i++ } return divisors } // Euler's totient function fun phi(n: Int): Int { var n = n var res = n var i = 2 while (i * i <= n) { if (n % i == 0) { while (n % i == 0) n /= i res -= res / i } i++ } if (n > 1) res -= res / n return res } // Euler's totient function fun generatePhi(n: Int): IntArray { val res: IntArray = IntStream.range(0, n + 1).toArray() for (i in 1..n) { var j = i + i while (j <= n) { res[j] -= res[i] j += i } } return res } // Usage example fun main(args: Array<String?>?) { var n = 31 val primes1 = generatePrimes(n) val primes2 = generatePrimesLinearTime(n) System.out.println(Arrays.toString(primes1)) System.out.println(Arrays.toString(primes2)) System.out.println(Arrays.equals(primes1, primes2)) System.out.println(Arrays.toString(numberOfPrimeDivisors(n))) System.out.println(Arrays.toString(generateMinDivisors(n))) System.out.println(Arrays.toString(generateDivisors(n))) n = 1000 val phi = generatePhi(n) val PHI: LongArray = MultiplicativeFunction.PHI.generateValues(n) for (i in 0..n) { if (phi[i] != phi(i) || phi[i] != PHI[i]) { System.err.println(i) } } } }
1
Java
0
0
4566f3145be72827d72cb93abca8bfd93f1c58df
4,506
codelibrary
The Unlicense
src/main/kotlin/year2022/Day20.kt
simpor
572,200,851
false
{"Kotlin": 80923}
import AoCUtils.test fun main() { data class LinkedList(val value: Long) { lateinit var prev: LinkedList lateinit var next: LinkedList fun moveBack() { val a = this.prev.prev val b = this.prev val d = this.next a.next = this this.next = b b.next = d this.prev = a b.prev = this d.prev = b } fun moveForward() { val b = this.prev val d = this.next val e = this.next.next b.next = d d.next = this this.next = e d.prev = b this.prev = d e.prev = this } } fun debugPrintOrder(num1: LinkedList, c: String) { var toPrint = num1.next println("Looking at: " + c) print(num1.value) while (num1 != toPrint) { print(", " + toPrint.value) toPrint = toPrint.next } println() } fun parse(input: String, times: Int = 1): List<LinkedList> { val list = input.lines().map { it.toLong() * times } .map { LinkedList(it) } for (i in 1 until list.size) { val prev = list[i - 1] val current = list[i] prev.next = current current.prev = prev } list.first().prev = list.last() list.last().next = list.first() return list } fun getResult(list: List<LinkedList>): MutableList<Long> { val num0 = list.filter { it.value == 0L }.first() var loopis = num0.next var counter = 1 val resultList = mutableListOf<Long>() while (counter <= 3000) { counter++ loopis = loopis.next if (counter % 1000 == 0) { resultList.add(loopis.value) } } return resultList } fun part1(input: String, debug: Boolean = false): Long { val list = parse(input) if (debug) debugPrintOrder(list.first(), "initial") list.forEach { c -> var value = c.value while (value != 0L) { if (value < 0) { c.moveBack() value++ } else { c.moveForward() value-- } } val num1 = list.first() if (debug) debugPrintOrder(num1, c.value.toString()) } val resultList = getResult(list) return resultList.sum() } fun part2(input: String, debug: Boolean = false): Long { val list = parse(input, 811589153) if (debug) debugPrintOrder(list.first(), "initial") repeat(10) { repeatNum -> list.forEach { c -> var value = c.value % list.size while (value != 0L) { if (value < 0) { c.moveBack() value++ } else { c.moveForward() value-- } } } val num1 = list.first { it.value == 0L } if (debug) debugPrintOrder(num1, repeatNum.toString()) } val resultList = getResult(list) return resultList.sum() } val testInput = "1\n" + "2\n" + "-3\n" + "3\n" + "-2\n" + "0\n" + "4" val input = AoCUtils.readText("year2022/day20.txt") part1(testInput, false) test Pair(3L, "test 1 part 1") part1(input, false) test Pair(4224L, "part 1") part2(testInput, true) test Pair(1623178306L, "test 2 part 2") part2(input) test Pair(0L, "part 2") }
0
Kotlin
0
0
631cbd22ca7bdfc8a5218c306402c19efd65330b
3,836
aoc-2022-kotlin
Apache License 2.0
Problems/Algorithms/1235. Maximum Profit in Job Scheduling/MaxProfit.kt
xuedong
189,745,542
false
{"Kotlin": 332182, "Java": 294218, "Python": 237866, "C++": 97190, "Rust": 82753, "Go": 37320, "JavaScript": 12030, "Ruby": 3367, "C": 3121, "C#": 3117, "Swift": 2876, "Scala": 2868, "TypeScript": 2134, "Shell": 149, "Elixir": 130, "Racket": 107, "Erlang": 96, "Dart": 65}
class Solution { fun jobScheduling(startTime: IntArray, endTime: IntArray, profit: IntArray): Int { val n = startTime.size val jobs = Array(n) { IntArray(3) { 0 } } for (i in 0..n-1) { jobs[i][0] = startTime[i] jobs[i][1] = endTime[i] jobs[i][2] = profit[i] } jobs.sortWith(compareBy { it[0] }) val start = (jobs.map { it[0] }).toIntArray() val dp = IntArray(n+1) { 0 } for (i in n-1 downTo 0) { val j = binarySearchLeft(start, jobs[i][1]) dp[i] = maxOf(dp[i+1], dp[j] + jobs[i][2]) } return dp[0] } private fun binarySearchLeft(nums: IntArray, target: Int): Int { var left = 0 var right = nums.size - 1 while (left <= right) { val mid = left + (right - left) / 2 if (nums[mid] >= target) { right = mid - 1 } else { left = mid + 1 } } return left } }
0
Kotlin
0
1
5e919965b43917eeee15e4bff12a0b6bea4fd0e7
1,070
leet-code
MIT License
aoc-2022/src/main/kotlin/nerok/aoc/aoc2022/day12/Day12.kt
nerok
572,862,875
false
{"Kotlin": 113337}
package nerok.aoc.aoc2022.day12 import nerok.aoc.utils.GenericGrid import nerok.aoc.utils.Input import nerok.aoc.utils.Point import nerok.aoc.utils.removeFirstOrNull import kotlin.time.DurationUnit import kotlin.time.measureTime fun main() { fun part1(input: List<String>): Long { val heightMap = GenericGrid(defaultValue = '.' to -1) var tmpStartPoint: Point<Pair<Char, Int>>? = null var tmpEndPoint: Point<Pair<Char, Int>>? = null input .filter { it.isNotEmpty() } .forEachIndexed { rowIndex, line -> heightMap.rows.add( line.mapIndexed { colIndex, s -> val point = Point(s to -1, rowIndex, colIndex) if (s == 'S') tmpStartPoint = point if (s == 'E') tmpEndPoint = point point }.toMutableList() ) } val startPoint = tmpStartPoint ?: throw NullPointerException("Start point not found") val endPoint = tmpEndPoint ?: throw NullPointerException("End point not found") heightMap[startPoint.row, startPoint.column].content = 'a' to -1 heightMap[endPoint.row, endPoint.column].content = 'z' to 0 var currentNode: Point<Pair<Char, Int>>? = endPoint val toCheck = mutableSetOf<Point<Pair<Char, Int>>>() while (currentNode != null) { heightMap .findLegalMoves(currentNode) .filter { it.content.second < 0 || it.content.second > currentNode!!.content.second + 1 } .map { neighbour -> neighbour.content = neighbour.content.first to currentNode!!.content.second + 1 neighbour } .also { toCheck.addAll(it) } currentNode = toCheck.removeFirstOrNull() } return startPoint.content.second.toLong() } fun part2(input: List<String>): Long { val heightMap = GenericGrid(defaultValue = '.' to -1) var tmpStartPoint: Point<Pair<Char, Int>>? = null var tmpEndPoint: Point<Pair<Char, Int>>? = null input .filter { it.isNotEmpty() } .forEachIndexed { rowIndex, line -> heightMap.rows.add( line.mapIndexed { colIndex, s -> val point = Point(s to -1, rowIndex, colIndex) if (s == 'S') tmpStartPoint = point if (s == 'E') tmpEndPoint = point point }.toMutableList() ) } val startPoint = tmpStartPoint ?: throw NullPointerException("Start point not found") val endPoint = tmpEndPoint ?: throw NullPointerException("End point not found") heightMap[startPoint.row, startPoint.column].content = 'a' to -1 heightMap[endPoint.row, endPoint.column].content = 'z' to 0 var currentNode: Point<Pair<Char, Int>>? = endPoint val toCheck = mutableSetOf<Point<Pair<Char, Int>>>() while (currentNode != null) { heightMap .findLegalMoves(currentNode!!) .filter { it.content.second < 0 || it.content.second > currentNode!!.content.second + 1 } .map { neighbour -> neighbour.content = neighbour.content.first to currentNode!!.content.second + 1 neighbour } .also { toCheck.addAll(it) } currentNode = toCheck.removeFirstOrNull() } return heightMap.rows .flatMap { row -> row.filter { point -> point.content.second > 0 && point.content.first == 'a' } } .minBy { it.content.second }.content.second.toLong() } // test if implementation meets criteria from the description, like: val testInput = Input.readInput("Day12_test") check(part1(testInput) == 31L) check(part2(testInput) == 29L) val input = Input.readInput("Day12") println(measureTime { println(part1(input)) }.toString(DurationUnit.MICROSECONDS, 3)) println(measureTime { println(part2(input)) }.toString(DurationUnit.MICROSECONDS, 3)) } private fun GenericGrid<Pair<Char, Int>>.findLegalMoves(currentPoint: Point<Pair<Char, Int>>): Set<Point<Pair<Char, Int>>> { val neighbours = this.orthogonalNeighbours(currentPoint) val legalMoves = mutableSetOf<Point<Pair<Char, Int>>>() neighbours.forEach { neighbour -> if (neighbour.content.first >= currentPoint.content.first - 1) { legalMoves.add(neighbour) } } return legalMoves }
0
Kotlin
0
0
7553c28ac9053a70706c6af98b954fbdda6fb5d2
4,780
AOC
Apache License 2.0
src/Day11.kt
kenyee
573,186,108
false
{"Kotlin": 57550}
import java.math.BigInteger interface Operation { fun exec(input: Long): Long } class Multiply(private val multiplier: Long) : Operation { override fun exec(input: Long): Long { return input * multiplier } } class Add(private val addValue: Long) : Operation { override fun exec(input: Long): Long { return input + addValue } } class Squared : Operation { override fun exec(input: Long): Long { return input * input } } data class Monkey( val itemWorryLevel: MutableList<Long>, val operation: (Long) -> Long, val shouldThrow: (Long) -> Boolean, val testDivisor: Int, val trueDest: Int, val falseDest: Int, var numInspections: Long = 0 ) fun main() { // ktlint-disable filename fun calcMonkeyInspections(input: List<String>, numRounds: Int, worryDivisor: Int): Long { val monkeys = mutableListOf<Monkey>() val opRegex = """Operation: new = old ([\+\*]) (old)?(\d+)?""".toRegex() val testRegex = """Test: divisible by (\d+)""".toRegex() input.windowed(7, step = 7, partialWindows = true).forEach { monkeyNotes -> val itemsList = monkeyNotes[1].split("items:")[1].split(",").map { it.trim().toLong() } val (_, op, old, opValue) = opRegex.find(monkeyNotes[2])!!.groupValues val testResult = testRegex.find(monkeyNotes[3])!!.groupValues[1].toInt() val trueResult = monkeyNotes[4].substring(monkeyNotes[4].lastIndexOf(" ") + 1).toInt() val falseResult = monkeyNotes[5].substring(monkeyNotes[5].lastIndexOf(" ") + 1).toInt() // NOTE: causes a backend compiler error w/ Kotlin 1.7.22 if you use the commented out code var operation = Squared()::exec if (old == "") operation = Multiply(opValue.toLong())::exec if (op == "+") operation = Add(opValue.toLong())::exec // val operation2 = when (op) { // "*" -> { // if (old == "old") Squared()::exec else Multiply(opValue.toLong())::exec // } // "+" -> { // Add(opValue.toInt())::exec // } // else -> { // throw IllegalArgumentException("Unexpected op: $op") // } // } monkeys.add( Monkey( itemWorryLevel = itemsList.toMutableList(), operation = operation, shouldThrow = { value -> value.rem(testResult) == 0L }, testDivisor = testResult, trueDest = trueResult, falseDest = falseResult ) ) } val testLCM = monkeys.map { BigInteger.valueOf(it.testDivisor.toLong()) } .reduce { acc, divisor -> acc.lcm(divisor) }.toLong() repeat(numRounds) { monkeys.forEach { monkey -> monkey.itemWorryLevel.forEach { level -> val newValue = if (worryDivisor == -1) { monkey.operation(level).rem(testLCM) } else { monkey.operation(level) / worryDivisor } if (monkey.shouldThrow(newValue)) { monkeys[monkey.trueDest].itemWorryLevel.add(newValue) } else { monkeys[monkey.falseDest].itemWorryLevel.add(newValue) } monkey.numInspections++ } monkey.itemWorryLevel.clear() } } val topMonkeys = monkeys.sortedByDescending { it.numInspections } // println("top monkeys: $topMonkeys") val topTwoInspectors = topMonkeys.take(2) return topTwoInspectors[0].numInspections * topTwoInspectors[1].numInspections } fun part1(input: List<String>): Long { return calcMonkeyInspections(input, numRounds = 20, worryDivisor = 3) } fun part2(input: List<String>): Long { return calcMonkeyInspections(input, numRounds = 10000, worryDivisor = -1) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day11_test") println("Test 20 rounds Top2 inspection count product: ${part1(testInput)}") check(part1(testInput) == 10605L) println("Test 10K rounds Top2 inspection count product: ${part2(testInput)}") check(part2(testInput) == 2713310158L) val input = readInput("Day11_input") println("Top2 20 rounds inspection count product: ${part1(input)}") println("Top2 10K rounds inspection count product: ${part2(input)}") }
0
Kotlin
0
0
814f08b314ae0cbf8e5ae842a8ba82ca2171809d
4,694
KotlinAdventOfCode2022
Apache License 2.0
LengthOfLongestSubstring.kt
linisme
111,369,586
false
null
class LengthOfLongestSubstringSolution { fun lengthOfLongestSubstring(s: String): Int { var set = hashSetOf<Char>() var maxLength = 0 val size = s.length s.forEachIndexed { index, c -> set.clear() var pos = index + 1 set.add(c) var next : Char? = if (pos < size) s.get(pos) else null while (next != null) { if (set.contains(next)) { break } set.add(next) pos++ next = if (pos < size) s.get(pos) else null } if (set.size > maxLength) { maxLength = set.size } } return maxLength } } class LengthOfLongestSubstringSolution2 { fun lengthOfLongestSubstring(s: String): Int { var maxLength = 0 var hashMap = hashMapOf<Char, Int>() var currentLength = 0 for (i in 0 until s.length) { val c = s.get(i) val preIndex = hashMap[c] hashMap[c] = i currentLength = if (preIndex == null || i - preIndex > currentLength) (currentLength + 1) else (i - preIndex) if (currentLength > maxLength) { maxLength = currentLength } } return maxLength } } fun main(args: Array<String>) { println(LengthOfLongestSubstringSolution2().lengthOfLongestSubstring("abba")) }
0
Kotlin
1
0
4382afcc782da539ed0d535c0a5b3a257e0c8097
1,331
LeetCodeInKotlin
MIT License
src/Day02.kt
ostersc
570,327,086
false
{"Kotlin": 9017}
fun main(){ fun part1(input: List<String>): Int { val dirMap= input.groupBy ( keySelector = {it.split(" ").get(0)}, valueTransform = { it.split(" ").get(1).toInt()}) return dirMap.get("forward")!!.sum() * (dirMap.get("down")!!.sum() -dirMap.get("up")!!.sum()) } fun part2(input: List<String>): Int { var aim=0 var horizontal=0 var depth=0 for(i in input){ val instruction=i.split(" ").get(0) val inc=i.split(" ").get(1).toInt() when(instruction){ "forward" ->{horizontal+=inc; depth+=aim*inc} "up" -> aim-=inc "down" -> aim+=inc } } return horizontal*depth } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput) == 150) check(part2(testInput) == 900) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
836ff780252317ee28b289742396c74559dd2b6e
1,016
advent-of-code-2021
Apache License 2.0
src/main/kotlin/g0801_0900/s0889_construct_binary_tree_from_preorder_and_postorder_traversal/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0801_0900.s0889_construct_binary_tree_from_preorder_and_postorder_traversal // #Medium #Array #Hash_Table #Tree #Binary_Tree #Divide_and_Conquer // #2023_04_09_Time_168_ms_(100.00%)_Space_35.5_MB_(75.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 constructFromPrePost(preorder: IntArray, postorder: IntArray): TreeNode? { return if (preorder.isEmpty() || preorder.size != postorder.size) { null } else buildTree(preorder, 0, preorder.size - 1, postorder, 0, postorder.size - 1) } private fun buildTree( preorder: IntArray, preStart: Int, preEnd: Int, postorder: IntArray, postStart: Int, postEnd: Int ): TreeNode? { if (preStart > preEnd || postStart > postEnd) { return null } val data = preorder[preStart] val root = TreeNode(data) if (preStart == preEnd) { return root } var offset = postStart while (offset <= preEnd) { if (postorder[offset] == preorder[preStart + 1]) { break } offset++ } root.left = buildTree( preorder, preStart + 1, preStart + offset - postStart + 1, postorder, postStart, offset ) root.right = buildTree( preorder, preStart + offset - postStart + 2, preEnd, postorder, offset + 1, postEnd - 1 ) return root } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,804
LeetCode-in-Kotlin
MIT License
src/main/kotlin/Day01.kt
arosenf
726,114,493
false
{"Kotlin": 40487}
import kotlin.system.exitProcess fun main(args: Array<String>) { if (args.isEmpty() or (args.size < 2)) { println("Calibration document not specified") exitProcess(1) } val calibrationDocument = args.first() println("Recovering $calibrationDocument") val calibrationValue = if (args[1] == "digits") { Day01().parseCalibrationDocumentDigits(calibrationDocument) } else { Day01().parseCalibrationDocumentDigitsAndText(calibrationDocument) } println("Calibration value: $calibrationValue") } class Day01 { /* * Part 1 */ fun parseCalibrationDocumentDigits(calibrationDocument: String): Int { return parse(readLines(calibrationDocument), ::extractCalibrationValueByDigits) } private fun extractCalibrationValueByDigits(calibrationLine: String): Int { val (digit, _) = calibrationLine.partition { c -> c.isDigit() } return if (digit.isEmpty()) { 0 } else { "${digit.first()}${digit.last()}".toInt() } } /* * Part 2 */ fun parseCalibrationDocumentDigitsAndText(calibrationDocument: String): Int { return parse(readLines(calibrationDocument), ::extractCalibrationValueByDigitsAndText) } private fun extractCalibrationValueByDigitsAndText(calibrationLine: String): Int { var result = Digits(null, null) val pointer = generateSequence(0) { it + 1 } pointer.take(calibrationLine.length).forEach { i -> result = if (calibrationLine.elementAt(i).isDigit()) { foundDigit(result, calibrationLine.elementAt(i)) } else { findWords(result, calibrationLine.substring(i)) } } return "${result.first ?: 0}${result.last ?: 0}".toInt() } private val words = listOf("one", "two", "three", "four", "five", "six", "seven", "eight", "nine") private fun findWords(result: Digits, substring: String): Digits { words.forEach { w -> if (substring.startsWith(w, true)) { return foundWord(result, w) } } return result } private fun foundDigit(digits: Digits, digit: Char): Digits { val value = digit.digitToInt() return Digits( digits.first ?: value, value ) } private fun foundWord(digits: Digits, word: String): Digits { val value = words.indexOf(word) + 1 return Digits( digits.first ?: value, value ) } /* * Stuff */ data class Digits(val first: Int?, val last: Int?) private fun parse(lines: Sequence<String>, extractor: (String) -> Int): Int { return lines .map(extractor) .reduce { x, y -> x + y } .or(0) } }
0
Kotlin
0
0
d9ce83ee89db7081cf7c14bcad09e1348d9059cb
2,886
adventofcode2023
MIT License
src/main/kotlin/days/Day11.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.* import kotlin.math.* fun main() { val data = readInput().map(String::toList).toGrid() val expandRows = data.verticalIndices.filter { y -> data.horizontalIndices.none { x -> data[x, y] == '#' } } val expandColumns = data.horizontalIndices.filter { x -> data.verticalIndices.none { y -> data[x, y] == '#' } } data class Pos(val x: Long, val y: Long) { infix fun distanceTo(other: Pos): Long = abs(other.x - x) + abs(other.y - y) } data class UnorderedPair(val first: Pos, val second: Pos) { override fun equals(other: Any?): Boolean = when { other === this -> true other is UnorderedPair -> (first == other.first && second == other.second) || (first == other.second && second == other.first) else -> false } override fun hashCode(): Int { val hash1 = first.hashCode() val hash2 = second.hashCode() return minOf(hash1, hash2) * 31 + maxOf(hash1, hash2) } override fun toString(): String = "[$first, $second]" } fun solve(expandBy: Long): Long { val galaxies = data.verticalIndices.flatMap { y -> data.horizontalIndices.mapNotNull { x -> if (data[x, y] == '.') return@mapNotNull null Pos( x = x.intValue.toLong() + expandColumns.count { x > it } * (expandBy - 1), y = y.intValue.toLong() + expandRows.count { y > it } * (expandBy - 1) ) } } return galaxies.flatMap { a -> galaxies.mapNotNull { b -> if (a != b) UnorderedPair(a, b) else null } }.toSet().sumOf { (a, b) -> a distanceTo b } } println("Part 1: ${solve(expandBy = 2L)}") println("Part 2: ${solve(expandBy = 1_000_000L)}") }
0
Kotlin
0
1
f94ff8a4c9fefb71e3ea183dbc3a1d41e6503152
2,966
AdventOfCode2023
MIT License
Bootcamp_01/test.kt
Hasuk1
740,111,124
false
{"Kotlin": 120039}
data class Incident( val x: Int, val y: Int, val type: IncidentType, val phoneNumber: String? ) enum class IncidentType(val name: String) { FIRE("Fire"), LEAK("Gas Leak"), CAT("Cat on the tree") } open class Zone( val phoneNumber: String = "800" ) { open fun isIncidentInside(incident: Incident): Boolean { return false } } class CircleZone( phoneNumber: String, val centerX: Int, val centerY: Int, val radius: Int ) : Zone(phoneNumber) { override fun isIncidentInside(incident: Incident): Boolean { val distance = Math.sqrt((incident.x - centerX).toDouble().pow(2) + (incident.y - centerY).toDouble().pow(2)) return distance <= radius } } class TriangleZone( phoneNumber: String, val point1: Pair<Int, Int>, val point2: Pair<Int, Int>, val point3: Pair<Int, Int> ) : Zone(phoneNumber) { override fun isIncidentInside(incident: Incident): Boolean { // Реализуйте логику для проверки, находится ли инцидент внутри треугольника return false } } class RectangleZone( phoneNumber: String, val point1: Pair<Int, Int>, val point2: Pair<Int, Int>, val point3: Pair<Int, Int>, val point4: Pair<Int, Int> ) : Zone(phoneNumber) { override fun isIncidentInside(incident: Incident): Boolean { // Реализуйте логику для проверки, находится ли инцидент внутри прямоугольника return false } } fun inputZone(): Zone? { println("Enter zone parameters:") val input = readLine() ?: return null val parts = input.split(" ") val phoneNumber = parts[0] val coordinates = parts.subList(1, parts.size).map { it.split(";").let { it[0].toInt() to it[1].toInt() } } return when (coordinates.size) { 1 -> { val (centerX, centerY, radius) = coordinates[0] CircleZone(phoneNumber, centerX, centerY, radius) } 3 -> { val (point1, point2, point3) = coordinates TriangleZone(phoneNumber, point1, point2, point3) } 4 -> { val (point1, point2, point3, point4) = coordinates RectangleZone(phoneNumber, point1, point2, point3, point4) } else -> null } } fun main() { val zone = inputZone() if (zone != null) { println("The zone info:") when (zone) { is CircleZone -> println(" The shape of zone: circle") is TriangleZone -> println(" The shape of zone: triangle") is RectangleZone -> println(" The shape of zone: rectangle") } println(" Phone number: ${zone.phoneNumber}") println("Enter an incident coordinates:") val incidentX = readLine()?.toInt() ?: return val incidentY = readLine()?.toInt() ?: return val incident = Incident(incidentX, incidentY, IncidentType.FIRE, null) println("The incident info:") println(" Description: ${incident.type.name}") incident.phoneNumber?.let { println(" Phone number: $it") } if (zone.isIncidentInside(incident)) { println("An incident is in the zone") } else { println("An incident is not in the zone") println("Switch the applicant to the common number: 88008473824") } } else { println("Invalid input format.") } }
0
Kotlin
0
1
1dc4de50dd3cd875e3fe76e3da4a58aa04bb87c7
3,504
Kotlin_bootcamp
MIT License
src/day20/Day20.kt
davidcurrie
579,636,994
false
{"Kotlin": 52697}
package day20 import java.io.File fun main() { val input = File("src/day20/input.txt").readLines().map { it.toLong() } println(grove(mix(input.mapIndexed { index, delta -> index to delta }.toMutableList()))) println(grove((1..10).fold(input.mapIndexed { index, delta -> index to delta * 811589153L } .toMutableList()) { positions, _ -> mix(positions) })) } fun mix(positions: MutableList<Pair<Int, Long>>): MutableList<Pair<Int, Long>> { positions.indices.forEach { index -> val from = positions.indexOfFirst { (initialIndex) -> initialIndex == index } val value = positions[from] val delta = value.second if (delta != 0L) { positions.removeAt(from) val to = (from + delta).mod(positions.size) positions.add(to, value) } } return positions } fun grove(positions: List<Pair<Int, Long>>): Long { val zeroPosition = positions.indexOfFirst { (_, delta) -> delta == 0L } return listOf(1000, 2000, 3000).sumOf { positions[(zeroPosition + it).mod(positions.size)].second } }
0
Kotlin
0
0
0e0cae3b9a97c6019c219563621b43b0eb0fc9db
1,089
advent-of-code-2022
MIT License
src/main/kotlin/nl/tiemenschut/aoc/y2023/day16.kt
tschut
723,391,380
false
{"Kotlin": 61206}
package nl.tiemenschut.aoc.y2023 import nl.tiemenschut.aoc.lib.dsl.aoc import nl.tiemenschut.aoc.lib.dsl.day import nl.tiemenschut.aoc.lib.util.Direction import nl.tiemenschut.aoc.lib.util.Direction.* import nl.tiemenschut.aoc.lib.util.grid.CharGridParser import nl.tiemenschut.aoc.lib.util.grid.Grid import nl.tiemenschut.aoc.lib.util.points.Point import nl.tiemenschut.aoc.lib.util.points.by typealias Beam = Pair<Point<Int>, Direction> fun Collection<Beam>.energized(): Int = map { it.first }.toSet().count() fun Beam.reflectForwardSlash(): Beam = when (second) { UP -> Beam(first.right(), RIGHT) DOWN -> Beam(first.left(), LEFT) LEFT -> Beam(first.down(), DOWN) RIGHT -> Beam(first.up(), UP) } fun Beam.reflectBackwardSlash(): Beam = when (second) { UP -> Beam(first.left(), LEFT) DOWN -> Beam(first.right(), RIGHT) LEFT -> Beam(first.up(), UP) RIGHT -> Beam(first.down(), DOWN) } fun Beam.forward() = Beam(first.moved(second), second) fun Beam.split() = when (second) { in listOf(RIGHT, LEFT) -> setOf(copy(second = UP).forward(), copy(second = DOWN).forward()) else -> setOf(copy(second = LEFT).forward(), copy(second = RIGHT).forward()) } fun Beam.next(c: Char): Set<Beam> = when (c) { '.' -> setOf(forward()) '/' -> setOf(reflectForwardSlash()) '\\' -> setOf(reflectBackwardSlash()) '-' -> if (second in listOf(RIGHT, LEFT)) setOf(forward()) else split() '|' -> if (second in listOf(UP, DOWN)) setOf(forward()) else split() else -> throw RuntimeException() } operator fun <T> Grid<T>.contains(p: Point<Int>) = (p.x in 0 until width() && p.y in 0 until height()) fun main() { aoc(CharGridParser) { puzzle { 2023 day 16 } fun propagateBeams(beams: Set<Beam>, visited: Set<Beam>, grid: Grid<Char>): Set<Beam> { val next = beams .flatMap { it.next(grid[it.first]) } .filter { it.first in grid } .toSet() - visited if (visited.containsAll(next)) return visited return propagateBeams(next, visited + next, grid) } part1 { input -> val startingBeams = setOf(Beam(0 by 0, RIGHT)) propagateBeams(startingBeams, startingBeams, input).energized() } part2 { input -> val startingBeams = buildSet { addAll((0 until input.width()).map { Beam(it by 0, DOWN) }) addAll((0 until input.width()).map { Beam(it by input.height() - 1, UP) }) addAll((0 until input.height()).map { Beam(0 by it, RIGHT) }) addAll((0 until input.height()).map { Beam(input.height() - 1 by it, LEFT) }) } startingBeams.maxOf { beam -> propagateBeams(setOf(beam), setOf(beam), input).energized() } } } }
0
Kotlin
0
1
a1ade43c29c7bbdbbf21ba7ddf163e9c4c9191b3
2,848
aoc-2023
The Unlicense
kotlin/wordy/src/main/kotlin/Wordy.kt
ErikSchierboom
27,632,754
false
{"C++": 14523188, "C": 1712536, "C#": 843402, "JavaScript": 766003, "Java": 570202, "F#": 559855, "Elixir": 504471, "Haskell": 499200, "Shell": 393291, "TypeScript": 381035, "Kotlin": 326721, "Scala": 321830, "Clojure": 303772, "Nim": 283613, "Ruby": 233410, "Elm": 157678, "Crystal": 155384, "Go": 152557, "Gleam": 150059, "Zig": 139897, "Python": 115799, "Makefile": 105638, "COBOL": 86064, "Prolog": 80765, "D": 66683, "CoffeeScript": 66377, "Scheme": 63956, "CMake": 62581, "Visual Basic .NET": 57136, "Rust": 54763, "Julia": 49727, "R": 43757, "Swift": 42546, "WebAssembly": 29203, "Wren": 27102, "Ballerina": 26773, "Fortran": 10325, "PowerShell": 4747, "OCaml": 4629, "Awk": 4125, "Tcl": 2927, "PLSQL": 2402, "Roff": 2089, "Lua": 1038, "Common Lisp": 915, "Assembly": 753, "Reason": 215, "jq": 37, "JSONiq": 16}
import java.lang.IllegalStateException import kotlin.math.pow object Wordy { const val PREFIX = "What is " const val SUFFIX = "?" fun answer(input: String): Int { require(input.startsWith(PREFIX)) require(input.endsWith(SUFFIX)) val parts = input.drop(PREFIX.length).dropLast(SUFFIX.length).split(' ') val initial = parts[0].toInt() return evaluate(initial, parts.drop(1)) } fun evaluate(acc: Int, unevaluated: List<String>): Int { if (unevaluated.isEmpty()) return acc return when { unevaluated[0] == "plus" -> evaluate(acc + unevaluated[1].toInt(), unevaluated.drop(2)) unevaluated[0] == "minus" -> evaluate(acc - unevaluated[1].toInt(), unevaluated.drop(2)) unevaluated[0] == "multiplied" && unevaluated[1] == "by" -> evaluate(acc * unevaluated[2].toInt(), unevaluated.drop(3)) unevaluated[0] == "divided" && unevaluated[1] == "by" -> evaluate(acc / unevaluated[2].toInt(), unevaluated.drop(3)) unevaluated[0] == "raised" && unevaluated[1] == "to" && unevaluated[2] == "the" && unevaluated[4] == "power" -> evaluate(acc.pow(unevaluated[3].replace("th", "").toInt()), unevaluated.drop(5)) else -> throw IllegalStateException("Invalid equation") } } private fun Int.pow(n: Int) = toDouble().pow(n).toInt() }
0
C++
10
29
d84c9d48a2d3adb0c37d7bd93c9a759d172bdd8e
1,399
exercism
Apache License 2.0
src/All_Filters_and_Built_In_Functions/getOrElse_first_last_map_max_min_filter_all_any_associateBy_groupBy.kt
RedwanSharafatKabir
280,724,526
false
null
package All_Filters_and_Built_In_Functions data class Hero( val name: String, val age: Int, val gender: Gender? ) enum class Gender { MALE, FEMALE } fun main (args: Array<String>){ val heroes = listOf( Hero("The Captain", 60, Gender.MALE), Hero("Frenchy", 42, Gender.MALE), Hero("<NAME>", 9, null), Hero("<NAME>", 29, Gender.FEMALE), Hero("<NAME>", 29, Gender.MALE), Hero("<NAME>", 37, Gender.MALE)) println(heroes.last().name) println(heroes.firstOrNull { it.age == 30 }?.name) println() try { println(heroes.first { it.age == 30 }.name) // It will throw exception } catch (e: Exception){ println(e)} println() println(heroes.map { it.gender }) println() println(heroes.map { it.age }) println(heroes.map { it.age }.distinct()) println(heroes.map { it.age }.distinct().size) // distinct() function will count two 29 ages once println() println(heroes.filter { it.age<30 }.size) // .filter shows output based on the given condition val (youngest, oldest) = heroes.partition { it.age < 30 } // .partition is similar to .filter println(oldest.size) println(youngest.size) println() println(heroes.maxBy { it.age }?.name) // .maxBy shows output based on the maximum value of given condition println(heroes.minBy { it.age }?.name) // .minBy shows output based on the minimum value of given condition println(heroes.groupBy { it.age==29 }) println() println(heroes.all { it.age<50 }) // here .all checks if all the values of ages are less than 50 println() println(heroes.any { it.gender == Gender.FEMALE }) // checks if any gender is FEMALE println() val mapByAge: Map<Int, List<Hero>> = heroes.groupBy { it.age } val (age, group) = mapByAge.maxBy { (_, group) -> group.size }!! println("$age $group") val mapByName: Map<String, Hero> = heroes.associateBy { it.name } // age of Frenchy println(mapByName["Frenchy"]?.age) // map[key] println(mapByName.getValue("Frenchy").age) // map.getValue(key) println(mapByName["Unknown"]?.age) // map[key] try { println(mapByName.getValue("Unknown").age) // map.getValue(key) } catch (e:Exception){ println(e) } val mapByName1 = heroes.associate { it.name to it.age } println(mapByName1.getOrElse("Unknown") { 0 }) val mapByName2 = heroes.associateBy { it.name } val unknownHero = Hero("Unknown", 25, null) println(mapByName2.getOrElse("unknown") { unknownHero }.age) // print maximum and minimum value using "flatMap" function val allPossiblePairs = heroes .flatMap { first -> heroes.map { second -> first to second }} val (older, younger) = allPossiblePairs.maxBy { it.first.age - it.second.age }!! println(older.name + ", " + younger.name) }
0
Kotlin
0
3
f764850ab3a7d0949f3e0401b0fe335d9df30cab
2,920
OOP-Kotlin
MIT License
app/src/test/java/com/terencepeh/leetcodepractice/LowestCommonAncestorBST.kt
tieren1
560,012,707
false
{"Kotlin": 26346}
package com.terencepeh.leetcodepractice /** * Created by <NAME> on 26/10/22. */ /** * Definition for a binary tree node. * class TreeNode(var `val`: Int = 0) { * var left: TreeNode? = null * var right: TreeNode? = null * } */ class TreeNode(var `val`: Int = 0) { var left: TreeNode? = null var right: TreeNode? = null } fun lowestCommonAncestor(root: TreeNode?, p: TreeNode?, q: TreeNode?): TreeNode? { if (root == null) { return null } val current = root.`val` val pVal = p!!.`val` val qVal = q!!.`val` if (pVal > current && qVal > current) { return lowestCommonAncestor(root.right, p, q) } if (pVal < current && qVal < current) { return lowestCommonAncestor(root.left, p, q) } return root } fun lowestCommonAncestor2(root: TreeNode?, p: TreeNode?, q: TreeNode?): TreeNode? { if (root == null) { return null } var node = root val pVal = p!!.`val` val qVal = q!!.`val` while (node != null) { node = if (pVal > node.`val` && qVal > node.`val`) { node.right } else if (pVal < node.`val` && qVal < node.`val`) { node.left } else { break } } return node } fun main() { val input = TreeNode(6).apply { left = TreeNode(2).apply { left = TreeNode(0) right = TreeNode(4).apply { left = TreeNode(3) right = TreeNode(5) } } right = TreeNode(8).apply { left = TreeNode(7) right = TreeNode(9) } } print(input) var p = TreeNode(2) var q = TreeNode(8) println(lowestCommonAncestor(input, p, q)?.`val`) p = TreeNode(2) q = TreeNode(4) println(lowestCommonAncestor2(input, p, q)?.`val`) p = TreeNode(2) q = TreeNode(1) println(lowestCommonAncestor(input, p, q)?.`val`) }
0
Kotlin
0
0
427fa2855c01fbc1e85a840d0be381cbb4eec858
1,946
LeetCodePractice
MIT License
src/Day03.kt
petoS6
573,018,212
false
{"Kotlin": 14258}
fun main() { fun part1(input: List<String>): Int { return input.sumOf { it.commonChar().priority() } } fun part2(input: List<String>): Int { return input.chunked(3).sumOf { it.commonChar().priority() } } val testInput = readInput("Day03.txt") println(part1(testInput)) println(part2(testInput)) } private fun String.commonChar(): Char { val length = length val firstPart = take(length / 2) val secondPart = takeLast(length / 2) return firstPart.find { secondPart.contains(it) }!! } private fun List<String>.commonChar() = get(0).find { get(1).contains(it) && get(2).contains(it) }!! val chars = ('a'..'z') + ('A'..'Z') private fun Char.priority(): Int = chars.indexOf(this) + 1
0
Kotlin
0
0
40bd094155e664a89892400aaf8ba8505fdd1986
720
kotlin-aoc-2022
Apache License 2.0
kotlin/0767-reorganize-string.kt
neetcode-gh
331,360,188
false
{"JavaScript": 473974, "Kotlin": 418778, "Java": 372274, "C++": 353616, "C": 254169, "Python": 207536, "C#": 188620, "Rust": 155910, "TypeScript": 144641, "Go": 131749, "Swift": 111061, "Ruby": 44099, "Scala": 26287, "Dart": 9750}
class Solution { fun reorganizeString(s: String): String { var count = HashMap<Char, Int>().apply { for (c in s) this[c] = getOrDefault(c, 0) + 1 } val maxHeap = PriorityQueue<Pair<Int, Char>>() { a, b -> b.first - a.first } for ((ch, cnt) in count) maxHeap.add(cnt to ch) var prev: Pair<Int, Char>? = null var res = StringBuilder() while (maxHeap.isNotEmpty() || prev != null) { if (maxHeap.isEmpty() && prev != null) return "" var (cnt, ch) = maxHeap.poll() res.append(ch) cnt-- prev?.let { maxHeap.add(it) prev = null } if (cnt != 0) prev = cnt to ch } return res.toString() } } // another solution without heap class Solution { fun reorganizeString(s: String): String { val freq = IntArray (26).apply { for (c in s) this[c - 'a']++ } var maxFreq = -1 var maxChar = -1 for (letter in 0..25) { if (freq[letter] > maxFreq) { maxFreq = freq[letter] maxChar = letter } } if (maxFreq > (s.length + 1) / 2) return "" var i = 0 val res = CharArray (s.length).apply { while (freq[maxChar] > 0) { this[i] = 'a' + maxChar i += 2 freq[maxChar]-- } } for (letter in 0..25) { while (freq[letter] > 0) { if (i > s.lastIndex) i = 1 res[i] = 'a' + letter i += 2 freq[letter]-- } } return res.joinToString("") } }
337
JavaScript
2,004
4,367
0cf38f0d05cd76f9e96f08da22e063353af86224
1,864
leetcode
MIT License
src/day08/Day08.kt
armanaaquib
572,849,507
false
{"Kotlin": 34114}
package day08 import readInput fun main() { fun parseInput(input: List<String>) = input.map { row -> row.split("").filter { it.isNotEmpty() }.map { it.toInt() } } // fun isEdge(data: List<List<Int>>, r: Int, c: Int): Boolean { // return r == 0 || r == data.lastIndex || c == 0 || c == data[r].lastIndex // } // fun isVisibleFromLeft(data: List<List<Int>>, r: Int, c: Int): Boolean { // if (data[r][c] <= data[r][c-1]) return false // // var column = c - 1 // while (column > 0 && data[r][column] >= data[r][column - 1]) { // column-- // } // // return column == 0 // } // // fun isVisibleFromTop(data: List<List<Int>>, r: Int, c: Int): Boolean { // if (data[r][c] <= data[r - 1][c]) return false // // var row = r - 1 // while (row > 0 && data[row][c] >= data[row - 1][c]) { // row-- // } // // return row == 0 // } // // fun isVisibleFromRight(data: List<List<Int>>, r: Int, c: Int): Boolean { // if (data[r][c] <= data[r][c + 1]) return false // // var column = c + 1 // while (column < data[r].lastIndex && data[r][column] >= data[r][column + 1]) { // column++ // } // // return column == data[r].lastIndex // } // // fun isVisibleFromBottom(data: List<List<Int>>, r: Int, c: Int): Boolean { // if (data[r][c] <= data[r + 1][c]) return false // // var row = r + 1 // while (row < data.lastIndex && data[row][c] >= data[row + 1][c]) { // row++ // } // // return row == data.lastIndex // } // // fun isVisible(data: List<List<Int>>, r: Int, c: Int): Boolean { // return isEdge(data, r, c) || isVisibleFromLeft(data, r, c) || isVisibleFromTop(data, r, c) || isVisibleFromRight(data, r, c) || isVisibleFromBottom(data, r, c) // } // fun part1(input: List<String>): Int { // val data = parseInput(input) // var visibleTrees = 0 // // for (r in data.indices) { // for (c in data[r].indices) { // if (isVisible(data, r, c)) { // visibleTrees++ // } // } // } // //// println(visibleTrees) // return visibleTrees // } fun findLeftDistance(data: List<List<Int>>, row: Int, col: Int): Int { var distance = 0 var c = col while (c > 0) { distance++ if(data[row][c - 1] >= data[row][col]) break c-- } return distance } fun findTopDistance(data: List<List<Int>>, row: Int, col: Int): Int { var distance = 0 var r = row while (r > 0) { distance++ if(data[r - 1][col] >= data[row][col]) break r-- } return distance } fun findRightDistance(data: List<List<Int>>, row: Int, col: Int): Int { var distance = 0 var c = col while (c < data[row].lastIndex) { distance++ if(data[row][c + 1] >= data[row][col]) break c++ } return distance } fun findBottomDistance(data: List<List<Int>>, row: Int, col: Int): Int { var distance = 0 var r = row while (r < data.lastIndex) { distance++ if(data[r + 1][col] >= data[row][col]) break r++ } return distance } fun findDistance(data: List<List<Int>>, r: Int, c: Int): Int { val leftDistance = findLeftDistance(data, r, c) val topDistance = findTopDistance(data, r, c) val rightDistance = findRightDistance(data, r, c) val bottomDistance = findBottomDistance(data, r, c) // println("$r,$c -> $leftDistance,$topDistance,$rightDistance,$bottomDistance") return leftDistance * topDistance * rightDistance * bottomDistance } fun part2(input: List<String>): Int { val data = parseInput(input) var maxDistance = 0 for (r in data.indices) { for (c in data[r].indices) { val distance = findDistance(data, r, c) if (distance > maxDistance) maxDistance = distance } } return maxDistance } // test if implementation meets criteria from the description, like: // check(part1(readInput("Day08_test")) == 21) // println(part1(readInput("Day08"))) check(part2(readInput("Day08_test")) == 8) println(part2(readInput("Day08"))) }
0
Kotlin
0
0
47c41ceddacb17e28bdbb9449bfde5881fa851b7
4,528
aoc-2022
Apache License 2.0
advent-of-code-2020/src/test/java/aoc/Day19MonsterMessages.kt
yuriykulikov
159,951,728
false
{"Kotlin": 1666784, "Rust": 33275}
package aoc import org.assertj.core.api.Assertions.assertThat import org.junit.Test sealed class Rule(open val index: Int) data class Compound( override val index: Int, val or: List<List<Int>>, ) : Rule(index) data class Letter( override val index: Int, val letter: String, ) : Rule(index) data class Repeating( override val index: Int, val child: Int, ) : Rule(index) data class Recursive( override val index: Int, val left: Int, val right: Int, ) : Rule(index) class Day19MonsterMessages { @Test fun silverTest() { assertThat(matchingRows(testInput).count()).isEqualTo(2) } @Test fun silver() { assertThat(matchingRows(taskInput).count()).isEqualTo(279) } private fun matchingRows(input: String): List<String> { val regex = parseRules(input).expand(0) .toRegex() val toTest = input.substringAfter("\n\n") .lines() return toTest.filter { line -> regex.matches(line) } } /** expand rule to regex string*/ private fun Map<Int, Rule>.expand(index: Int = 0): String { return when (val rule = getValue(index)) { is Letter -> rule.letter is Compound -> rule.or.joinToString("|", "(", ")") { children -> children.joinToString("") { child -> expand(child) } } is Repeating -> "(${expand(rule.child)})+" is Recursive -> { // 11: 42 31 | 42 11 31 // 11: 42 (42 (42 (42 (42 31)? 31)? 31)? 31)? 31 val exp1 = expand(rule.left) val exp2 = expand(rule.right) "$exp1($exp1($exp1($exp1$exp2)?$exp2)?$exp2)?$exp2" } } } private fun parseRules(input: String) = input.substringBefore("\n\n") .lines() .map { line -> val index = line.substringBefore(":").toInt() when (val tail = line.substringAfter(": ")) { "\"a\"" -> Letter(index, "a") "\"b\"" -> Letter(index, "b") else -> { val children = tail .split("|") .map { subline -> subline.trim().split(" ").map { it.toInt() } } Compound(index, children) } } }.associateBy { it.index } @Test fun goldTest() { val regex = parseRules(testInput2) .plus(8 to Repeating(8, 42)) .plus(11 to Recursive(11, 42, 31)) .expand(0) .toRegex() val toTest = testInput2.substringAfter("\n\n").lines() assertThat(toTest.filter { line -> regex.matches(line) }.count()).isEqualTo(12) } @Test fun gold() { val regex = parseRules(taskInput) .plus(8 to Repeating(8, 42)) .plus(11 to Recursive(11, 42, 31)) .expand(0) .toRegex() val toTest = taskInput.substringAfter("\n\n").lines() assertThat(toTest.filter { line -> regex.matches(line) }.count()).isEqualTo(384) } private val testInput2 = """ 42: 9 14 | 10 1 9: 14 27 | 1 26 10: 23 14 | 28 1 1: "a" 11: 42 31 5: 1 14 | 15 1 19: 14 1 | 14 14 12: 24 14 | 19 1 16: 15 1 | 14 14 31: 14 17 | 1 13 6: 14 14 | 1 14 2: 1 24 | 14 4 0: 8 11 13: 14 3 | 1 12 15: 1 | 14 17: 14 2 | 1 7 23: 25 1 | 22 14 28: 16 1 4: 1 1 20: 14 14 | 1 15 3: 5 14 | 16 1 27: 1 6 | 14 18 14: "b" 21: 14 1 | 1 14 25: 1 1 | 1 14 22: 14 14 8: 42 26: 14 22 | 1 20 18: 15 15 7: 14 5 | 1 21 24: 14 1 abbbbbabbbaaaababbaabbbbabababbbabbbbbbabaaaa bbabbbbaabaabba babbbbaabbbbbabbbbbbaabaaabaaa aaabbbbbbaaaabaababaabababbabaaabbababababaaa bbbbbbbaaaabbbbaaabbabaaa bbbababbbbaaaaaaaabbababaaababaabab ababaaaaaabaaab ababaaaaabbbaba baabbaaaabbaaaababbaababb abbbbabbbbaaaababbbbbbaaaababb aaaaabbaabaaaaababaa aaaabbaaaabbaaa aaaabbaabbaaaaaaabbbabbbaaabbaabaaa babaaabbbaaabaababbaabababaaab aabbbbbaabbbaaaaaabbbbbababaaaaabbaaabba """.trimIndent() private val testInput = """ 0: 4 1 5 1: 2 3 | 3 2 2: 4 4 | 5 5 3: 4 5 | 5 4 4: "a" 5: "b" ababbb bababa abbbab aaabbb aaaabbb """.trimIndent() private val taskInput = """ 25: 6 54 | 28 122 52: 27 54 | 25 122 44: 118 122 | 30 54 37: 122 97 | 54 98 38: 122 22 | 54 3 77: 54 34 | 122 7 17: 122 124 | 54 47 1: 54 79 | 122 119 13: 122 121 | 54 15 29: 122 3 | 54 97 24: 54 97 | 122 62 80: 122 1 | 54 21 62: 54 54 | 122 54 5: 54 61 | 122 119 28: 54 57 | 122 36 101: 122 48 | 54 44 81: 120 54 | 14 122 14: 54 96 | 122 38 18: 40 122 | 76 54 27: 122 93 | 54 103 4: 123 122 | 90 54 65: 122 87 | 54 22 113: 54 | 122 23: 122 127 | 54 62 117: 71 54 | 119 122 53: 35 54 | 126 122 26: 122 52 | 54 108 125: 54 33 | 122 4 10: 74 122 | 53 54 84: 54 19 | 122 109 123: 122 114 | 54 115 42: 70 122 | 26 54 16: 122 39 | 54 98 63: 98 54 | 51 122 39: 54 122 76: 122 83 | 54 101 61: 122 3 | 54 39 50: 122 85 | 54 95 78: 22 122 | 3 54 114: 122 122 64: 122 122 | 122 54 40: 122 81 | 54 55 92: 127 122 | 97 54 119: 122 51 57: 98 54 | 114 122 3: 113 122 | 54 54 97: 122 113 | 54 122 7: 122 37 | 54 59 74: 54 46 | 122 56 2: 122 67 | 54 50 48: 43 122 | 65 54 124: 54 94 | 122 36 82: 54 98 | 122 64 93: 59 122 | 116 54 96: 115 122 | 97 54 98: 54 54 60: 51 54 | 22 122 72: 122 98 | 54 3 106: 39 54 | 39 122 41: 51 54 | 97 122 31: 18 54 | 69 122 91: 122 62 | 54 127 120: 105 122 | 19 54 56: 60 122 | 78 54 47: 16 122 | 91 54 88: 97 113 30: 22 122 | 115 54 71: 51 54 | 39 122 87: 122 122 | 54 122 21: 122 102 | 54 73 43: 122 22 | 54 127 35: 54 23 | 122 90 51: 113 113 90: 122 62 | 54 87 32: 54 127 | 122 97 115: 122 54 | 54 113 55: 54 84 | 122 89 73: 122 51 | 54 39 36: 22 54 | 114 122 68: 122 87 | 54 98 34: 118 54 | 32 122 95: 54 87 83: 122 117 | 54 20 33: 99 54 | 29 122 19: 122 127 | 54 98 46: 54 112 | 122 79 89: 54 72 | 122 66 110: 54 51 | 122 98 109: 64 54 | 22 122 9: 54 107 | 122 5 12: 54 80 | 122 45 104: 54 100 | 122 32 15: 75 122 | 63 54 69: 122 49 | 54 12 8: 42 75: 97 54 | 3 122 108: 122 77 | 54 125 103: 122 88 | 54 24 111: 3 54 | 39 122 70: 122 58 | 54 10 20: 122 105 | 54 68 0: 8 11 122: "a" 79: 62 54 | 22 122 102: 87 122 | 97 54 105: 98 54 | 98 122 49: 13 54 | 2 122 112: 54 39 | 122 62 58: 9 122 | 17 54 11: 42 31 107: 66 122 | 110 54 86: 54 106 | 122 82 99: 127 122 | 39 54 22: 54 122 | 122 54 118: 54 3 | 122 64 67: 122 59 | 54 111 126: 78 54 | 92 122 121: 54 41 | 122 38 66: 22 113 94: 54 39 6: 88 122 | 29 54 127: 122 54 116: 54 39 | 122 87 59: 54 51 85: 64 122 | 97 54 100: 98 122 | 62 54 54: "b" 45: 86 122 | 104 54 baaabbaabababaaababaaaaababbbabaabbbabba baabbbbbaababbabaaabbabb abbabbaabbabbbaabbabaaaaaabaabbbabbabbaa bababbaababaabbaaabbabbb baaabbaababbbbaabbbaaaba bababbaababbbbbbaabbbbbb ababababbabbaababbaabbbabbaabababaaababbaabaaaabbbbbaaaa bbabbabaaaaabaaabbaabbab abbbaabbababaabbbaabaaab bababaaaabbbbbaaaabbbbbb bbabaabbbbabbaabbabaabbaabbbbbaa babaabaaabaaabbbbbbabbababaaabbbaaaaababbaabaabb abaaaaaabaaabbbabbbaaabaababaabaaabababaaabaabba aabbbaaaababbaaaaababbbb babaabbaaaaabaaabaabbbabbababbbb aabbabbbbbabaaaabbaabbab abbabaaaaaaaaaaaabaabbbbaaabbbabaaabbabb aaababbbaabbabbbaaabaaba babbaabbbabaaaaaaabbbbabbabaabbababbbbabaababbba abababbbabbabbaabaaabbbbababbabb aaaaabbbbbbbaaaabbbaaabb baababaaababaaabbaabaaabaabbabbabbaaaabb babaabbbababaabaaababbbb babaabaababbbbbbaabbaaba babaabbbbabaaaabbbabbbaaaabaaaba bbbabbbabbbbbaabbbbaabba aaaaaababbabbbaaaaabbabb bbabbbaaaababaaaababaaab baabaababbbbbbbaaaaababb abaababbaaaabbbaaabbabababaababbbbaabaab abbbbbaaaababaabbbbababa aabbabababbbbbaabbaaabba abbaaababaabbbaaaabbaaaabbbabbabbababababaaaaaaabaabaabaaaaabaabbaabaaabaababbbbbbaabbaa abbabaaaaaaaababbbbaabba bbabbbaaaaabaababbbbbaaabbaaaabababbbabaabbabaababaaababbaabbbbbaababbbb abbabaabbbbbaababbabbbbaabbaaaab baaaabababaabbabbbbbbaabbaaaaabbbabbbbba abbbabbbbbabaabbaaabaabb aaaaababbbbabbaabaababba baabbbbaaaaabbababababba bbbabbaaabbaaaaaabaabbaa babbaabbbabbaabbaaababababaaabab ababaabbbaaabaaabaaaababbbaababaaababaabbbbbabbaaabbaaaa aabbbabaaaaaabaaaaabbbaa aabaaabbbbbbbbbaaabababa abbaabababbbaabbbabbbbaaaaaaabbaaaababababaabbbabbbababa aabbbabbabbaaaaabbbaaabb bbbabbbabbaabbbbbbbaaaba bbabababaababbaaababbaab abbabbbabbbbbaaaabbabaaabbabaabaababbaaaaaabbabb abbbbaabbabaaababbabaaab aabbbbabaaaabbbaabbaabbbbbaabaaaaaaaaabaaaabbbaabaabaaab abaaabababbbbaabbbbbaaba bbbbbabbbabbbaaabbaababaaaabbabbaaaaaaabaaaaaaaaabbabaaaabbabbaabbbbaaabaaaabbba baabaabaabbbabbbbbaabaaaaaabbbaa bbbaaaaabbbbbbaabbaabaabbbbbbbbbabbababaaabbbbbb bababaabbabaabbabbbbbabababaaabb abaabbabaabaaabbbbaaabba babbaababbabbaababbbbaaa aabaababbabaababaababbbb aaababbaabbaaaaababaaabaaabbbabbbaaabababbbabbbb aaaaaabaabaabbbaabaaabaa babaabababbabaaaaaaababb bbabaabbabaabbbaaaaaaabb abbabbbbbaaabbaaaaabaaab ababaaaabbabbbaabababaaaaababaabbbaabbaaaababbbb babaaaaaababbbbaaabbbaaaabbbbbabbbababba bbbbabbbaababbabaabaabba babbabbbbaaaaabbbabbbaaaabaabaaa aabaaabbaabbbbabbbbababa babbabbaaaababbbaabbaaaa aabaababbaaabbbbbbbaabbb babaaaabbabaabbaabaaabababbaabbbbaaaabbb bbaabbbbbbabbbababbbabba bbbabaabbaabaabababbbaaa bbabaabbbaababbaaaabbbababbaaabaaaaabababaaaabbabbbaaabb ababaabababaabbbbbababaa abbabbaabbbbabababbababb baabbbbaaababbabaaabbaaa ababaabaababababaaabbabb babbbbaaabaabbbababbaaaa aaaabbabbabaaabbbbbaabbb babbababaabbbababbabababbababbba aabbbabbbaaabbaabbbabaaa aaaabbabbbbabbaaaaabbbba aaabbaabaaaaabaababaabbaababaaaababaabababbbaaaababbabaa babbabbabbaabbaaaaabbbbb bbababbbaaaabaaaabbaababbbaabaabaababbbabbbbbbaabbbaababbbbbbaabaaaaabbbaabbbbabaabbbbba aabbbabaaaaaabbbbbaabbaababbaaabaabaabbbaabaabbb bababaababbbbbaaabbaabab baaaaaababaaaaabbabbbbba aaababbabaaaababbbabbbaabbbbaabb bbabbbaabaaaababbaaaaaba abbbbbaaaabbbbababbbaaba bbbababbabbbaabbbbbbabaa abbbbabaabababbbbabaabaabbbaabba bbbbbbbaabbaabaabbbbaaaa bbbbbaaabaabaaaabaababbb abaaababbbbbbaaaaabbbaab abaaaaabbbbaaaabaababbaa baaaababbbabaabbaaabaaab aaababbbaaabbaababaaaaaabbaaaabaaaaabbaa bbabbaabbaaaababbbaababaaabbabba abaaaaabbbbaaaabbaaabaab ababbbaaabbabbabbabbaaab baaabbbbaaabbaababaabbabababbabb abbabbbbbbaaabbbbbaaaabb baabbbaaabbbabbbbababbaabbbbbbbbabbaaaabbbaababbbaaaaabbbabaabbaaababbbbbabaaaba aababbaabbbbbababbbbabbabbababbaabbaabbaaaaaaaab bbbbaaabaaabababbbabbababbbaabab bbaabababbaaabbbaaaababb abbbaabbbaabbaabbaababba aabababbbabbbbaabaaaaaabbbaabbabbabbabbb babbbbbabbbbbbbaaaaaabaaababbbbaaaabbaaa babaabbaaabbabababbbbbbb bbbaabaaabaaaaabbabaaabbaabaabaa babbababaabaababababaabaababaaab bbaaaaababbabbabbbbbaabb babbbabbabaaaabbabaabaaa babbababbaabbaabbbaabaab abbabaabbaaabaaaaabbbabbbbabbabaaababbbbbabaabba bababbaabaabbbabbbabbbbb babbbbbbbaaaaabbbbababaa baaaaaababbabaabbaaaaaba aabababbbbaababaabbaabaaaaaabaaabaababba abaaababbaabbabbaaaaababaabbaabbabbaaaabbbbaababababaaba bbbabbbababbbabbbbbaabaaaababbaababaaaaabaababaaabbaabababbaabab aaababbbbbabaabaababbaab bbbbaaabbbbabbbabbbbaaaa bbbabbababaaababaaaababb baabbbbbbbabaababababaabaabbaaaaaabbabaa abbabbaaaaaabbbaababbbbb bbaabbbbbaaabbbbbbbaabba bbbaaaababbabbabbaababab baaabbaababaabaaabbbabab ababaaaaaabaaabbabaabbaa aababaabbababbaababbababbbaabababaabbabababbabaaaaababaaaabbbaabaabaabaa bbaababababbabbaababaaab aaabababababbbbabbbaabab aabaaaaabaaaaabbaaaaababaaabbaabbaabbbabbaababab bbaaabaaaaabaabbabaaaaba babbbbabbabbbbaaabbaaaaaabbaabbababababb abbbbaabaaababbbbabbabbabbaabaaabbbbbbbbbaaaabaabbaaabab abbaaaaaabbbbabbabaabbbbaaaabababbbbaaba bababaaaababbbbaaaababbaababbaaababaaababababbbbaaabbbba baaabbbbabaaaaabbbbbbbbb bbbbbabbaaaabaabababbbbb ababaaaaaaababbabaaaabba abbbbaabbbaabbbabaaababa abaaababbabababaaabaabaa baaaababaaabaaabbaabaaab abbbbabababbabbaaabbbabbaabaaabaaabababaabbbabab babaaabaaabaabababbaaaab bbabbabbbabbaabbaaaaaabababababbbaabababaaabaababbaabbab abbaabbbbabaabaaaaababaa bbaabbaaaaababbaabbbaabbbbabbabaaabbbababbaabbaaaabbbbaa bbbbababbbbababbbbbabbaaaaaabaabbbbbaabb babbabbbabbabbaaabbbbbaa abababbbbbabbabbabbaaabb bbaabbbabbbbababbbabbaaa baabbabbbbbabbabbbabbbba aabaababbabbbabbbababbbb babbababbbabaababbbaabba aaaabbababbbbaabbbabbabbbabaaabbbaababaabaababbb abbbaabbabbbbbaababababb abbaabaabbbabbaaababbabb baabbabbbaabaaaaaaaaabba bbaabababaaaaaabababaabaabaaaaabaabbbbbbabbbbaaa babaabababbaaaababaababababbbaab aaaaabbbbbabaabbbaababab bbbbbaababbbbaabaaabbaba abbabbaaababaabbbbbaabaabbababab bbbabaabababbbabaaaababa baaabbbababbaababbbbabba aaaabbaabbaabbbabbbbaaaa aabaaabbaabbaabbabbbbbab bbbababbbababbaaabaaabba abbbbbaaabbaaaaaabbaabba babaaaababbbbababaaaabbb baaabbbaaaababbabbbaaaaa bbbababbababbaabbbabbbbb aabbbbababaabbbaabaaaaaa abaababbaaaaabaababbababababbbaaabaaaababbbaabbb babaaaababbaabaabbbbaaaa baabbabbabbbabbbaabaababbabaaaaa babbbbbbabbbabbbaaabbabbaabababaaabaaaba abbabbbaabbaabaabbaaaaaa bbbabbaababbbbaabaaababb abaabbabaababbaabbaaaabb baabbabbbabbbabbabbbaaab abbbbaabbababbaababaaaaaaababbaabbababaa ababababbbbbabababaaaaaa bbbaaaabbabbaabbbabbbabbbbababaa bbbbbbbaabbabbbbbbbabbbb baaaaaababbabbbabbbbbbbaaaaaaabbbaaababb bbabbbababbaaabaaabbabaaabbabbbabbabbbaaababbbab bbabbaabbbaaabbbabaaabbbabaabbaabbaaabba abaaaaabbbaababbababbbabbbbabaabaabbaabbbbababbbababbaaaabaaabaabbaaabaa bbabaabbaabbaabbaabaabbb baabbaaabbabababbaababab bbaababaaabbbaaababbbaba babaaabaabaabaabaaabbaabbaaabbaabaabaaba babaabbabaababaabbbaaaaa bababbaaabababababaaaaba aaaabbabbabbaababbaabbab abbabababaaabbbaaaabaabbbbaabaabbababbbbbbbbaaabbaaababbabbbbaaabbaaabab bababaabaaaabaaaabababbbabbaaaba aabbbbabaabbaabbbbbabaabbaababbabbaaabababbbbbba baabbabaaabbbbabbbaaabaa bbbbbababababaabaaababaa aabaabbaabaaaaabbbbbabababbababb baabbabbaabbbbabbaaababa aababbaabbaabababbaabaab baababaabbbabbbaabaabaab aaaaabaaaaaaaabaaabaaaab abbabbabaabbabbbabaabbbabaababaababbbbbbaaabbaaaabaaabaa aabbbbabbbaabababaababbb aabaababbababaaaabbaabba aabbaabbbabaabaabbabbbbb bababaaaabbbbbaabbbaabbb babbbaaababbbaaaaaaabbbb aabbbabaabbbabaabbbaabbb aaaabbaabbbbabbbbbabaabaabaaabaa abbabbaaabbabbbaabbbaaba ababaabbbbabababaaabbaaa aaabababaaaaabaaaaaaabbbbbbbabababbaaabaabbbaaab baaaababbaababaaabababaa aaaabbaaabbbabbbbaaaabba abaabbbbbaaaaaabaababbaaababbaabaabababa abbabbbbababbbaabaabbaaabbbbbbaabbbbabaa bbabbabbbbabaabbabbbaaab aabbbababbbaaaabaabaabbb bbbabaabbaaabbbbbaabaabb ababaabaaaaaababaaabbaaa baaaaaabbabbabbaabbbaaab bbabaabaababaaaaabbabaaaabababba aabbbaaaaaabbaabbbabbaabbaabaaaa abaaabbbbbaaabbbbaaabbab bbabbabbabaaabbbbabbbbbbabbbbbbaababaaaaabbbbbabaaababbabbbabaababaabbbbabbabbab babaabaababababaaaabbbba bbaabaaababbbbbbbaabaabb baabbbabababaaaaaabbbbaabbbaabab abbbaaaababaabbabaabbbabbabbaaabaaabbaababbbbaaa abbbabaabaababaaabbaaaab ababababaabbbbabbbbbbbabbbbabbbaaaaaaabbbaabbabaabaaaabb abaaabbbabaabbababbaabaaaaaabbbaaaabbbba baaaaabbababababbaaabbab babaaabaaabbbaaabaaabbaa babbbabbbabaabaabbbbbbbb aabbbabbabaaababaaabbabb bbaabbaaaaababbaaabbbaab aabbbbabbbbabbbaaabaaaab abaabbbaababababbabaaabbbabbbaba abbaaaaabbabbbabbbaaabba aabaababbaabbabbabbaabba bbabbabbbabbbbaabaababba bbabaabbbbabaabbbbbbaaaa abbbbabaabbbaabbaaababbaabbbabbaaaaababb bbaaabbbbabaabbaabbbbbbb abaaaabababbaaababbbbbbaababbaab abaabbbbababaaaabbbaaabb aaabaabbaababbbbbbbaaaaaabbbaaba aaaaababbaabbaabbabbabbb aaaaaaabaabababbbbbaaaaa bbbbbaaaababaaaaaaabbaba ababbaaababbbaaaaaabbbba babaabbbbbabababbaabaaab aabbbababbbabaabaabbaaab abbbabaaabbbaabbabbaabba baabbaababaabbabaabaaaab baabbabbaabaababbaababbb bbbaaaabaabbbaaaaaaaaaaabaaabbbaabbaaaaaabbbaababaabababababbaabaaabbbab baabbabaaaaabbaaabbbabba babaaabbabbbaabbabbababa bbabbabbaaababbbbbbaaabb aaaaababbabababaaaaababa babaabbbbbbbbbbababbbbbbbbbaaaabaababaaa aaabababaababbaabaaababa ababaabbbabaabaabbaaaaaa aaaabaaaabbabaaababaabaabababaabbaabbbbbaabbbbba baaaaaabbabaabaabbaababb aaabababaaabababaabaabba abbabaaaabbabbbbbbbbbabbaaaaabab bababaaaaababbabbbbbbbbb ababbaaabbbbababbaaaaaba ababaaaabbbaabaabbaaabaa baaabbaabbbaababbaabaaabaaaaabababaabaaabababaaa aaabbaabbaabbabbbbbababbabaaaababaaabaab bbbbbaaabbaabbaababababb aabbbbabaaaaabbbbaabaabb abbabbaaaabbaabaaaaababbabbabbbaabbbbbbaabbabaaababbaabaaabbabab abbabbababbbbababbbaabaabbbaaababbbaaabb bababbaaabaabbabababaaaaabbbabbbaaaaabbb babbaabaaabbaabbbbaaabaa ababbaaababababaabababbbbbaababaabbbbbbb aababaabbbabbaabababababbbbabbbaaaabaaabaaabbabb baabaaaabababaaaababbbbb bbbbabbbabaaabbbbbbababa bbabbbaaaabbbaaabaababbb bbbabbabbaabbabbbaababbb baabaabaaaaaababaabaaaab aabaabbaabaabbbbaaaabaaabbaababbbbbababbbabbbababaaabaabbaabbaabababaaab babbababbbbababbabbbbbaaaaabbbaa bbaabbbaaabaaabbbaababba bbabbbabbbbabbbabbbbaaababbabaaaababbaabaaabaabbabaaabaa abbaabbbabbbbabbbaaabbaaaabaabba baaaaabbbabaaabababaaabbbabababaaababaaabaaaabbaabbaaababababbbaabbbbaaa babbbaaabaaabbbbbbababba aabbbbabbaabaaaababbabbb baabbbbababbbbbbbbbbaaba baabbbabbbaabaaababbaabbabbbababbbabaaab bbabbbababbabbbbababbaaabababbbbabaabbaa aaabababbbbbababaabababbbbbabbbbbabbbaba bbbbabbbbaabbbabbababaaabbbaaabaabbababb ababbbbaababbbabbbababba abbaaaaabaabaaaabbbbaaba aaababababaabbabbbbbbaaaaaaababa bbbabbbabaaabbbbbbabbaabbbbabaaa bababaabbabbbabbaaabbbaa abbbbabbaaaaabbbbababababbbbabbbaaaaabaaaabbaaaa bbabbbaaaabaaabbaaaabbaabbabaaab abbabaaaaaaaaaaaaaabbabb babbbabbbbabaabaabaaaaba babbaabaabaaabbbbbbbbbaa ababbbbabbbbabbbbababaaaabbaaabbbbbaabba aabaababababaabbbbbaaaaa abbbbbaaabbbbabbaaaababa aaabaaabaabbbaabaabababaaaabaaba babbbabbbbaabaaabababbbbbabbababbaabaabb babaabbbbbbabbabaaaabbbaabaaabaaaabaabba bababaabbabaababbabbbabbbbbbababbabbaaaaaabbabaa babaaaabaababaabbbbaabba bbaabbbbbaaabbbaaabbbbabbbaaaaabbabbabbababbabaabaaabababbabbbba baabbaabbbabbababbbabaaa aaaaaaaaababbbababababbbbbabaaaabaaaaababaabbbbb aaaabaaabaabbbbbbbabbbabbabbabaabbbbaaabaaaabbbbbabaabaa aabaabababbbaabbbbabaabbbbaabababbabbabaaaabaabb aabaababbbabaabababbbbab bbaabbbabbbabbbabbabbbba bbaaaaabaaaabbaaaaaaabba bbaaaaabaababbaababbbabbabbabbaa aaabaabbbabaabaaaaabbbabaabbbbbabbbaabaa aaabbbaabbbbaaabababbbbbabbbbbbbbbbabbbaabbabbbbaaaaaababbbbabbaabbabbaaaababbbb aababaabaabbababbababbba babaaaaaaaaaaaabaabaabba aaabbaabbabbaabbbaabbbbbaabbaaba aaababbabbabbabbababbbbb abaaabbbbbaabaaaabbaaaba bbaababaababbbabaabbbaab abbbaabbbaaabbbabaabbbbbaaaaaaabbaaaaabbbbbbabaaabbaaaba babaaaabbabaaaaababbabaa bbbbaaababbbbaabababbbbb abbababbaabaababbbaaaaabaabaabbbbabbabaababababaaaaaabbababbabbbbabbaaaabbbbabaa babaaababbabaaaabbaaaaba bbabbabaabbbbababbbaaabb bbaababaaaaabbbaaaabbaaa babaaaaaaabaababbabbabbaabababbbaaabbbaaaabbbbbabbbbaaaa babaabbababaaabbbaaaabbb aabaababbabbbabababbbbaabaaabaaaaaabbababbbabaaaabaaaaabaaaababaaabbbaaabbaaabbb abbbabaabbbaaaabaaabaabb bbbbbbbaaaabababaabbbbbb ababaaaabbababababbaaabb abbabbabbabbaabbbaaaaabbaabababa bbabbabaababbbabaaaababb babbabbababaaabbabbaaaba aabbaaababbaaabbbbaabaabbbbabbbaaabbbbababbbabbaaabaaaabaaaabaabaabbbaab bbbbbbbaaabbbabbbbaaaabb bbabbaabbbbaabaabbbaaaaa bbbabaabbaabbaaabaaabaaabbbbbbbb aaabababbaabbbbaaababbbb abbbbbbbabaaaaaaabbbbababbababaa bbbaaaabaabaaaaabbaabbab bbbbabbbaaaababbaabaaaab bbaaabbbababbbabbbbbabaa aaaabbaaabaababbbbabbabbbbbbbaaaabbbbbba aabbbabbaaaaabbbbaaabaab abbabbbbbaaaaaabaaabbaaa baaaabababbbbaabaababaaaabaaabbbbbbaaaababbababa bbbbabbbbbbbabbbbabbabbb abbabaaaaabbaabbabaaaaaa abbabbaaaababbaaababaababbbaabbbabbaaaab abbaabaaaaaaabaaaaabbbaa bbbaaaabbaabaabaaabababa bbbaababbbbabaaabbbabaabaabababa baabaababbabababbbbaaaaa baaaabababbaabbbbaabbbabbbbaabab baabbbbaababbaaaabbaabbb babbbbbbabbbbabbabbabbabaabaaabbaaabbbab ababaabbbabbaabbabaababbbbbbbaba baabbabbaaabababbaabaabb ababababbbabbbabbbababaa abbaababaabbbbbabbaaabbabbabaaab babbbbaaababbbabbbababba abababbbabaaababaabbbbbbbbabbbbbbaaaabbbaabaaababababbba aabbaabbbabaabbbbabbbbab baabbbbabbbbabbbbaaababa aaababbbbbbabbaabbbaaabb bbbaaababaabaaabaababbbabaaaaabaaaabbbaa baaabaabbabbaaabbaaababa bbabaabbaababaaaababbbbb ababbbbababbabbababaabaaaaaaaaababababbbaabbbaab bbbbbabaabbbaabbaaaaabba aaabababbbabbaabbbaabaab bbabbabbbabaabbabaababbb aaaaaaababbabbabbabbabaa abbabaaaaaaaaaaaababbbbb babaababbaabbabbabbabbaabababbbaabaabbaa aabbbbaaaababbbbabababbabbbababa bbbabbaabbabaaaaaaabaaaa bbabbabaabbaaaabbbaaaaaa bbaabaaabbabaaaabbbbaabb bbabbaababbabbaaabbbabbbababbaab bbbbababbabbaabbaabbaaab aaaabbababbabaaababbbbbbbbbbbababbbababbabbbaabaaaabbaba abbbaaaababbbbbaaaabababababbaabaabbbbaabaabaabbbabababa bbbbabbbbbbbabbbbbbbbbab bbabababbbabaaaababababb abbabaaaaaaabbbaaaabbbbb baababaaabababbbbabbaaaa bbabbabbbabbabbaabaaabba aaabababbabaabbaaaabbbbb abaaababbaabbbbaaaaabbaaaaaabaaabbabbbabbbabbbbb bbaaabbbbbbababbabababba bbbbaaabbbabbbabbabaaabbbabaabaaaaaaababbabababbbbbbabaababbabbb babbbabbbaaabbabbbabaaabababbaba bbbabbbbbbabbabbaababbbb baaabaaabbaabbaabaaabbabbababbab bbabaaaaabbabbaaabbabaab abbaabaabaaaaabbbbbaabba aabbbbbaaaabbbbaabaaabbbbbaaabbaaababbbaaabbbaababababbaaabbbaabbbabaaab bbbabbbaabbbbababaaabbabaabaabbbbababbaaaaaaabbbaaabbbabaababbaabbaaabaaabababba aaaaababbbbbbaaaabaababbabbbbabaaaabbaabaabaabbabbabbbbbaaaaabba babbabbabaabbbababaaabaa aabaaaaabbbbaaabababbaab babaaabbbabaabbbaaabaaba bababaaabbaabababbbbaabb aabbbababbaabbbaabbababb babaabaabbbbaabbaaaaabababaaababaababbabbabbabbaabbbbbaababbaabbaaaabaaa aabbbbabaaababbabbaaaaaa ababaabbabaababbbbbaaaaa aaababbbbaabbbabbbabaabbaabbbabaabbaababaaabbaaa bbbbaaabbbaabababaababbb ababababaabababbbbababaa baaabaaaabaaabbbabbbbbaababaaabaabaaaabaaabaabaaaaabaaaa abaabbbabaaabaaaababbbababbbbbaaaabaabaa bbaabaaabbbbbbbbbaaabaaababbbbbabababbaabaaaaaba babbababaabaaaaaaabaabba bbbabaaaabbaabbbaabaabbbaaabababaaababaabbbabaaabbbbaababaaaaaabbabbbaba aabaaaaaaabbabbbaabbbbba abbbbababbabaaaaaaaaaaaaaabbbaaababbabbabbbbabaa aaababbabababaaaabbaabba bbbbabababbabbbaabbbabab aaababbbbaabaaaabbbaabbb bbbaaaabaabaaabbbbaaabab ababbbaabaabaabababbbbab babaabababbabbbbbbbbabba abbbabbbabaaabbaaaaaabbbabababbabaaaaaab baaabbbbbababaababbbbbbb aabbbaaaaabaaaaaabbababb aaaaabaaabababababbbbaaa ababaabbaaaabbababaaaaaa bbbaaaabaaaabbaabaaabaab baaabbbbbbbabbaaabbaaaaababbabbbbbbaabbbbbbabbbabbbaaaab bbbbbaabaaaabbabaaaaaaaabbbabbbb bbbaabaaaabbabbbabbaabaaaaabbbbbabbababbaabbbababbababab bbabbabbbaabbaaaabbabbaaabbbabaababbabbaaaabbbab baaabbbababbbabbaabaabbb aaaabbaababababaaabbbbbb abbbbbaabbbabaabbababbba bbbbbbbababbaabbabaaabba abbbaabbbabaababbbaaaaabaabbbbaa babbaabaabbbbababaaabbab baaabbbabaabbbbabbbbaaabaaabbabb aabbbabbabbbbabbababaabababaabaabbaaabaabbbbbbbbaabababa bbbaabaaababaaaabbaabbaaaabbbabaabababaa bababbaababbababaabbabaa """.trimIndent() }
0
Kotlin
0
1
f5efe2f0b6b09b0e41045dc7fda3a7565cb21db3
27,769
advent-of-code
MIT License
app/src/main/java/com/betulnecanli/kotlindatastructuresalgorithms/CodingPatterns/FastSlowPointers.kt
betulnecanli
568,477,911
false
{"Kotlin": 167849}
/* The Fast and Slow Pointers technique involves using two pointers to traverse a sequence at different speeds, often leading to efficient solutions for problems involving cycle detection, finding middle elements, or other related tasks. Let's explore three problems: "Middle of the LinkedList," "Happy Number," and "Cycle in a Circular Array," providing Kotlin implementations for each. */ //1. Middle of the LinkedList class ListNode(var `val`: Int) { var next: ListNode? = null } fun middleNode(head: ListNode?): ListNode? { var slow = head var fast = head while (fast?.next != null) { slow = slow?.next fast = fast.next?.next } return slow } fun main() { // Example of creating a linked list: 1 -> 2 -> 3 -> 4 -> 5 val head = ListNode(1) head.next = ListNode(2) head.next?.next = ListNode(3) head.next?.next?.next = ListNode(4) head.next?.next?.next?.next = ListNode(5) val result = middleNode(head) println("Middle Node: ${result?.`val`}") } //2. Happy Number fun isHappy(n: Int): Boolean { var slow = n var fast = n do { slow = squareSum(slow) fast = squareSum(squareSum(fast)) } while (slow != fast) return slow == 1 } fun squareSum(n: Int): Int { var sum = 0 var num = n while (num > 0) { val digit = num % 10 sum += digit * digit num /= 10 } return sum } fun main() { val number = 19 val result = isHappy(number) println("$number is a Happy Number: $result") } //3. Cycle in a Circular Array fun circularArrayLoop(nums: IntArray): Boolean { val n = nums.size fun getNextIndex(currentIndex: Int): Int { val nextIndex = (currentIndex + nums[currentIndex]) % n return if (nextIndex >= 0) nextIndex else n + nextIndex } for (i in 0 until n) { var slow = i var fast = i var isForward = nums[i] >= 0 do { slow = getNextIndex(slow) fast = getNextIndex(getNextIndex(fast)) if (nums[fast] * nums[i] < 0) { break // Direction changed, no cycle possible } } while (slow != fast) if (slow == fast) { return true } } return false } fun main() { val nums = intArrayOf(2, -1, 1, 2, 2) val result = circularArrayLoop(nums) println("Contains a Circular Array Loop: $result") }
2
Kotlin
2
40
70a4a311f0c57928a32d7b4d795f98db3bdbeb02
2,447
Kotlin-Data-Structures-Algorithms
Apache License 2.0
2022/src/test/kotlin/Day05.kt
jp7677
318,523,414
false
{"Kotlin": 171284, "C++": 87930, "Rust": 59366, "C#": 1731, "Shell": 354, "CMake": 338}
import io.kotest.core.spec.style.StringSpec import io.kotest.matchers.shouldBe private data class Move5(val times: Int, val src: Int, val dest: Int) class Day05 : StringSpec({ "puzzle part 01" { val (stacks, moves) = getStacksAndMoves() moves.forEach { move -> repeat(move.times) { stacks[move.dest].add(stacks[move.src].removeLast()) } } val result = stacks.joinToString("") { it.removeLast() } result shouldBe "TWSGQHNHL" } "puzzle part 02" { val (stacks, moves) = getStacksAndMoves() val deque = ArrayDeque<String>(1) moves.forEach { move -> repeat(move.times) { deque.add(stacks[move.src].removeLast()) } repeat(move.times) { stacks[move.dest].add(deque.removeLast()) } deque.clear() } val result = stacks.joinToString("") { it.removeLast() } result shouldBe "JNRSCDWPP" } }) private fun getStacksAndMoves(): Pair<List<ArrayDeque<String>>, List<Move5>> { val input = getPuzzleInput("day05-input.txt", "$eol$eol").toList() val startingStacks = input.first().split(eol) val numberOfStacks = startingStacks.last().trim().last().digitToInt() val stacks = buildList<ArrayDeque<String>> { repeat(numberOfStacks) { add(ArrayDeque(1)) } } startingStacks.reversed().drop(1).forEach { for (i in 1..numberOfStacks * 4 step 4) if (it.length >= i && it[i].isLetter()) stacks[(i - 1) / 4].add(it[i].toString()) } val moves = input.last().split(eol) .map { line -> line.split(" ").let { Move5(it[1].toInt(), it[3].toInt() - 1, it[5].toInt() - 1) } } return stacks to moves }
0
Kotlin
1
2
8bc5e92ce961440e011688319e07ca9a4a86d9c9
1,822
adventofcode
MIT License
src/main/kotlin/g1501_1600/s1514_path_with_maximum_probability/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1501_1600.s1514_path_with_maximum_probability // #Medium #Heap_Priority_Queue #Graph #Shortest_Path // #2023_06_12_Time_681_ms_(100.00%)_Space_67.5_MB_(62.50%) import java.util.ArrayDeque import java.util.Queue class Solution { fun maxProbability(n: Int, edges: Array<IntArray>, succProb: DoubleArray, start: Int, end: Int): Double { val nodeToNodesList: Array<MutableList<Int>?> = arrayOfNulls(n) val nodeToProbabilitiesList: Array<MutableList<Double>?> = arrayOfNulls(n) for (i in 0 until n) { nodeToNodesList[i] = mutableListOf() nodeToProbabilitiesList[i] = ArrayList() } for (i in edges.indices) { val u = edges[i][0] val v = edges[i][1] val w = succProb[i] nodeToNodesList[u]?.add(v) nodeToProbabilitiesList[u]?.add(w) nodeToNodesList[v]?.add(u) nodeToProbabilitiesList[v]?.add(w) } val probabilities = DoubleArray(n) probabilities[start] = 1.0 val visited = BooleanArray(n) val queue: Queue<Int> = ArrayDeque() queue.add(start) visited[start] = true while (queue.isNotEmpty()) { val u = queue.poll() visited[u] = false for (i in nodeToNodesList[u]?.indices!!) { val v = nodeToNodesList[u]?.get(i) val w = nodeToProbabilitiesList[u]?.get(i) if (probabilities[u] * w!! > probabilities[v!!]) { probabilities[v] = probabilities[u] * w if (!visited[v]) { visited[v] = true queue.add(v) } } } } return probabilities[end] } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,794
LeetCode-in-Kotlin
MIT License
code/day_14/src/jvm8Main/kotlin/task2.kt
dhakehurst
725,945,024
false
{"Kotlin": 105846}
package day_14 val List<Char>.join get() = this.joinToString(separator = "") fun String.tilt(): String { val segments = this.split("#") return segments.map { val os = it.count { it == 'O' } "O".repeat(os) + ".".repeat(it.length - os) }.joinToString(separator = "#") } fun GridAsString.tiltAndRotate(): GridAsString { val newLines = this.columns.map { it.tilt().reversed() } return GridAsString(newLines) } fun GridAsString.cycle(): GridAsString { var g = this for (i in 0 until 4) { g = g.tiltAndRotate() } return g } fun String.sumWeight():Long { var sum = 0L val top = this.length for (i in 0 until this.length) { val c = this[i] when(c) { '.' -> {} '#' -> {} 'O' -> { sum += top-i } } } return sum } fun GridAsString.sumWeight():Long = this.columns.fold(0) { a,i -> a + i.sumWeight() } fun task2(lines: List<String>): Long { var total = 0L val grid = GridAsString(lines) val os = lines.fold(0) { a, l -> a+l.count { it=='O' } } val hs = lines.fold(0) { a, l -> a+l.count { it=='#' } } var g = grid println(g.sumWeight()) for (i in 0 until 10000){ //0000000) { g = g.cycle() } println(g.sumWeight()) return g.sumWeight() }
0
Kotlin
0
0
be416bd89ac375d49649e7fce68c074f8c4e912e
1,369
advent-of-code
Apache License 2.0
src/main/kotlin/dev/patbeagan/days/Day11.kt
patbeagan1
576,401,502
false
{"Kotlin": 57404}
package dev.patbeagan.days import java.lang.IllegalArgumentException /** * [Day 11](https://adventofcode.com/2022/day/11) */ class Day11 : AdventDay<Int> { override fun part1(input: String) = parseInput(input).let { monkeyList -> Main(monkeyList, Person()).let { main -> repeat(20) { main.round() } monkeyList.forEach { println("Monkey ${it.id} inspected items ${it.inspectionCount} times.") } monkeyList .sortedBy { it.inspectionCount } .takeLast(2) .fold(1) { acc, each -> acc * each.inspectionCount } .also { println(it) } } } override fun part2(input: String) = 0 fun parseInput(input: String) = input .trim() .split("\n\n") .map { Monkey.parse(it) } .also { println(it) } class Main( private val monkeys: List<Monkey>, private val person: Person ) { fun round() { monkeys.forEach { monkey -> monkey.performTurn(person, monkeys) } monkeys.forEach { println("Monkey ${it.id}: ${it.items}") } } } class Person( var worryLevel: Int = 0 ) { fun reduceWorryLevel() { worryLevel /= 3 } } data class Monkey( val id: Int, val items: MutableList<Item>, val operation: Operation, val test: MonkeyTest, val onTrue: MonkeyAction, val onFalse: MonkeyAction, ) { var inspectionCount = 0 private fun performItemInspection(item: Item, person: Person, monkeys: List<Monkey>) { // person.worryLevel = item.worryLevel println(" Monkey $id inspects an item with a worry level of ${item.worryLevel}.") // val oldWorryLevel = person.worryLevel person.worryLevel = operation.interpret(person) println(" Worry level increases from $oldWorryLevel to ${person.worryLevel}.") // person.reduceWorryLevel() println(" Monkey gets bored with item. Worry level is divided by 3 to ${person.worryLevel}.") // val divisibleInt = test.asDivisibleInt() val worryIsDivisible = person.worryLevel % divisibleInt == 0 println(" Current worry level is${if (worryIsDivisible) " " else " not"} divisible by ${divisibleInt}.") // val monkeyAction = if (worryIsDivisible) onTrue else onFalse monkeyAction.asThrowActionId()?.let { monkeys[it].items.add(Item(person.worryLevel)) } println(" Item with worry level ${item.worryLevel} is thrown to monkey ${monkeyAction.asThrowActionId()}.") println() inspectionCount++ } fun performTurn(person: Person, monkeys: List<Monkey>) { println("Monkey $id.") items.forEach { performItemInspection(it, person, monkeys) } items.clear() } @JvmInline value class Item(val worryLevel: Int) @JvmInline value class Operation(private val operationString: String) { fun interpret(person: Person): Int = regexOperation .find(operationString) ?.groupValues!! .let { strings -> println("$operationString: $strings") val op = strings[1] val scale = strings[2] .toIntOrNull() ?: when (strings[2]) { "old" -> person.worryLevel else -> throw IllegalArgumentException("implicit var not found") } val new = when (op) { "*" -> person.worryLevel * scale "/" -> person.worryLevel / scale "+" -> person.worryLevel + scale "-" -> person.worryLevel - scale else -> throw IllegalArgumentException() } new } companion object { val regexOperation = Regex("new = old ([^ ]+) ([^ ]*)") } } @JvmInline value class MonkeyTest(private val testString: String) { fun asDivisibleInt() = regexTest .find(testString) ?.groupValues ?.get(1) ?.toInt()!! companion object { val regexTest = Regex("divisible by (\\d*)") } } @JvmInline value class MonkeyAction(private val actionString: String) { fun asThrowActionId() = regexThrow .find(actionString) ?.groupValues ?.get(1) ?.toIntOrNull() companion object { val regexThrow = Regex("throw to monkey (\\d*)") } } companion object { fun parse(input: String): Monkey = Monkey( regexMonkeyId.find(input) ?.groupValues ?.get(1) ?.toInt()!!, regexStartingItems.find(input) ?.groupValues ?.get(1) ?.split(",") ?.map { Item(it.trim().toInt()) } ?.toMutableList()!!, Operation( regexOperation.find(input) ?.groupValues ?.get(1)!! ), MonkeyTest( regexTest.find(input) ?.groupValues ?.get(1)!! ), MonkeyAction( regexOnTrue.find(input) ?.groupValues?.get(1)!! ), MonkeyAction( regexOnFalse.find(input) ?.groupValues ?.get(1)!! ), ) private val regexMonkeyId = Regex("\\w*Monkey (\\d*):") private val regexStartingItems = Regex("\\w*Starting items: (.*)") private val regexOperation = Regex("\\w*Operation: (.*)") private val regexTest = Regex("\\w*Test: (.*)") private val regexOnTrue = Regex("\\w*If true: (.*)") private val regexOnFalse = Regex("\\w*If false: (.*)") } } }
0
Kotlin
0
0
4e25b38226bcd0dbd9c2ea18553c876bf2ec1722
6,681
AOC-2022-in-Kotlin
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/LongestValidParentheses.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.util.Stack import kotlin.math.max /** * 32. Longest Valid Parentheses * https://leetcode.com/problems/longest-valid-parentheses/ */ fun interface LongestValidParenthesesStrategy { operator fun invoke(s: String): Int } class LongestValidParenthesesBruteForce : LongestValidParenthesesStrategy { override operator fun invoke(s: String): Int { var maxLen = 0 for (i in s.indices) { var j = i + 2 while (j <= s.length) { if (isValid(s.substring(i, j))) { maxLen = max(maxLen, j - i) } j += 2 } } return maxLen } private fun isValid(s: String): Boolean { val stack: Stack<Char> = Stack<Char>() val sym = '(' for (element in s) { if (element == sym) { stack.push(sym) } else if (!stack.empty() && stack.peek() == sym) { stack.pop() } else { return false } } return stack.empty() } } class LongestValidParenthesesDP : LongestValidParenthesesStrategy { override operator fun invoke(s: String): Int { var maxAns = 0 val dp = IntArray(s.length) for (i in 1 until s.length) { if (s[i] == ')') { if (s[i - 1] == '(') { dp[i] = (if (i >= 2) dp[i - 2] else 0) + 2 } else if (i - dp[i - 1] > 0 && s[i - dp[i - 1] - 1] == '(') { dp[i] = dp[i - 1] + (if (i - dp[i - 1] >= 2) dp[i - dp[i - 1] - 2] else 0) + 2 } maxAns = max(maxAns, dp[i]) } } return maxAns } } class LongestValidParenthesesStack : LongestValidParenthesesStrategy { override operator fun invoke(s: String): Int { var maxAns = 0 val stack = Stack<Int>() stack.push(-1) for (i in s.indices) { if (s[i] == '(') { stack.push(i) } else { stack.pop() if (stack.empty()) { stack.push(i) } else { maxAns = max(maxAns, i - stack.peek()) } } } return maxAns } } class LongestValidParenthesesWithoutExtraSpace : LongestValidParenthesesStrategy { override operator fun invoke(s: String): Int { var left = 0 var right = 0 var maxLength = 0 for (i in s.indices) { if (s[i] == '(') { left++ } else { right++ } if (left == right) { maxLength = max(maxLength, 2 * right) } else if (right >= left) { right = 0 left = right } } left = 0.also { right = it } for (i in s.length - 1 downTo 0) { if (s[i] == '(') { left++ } else { right++ } if (left == right) { maxLength = max(maxLength, 2 * left) } else if (left >= right) { right = 0 left = right } } return maxLength } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,928
kotlab
Apache License 2.0
kotlin/src/katas/kotlin/leetcode/regex_matching/RegexMatching.kt
dkandalov
2,517,870
false
{"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221}
package katas.kotlin.leetcode.regex_matching import datsok.shouldEqual import org.junit.Test class RegexMatchingTests { @Test fun `it mostly works`() { "".matches("") shouldEqual true "a".matches("a") shouldEqual true "a".matches("b") shouldEqual false "a".matches(".") shouldEqual true "ab".matches("a.") shouldEqual true "ab".matches(".b") shouldEqual true "ab".matches("..") shouldEqual true "ab".matches("X.") shouldEqual false "ab".matches("...") shouldEqual false "aa".matches("a*") shouldEqual true "ab".matches("a*b") shouldEqual true "ab".matches("a*b*") shouldEqual true "ab".matches("a*b*c*") shouldEqual true "ab".matches("a*") shouldEqual false "ab".matches("X*ab") shouldEqual true "aa".matches("a") shouldEqual false "aa".matches("a*") shouldEqual true "ab".matches(".*") shouldEqual true "aab".matches("c*a*b") shouldEqual true "mississippi".matches("mis*is*p*.") shouldEqual false } } private class Matcher(val s: String, val regex: String) { fun match(): Boolean { if (regex.isEmpty()) return s.isEmpty() when { regex.length >= 2 && regex[1] == '*' -> { return Matcher(s, regex.substring(2)).match() || ((s[0] == regex[0] || regex[0] == '.') && Matcher(s.substring(1), regex).match()) } regex[0] == '.' -> { if (s.isEmpty()) return false return Matcher(s.substring(1), regex.substring(1)).match() } else -> { if (s[0] != regex[0]) return false return Matcher(s.substring(1), regex.substring(1)).match() } } } } private fun String.matches(regex: String): Boolean { return Matcher(this, regex).match() }
7
Roff
3
5
0f169804fae2984b1a78fc25da2d7157a8c7a7be
1,970
katas
The Unlicense
src/leetcodeProblem/leetcode/editor/en/RansomNote.kt
faniabdullah
382,893,751
false
null
//Given two stings ransomNote and magazine, return true if ransomNote can be //constructed from magazine and false otherwise. // // Each letter in magazine can only be used once in ransomNote. // // // Example 1: // Input: ransomNote = "a", magazine = "b" //Output: false // Example 2: // Input: ransomNote = "aa", magazine = "ab" //Output: false // Example 3: // Input: ransomNote = "aa", magazine = "aab" //Output: true // // // Constraints: // // // 1 <= ransomNote.length, magazine.length <= 10⁵ // ransomNote and magazine consist of lowercase English letters. // // Related Topics Hash Table String Counting 👍 1215 👎 266 package leetcodeProblem.leetcode.editor.en class RansomNote { fun solution() { } //below code will be used for submission to leetcode (using plugin of course) //leetcode submit region begin(Prohibit modification and deletion) class Solution { fun canConstruct(ransomNote: String, magazine: String): Boolean { if (ransomNote == magazine) return true val hashMap = mutableMapOf<Char, Int>() for (i in magazine.indices) { hashMap[magazine[i]] = hashMap.getOrDefault(magazine[i], 0) + 1 } for (i in ransomNote.indices) { if (hashMap.containsKey(ransomNote[i])) { hashMap[ransomNote[i]] = hashMap[ransomNote[i]]!! - 1 if (hashMap[ransomNote[i]] == 0) hashMap.remove(ransomNote[i]) } else { return false } } return true } } //leetcode submit region end(Prohibit modification and deletion) } fun main() {}
0
Kotlin
0
6
ecf14fe132824e944818fda1123f1c7796c30532
1,704
dsa-kotlin
MIT License
src/Day03.kt
ivancordonm
572,816,777
false
{"Kotlin": 36235}
fun main() { fun part1(input: List<String>) = input.fold(0) { acc, it -> acc + it.take(it.length / 2).toSet().intersect(it.substring(it.length / 2).toSet()).first().getValue() } fun part2(input: List<String>) = input.chunked(3).fold(0) { acc, triple -> acc + triple[0].toSet().intersect(triple[1].toSet().intersect(triple[2].toSet())).first().getValue() } val testInput = readInput("Day03_test") val input = readInput("Day03") println(part1(testInput)) check(part1(testInput) == 157) println(part1(input)) println(part2(testInput)) check(part2(testInput) == 70) println(part2(input)) } private fun Char.getValue() = if (isLowerCase()) code - 96 else code - 38
0
Kotlin
0
2
dc9522fd509cb582d46d2d1021e9f0f291b2e6ce
765
AoC-2022
Apache License 2.0
day05/src/main/kotlin/Main.kt
rstockbridge
159,586,951
false
null
import java.io.File import java.lang.Double.POSITIVE_INFINITY fun main() { val input = readInputFile()[0] println("Part I: the solution is ${solvePartI(input)}.") println("Part II: the solution is ${solvePartII(input)}.") } fun readInputFile(): List<String> { return File(ClassLoader.getSystemResource("input.txt").file).readLines() } fun solvePartI(polymer: String): Int { return getReactedPolymerLength(polymer) } fun solvePartII(polymer: String): Int { var minLength = POSITIVE_INFINITY.toInt() for (letter in 'a'..'z') { val newLength = getReactedPolymerLength(removeLetter(polymer, letter)) if (newLength < minLength) { minLength = newLength } } return minLength } fun getReactedPolymerLength(polymer: String): Int { val result = polymer.toMutableList() var previousLength = result.size var keepGoing = true while (keepGoing) { val iterator = result.listIterator() iterator.next() while (iterator.hasNext()) { val letter2Index = iterator.nextIndex() val letter1 = result[letter2Index - 1] val letter2 = result[letter2Index] if (Math.abs(letter1.toInt() - letter2.toInt()) == 32) { iterator.remove() iterator.next() iterator.remove() } if (iterator.hasNext()) { iterator.next() } } keepGoing = (result.size != previousLength) previousLength = result.size } return result.size } fun removeLetter(input: String, letter: Char): String { return input.replace(("[$letter${letter.toUpperCase()}]").toRegex(), "") }
0
Kotlin
0
0
c404f1c47c9dee266b2330ecae98471e19056549
1,727
AdventOfCode2018
MIT License
src/main/kotlin/com/ginsberg/advent2020/Day14.kt
tginsberg
315,060,137
false
null
/* * Copyright (c) 2020 by <NAME> */ /** * Advent of Code 2020, Day 14 - Docking Data * Problem Description: http://adventofcode.com/2020/day/14 * Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2020/day14/ */ package com.ginsberg.advent2020 class Day14(private val input: List<String>) { private val memory: MutableMap<Long, Long> = mutableMapOf() fun solvePart1(): Long { var mask = DEFAULT_MASK input.forEach { instruction -> if (instruction.startsWith("mask")) { mask = instruction.substringAfter("= ") } else { val address = instruction.substringAfter("[").substringBefore("]").toLong() val value = instruction.substringAfter("= ") memory[address] = value maskedWith mask } } return memory.values.sum() } fun solvePart2(): Long { var mask = DEFAULT_MASK input.forEach { instruction -> if (instruction.startsWith("mask")) { mask = instruction.substringAfter("= ") } else { val unmaskedAddress = instruction.substringAfter("[").substringBefore("]") val value = instruction.substringAfter("= ").toLong() unmaskedAddress.generateAddressMasks(mask).forEach { address -> memory[address] = value } } } return memory.values.sum() } private infix fun String.maskedWith(mask: String): Long = this.toBinary().zip(mask).map { (valueChar, maskChar) -> maskChar.takeUnless { it == 'X' } ?: valueChar }.joinToString("").toLong(2) private fun String.toBinary(): String = this.toLong().toString(2).padStart(36, '0') private fun String.generateAddressMasks(mask: String): List<Long> { val addresses = mutableListOf(this.toBinary().toCharArray()) mask.forEachIndexed { idx, bit -> when (bit) { '1' -> addresses.forEach { it[idx] = '1' } 'X' -> { addresses.forEach { it[idx] = '1' } addresses.addAll( addresses.map { it.copyOf().apply { this[idx] = '0' } } ) } } } return addresses.map { it.joinToString("").toLong(2) } } companion object { const val DEFAULT_MASK = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" } }
0
Kotlin
2
38
75766e961f3c18c5e392b4c32bc9a935c3e6862b
2,628
advent-2020-kotlin
Apache License 2.0
src/main/kotlin/g0501_0600/s0564_find_the_closest_palindrome/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0501_0600.s0564_find_the_closest_palindrome // #Hard #String #Math #2023_01_21_Time_179_ms_(100.00%)_Space_33.7_MB_(100.00%) @Suppress("NAME_SHADOWING") class Solution { fun nearestPalindromic(n: String): String { if (n.length == 1) { return (n.toInt() - 1).toString() } val num = n.toLong() val offset = Math.pow(10.0, (n.length / 2).toDouble()).toInt() val first = if (isPalindrome(n)) palindromeGenerator(num + offset, n.length) else palindromeGenerator(num, n.length) val second = if (first < num) palindromeGenerator(num + offset, n.length) else palindromeGenerator( num - offset, n.length ) if (first + second == 2 * num) { return if (first < second) first.toString() else second.toString() } return if (Math.abs(num - first) > Math.abs(num - second)) second.toString() else first.toString() } private fun palindromeGenerator(num: Long, length: Int): Long { var num = num if (num < 10) { return 9 } val numOfDigits = num.toString().length if (numOfDigits > length) { return Math.pow(10.0, (numOfDigits - 1).toDouble()).toLong() + 1 } else if (numOfDigits < length) { return Math.pow(10.0, numOfDigits.toDouble()).toLong() - 1 } num = num - num % Math.pow(10.0, (numOfDigits / 2).toDouble()).toLong() var temp = num for (j in 0 until numOfDigits / 2) { val digit = Math.pow(10.0, (numOfDigits - j - 1).toDouble()).toLong() num += (temp / digit * Math.pow(10.0, j.toDouble())).toInt().toLong() temp = temp % digit } return num } private fun isPalindrome(str: String): Boolean { for (i in 0 until str.length / 2) { if (str[i] != str[str.length - 1 - i]) { return false } } return true } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,001
LeetCode-in-Kotlin
MIT License
src/util/Graph.kt
pghj
577,868,985
false
{"Kotlin": 94937}
package util import java.util.Collections class Graph<K, N> { inner class Node( val key: K, val value: N ) { val connected: ArrayList<Vertex> = ArrayList() } inner class Vertex( val a: Node, val b: Node, val aToB: Int, val bToA: Int, ) { fun other(n: Node): Node = if (n == a) b else a fun other(k: K): Node = if (k == a.key) b else a fun distanceFrom(k: K) = if (k == a.key) aToB else bToA fun distanceTo(k: K) = if (k == a.key) bToA else aToB } private val nodeMap = HashMap<K, Node>() private val vertexes = ArrayList<Vertex>() fun nodes() : Collection<Node> { return Collections.unmodifiableCollection(nodeMap.values) } fun add(key: K, value: N) { if (nodeMap.containsKey(key)) throw IllegalArgumentException("duplicate key") val n = Node(key, value) nodeMap[key] = n } operator fun get(key: K): Node? { return nodeMap[key] } fun connect(key0: K, key1: K, distance: Int, reversed: Int = distance) { val a = nodeMap[key0]!! val b = nodeMap[key1]!! val vtx = Vertex(a, b, distance, reversed) a.connected.add(vtx) b.connected.add(vtx) vertexes.add(vtx) } /** Calculate the shortest distance needed from the given node to each other node. * Entries that are missing in the returned map are disconnected from the given node. * */ fun calculateLeastDistanceTable(key: K) : HashMap<K, Int> { val a = nodeMap[key]!! val minDist = HashMap<K, Int>() val mod = HashSet<Node>() val l = ArrayList<Node>() minDist[key] = 0 mod.add(a) while(mod.isNotEmpty()) { l.clear() l.addAll(mod) mod.clear() l.forEach { n -> for(v in n.connected) { val d0 = minDist[n.key]!! val m = v.other(a) val d1 = minDist[m.key] if ((d1 != null && d0+v.aToB < d1) || d1 == null) { mod.add(m) minDist[m.key] = d0+v.aToB } } } } return minDist } }
0
Kotlin
0
0
4b6911ee7dfc7c731610a0514d664143525b0954
2,297
advent-of-code-2022
Apache License 2.0
app/src/main/kotlin/day02/Day02.kt
W3D3
433,748,408
false
{"Kotlin": 72893}
package day02 import common.InputRepo import common.readSessionCookie import common.solve fun main(args: Array<String>) { val day = 2 val input = InputRepo(args.readSessionCookie()).get(day = day) solve(day, input, ::solveDay02Part1, ::solveDay02Part2) } enum class Command { FORWARD, DOWN, UP } fun parseCommand(cmd: String): Pair<Command, Int> { return cmd.split(" ") .let { Command.valueOf(it[0].uppercase()) to it[1].toInt() } } fun solveDay02Part1(input: List<String>): Int { var pos = 0 var depth = 0 for (commandLine in input) { val cmd = parseCommand(commandLine) when (cmd.first) { Command.FORWARD -> pos += cmd.second Command.DOWN -> depth += cmd.second Command.UP -> depth -= cmd.second } } return pos * depth } fun solveDay02Part2(input: List<String>): Int { var aim = 0 var pos = 0 var depth = 0 for (commandLine in input) { val cmd = parseCommand(commandLine) when (cmd.first) { Command.FORWARD -> { pos += cmd.second depth += cmd.second * aim } Command.DOWN -> aim += cmd.second Command.UP -> aim -= cmd.second } } return pos * depth }
0
Kotlin
0
0
df4f21cd99838150e703bcd0ffa4f8b5532c7b8c
1,310
AdventOfCode2021
Apache License 2.0
src/Day04.kt
dannyrm
573,100,803
false
null
fun main() { fun part1(input: List<String>): Int { return input.map { splitIntoRange(it) }.filter { it.first.subtract(it.second).isEmpty() }.size } fun part2(input: List<String>): Int { return input.map { splitIntoRange(it) }.filter { (it.first.subtract(it.second).size) < it.first.count() }.size } val input = readInput("Day04") println(part1(input)) println(part2(input)) } fun splitIntoRange(input: String): Pair<IntRange, IntRange> { return input .split(",") .map { it.split("-") } .map { IntRange(it[0].toInt(), it[1].toInt()) } .sortedBy { it.count() } .run { Pair(this[0], this[1]) } }
0
Kotlin
0
0
9c89b27614acd268d0d620ac62245858b85ba92e
683
advent-of-code-2022
Apache License 2.0
y2016/src/main/kotlin/adventofcode/y2016/Day14.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2016 import adventofcode.io.AdventSolution import adventofcode.util.algorithm.md5 object Day14 : AdventSolution(2016, 14, "One-Time Pad") { override fun solvePartOne(input: String) = generateSequence(0,Int::inc) .map { md5("$input$it") } .solve() override fun solvePartTwo(input: String) = generateSequence(0,Int::inc) .map { generateSequence("$input$it",::md5).elementAt(2017) } .solve() private fun Sequence<String>.solve() = windowed(1001, partialWindows = true) .withIndex() .filter { val ch = it.value[0].threes() if (ch != null) it.value.subList(1, it.value.lastIndex).any { s -> s.five(ch) } else false } .elementAt(63) .index private fun String.threes(): Char? = windowedSequence(3).firstOrNull { sub -> sub.all { ch -> sub[0] == ch } }?.get(0) private fun String.five(expected: Char): Boolean = windowedSequence(5).any { sub -> sub.all { it == expected } } }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
954
advent-of-code
MIT License
src/Day17.kt
jinie
572,223,871
false
{"Kotlin": 76283}
class Day17(input: List<String>) { enum class Rock(val height: Int, val parts: List<Point2d>) { Dash(1, listOf(Point2d(0, 0), Point2d(1, 0), Point2d(2, 0), Point2d(3, 0))), Plus(3, listOf(Point2d(1, 0), Point2d(0, 1), Point2d(1, 1), Point2d(2, 1), Point2d(1, 2))), Angle(3, listOf(Point2d(0, 0), Point2d(1, 0), Point2d(2, 0), Point2d(2, 1), Point2d(2, 2))), Pipe(4, listOf(Point2d(0, 0), Point2d(0, 1), Point2d(0, 2), Point2d(0, 3))), Square(2, listOf(Point2d(0, 0), Point2d(0, 1), Point2d(1, 0), Point2d(1, 1))) } private val pattern = input.first().map { if (it == '>') 1 else -1 } private val chamber = mutableMapOf<Point2d,Char>().apply { for (i in 0..6) { this[Point2d(i, 0)] = '-' // Add a floor to get something more print friendly while debugging } } private var currentMax = 0 // Floor is at y=0, first rock is at y=1 private var jetOffset = 0 fun <T> Map<Point2d, T>.yRange() = keys.minByOrNull { it.y }!!.y..keys.maxByOrNull { it.y }!!.y private fun fall(rock: Rock) { var x = 2 var y = currentMax + 4 while (true) { //push if possible val xAfterPush = x + pattern[jetOffset++ % pattern.size] if (rock.parts.map { it + Point2d(xAfterPush, y) }.all { it.x in 0..6 && it !in chamber.keys }) { x = xAfterPush } //fall if possible if (y > 1 && rock.parts.map { it + Point2d(x, y - 1) }.none { it in chamber.keys }) { y-- } else { // update chamber with final position of rock rock.parts.map { it + Point2d(x, y) }.forEach { chamber[it] = '#' } // update currentMax as well currentMax = chamber.yRange().max() break } } } fun part1(): Int { (0 until 2022).forEach { fall(Rock.values()[it % 5]) } return currentMax } // First entry is the floor height private val maxHeightHistory = mutableListOf(0) fun part2(): Long { val numRocks = 1_000_000_000_000 // First simulate a bit and record with how much the height increases for each rock (0 until 2022).forEach { fall(Rock.values()[it % 5]) maxHeightHistory.add(currentMax) } val diffHistory = maxHeightHistory.zipWithNext().map { (a, b) -> b - a } // Now detect loops. Manual inspection of the diffHistory shows no loops that start from the very beginning // so start a bit into the sequence. Then use a marker that's long enough to not be repeating anywhere else // than when the loop restarts. The marker is the first markerLength entries in the loop. val loopStart = 200 // could be anything that's inside the loop val markerLength = 10 val marker = diffHistory.subList(loopStart, loopStart + markerLength) var loopHeight = -1 var loopLength = -1 val heightBeforeLoop = maxHeightHistory[loopStart - 1] for (i in loopStart + markerLength until diffHistory.size) { if (marker == diffHistory.subList(i, i + markerLength)) { // Marker matches the sequence starting at i, so Loop ends at i - 1 loopLength = i - loopStart loopHeight = maxHeightHistory[i - 1] - heightBeforeLoop break } } // Calculate the height at the target based on the number of loops and the height of the loop val numFullLoops = (numRocks - loopStart) / loopLength val offsetIntoLastLoop = ((numRocks - loopStart) % loopLength).toInt() val extraHeight = maxHeightHistory[loopStart + offsetIntoLastLoop] - heightBeforeLoop return heightBeforeLoop + loopHeight * numFullLoops + extraHeight } } fun main(){ val testInput = readInput("Day17_test") check(Day17(testInput).part1() == 3068) measureTimeMillisPrint { val input = readInput("Day17") println(Day17(input).part1()) println(Day17(input).part2()) } }
0
Kotlin
0
0
4b994515004705505ac63152835249b4bc7b601a
4,171
aoc-22-kotlin
Apache License 2.0
src/Day23.kt
joy32812
573,132,774
false
{"Kotlin": 62766}
import java.lang.Math.abs data class Elf(var x: Int, var y: Int, var d: Int = 0) fun main() { val dirs = listOf( listOf(-1, -1, -1) to listOf(-1, 0, 1), // north listOf(1, 1, 1) to listOf(-1, 0, 1), // south listOf(-1, 0, 1) to listOf(-1, -1, -1), // west listOf(-1, 0, 1) to listOf(1, 1, 1) // east ) val deltaX = listOf(-1, 1, 0, 0) val deltaY = listOf(0, 0, -1, 1) fun getElves(input: List<String>): List<Elf> { val elves = mutableListOf<Elf>() for (i in input.indices) { for (j in input[i].indices) { if (input[i][j] == '#') { elves.add(Elf(i, j)) } } } return elves } fun Elf.toPosId() = "${this.x}_${this.y}" fun String.toCord() = this.split("_").map { it.toInt() } fun move(elves: List<Elf>): Boolean { val posMap = elves.associateBy { it.toPosId() }.toMutableMap() fun hasNeighbor(elf: Elf): Boolean { for (i in -1..1) { for (j in -1..1) { if (i == 0 && j == 0) continue val key = "${elf.x + i}_${elf.y + j}" if (key in posMap) return true } } return false } if (elves.all { !hasNeighbor(it) }) return false fun getProposals(): Map<String, String> { val proposals = mutableMapOf<String, String>() for (elf in elves) { if (!hasNeighbor(elf)) { proposals[elf.toPosId()] = "x_x" continue } for (k in 0 until 4) { val z = (elf.d + k) % 4 val (dx, dy) = dirs[z] var count = 0 for (t in dx.indices) { val x = elf.x + dx[t] val y = elf.y + dy[t] val id = "$x" + "_" + "$y" if (id in posMap) count ++ } if (count == 0) { proposals[elf.toPosId()] = "${elf.x + deltaX[z]}_${elf.y + deltaY[z]}" break } } if (elf.toPosId() !in proposals) { proposals[elf.toPosId()] = "x_x" } } return proposals } // first round val proposals = getProposals() val propCntMap = proposals.values.groupingBy { it }.eachCount() // second round for (p in proposals) { val elf = posMap[p.key]!! if (propCntMap[p.value] == 1) { val (tx, ty) = p.value.toCord() posMap.remove(p.key) elf.x = tx elf.y = ty posMap[elf.toPosId()] = elf } elf.d = (elf.d + 1) % 4 } return true } fun part1(input: List<String>): Int { val elves = getElves(input) repeat(10) { move(elves) } val minX = elves.minBy { it.x }.x val maxX = elves.maxBy { it.x }.x val minY = elves.minBy { it.y }.y val maxY = elves.maxBy { it.y }.y return (maxX - minX + 1) * (maxY - minY + 1) - elves.size } fun part2(input: List<String>): Int { val elves = getElves(input) var round = 0 while (true) { round ++ if (!move(elves)) break } return round } println(part1(readInput("data/Day23_test"))) println(part1(readInput("data/Day23"))) println(part2(readInput("data/Day23_test"))) println(part2(readInput("data/Day23"))) }
0
Kotlin
0
0
5e87958ebb415083801b4d03ceb6465f7ae56002
3,785
aoc-2022-in-kotlin
Apache License 2.0
2023/src/main/kotlin/day3_fast.kt
madisp
434,510,913
false
{"Kotlin": 388138}
import utils.Grid import utils.IntGrid import utils.Solution import utils.Vec2i fun main() { Day3_fast.run(skipTest = false) } object Day3All { @JvmStatic fun main(args: Array<String>) { mapOf("func" to Day3, "fast" to Day3_fast).forEach { (header, solution) -> solution.run( header = header, printParseTime = false, skipTest = false, skipPart1 = false, ) } } } object Day3_fast : Solution<Grid<Char>>() { override val name = "day3" override val parser = Grid.chars(oobBehaviour = Grid.OobBehaviour.Default('.')) override fun part1(input: Grid<Char>): Int { var sum = 0 input.rows.forEach { row -> var curNum = 0 var start: Vec2i? = null var isAdjacent = false row.cells.forEach { (p, c) -> if (c.isDigit()) { if (start == null) { // left here if (input[p.x - 1][p.y].isSymbol()) { isAdjacent = true } else if (p.y - 1 >= 0 && input[p.x - 1][p.y - 1].isSymbol()) { isAdjacent = true } else if (p.y + 1 < input.height - 1 && input[p.x - 1][p.y + 1].isSymbol()) { isAdjacent = true } start = p } curNum = curNum * 10 + (c - '0') // up and down here if (!isAdjacent) { if (input[p.x][p.y - 1].isSymbol()) { isAdjacent = true } else if (input[p.x][p.y + 1].isSymbol()) { isAdjacent = true } } } else { // right here if (curNum != 0) { if (!isAdjacent) { if (input[p.x][p.y].isSymbol()) { isAdjacent = true } else if (input[p.x][p.y - 1].isSymbol()) { isAdjacent = true } else if (input[p.x][p.y + 1].isSymbol()) { isAdjacent = true } } if (isAdjacent) { sum += curNum } } curNum = 0 start = null isAdjacent = false } } if (curNum != 0 && isAdjacent) { sum += curNum } } return sum } override fun part2(input: Grid<Char>): Int { var sum = 0 val nums = IntGrid(input.width, input.height, 0).toMutable() val gears = mutableListOf<Vec2i>() input.rows.forEach { row -> var curNum = 0 var start = 0 row.cells.forEach { (p, c) -> if (c.isDigit()) { if (curNum == 0) { start = p.x } curNum = curNum * 10 + (c - '0') } else { if (c == '*') { gears.add(p) } // right here if (curNum != 0) { (start until p.x).forEach { x -> nums[x][p.y] = curNum } curNum = 0 } } } if (curNum != 0) { (start until input.width).forEach { x -> nums[x][row.y] = curNum } curNum = 0 } } gears.forEach { p -> var gear = 1 var count = 0 // left if (p.x - 1 >= 0 && nums[p.x - 1][p.y] != 0) { gear *= nums[p.x - 1][p.y] count++ } // right if (p.x + 1 < input.width - 1 && nums[p.x + 1][p.y] != 0) { gear *= nums[p.x + 1][p.y] count++ } // top if (p.y - 1 >= 0) { if (nums[p.x][p.y - 1] != 0) { gear *= nums[p.x][p.y - 1] count++ } else { // top-left if (p.x - 1 >= 0 && nums[p.x - 1][p.y - 1] != 0) { gear *= nums[p.x - 1][p.y - 1] count++ } // top-right if (p.x + 1 < input.width && nums[p.x + 1][p.y - 1] != 0) { gear *= nums[p.x + 1][p.y - 1] count++ } } } // bottom if (p.y + 1 < input.height - 1) { if (nums[p.x][p.y + 1] != 0) { gear *= nums[p.x][p.y + 1] count++ } else { // bottom-left if (p.x - 1 >= 0 && nums[p.x - 1][p.y + 1] != 0) { gear *= nums[p.x - 1][p.y + 1] count++ } // bottom-right if (p.x + 1 < input.width && nums[p.x + 1][p.y + 1] != 0) { gear *= nums[p.x + 1][p.y + 1] count++ } } } if (count == 2) { sum += gear } } return sum } } private fun Char.isSymbol(): Boolean { return !isDigit() && this != '.' }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
4,560
aoc_kotlin
MIT License
src/main/kotlin/co/csadev/advent2021/Day13.kt
gtcompscientist
577,439,489
false
{"Kotlin": 252918}
/** * Copyright (c) 2021 by <NAME> * Advent of Code 2021, Day 13 * Problem Description: http://adventofcode.com/2021/day/13 */ package co.csadev.advent2021 import co.csadev.adventOfCode.BaseDay import co.csadev.adventOfCode.Point2D import co.csadev.adventOfCode.Resources.resourceAsList import co.csadev.adventOfCode.printGraph class Day13(override val input: List<String> = resourceAsList("21day13.txt")) : BaseDay<List<String>, Int, Int> { private val inputInstructions = input.indexOf("").run { input.subList(this + 1, input.size) }.map { instr -> instr.split(" ")[2].split("=").let { it[0] to it[1].toInt() } } private val inputCoords = input.indexOf("").run { input.subList(0, this) } .map { it.split(",").let { p -> Point2D(p[0].toInt(), p[1].toInt()) } } private fun List<Point2D>.fold(move: Pair<String, Int>): List<Point2D> { val pos = move.second return map { p -> when (move.first) { "x" -> if (p.x > pos) p.copy(x = pos - (p.x - pos)) else p else -> if (p.y > pos) p.copy(y = pos - (p.y - pos)) else p } }.distinct() } override fun solvePart1() = inputCoords.fold(inputInstructions.first()).count() override fun solvePart2(): Int { var coords = inputCoords inputInstructions.forEach { move -> coords = coords.fold(move) } // Test: Square // Actual: PZFJHRFZ coords.printGraph() return 0 } }
0
Kotlin
0
1
43cbaac4e8b0a53e8aaae0f67dfc4395080e1383
1,522
advent-of-kotlin
Apache License 2.0
src/main/java/challenges/educative_grokking_coding_interview/k_way_merge/_4/MergeSortList.kt
ShabanKamell
342,007,920
false
null
package challenges.educative_grokking_coding_interview.k_way_merge._4 import challenges.educative_grokking_coding_interview.LinkedList import challenges.educative_grokking_coding_interview.LinkedListNode import challenges.educative_grokking_coding_interview.PrintList.printListWithForwardArrow import challenges.util.PrintHyphens import java.util.* /** Given an array of k sorted linked lists, your task is to merge them into a single sorted list. https://www.educative.io/courses/grokking-coding-interview-patterns-java/NEYEqvwL8W6 */ internal object MergeSortList { // helper function private fun merge2Lists(head1: LinkedListNode?, head2: LinkedListNode?): LinkedListNode? { var head1: LinkedListNode? = head1 var head2: LinkedListNode? = head2 val dummy = LinkedListNode(-1) var prev: LinkedListNode? = dummy // set prev pointer to dummy node // traverse over the lists until both or one of them becomes null while (head1 != null && head2 != null) { // if l1 value is<= l2 value, add l1 node to the list if (head1.data <= head2.data) { prev?.next = head1 head1 = head1.next } else { // if l1 value is greater than l2 value, add l2 node to the list prev?.next = head2 head2 = head2.next } prev = prev?.next } if (head1 == null) prev?.next = head2 else prev?.next = head1 return dummy.next } // Main function private fun mergeKLists(lists: List<LinkedList>): LinkedListNode? { val temp = 0 return if (lists.isNotEmpty()) { var step = 1 while (step < lists.size) { //temp = step; var i = 0 while (i < lists.size - step) { lists[i].head = merge2Lists(lists[i].head, lists[i + step].head) i += step * 2 } step *= 2 } lists[0].head } else null } @JvmStatic fun main(args: Array<String>) { val inputLists = listOf( listOf(listOf(21, 23, 42), listOf(1, 2, 4)), listOf(listOf(11, 41, 51), listOf(21, 23, 42)), listOf(listOf(2), listOf(1, 2, 4), listOf(25, 56, 66, 72)), listOf( listOf(11, 41, 51), listOf(2), listOf(2), listOf(2), listOf(1, 2, 4) ), listOf( listOf(10, 30), listOf(15, 25), listOf(1, 7), listOf(3, 9), listOf(100, 300), listOf(115, 125), listOf(10, 70), listOf(30, 90) ) ) for (i in inputLists.indices) { println((i + 1).toString() + ".\tInput lists:") val llList: MutableList<LinkedList> = ArrayList<LinkedList>() for (x in inputLists[i]) { val a = LinkedList() a.createLinkedList(x.toIntArray()) llList.add(a) print("\t") printListWithForwardArrow(a.head) println() } print("\tMerged list: \n\t") printListWithForwardArrow(mergeKLists(llList)) println( """ ${PrintHyphens.repeat("-", 100)} """.trimIndent() ) } } }
0
Kotlin
0
0
ee06bebe0d3a7cd411d9ec7b7e317b48fe8c6d70
3,567
CodingChallenges
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/NextLargerNodes.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.util.Stack /** * 1019. Next Greater Node In Linked List * @see <a href="https://leetcode.com/problems/next-greater-node-in-linked-list/">Source</a> */ fun interface NextLargerNodes { operator fun invoke(head: ListNode?): IntArray } class NextLargerNodesStack : NextLargerNodes { override operator fun invoke(head: ListNode?): IntArray { val arr: ArrayList<Int> = ArrayList() var node = head while (node != null) { arr.add(node.value) node = node.next } val res = IntArray(arr.size) val stack: Stack<Int> = Stack() for (i in 0 until arr.size) { while (stack.isNotEmpty() && arr[stack.peek()] < arr[i]) res[stack.pop()] = arr[i] stack.push(i) } return res } } class NextLargerNodesOnePass : NextLargerNodes { override operator fun invoke(head: ListNode?): IntArray { // Keeps track of indices of values in nums val stack = Stack<Int>() // Store node values as we go, // updates to output value ("next greatest") within while loop as we see them val nums: MutableList<Int> = ArrayList() var n = head // For generating the corresponding index in nums as we step through LinkedList var index = 0 while (n != null) { nums.add(n.value) // Process anything that is less than current node value // i.e. current node value is the "next"greatest for elements (index-referenced) in the stack while (stack.isNotEmpty() && nums[stack.peek()] < n.value) { nums[stack.pop()] = n.value } // Set up for next iteration. // Note: Every node gets into the stack. stack.push(index) n = n.next index++ } // Handle remaining items in stack / write in 0 (no "next greatest" found for these) while (stack.isNotEmpty()) { nums[stack.pop()] = 0 } // Format output val result = IntArray(nums.size) for (i in result.indices) { result[i] = nums[i] } return result } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,849
kotlab
Apache License 2.0
datastructures/src/main/kotlin/com/kotlinground/datastructures/trees/trie/Trie.kt
BrianLusina
113,182,832
false
{"Kotlin": 483489, "Shell": 7283, "Python": 1725}
package com.kotlinground.datastructures.trees.trie /** * Trie is a trie tree */ class Trie(private var root: TrieNode) { /** * Searches for a word in the trie, returning a collection of words that match it * @param word [String] word to search for * @return [Collection] matching words */ fun search(word: String): Collection<String> { var currentNode = root for (char in word) { if (currentNode.children.containsKey(char)) { currentNode = currentNode.children[char]!! } else { return emptyList() } } val result = arrayListOf<String>() fun dfs(currentNode: TrieNode, prefix: String) { if (currentNode.isEnd) { result.add(prefix + currentNode.char) } for ((char, node) in currentNode.children) { dfs(node, prefix + char.toString()) } } dfs(currentNode, word.substring(0, word.length - 1)) return result } fun insert(word: String) { var currentNode = root for (char in word) { // if the current node has a child key with the current character if (currentNode.children.containsKey(char)) { // follow the child node currentNode = currentNode.children[char]!! } else { // if the current character is not found among the children, we add the character as a new child node val newNode = TrieNode(char) currentNode.children[char] = newNode // follow this new node currentNode = newNode } } // after inserting the entire word into the trie, mark the node as the end currentNode.isEnd = true } /** * Collect all words from the trie */ fun collectAllWords(): Collection<String> { val words = arrayListOf<String>() fun collectAllWordsHelper(currentNode: TrieNode, word: String) { for ((char, node) in currentNode.children) { if (node.isEnd) { words.add(word) } else { collectAllWordsHelper(node, word + char) } } } collectAllWordsHelper(root, "") return words } }
1
Kotlin
1
0
5e3e45b84176ea2d9eb36f4f625de89d8685e000
2,394
KotlinGround
MIT License
day7.main.kts
goncalossilva
319,515,627
false
{"Kotlin": 5954, "Erlang": 2329}
#!/usr/bin/env kotlinc -script import java.io.File val rules = File("day7.txt").readLines() val bagRegex = "(^[\\w\\s]+) bags contain".toRegex() val ruleRegex = "(\\d+) ([\\w\\s]+) bags?,?".toRegex() data class Rule(val bag: String, val count: Int) val bagRules = mutableMapOf<String, List<Rule>>() rules.forEach { rule -> val node = bagRegex.find(rule)!!.groupValues[1] val links = ruleRegex.findAll(rule).map { val (count, bag) = it.destructured Rule(bag, count.toInt()) } bagRules[node] = links.toList() } fun contains(bag: String, otherBag: String): Boolean { val links = bagRules[bag] ?: return false return links.any { it.bag == otherBag } || links.any { contains(it.bag, otherBag) } } fun countInside(bag: String): Int { val links = bagRules[bag] ?: return 1 return links.sumOf { it.count } + links.sumOf { it.count * countInside(it.bag) } } // Part 1 println("# can contain: ${bagRules.count { (bag, _) -> contains(bag, "shiny gold") }}") // Part 2 println("# inside: ${countInside("shiny gold")}")
0
Kotlin
0
1
2d63c5760236274418f7ed134da6d8d8ba9838eb
1,063
aoc-2020
The Unlicense
src/me/bytebeats/algo/kt/Solution.kt
bytebeats
251,234,289
false
null
package me.bytebeats.algo.kt import me.bytebeats.algo.designs.Trie import me.bytebeats.algs.ds.ListNode import me.bytebeats.algs.ds.TreeNode import java.util.* import kotlin.collections.ArrayList import kotlin.collections.HashMap import kotlin.collections.HashSet class Solution { fun findDuplicate(nums: IntArray): Int {//287 var fast = 0 var slow = 0 while (true) { fast = nums[nums[fast]] slow = nums[slow] if (slow == fast) { fast = 0 while (nums[slow] != nums[fast]) { fast = nums[fast] slow = nums[slow] } return nums[slow] } } return 0 } fun invertTree(root: TreeNode?): TreeNode? {//226 root?.apply { val tmp = left left = right right = tmp left?.apply { invertTree(root.left) } right?.apply { invertTree(root.right) } } return root } fun myPow(x: Double, n: Int): Double {//50, 面试题16 var xVal = x if (n < 0) { xVal = 1 / x } return recursivePow(xVal, n) } fun recursivePow(x: Double, n: Int): Double { if (n == 0) { return 1.0 } val halfP = recursivePow(x, n / 2) return if (n and 1 == 1) halfP * halfP * x else halfP * halfP } fun mySqrt(x: Int): Int {//69 if (x == 0) { return 0 } else { return binarySearch(1, x.toLong(), x.toLong()).toInt() } } private fun binarySearch(low: Long, high: Long, x: Long): Long { var mid = 0L var l = low var h = high while (l < h) { mid = l + (h - l) / 2L if (mid * mid == x || l == mid) { return mid } else if (mid * mid > x) { h = mid } else { l = mid } } return 1L } fun isPerfectSquare(num: Int): Boolean {//367, binary search if (num < 1) { return false } else if (num == 1) { return true } else { val n = num.toLong() var l = 1L var h: Long = (num / 2).toLong() var mid = 0L while (l <= h) { mid = l + (h - l) / 2L if (mid * mid == n) { return true } else if (mid * mid > n) { h = mid - 1 } else { l = mid + 1 } } return false } } fun judgeSquareSum(c: Int): Boolean { if (c < 3) { return true } else { var sum = 0L var d = 0L var n = 0.0 for (i in 0..Math.sqrt(c.toDouble()).toInt()) { sum = (i * i).toLong() d = c - sum if (d < 0) { return false } else { n = Math.sqrt(d.toDouble()) var dd = n - n.toInt() if (dd == 0.0) { return true } } } return false } } fun isPowerOfTwo(n: Int): Boolean {//is n equal to 2^n if (n < 1) { return false } var num = n var has1 = false while (num != 0) { if (has1) { return false } if (num % 2 != 0) { has1 = true } num = num shr 1 } return true } fun isPowerOfThree(n: Int): Boolean { if (n < 1) { return false } else if (n == 1) { return true } else if (n % 2 == 0) { return false } else { var num = n while (num != 1) { var d = num / 3.0 var dd = d - d.toInt() if (dd != 0.0) { return false } num = d.toInt() } return true } } fun isPowerOfFour(num: Int): Boolean { if (num <= 0) { return false } else if (num == 1) { return true } else { if (num % 10 != 4 && num % 10 != 6) { return false } var n = num while (n != 1) { var d = n / 4.0 if (d - d.toInt() != 0.0) { return false } n = d.toInt() } return true } } fun findShortestSubArray(nums: IntArray): Int { val count = HashMap<Int, Int>() for (i in nums.indices) { count[nums[i]] = count.getOrDefault(nums[i], 0) + 1 } val degree = count.values.maxOfOrNull { it } ?: 0 var slow = 0 var minLength = nums.size val windowCount = HashMap<Int, Int>() var windowDegree = 0 for (fast in nums.indices) { windowCount[nums[fast]] = windowCount.getOrDefault(nums[fast], 0) + 1 windowDegree = Math.max(windowDegree, windowCount[nums[fast]]!!) while (windowDegree == degree) { minLength = Math.min(minLength, fast - slow + 1) windowCount[nums[slow]] = windowCount[nums[slow]]!! - 1 slow++ if (nums[slow - 1] == nums[fast]) { windowDegree-- } } } return minLength } fun isSymmetric(root: TreeNode?): Boolean { if (root == null) { return false } return isSymmetric(root.left, root.right) } private fun isSymmetric(left: TreeNode?, right: TreeNode?): Boolean { if (left == null && right == null) { return true } else if (left == null || right == null) { return false } else if (left.`val` != right.`val`) { return false } else { return isSymmetric(left.left, right.right) && isSymmetric(left.right, right.left) } } fun getMinimumDifference(root: TreeNode?): Int { var minVal = Int.MAX_VALUE if (root != null) { val s = Stack<TreeNode>() val output = Stack<TreeNode>() var p = root while (p != null || !s.isEmpty()) { if (p != null) { s.push(p) p = p.left } else { p = s.pop() output.push(p) p = p.right } } var top = s.pop() var diff = 0 while (!s.isEmpty()) { diff = top.`val` - s.peek().`val` if (diff < minVal) { minVal = diff } top = s.pop() } } return minVal } fun findPairs(nums: IntArray, k: Int): Int { var count = 0 if (nums.isNotEmpty() && k >= 0) { val set = HashSet<Int>() for (num in nums) { if (set.isEmpty()) { set.add(num) } else { val num1 = num - k if (set.contains(num1)) { count++ } val num2 = num + k if (set.contains(num2)) { count++ } set.add(num) } } count /= 2 } return count } fun tree2str(t: TreeNode?): String { var res = concat(t) if (res.length > 3) { res = res.substring(1, res.length - 1) } return res } private fun concat(t: TreeNode?): String { var res = "" if (t != null) { if (t.left == null && t.right == null) { res = "(${t.`val`})" } else { res = "${t.`val`}" if (t.left != null) { res += "${concat(t.left)}" } else { res += "()" } if (t.right != null) { res += "${concat(t.right)}" } res = "($res)" } } return res } fun str2tree(s: String): TreeNode? { return createTree("($s)") } private fun createTree(s: String): TreeNode? { var str = s.substring(1, s.length - 1) if (str.isEmpty()) { return null } else { val numEndIndex = str.indexOfFirst { it == '(' } if (numEndIndex <= 0) { return TreeNode(str.toInt()) } else { val num = str.subSequence(0, numEndIndex).toString().toInt() val splitIndex = str.lastIndexOf(")(") val newTreeNode = TreeNode(num) if (splitIndex > 0) { newTreeNode.left = createTree(str.substring(numEndIndex, splitIndex + 1)) newTreeNode.right = createTree(str.substring(splitIndex + 1)) } else { newTreeNode.left = createTree(str.substring(numEndIndex)) } return newTreeNode } } } fun longestWord(words: Array<String>): String { var res = "" if (words.isNotEmpty()) { val trie = Trie() words.sortBy { it.length } words.forEach { if (it.length > 0) { // if (trie.) { // // } else { trie.insert(it) // } } } } return res } fun searchInsert(nums: IntArray, target: Int): Int { if (nums.isEmpty() || target < nums.first()) { return 0 } if (target > nums.last()) { return nums.size } var index = -1 for (i in 0 until nums.size) { println(i) if (nums[i] == target) { return i } else if (nums[i] > target) { index = i break } } return index } fun findClosestElements(arr: IntArray, k: Int, x: Int): List<Int> { val res = ArrayList<Int>(k) if (x < arr.first()) { for (i in 0 until k) { res.add(arr[i]) } } else if (x > arr.last()) { for (i in arr.size - k until arr.size) { res.add(arr[i]) } } else { var low = 0 var high = arr.size - 1 var mid = 0 while (low < high) { mid = low + (high - low) / 2 if (arr[mid] < x) { low = mid + 1 } else { high = mid } } var newK = 0 if (arr[low] == x) { res.add(arr[low]) high = low + 1 low-- newK = k - 1 } else { high = low low-- newK = k } while (newK > 0) { if (low > -1 && high < arr.size) { if (Math.abs(arr[low] - x) <= Math.abs(arr[high] - x)) { res.add(0, arr[low]) low-- } else { res.add(arr[high]) high++ } } else if (low > -1) { res.add(0, arr[low]) low-- } else if (high < arr.size) { res.add(arr[high]) high++ } newK-- } } return res } fun generate(numRows: Int): List<List<Int>> { val triangle = ArrayList<List<Int>>(numRows) var pre: List<Int>? = null for (i in 0 until numRows) { val row = ArrayList<Int>(i + 1) if (i > 0) { pre = triangle[i - 1] } for (j in 0..i) { if (j == 0) { row.add(1) } else if (j == i) { row.add(1) } else { if (j > 0 && pre != null) { row.add(pre[j] + pre[j - 1]) } } } triangle.add(row) } return triangle } fun getRow(rowIndex: Int): List<Int> { val row = ArrayList<Int>(rowIndex + 1) for (i in 0..rowIndex) { row.add(1) if (i >= 2) { for (j in i - 1 downTo 1) { row[j] += row[j - 1] } } } return row } fun largestUniqueNumber(A: IntArray): Int { if (A.size == 1) { return A[0] } A.sort() var res = -1 var index = A.lastIndex while (index > -1) { if (index == A.lastIndex) { if (A[index] != A[index - 1]) { return A.last() } else { index-- } } else if (index == 0) { if (A[index] != A[index + 1]) { return A.first() } else { break } } else { if (A[index] != A[index - 1] && A[index] != A[index + 1]) { return A[index] } else { index-- } } } return res } fun dietPlanPerformance(calories: IntArray, k: Int, lower: Int, upper: Int): Int { var grade = 0 var calorie = 0 if (k > 1) { for (i in 0..k - 2) { calorie += calories[i] } } for (i in k - 1 until calories.size) { calorie += calories[i] if (calorie < lower) { grade-- } else if (calorie > upper) { grade++ } calorie -= calories[i - k + 1] } return grade } fun rotate(nums: IntArray, k: Int): Unit {//189 if (nums.isEmpty() || nums.size == 1 || k < 1) { return } var j = 0 val size = nums.size val newK = k % size var tmp = 0 for (i in 0 until newK) { j = i + size - newK tmp = nums[j] for (h in j downTo i + 1) { nums[h] = nums[h - 1] } nums[i] = tmp } } fun rotate2(nums: IntArray, k: Int): Unit {//189 if (nums.isEmpty() || nums.size == 1 || k < 1) { return } val size = nums.size val newK = k % size reverse(nums, 0, size - newK - 1) reverse(nums, size - newK, size - 1) reverse(nums, 0, size - 1) } private fun reverse(nums: IntArray, start: Int, end: Int) { var s = start var e = end var tmp = 0 while (s < e) { tmp = nums[s] nums[s] = nums[e] nums[e] = tmp s++ e-- } } fun canReorderDoubled(A: IntArray): Boolean {//954 val map = mutableMapOf<Int, Int>() A.forEach { map.compute(it) { _, v -> if (v == null) 1 else v + 1 } } for (num in A.sortedBy { Math.abs(it) }) { if (map[num]!! == 0) continue if (map[num * 2] ?: 0 <= 0) return false map[num] = map[num]!! - 1 map[num * 2] = map[num * 2]!! - 1 } return true } fun countAndSay(n: Int): String { if (n <= 1) { return "1" } else { var res = "" val pre = countAndSay(n - 1) var count = 0 var ch = pre[0] for (i in 0 until pre.length) { if (ch == pre[i]) { count++ } else { res += "$count$ch" count = 1 ch = pre[i] } } res += "$count$ch" return res } } fun countAndSay2(n: Int): String { var res = "1" var k = n var count = 0 var ch = ' ' var tmp = "" while (k > 0) { count = 0 ch = res[0] tmp = "" for (i in 0 until res.length) { if (ch == res[i]) { count++ } else { tmp += "$count$ch" count = 1 ch = res[i] } } tmp += "$count$ch" res = tmp k-- } return res } fun compress(chars: CharArray): Int { var res = 0 if (chars.isNotEmpty()) { var ch = chars[0] var count = 0 for (i in 0 until chars.size) { if (ch == chars[i]) { count++ } else { chars[res++] = ch if (count > 1) { count.toString().forEach { chars[res++] = it } } count = 1 ch = chars[i] } } chars[res++] = ch if (count > 1) { count.toString().forEach { chars[res++] = it } } } return res } fun smallerNumbersThanCurrent(nums: IntArray): IntArray {//1365 val copy = nums.copyOfRange(0, nums.size) for (i in nums.indices) { nums[i] = copy.filter { it < nums[i] }.count() } return nums } fun rankTeams(votes: Array<String>): String { val res = StringBuilder() if (votes.isNotEmpty()) { val map = HashMap<Int, HashMap<Char, Int>>() votes.forEach { vote -> for (i in 0 until vote.length) { map.compute(i) { _, v -> if (v == null) { val newV = HashMap<Char, Int>() newV[vote[i]] = 1 newV } else { val key = vote[i] if (v.containsKey(key)) { v[key] = v?.getValue(key)?.plus(1) } else { v[key] = 1 } v } } } } val count = votes[0].length for (i in 0 until count) { var ch: Char? = null var j = i while (j < count) { val e = map[j] val maxCount = e!!.values.maxOfOrNull { it } val keys = e.filter { it -> it.value == maxCount }.keys if (keys.size == 1) { ch = keys.first() res.append(ch) } else { j++ } } } if (res.length != count) { res.append(votes[0].substring(res.length)) } } return res.toString() } var found = false var treeHead: TreeNode? = null fun isSubPath(head: ListNode?, root: TreeNode?): Boolean { if (head == null || root == null) { return false } found = false treeHead = null findSubPathHead(root, head.`val`) if (!found || treeHead == null) { return false } var p = treeHead var q = head while (q != null) { if (p?.`val` != q?.`val`) { return false } else { if (p.left != null && p.left.`val` == q.`val`) { p = p.left q = q.next } if (p?.right != null && p.right.`val` == q?.`val`) { p = p.right q = q.next } } } return true } private fun findSubPathHead(root: TreeNode?, listHeadValue: Int) { if (found) { return } if (root != null) { if (root.`val` == listHeadValue) { treeHead = root found = true } else { findSubPathHead(root.left, listHeadValue) findSubPathHead(root.right, listHeadValue) } } } fun merge(A: IntArray, m: Int, B: IntArray, n: Int): Unit { for (i in 0 until n) { A[m + i] = B[i] } A.sort(0, m + n) } fun isBalanced(root: TreeNode?): Boolean {//110 if (root == null) { return true } else if (root.left == null && root.right == null) { return true } else if (Math.abs(height(root.left) - height(root.right)) > 1) { return false } else { return isBalanced(root.left) && isBalanced(root.right) } } private fun height(root: TreeNode?): Int { if (root == null) { return 0 } else { return 1 + Math.max(height(root.left), height(root.right)) } } fun singleNumber(nums: IntArray): Int { var res = 0 for (i in nums.indices) { res = res xor nums[i] } nums.forEach { res = res xor it } return res } fun singleNumber2(nums: IntArray): IntArray { var bitmask = 0 nums.forEach { bitmask = bitmask xor it } val diff = bitmask and (-bitmask) var x = 0 nums.forEach { if (it and diff != 0) { x = x xor it } } return intArrayOf(x, bitmask xor x) } fun majorityElement(nums: IntArray): Int { if (nums.isEmpty()) { return -1 } var count = 1 var tmp = nums.first() for (i in nums.indices) { if (tmp == nums[i]) { count++ } else { count-- } if (count == 0) { count = 1 tmp = nums[i] } } val halfSize = nums.size / 2 + 1 count = 0 for (i in nums.indices) { if (tmp == nums[i]) { count++ } if (count == halfSize) { return tmp } } return -1 } val dr = intArrayOf(-1, 0, 1, 0) val dc = intArrayOf(0, -1, 0, 1) fun orangesRotting(grid: Array<IntArray>): Int { val R = grid.size val C: Int = grid[0].size // queue : all starting cells with rotten oranges val queue = ArrayDeque<Int>() val depth = HashMap<Int?, Int?>() for (r in 0 until R) for (c in 0 until C) if (grid[r][c] == 2) { val code = r * C + c queue.add(code) depth[code] = 0 } var ans = 0 while (!queue.isEmpty()) { val code = queue.remove() val r = code / C val c = code % C for (k in 0..3) { val nr = r + dr[k] val nc = c + dc[k] if (nr in 0 until R && nc in 0 until C && grid[nr][nc] == 1) { grid[nr][nc] = 2 val ncode = nr * C + nc queue.add(ncode) depth[ncode] = depth[code]!! + 1 ans = depth[ncode]!! } } } for (row in grid) for (v in row) if (v == 1) return -1 return ans } fun distributeCandies(candies: Int, num_people: Int): IntArray {//1103 val arr = IntArray(num_people) var left = candies var index = 0 var candy = 0 while (left > 0) { candy++ index = (candy - 1) % num_people if (candy <= left) { arr[index] += candy left -= candy } else { arr[index] += left left = 0 } } return arr } fun findContinuousSequence(target: Int): Array<IntArray> { val res = ArrayList<IntArray>() var sum = 0 val end = (target + 1) / 2 for (i in 1..end) { sum = 0 for (j in i..end) { sum += j if (sum >= target) { if (sum == target) { val sub = IntArray(j - i + 1) for (k in i..j) { sub[k - i] = k } res.add(sub) } break } } } return res.toTypedArray() } fun levelOrder(root: TreeNode?): List<List<Int>> { val res = ArrayList<List<Int>>() if (root != null) { val q = LinkedList<TreeNode>() var levelRes = ArrayList<Int>() q.add(root) var countDown = 1 var count = 0 var p: TreeNode? = null while (!q.isEmpty()) { p = q.remove() levelRes.add(p.`val`) countDown-- if (root.left != null) { count++ q.add(root.left) } if (root.right != null) { count++ q.add(root.right) } if (countDown == 0) { res.add(ArrayList<Int>(levelRes)) countDown = count count = 0 levelRes.clear() } } } return res } fun plusOne(digits: IntArray): IntArray { var b = 1 for (i in digits.lastIndex downTo 0) { digits[i] += b b = digits[i] / 10 digits[i] %= 10 } if (b == 0) { return digits } else { val newDigits = IntArray(digits.size + 1) newDigits[0] = b digits.forEachIndexed { index, i -> newDigits[index + 1] = i } return newDigits } } fun addBinary(a: String, b: String): String {//67 val res = StringBuilder() var i = a.lastIndex var j = b.lastIndex var subSum = 0 while (i > -1 && j > -1) { subSum += (a[i] - '0') + (b[j] - '0') res.append(subSum % 2) println(res) subSum /= 2 i-- j-- } while (i > -1) { subSum += (a[i] - '0') res.append(subSum % 2) println(res) subSum /= 2 i-- } while (j > -1) { subSum += (b[j] - '0') res.append(subSum % 2) println(res) subSum /= 2 j-- } if (subSum != 0) { res.append(subSum) println(res) } return res.reversed().toString() } fun addToArrayForm(A: IntArray, K: Int): List<Int> { val sum = ArrayList<Int>() var i = A.lastIndex var j = K var d = 0 while (i > -1 && j != 0) { d += A[i] + j % 10 sum.add(d % 10) d /= 10 i-- j /= 10 } while (i > -1) { d += A[i] sum.add(d % 10) d /= 10 i-- } while (j != 0) { d += j % 10 sum.add(d % 10) d /= 10 j /= 10 } if (d != 0) { sum.add(d) } return sum.reversed() } fun addStrings(num1: String, num2: String): String { if (num1.isEmpty()) { return num2 } else if (num2.isEmpty()) { return num1 } else { val sum = StringBuilder() var i = num1.lastIndex var j = num2.lastIndex var d = 0 while (i > -1 && j > -1) { d += (num1[i] - '0') + (num2[j] - '0') sum.append(d % 10) d /= 10 i-- j-- } while (i > -1) { d += (num1[i] - '0') sum.append(d % 10) d /= 10 i-- } while (j > -1) { d += (num2[j] - '0') sum.append(d % 10) d /= 10 j-- } if (d != 0) { sum.append(d) } return sum.reverse().toString() } } fun multiply(num1: String, num2: String): String { var sum = "" if (num1.isNotEmpty() && num2.isNotEmpty()) { for (i in num1.lastIndex downTo 0) { sum = addStrings(sum, multiply(num2, num1[i], num1.lastIndex - i)) } } while (sum.startsWith('0') && sum.length > 1) { sum = sum.substring(1) } return sum } fun multiply(num1: String, num2: Char, count: Int): String { val times = num2 - '0' if (times == 0) { return "0" } var sum = StringBuilder() var d = 0 for (i in num1.lastIndex downTo 0) { d += (num1[i] - '0') * times sum.append(d % 10) d /= 10 } if (d != 0) { sum.append(d) } sum.reverse() var zeroCount = count while (zeroCount > 0) { sum.append(0) zeroCount-- } return sum.toString() } fun plusOne(head: ListNode?): ListNode? { if (head == null) { return head } var reverseList = reverse(head) var p = reverseList var d = 1 while (p != null) { d += p.`val` p.`val` = d % 10 d /= 10 p = p.next } if (d != 0) { p = reverseList while (p?.next != null) { p = p.next } p?.next = ListNode(d) } return reverse(reverseList) } fun reverse(head: ListNode?): ListNode? { val dummy = ListNode(-1) var dummyNext = dummy.next var p = head var tmp: ListNode? = null while (p != null) { tmp = p p = p.next dummyNext = dummy.next dummy.next = tmp tmp.next = dummyNext } return dummy.next } fun sortString(s: String): String { val chCounts = IntArray(26) s.forEach { chCounts[it - 'a']++ } val res = StringBuilder() while (chCounts.sum() > 0) { for (i in chCounts.indices) { if (chCounts[i] > 0) { res.append('a' + i) chCounts[i]-- } } for (i in 25 downTo 0) { if (chCounts[i] > 0) { res.append('a' + i) chCounts[i]-- } } } return res.toString() } fun sortString2(s: String): String { val chCounts = IntArray(26) var count = 0 s.forEach { chCounts[it - 'a']++ count++ } val res = StringBuilder() while (count > 0) { for (i in chCounts.indices) { if (chCounts[i] > 0) { res.append('a' + i) chCounts[i]-- count-- } } for (i in 25 downTo 0) { if (chCounts[i] > 0) { res.append('a' + i) chCounts[i]-- count-- } } } return res.toString() } fun findTheLongestSubstring(s: String): Int { val map = HashMap<Char, Int>(5) s.forEach { if (isVowel(it)) { map.compute(it) { _, value -> if (value == null) { 1 } else { value + 1 } } } } var start = 0 var end = s.lastIndex while (map.values.sum() % 2 != 0) { for (i in s.indices) { if (isVowel(s[i])) { start = i break } } for (i in s.lastIndex downTo 0) { if (isVowel(s[i])) { end = i break } } } return 0 } private fun isVowel(char: Char): Boolean = char == 'a' || char == 'e' || char == 'i' || char == 'o' || char == 'u' fun longestPalindromeSubseq(s: String): Int { val mnchStr = StringBuilder() s.forEach { mnchStr.append('#') mnchStr.append(it) } mnchStr.append('#') val radius = IntArray(mnchStr.length) var R = -1 var C = -1 var max = Int.MIN_VALUE for (i in mnchStr.indices) { radius[i] = if (R < i) 1 else Math.min(R - i, radius[2 * C - i]) while (i - radius[i] > -1 && i + radius[i] < mnchStr.length && mnchStr[i - radius[i]] == mnchStr[i + radius[i]]) { radius[i]++ } if (i + radius[i] > R) { R = i + radius[i] - 1 C = i } if (max < radius[i]) { max = radius[i] } } return max - 1 } fun longestPalindromeSubseq2(s: String): Int { val n = s.length val f = Array(n) { IntArray(n) } for (i in n - 1 downTo 0) { f[i][i] = 1 for (j in i + 1 until n) { if (s[i] == s[j]) { f[i][j] = f[i + 1][j - 1] + 2 } else { f[i][j] = Math.max(f[i + 1][j], f[i][j - 1]) } } } return f[0][n - 1] } fun generateTheString(n: Int): String {//1374 val res = StringBuilder() var k = n if (k % 2 == 0) { for (i in 0 until k - 1) { res.append('a') } res.append('b') } else { for (i in 0 until k) { res.append('a') } } return res.toString() } fun numTimesAllBlue(light: IntArray): Int { var count = 0 val states = IntArray(light.size) { -1 } var index = 0 var maxIndex = -1 for (i in light.indices) { index = light[i] - 1 if (maxIndex < index) { maxIndex = index } states[index] = 0 if (isAllAtLeatOnBefore(states, maxIndex)) { setAllBlue(states, maxIndex) if (isAllOnBlue(states)) { count++ } } } return count } fun isAllOnBlue(states: IntArray): Boolean { for (i in states.indices) { if (states[i] == 0) { return false } } return true } fun setAllBlue(states: IntArray, n: Int) { for (i in 0..n) { states[i] = 1 } } fun isAllAtLeatOnBefore(states: IntArray, n: Int): Boolean { for (i in 0..n) { if (states[i] < 0) { return false } } return true } fun numOfMinutes(n: Int, headID: Int, manager: IntArray, informTime: IntArray): Int { var k = n var minutes = 0 val list = ArrayList<Int>() var minVal = 0 manager[headID] = Int.MAX_VALUE minutes += informTime[headID] k -= 1 while (k > 0) { list.clear() minVal = manager.minOfOrNull { it } ?: Int.MAX_VALUE if (minVal != Int.MAX_VALUE) { for (i in manager.indices) { if (minVal == manager[i]) { list.add(i) } else { continue } } for (i in list.indices) { minutes += informTime[i] manager[i] = Int.MAX_VALUE } } k -= list.size } return minutes } fun coinChange(coins: IntArray, amount: Int): Int { if (amount <= 0) { return 0 } if (coins.isEmpty()) { return -1 } coins.sort() val matrix = Array(amount + 1) { IntArray(coins.size + 1) { -1 } } var preAmount = 0 for (i in 1..amount) { for (j in 0..coins.lastIndex) { preAmount = i - coins[j] if (preAmount > -1) { if (preAmount == 0) { matrix[i][j] = 1 } else if (matrix[preAmount][coins.size] > 0) { matrix[i][j] = matrix[preAmount][coins.size] + 1 } if (matrix[i][coins.size] == -1 || matrix[i][j] < matrix[i][coins.size]) { matrix[i][coins.size] = matrix[i][j] } } } } return matrix[amount][coins.size] } fun maxProfit(prices: IntArray): Int { var maxProfit = 0 if (prices.isNotEmpty()) { var minPrice = prices[0] for (i in prices.indices) { if (prices[i] - minPrice > maxProfit) { maxProfit = prices[i] - minPrice } if (minPrice > prices[i]) { minPrice = prices[i] } } } return maxProfit } fun minFlips(a: Int, b: Int, c: Int): Int { var flips = 0 var bitA = 0 var bitB = 0 var bitC = 0 for (i in 0..31) { bitA = (a shr i) and 1 bitB = (b shr i) and 1 bitC = (c shr i) and 1 if (bitC == 0) { flips += bitA + bitB } else { flips += if (bitA + bitB == 0) 1 else 0 } } return flips } fun maximum(a: Int, b: Int): Int { val sum = a.toLong() + b.toLong() val diff = a.toLong() - b.toLong() val absDiff = (diff xor (diff shr 63)) - (diff shr 63) return ((sum + absDiff) / 2).toInt() } fun findComplement(num: Int): Int {//476 var tmp = 1L while (num >= tmp) { tmp = tmp shl 1 } return (tmp - 1 - num).toInt() } fun numberOfSteps(num: Int): Int { var steps = 0 var k = num while (k != 0) { if (k and 1 == 1) { k-- } else { k /= 2 } steps++ } return steps } var d = 0 fun diameterOfBinaryTree(root: TreeNode?): Int { d = 1 depth(root) return d - 1 } private fun depth(root: TreeNode?): Int { if (root == null) { return 0 } else { val left = depth(root.left) val right = depth(root.right) d = Math.max(d, left + right + 1) return Math.max(left, right) + 1 } } fun isBalanced2(root: TreeNode?): Boolean {//110 if (root == null) { return true } else if (root.left == null && root.right == null) { return true } else { val left = height(root.left) val right = height(root.right) if (Math.abs(left - right) <= 1) { return isBalanced2(root.left) && isBalanced2(root.right) } else { return false } } } fun increasingBST(root: TreeNode?): TreeNode? { if (root == null || root.left == null && root.right == null) { return root } val list = ArrayList<TreeNode>() val stack = Stack<TreeNode>() var p = root while (p != null || stack.isNotEmpty()) { if (p != null) { stack.push(p) p = p.left } else { p = stack.pop() list.add(p) p = p.right } } list.forEach { print(it.`val`) } return root } fun pivotIndex(nums: IntArray): Int { var leftSum = 0L var rightSum = nums.sum().toLong() for (i in 0..nums.lastIndex) { rightSum -= nums[i] if (leftSum == rightSum) { return i } leftSum += nums[i] } return -1 } fun canThreePartsEqualSum(A: IntArray): Boolean { if (A.size > 2) { val sum = A.sum().toLong() if (sum % 3 != 0L) { return false } var left = -1 var mid = -1 var target = sum / 3 var subSum = 0L for (i in A.indices) { subSum += A[i] if (subSum == target) { left = i break } } if (left > A.size - 3) { return false } subSum = 0 for (i in left + 1..A.lastIndex) { subSum += A[i] if (subSum == target) { mid = i break } } if (mid > A.size - 2) { return false } subSum = 0L if (left < mid && mid < A.lastIndex) { subSum = A.drop(mid + 1).sum().toLong() if (subSum == target) { return true } } } return false } fun dayOfTheWeek(day: Int, month: Int, year: Int): String { //1185, Zeller's Formula var myDay = day var myMonth = month var myYear = year if (month == 1) { myMonth = 13 myYear-- } if (month == 2) { myMonth = 14 myYear-- } val week = (myDay + myMonth * 2 + 3 * (myMonth + 1) / 5 + myYear + myYear / 4 - myYear / 100 + myYear / 400) % 7 return when (week) { 0 -> "Monday" 1 -> "Tuesday" 2 -> "Wednesday" 3 -> "Thursday" 4 -> "Friday" 5 -> "Saturday" else -> "Sunday" } } fun daysBetweenDates(date1: String, date2: String): Int {//1360 return Math.abs(daysOfDate(date1) - daysOfDate(date2)) } private fun daysOfDate(date: String): Int {//Zeller formula val arr = date.split("-") var day = arr[2].toInt() var month = arr[1].toInt() var year = arr[0].toInt() if (month <= 2) { month += 10 year-- } else { month -= 2 } return day + month * 30 + (3 * month - 1) / 5 + 365 * year + year / 4 - year / 100 + year / 400 } fun gcdOfStrings(str1: String, str2: String): String { val l1 = str1.length val l2 = str2.length val gcd = if (l1 >= l2) { gcd(l1, l2) } else { gcd(l2, l1) } val gcdStr = str1.substring(0, gcd) for (i in 1 until str1.length / gcd) { if (gcdStr != str1.substring(i * gcd, (i + 1) * gcd)) { return "" } } for (i in 0 until str2.length / gcd) { if (gcdStr != str2.substring(i * gcd, (i + 1) * gcd)) { return "" } } return gcdStr } private fun gcd(m: Int, n: Int): Int { var j = m var k = n var rem = 0 while (k != 0) { rem = j % k j = k k = rem } return j } fun rotatedDigits(N: Int): Int { var count = 0 for (i in 2..N) { if (isGoodNumber(i)) { count++ } } return count } private fun isGoodNumber(num: Int): Boolean { var n = num var rem = 0 var isDifferentAfterRotated = false while (n != 0) { rem = n % 10 if (isValidDigit(rem)) { if (isDifferentAfterRotated(rem)) { isDifferentAfterRotated = true } } else { return false } n /= 10 } return isDifferentAfterRotated } private fun isValidDigit(i: Int): Boolean = i == 1 || i == 0 || i == 8 || i == 2 || i == 5 || i == 6 || i == 9 private fun isDifferentAfterRotated(i: Int): Boolean = i == 2 || i == 5 || i == 6 || i == 9 fun primePalindrome(N: Int): Int { var n = N while (!isNumPalindrome(n) || !isPrime(n)) { n++ } return -1 } private fun isNumPalindrome(n: Int): Boolean { if (n < 10) { return true } else { val numStr = n.toString() val count = numStr.length / 2 for (i in 0..count) { if (numStr[i] != numStr[numStr.lastIndex - i]) { return false } } return true } } private fun isPrime(n: Int): Boolean { if (n < 6) { return n != 4 } else { val sqrt = Math.sqrt(n.toDouble()).toInt() for (i in 2..sqrt) { if (n % i == 0) { return false } } return true } } fun majorityElement2(nums: IntArray): Int { val map = HashMap<Int, Int>() nums.forEach { map.compute(it) { _, v -> if (v == null) 1 else v + 1 } } var key = 0 var maxCount = 0 map.forEach { t, u -> if (u > maxCount) { maxCount = u key = t } } if (maxCount > nums.size / 2) { return key } else { return 0 } } fun isMajorityElement(nums: IntArray, target: Int): Boolean { val count = nums.filter { it > target }.count() return count > nums.size / 2 } fun sumZero(n: Int): IntArray { val nums = IntArray(n) for (i in 0 until n / 2) { nums[i * 2] = i + 1 nums[i * 2 + 1] = -i - 1 } if (n % 2 != 0) { nums[n - 1] = 0 } return nums } fun decompressRLElist(nums: IntArray): IntArray { var newSize = nums.filterIndexed { index, i -> index and 1 == 0 }.sum() val res = IntArray(newSize) var index = 0 var count = 0 for (i in 0 until nums.size / 2) { count = nums[i * 2] while (count-- > 0) { res[index++] = nums[i * 2 + 1] } } return res } fun numSmallerByFrequency(queries: Array<String>, words: Array<String>): IntArray { val res = IntArray(queries.size) val wordsFrequency = IntArray(words.size) words.forEachIndexed { index, s -> wordsFrequency[index] = getFrequency(s) } queries.forEachIndexed { index, s -> val freq = getFrequency(s) res[index] = wordsFrequency.filter { it > freq }.count() } return res } private fun getFrequency(word: String): Int { var frequency = 0 var ch = 'z' word.forEach { if (it == ch) { frequency++ } else if (ch > it) { ch = it frequency = 1 } } println(frequency) return frequency } fun lengthOfLIS(nums: IntArray): Int { if (nums.isEmpty()) { return 0 } val dp = IntArray(nums.size) dp[0] = 1 var maxAns = 1 for (i in 1..nums.lastIndex) { var maxVal = 0 for (j in 0..i) { if (nums[i] > nums[j]) { maxVal = Math.max(maxVal, dp[j]) } } dp[i] = maxVal + 1 maxAns = Math.max(maxAns, dp[i]) } return maxAns } fun luckyNumbers(matrix: Array<IntArray>): List<Int> {//1380 val res = ArrayList<Int>() outer@ for (i in matrix.indices) { var minVal = Int.MAX_VALUE var minIndex = -1 for (j in matrix[i].indices) { if (matrix[i][j] < minVal) { minVal = matrix[i][j] minIndex = j } } for (k in matrix.indices) { if (matrix[k][minIndex] > minVal) { continue@outer } } res.add(matrix[i][minIndex]) } return res } fun isPalindrome(head: ListNode?): Boolean { if (head?.next == null) { return true } var p = head var count = 0 while (p != null) { count++ p = p.next } var half = count / 2 val list = IntArray(half) p = head while (half-- > 0) { list[half] = p?.`val` ?: 0 p = p?.next } if (count and 1 == 1) { p = p?.next } half = 0 while (half < count / 2) { if (p?.`val` != list[half]) { return false } half++ p = p.next } return true } fun compressString(S: String): String { val ans = StringBuilder() var ch = ' ' var count = 0 for (i in S.indices) { if (ch == S[i]) { count++ } else { if (ch == ' ') { ch = S[i] count++ } else { ans.append(ch) ans.append(count) ch = S[i] count = 1 } } if (ans.length >= S.length) { return S } } if (ch != ' ') { ans.append(ch) ans.append(count) } if (ans.length >= S.length) { return S } return ans.toString() } fun validPalindrome(s: String): Boolean { var start = 0 var end = s.lastIndex while (start < end) { if (s[start] == s[end]) { start++ end-- } else { return validPalindrome(s, start + 1, end) || validPalindrome(s, start, end - 1) } } return true } fun validPalindrome(str: String, start: Int, end: Int): Boolean { var s = start var e = end while (s < e) { if (str[s] == str[e]) { s++ e-- } else { return false } } return true } fun isPalindrome(s: String): Boolean {//125 var start = 0 var end = s.lastIndex while (start < end) { while (!s[start].isLetterOrDigit()) { start++ if (start > end) { return true } } while (!s[end].isLetterOrDigit()) { end-- if (start > end) { return true } } if (!s[start++].equals(s[end--], true)) { return false } } return true } fun countCharacters(words: Array<String>, chars: String): Int { val charCounts = IntArray(26) chars.forEach { charCounts[it - 'a']++ } var sum = 0 val wordCounts = IntArray(26) words.forEach { wordCounts.fill(0) inflate(wordCounts, it) if (contains(wordCounts, charCounts)) { sum += it.length } } return sum } private fun inflate(arr: IntArray, word: String) { word?.forEach { arr[it - 'a']++ } } private fun contains(arr: IntArray, chars: IntArray): Boolean { for (i in arr.indices) { if (arr[i] > chars[i]) { return false } } return true } fun shortestDistance(words: Array<String>, word1: String, word2: String): Int { val indices1 = findIndex(words, word1) val indices2 = findIndex(words, word2) return minDistance(indices1, indices2) } private fun findIndex(words: Array<String>, word: String): List<Int> { val list = ArrayList<Int>() words.forEachIndexed { index, s -> if (word == s) { list.add(index) } } return list } private fun minDistance(indices1: List<Int>, indices2: List<Int>): Int { var minDistance = Int.MAX_VALUE for (i in indices1.indices) { for (j in indices2.indices) { if (Math.abs(indices1[i] - indices2[j]) < minDistance) { minDistance = Math.abs(indices1[i] - indices2[j]) if (minDistance == 1) { return minDistance } } } } return minDistance } private fun minDistance2(indices1: List<Int>, indices2: List<Int>): Int { var minDistance = Int.MAX_VALUE for (i in indices1.indices) { for (j in indices2.indices) { if (indices1[i] == indices2[j]) { continue } if (Math.abs(indices1[i] - indices2[j]) < minDistance) { minDistance = Math.abs(indices1[i] - indices2[j]) if (minDistance == 1) { return minDistance } } } } return minDistance } fun maxSlidingWindow(nums: IntArray, k: Int): IntArray { if (nums.isEmpty() || k <= 0 || k > nums.size) { return IntArray(0) } val ans = IntArray(nums.size - k + 1) var pre = 0 var j = 0 var maxVal = Int.MIN_VALUE val window = ArrayList<Int>(k) for (i in 0 until k - 1) { if (nums[i] > maxVal) { maxVal = nums[i] } window.add(nums[i]) } for (i in k - 1 until nums.size) { if (nums[i] > maxVal) { maxVal = nums[i] } window.add(nums[i]) ans[j++] = maxVal pre = nums[i - k + 1] window.removeAt(window.indexOf(pre)) if (pre == maxVal) { maxVal = window.maxOfOrNull { it } ?: Int.MIN_VALUE } } return ans } } class Trie() { /** Initialize your data structure here. */ val root = TrieNode() /** Inserts a word into the trie. */ fun insert(word: String) { word?.apply { var node = root forEach { ch: Char -> if (!node.children.containsKey(ch)) { node.children[ch] = TrieNode() } node = node.children[ch]!! } node.wordEnd = true } } /** Returns if the word is in the trie. */ fun search(word: String): Boolean { word?.apply { var node = root forEach { ch -> if (!node.children.containsKey(ch)) { return false } node = node.children[ch]!! } return node.wordEnd } return false } /** Returns if there is any word in the trie that starts with the given prefix. */ fun startsWith(prefix: String): Boolean { prefix?.apply { var node = root forEach { ch -> if (!node.children.containsKey(ch)) { return false } node = node.children[ch]!! } return true } return false } class TrieNode { val children = HashMap<Char, TrieNode>() var wordEnd = false } }
0
Kotlin
0
1
7cf372d9acb3274003bb782c51d608e5db6fa743
57,740
Algorithms
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/PathCrossing.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode /** * 1496. Path Crossing * @see <a href="https://leetcode.com/problems/path-crossing">Source</a> */ fun interface PathCrossing { operator fun invoke(path: String): Boolean } class PathCrossingHashSet : PathCrossing { override fun invoke(path: String): Boolean { val moves: MutableMap<Char, Pair<Int, Int>> = HashMap() moves['N'] = Pair(0, 1) moves['S'] = Pair(0, -1) moves['W'] = Pair(-1, 0) moves['E'] = Pair(1, 0) val visited: MutableSet<Pair<Int, Int>?> = HashSet() visited.add(Pair(0, 0)) var x = 0 var y = 0 for (c in path.toCharArray()) { val curr = moves.getOrDefault(c, Pair(0, 0)) val dx: Int = curr.first val dy: Int = curr.second x += dx y += dy val pair = Pair(x, y) if (visited.contains(pair)) { return true } visited.add(pair) } return false } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,645
kotlab
Apache License 2.0
hackerrank/lilys-homework/Solution.kts
shengmin
5,972,157
false
null
import java.io.* import java.math.* import java.security.* import java.text.* import java.util.* import java.util.concurrent.* import java.util.function.* import java.util.regex.* import java.util.stream.* import kotlin.collections.* import kotlin.comparisons.* import kotlin.io.* import kotlin.jvm.* import kotlin.jvm.functions.* import kotlin.jvm.internal.* import kotlin.ranges.* import kotlin.sequences.* import kotlin.text.* // Complete the lilysHomework function below. fun lilysHomework(originalArray: Array<Int>): Int { // to minimize the sum of adjacent elements, the array needs to be sorted val swapCount1 = countSwaps(originalArray, originalArray.sortedArray()) val swapCount2 = countSwaps(originalArray, originalArray.sortedArrayDescending()) return minOf( swapCount1, swapCount2 ) } fun countSwaps(arr: Array<Int>, sortedArray: Array<Int>): Int { val originalArray = arr.toIntArray() val indices = mutableMapOf<Int, Int>() for (i in 0 until originalArray.size) { val number = originalArray[i] if (number != sortedArray[i]) { indices[number] = i } } var count = 0 for (i in 0 until originalArray.size) { val number = originalArray[i] val expectedNumber = sortedArray[i] if (number == expectedNumber) { // in the right place, no need to swap continue } // swap the expected number here count++ val swapIndex = indices[expectedNumber]!! indices[number] = swapIndex originalArray[i] = expectedNumber originalArray[swapIndex] = number } return count } fun main(args: Array<String>) { val scan = Scanner(System.`in`) val n = scan.nextLine().trim().toInt() val arr = scan.nextLine().split(" ").map { it.trim().toInt() }.toTypedArray() val result = lilysHomework(arr) println(result) } main(arrayOf())
0
Java
18
20
08e65546527436f4bd2a2014350b2f97ac1367e7
1,839
coding-problem
MIT License
src/main/kotlin/adventofcode/y2021/Day13.kt
Tasaio
433,879,637
false
{"Kotlin": 117806}
import adventofcode.* import java.math.BigInteger fun main() { val testInput = """ 6,10 0,14 9,10 0,3 10,4 4,11 6,0 6,12 4,1 0,13 10,12 3,4 3,0 8,4 1,10 2,14 8,10 9,0 fold along y=7 fold along x=5 """.trimIndent() runDay( day = Day13::class, testInput = testInput, testAnswer1 = 17, testAnswer2 = null ) } open class Day13(staticInput: String? = null) : Y2021Day(13, staticInput) { private val input = fetchInput() val dots = input.filter { it.contains(",") }.map { it.toPair().toCoordinate() } val folds = input.filter { it.startsWith("fold") } var grid: Grid init { val maxXY = dots.getMinMaxValues() grid = Grid(maxXY.maxX + BigInteger.ONE, maxXY.maxY + BigInteger.ONE, '.') dots.forEach { grid.get(it)!!.content = '#' } } override fun reset() { super.reset() } override fun part1(): Number? { fold(folds[0]) return grid.count { it eq '#'} } fun fold(line: String) { if (line.contains('y')) { val num = line.parseNumbersToSingleInt() val top = grid.partOfGrid(toY = num - 1) val bottom = grid.partOfGrid(fromY = num + 1) for (y in 0 until bottom.sizeY()) { for (x in 0 until bottom.sizeX()) { if (bottom.get(x, y).content == '#') { top.get(x, top.sizeY() - y - 1).content = '#' } } } grid = top } else if (line.contains('x')) { val num = line.parseNumbersToSingleInt() val left = grid.partOfGrid(toX = num - 1) val right = grid.partOfGrid(fromX = num + 1) for (y in 0 until right.sizeY()) { for (x in 0 until right.sizeX()) { if (right.get(x, y).content == '#') { left.get(left.sizeX() - x - 1, y).content = '#' } } } grid = left } } override fun part2(): Number? { for (fold in folds.subList(1, folds.size)) { fold(fold) } grid.printReadable() return null } }
0
Kotlin
0
0
cc72684e862a782fad78b8ef0d1929b21300ced8
2,414
adventofcode2021
The Unlicense
src/main/kotlin/dev/shtanko/algorithms/leetcode/UniquePaths3.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 /** * 980. Unique Paths III * @see <a href="https://leetcode.com/problems/unique-paths-iii/">Source</a> */ fun interface UniquePaths3 { operator fun invoke(grid: Array<IntArray>): Int } class UniquePaths3Backtracking : UniquePaths3 { private var res = 0 private var empty: Int = 1 private var sx: Int = 0 private var sy: Int = 0 override operator fun invoke(grid: Array<IntArray>): Int { val m: Int = grid.size val n: Int = grid[0].size for (i in 0 until m) { for (j in 0 until n) { if (grid[i][j] == 0) { empty++ } else if (grid[i][j] == 1) { sx = i sy = j } } } dfs(grid, sx, sy) return res } fun dfs(grid: Array<IntArray>, x: Int, y: Int) { if (x < 0 || x >= grid.size || y < 0 || y >= grid[0].size || grid[x][y] < 0) return if (grid[x][y] == 2) { if (empty == 0) res++ return } grid[x][y] = -2 empty-- dfs(grid, x + 1, y) dfs(grid, x - 1, y) dfs(grid, x, y + 1) dfs(grid, x, y - 1) grid[x][y] = 0 empty++ } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,888
kotlab
Apache License 2.0
src/main/kotlin/me/grison/aoc/y2020/Day12.kt
agrison
315,292,447
false
{"Kotlin": 267552}
package me.grison.aoc.y2020 import me.grison.aoc.* import me.grison.aoc.y2020.Day12.Direction.E class Day12 : Day(12, 2020) { override fun title() = "Rain Risk" override fun partOne(): Int { var (pos, dir) = p(p(0, 0), E) inputList.forEach { l -> val (cmd, amount) = p(l.slice(0..0), l.substring(1).toInt()) when (cmd) { "L" -> dir = Direction.values()[(dir.ordinal + 1 * (amount / 90)) % 4] "R" -> dir = Direction.values()[(dir.ordinal + 3 * (amount / 90)) % 4] "F" -> pos = move(pos, dir, amount) // N, E, S, W else -> pos = move(pos, cmd.direction(), amount) } } return pos.manhattan() } override fun partTwo(): Int { var (pos, waypoint) = p(p(0, 0), p(10, 1)) inputList.forEach { l -> val (cmd, amount) = p(l.slice(0..0), l.substring(1).toInt()) when (cmd) { "L" -> repeat(amount / 90) { waypoint = p(-waypoint.second, waypoint.first) } "R" -> repeat(amount / 90) { waypoint = p(waypoint.second, -waypoint.first) } "F" -> pos += p(amount * waypoint.first, amount * waypoint.second) // N, E, S, W else -> waypoint = move(waypoint, cmd.direction(), amount) } } return pos.manhattan() } enum class Direction(val dx: Int, val dy: Int) { N(0, 1), E(1, 0), S(0, -1), W(-1, 0) } private fun String.direction() = Direction.valueOf(this) private fun move(pos: Pair<Int, Int>, direction: Direction, amount: Int) = pos + p(direction.dx * amount, direction.dy * amount) }
0
Kotlin
3
18
ea6899817458f7ee76d4ba24d36d33f8b58ce9e8
1,713
advent-of-code
Creative Commons Zero v1.0 Universal
6_kyu/Playing_with_digits.kt
UlrichBerntien
439,630,417
false
{"Go": 293606, "Rust": 191729, "Python": 184557, "Lua": 137612, "Assembly": 89144, "C": 76738, "Julia": 35473, "Kotlin": 33204, "R": 27633, "C#": 20860, "Shell": 14326, "Forth": 3750, "PLpgSQL": 2117, "C++": 122}
/** Power function for integers */ fun Int.pow(exp: Int): Long { return this.toBigInteger().pow(exp).toLong() } /** * Sum decimal digits with power. * * @param x Calculate the digit powerd sum of this int. * @param p The exponent of the most significant digit. * @return sum of all decimal digits with power p,p+1,.. */ fun digitSum(x: Int, p: Int): Long { var digits = IntArray(32) assert( 10.pow(digits.size) > Int.MAX_VALUE.toLong() ) var nDigits = 0 var rest = x while (rest > 0) { digits[nDigits] = rest % 10 rest /= 10 nDigits++ } var sum: Long = 0 for (i in 0..nDigits - 1) { sum += digits[i].pow(p + nDigits - i - 1) } return sum } /** * Calculates funny integer. * * @param n Integer to analyse. * @param p exponent of the most significant digit in the sum. * @return k with k*n = powered decimal digit sum of n. */ fun digPow(n: Int, p: Int): Int { val s = digitSum(n, p) return if (s % n == 0L) (s / n).toInt() else -1 }
0
Go
0
0
034d7f2bdcebc503b02877f2241e4dd143188b43
1,030
Codewars-Katas
MIT License
src/main/kotlin/de/startat/aoc2023/Day3.kt
Arondc
727,396,875
false
{"Kotlin": 194620}
package de.startat.aoc2023 data class Number(val value: Int, val lineNumber : Int, val indices : IntRange) data class Symbol(val value: String,val lineNumber: Int, val index : Int) data class Schematic(val numbers : List<Number>, val symbols: List<Symbol>) fun Symbol.isAdjacentTo(number: Number) : Boolean{ val lineRange = number.lineNumber-1 .. number.lineNumber+1 val indexRange = number.indices.first-1 .. number.indices.last+1 return this.lineNumber in lineRange && this.index in indexRange } fun Schematic.sumOfNumbers() : Int { return numbers.fold(0){acc, number -> acc + number.value } } fun Schematic.gears() : List<Pair<Number,Number>> { return symbols.filter { s -> s.value == "*" }.mapNotNull { possibleGear -> val adjacentNumbers = numbers.filter { n -> possibleGear.isAdjacentTo(n) }.toList() return@mapNotNull if (adjacentNumbers.size == 2) { Pair(adjacentNumbers[0], adjacentNumbers[1]) } else null }.toList() } class Day3 { private val numberRegex = Regex("\\d+") private val symbolRegex = Regex("[^\\d.\\n]") fun star1() { val schematic: Schematic = readSchematic(day3Input) println("Sum of schematic numbers = ${schematic.sumOfNumbers()}") } fun star2() { val schematic: Schematic = readSchematic(day3Input) val gearRatio = schematic.gears().fold(0) { acc, (first, second) -> acc + first.value * second.value } println("Gear ratio = $gearRatio") } private fun readSchematic(schematicString : String) : Schematic { val allNumbers: MutableList<Number> = mutableListOf() val allSymbols: MutableList<Symbol> = mutableListOf() for ((idx, line) in schematicString.lines().withIndex()) { println(line) val numbersInLine = numberRegex.findAll(line).map { match -> Number(match.value.toInt(), idx, match.range) }.toList() println("\t$numbersInLine") allNumbers += numbersInLine val symbolsInLine = symbolRegex.findAll(line).map { match -> Symbol(match.value, idx, match.range.first) }.toList() println("\t$symbolsInLine") allSymbols += symbolsInLine } val validNumbers = allNumbers.filter { n -> allSymbols.any{s -> s.isAdjacentTo(n)}}.toList() return Schematic(validNumbers, allSymbols) } } val day3testInput = """467..114.. ...*...... ..35..633. ......#... 617*...... .....+.58. ..592..... ......755. ...$.*.... .664.598..""" val day3Input = """.......358..........31.....339.....669.............598......328.....575......................447..650..............964...........692........ ...............415..*.........@......*...627*...................945*.............144/.506............................*......514...*...150... .........182..+.....873.756.......737........784..568....667..............258........./.........741...........707*....84........520......... ..579...@.........$........*..........258.................*.........274..*.....739.......157./.....*580...........893.....696*........889... .....*.........875.........173.........*..................109...896*......959...*........=...677...........&636.........................$... ......961..$............-...............907...569....#...........................756.....................................681................ ...........478...616.....30.....221*...............552.../33...258*343.....488........*682...526..*.........422...........&..........764.... ................+..........................................................*................*.....7...550..........=.........878............ ...171..275............#.....................401....50.$.................43...............123.............../949..135..331.....@.495........ ........*...48@.662.100...............590...*........#.566.....................15..../426.............774...............+...........*....... ...944.28.........*.....................*....307...........410.361....55..................24.447.*......*....787*...266....361.......161.... ....*...........405.&...=785...146......654.......281.............*.....+...................*....760..80..17.....84....*..+................. .....830...140......745.........%..$..........972.......406*864..762..............695.327.................*...........512................... ............*...............#......414...........*..960...............1..............*.................374.....264.............833....336... .......-.252.......10....518..................777...=...811..103.454..*....................774*433.........951*....826........@....=...*.... .....44..............*................-....................@..$......957...............216..........=..................614........521..232.. .........=232......802...+779.....759..307....................................%941.......*........512.............865.....*................. ...................................*.......162...662....816.681.....21*................290.........................*......364..........=.... .................258....195.........1..535......*.......*.....*........261............................650.......152.................514..... ..425...411@...../.........@...........*.....788.........186...91.279............-.....................*............268.......639.......864. ....................................=.933........../.................%...%........73........%203....187..362...861.....*389.....*.......*... ...254....847............@........135......6.......529..........202......96...........840.........@........*...*.../.........998.......989.. .........*.....288......650............349*.......................%.609...................526.....655.....854....425..............531*...... ..../....848....&..............505...........................594..........434.................@.......$68............767..............732... .410...............585...............185........................*...91........773..579........454............757.....*....568..+742......... ..............................*70.......*......478............769....&.182.......%.*..................568......-.570.861....*............... ..............*993.48......893........835....*..*......*.................*..........798..473.........../....................965...691....... ...........306.......*............531.......938.200.335.432...343.....360......836......-...........*..........951.691..............*....... ...341*360............958............*.........................#.........../.....*.../........728..585.........*.............902=..696...... .............190...................808..451........+..................272...59.641...822.........*..........289...36...................509.. ..464*10.604.+....241.102%..............*...633.450......................+........................797............*.......575..........*..... ...........-............................488..........402.....936.847................+.......434.......................&.....&....844...478.. ......147..............826...297................257...*...........*.....$.....932...492..81...%....829..........560...661.........*......... .........*....379.......*....*...884..700.......*.....646..........914..659...............*....................=..........513/..621..790.... .369....472..*.......843....734....#.+....%...738........................................989............501.......817.375...............@... ..............727.........................131.....767..........=......665...685..............747..727.......868..*.............478#......... ........247.............-...........649.............*..*82..507...............*..................................504........................ .........*...........909...............*.....707..922..............701...213.833.866$.630...&..606+....................102.183@..*281.225... ...465.108...............772.....915.109..96.%...................../.....*.............*..685........155....811*...220.*...............*.... .................106.....=.................&........*........*488.........233.......590........$551.....*..........+...287.#874..%....956... ....................*513.........&...............829.487................................350..-........338.......55................464....... ....&............@............695......227................$.793.............802.....294...*...822..........960....*....295..946............. ....587...........859...204.......246*....*644.........925.........167.210..../..........129.............%....*...102.....*..*..........832. .......................*..............558.......404.......................%..........................817..870.791......120..483..406...$.... ....797%..68....929-.87....411............*........*.............458*143....721.-....706.......694....*.........................+........... ...........*..................*........369..........899..79................*....417.....*930..*........78.....@174.........276.............. .313........394...750..........773.........................................916......37+.......384...........-......355.203....*.....180..... ....@...902...........829.......................................*823........................*.............408.......*......960......*....... ........*......%........#...........@871..........756.........22.........956..............56.622.=461.823..........749...........297..557... ......877.......863..............................*.........................=.968..............................12.......946%..........%...... ..............................123.39.551...12...700..507*....................*........320.........*...54.................................... .............583........424..................$...........571......#.......499.......-.............803......92.&......942..........782....... ....726.....$...............=....688.580...*...........#..........905............446....397...................629...*............*.......... .....*..758.......831........760..-....*.427......473...729............298...618........-.........562*865.........553....267...12........... .................$.....971...........472.....61....#..................*.........@..714.......712............173.............*......-780..... .....*948..........&.....*..750.311..................*425.193....@336..882........*..........*....913.........*...........369............... ..942..............209.791....-....%.626.787..812.954......................725/.806.%...............#.......447....679..........706...11.... ...............922......................*................217@......962..............9.104...806...................%.....278*.....*.......... .........382......*........./.......346.......346....448............*....................$...................*................820..454%..... .315......./....418.........748................%...............577..655.......*254..266.....383*...$......316.243.........*................. .....................363................709.....................=..........714..........224......479...................817.428....../....... ......................*................*........318................237....................*...................497.152............457........ ...........911........756..589..........562......=..253........8*................498...392.......394.768...@................................ ...............$..751..........856...................*...56......202...201.........+................*.......525.......430................... .193........953...*.....456..@................310*........*............../.58@.........*..............863..........$....%..675..+117...447.. .......940.................*.905.889......542.....723......591....*956.........743.$..156.........791*......923..84......../..........$..... .........&.....538&......643......*..=......*..................659............@....66.....681............................................... .................................127.585.238.......-866....654......................................393................80..19..979.......... .........................300.................102........................465*..............705.332......................%.........*.....*142. ......+....#.....*...500..%..336.419........*....+116.719...........237.....81...461*931.....*.........613.#426...................434....... ......489.420.459......*......*....*.....277.............%.........=...............................*..............746....512............%848 .......................804....445.197.........658.*342....................+461.630......%...930@....804.504........*.............+..299..... ...........270.....257........................./.........283....................*.......357.......................702.....644.587......*.... ...460%...=...........*.......406.........162..............*...259.......*.......121.............360$.#...76..228.....847..*............666. .....................612..178*.............*...527*872.762.267........307.606.........#........$......224....&....13*....-.455.......&...... ..........152.......................919..485............/.........70.................623....968......................810............281.230. ......693.*...520............$......*...........*909.....................586.........................794......229.........88...385.......... ..363*....636..*......619.....238....45..............982...........*145.....*803......-.......426.......#.....+.......213*...#....*......... ...............536.....+........................&.......*.......708.....170......360..220......*../.......16................796....283..564. .652....&...........$.....*....................89...944.894................*....-............975.27...409*...978......./445................. ...*.538...........822.274.491.....-..........................572.........329.........*468......................&.......................213. .47......568.......................706.....232....74..490............&965..........685................125...........................824*.... ........*....725...........#548............=......*.........................................77*391...*........253...............767......... .......769...&......................183........687..921......913$...@.....162...724.................220.........*...880.834.........404..... ...+.................466...%411...../...............*...............894....*.......*.............*............196.....*................*.... .90.......423..../......*.......1.........-.......360.....233...............2........=......@....422.....334.........878......322......573.. ....649..........475....450....%......-....249.................905.............760..879......829..........-....................*............ ......*......290.....................680............/............/.244&.........................................9.596.326.........359....... ...............*........200.....723................826....773...........576..790..=..............642.................*....617....*.....649.. .....#979....776..562.......@.....*........................#........363.....&....915..704....401....*...32*681.%261.......&.......351....... 896*.................*896...493.88....*.........622.............925*.................*....17*.......265..............893.................... ....778.%222.......................873.872..........635@...852..........559........456..%......*128........179.......*............336*...... .................985.......................77...482.........-.......502*......404......206...41......631..*.........761...............782... .....194...........&...............514*130..=..*.............................*...........................168.............../..46+........... .............207...............................195.....619..$..........544..191.......419*842....64......................206..........816... ..............................670..84*78.................*.966......%.....*.....................*........=............................*..... .564.........185-........250....*........464...762.....412.......302.....27..764.653/.738*596..........563....741.........13.148.......928.. ....*.............%..565....%.60....+158..*...$............*503...................................824.................284.......*.931-...... ....710...763...272..*...................851..../....................456.......121....603................3..445...............382.......837. ....................956..970........-..........377......381.......56.......926........../......135......*....../.........315........172.&... ........201.............+...........261.517..................606........../.....347......................655.......717........468..*........ ...746...&...332...............681...............703...........*.....=............*...........................................*....824...... ......-.........*478.............*.....595.245....*...918.....875...875.........965...........676...745*...858...479.......132.............. ..354........*.................776.-...*...*...820...../..%..............291........../........*........59.*........*....................485 ...&......668.956......738.........921.312.803.....770...613....78*522..&...........665......692............253......863............537..... ...................498......258...................................................................426.........................#............. .....108..........&.....357.-......794..594#............#............255........$.........664.525./....885...$..............353..823........ ........+...590..........*........*...........111.......420..374..............144...........*...*...80*.....164...928...427......&.......... ...+...........*..289.185......$...659.772/....*.............*........361..........504.........436...................*......@............... ...14....*...296...*........453..............753.368.733...167..675....*....................................22........502..443.............. .......413........................200=..616.......+...*...........#.....143..768..........404.............@...=...102..............378...... ...538..........579.......................=...........311.267...................*.....445...*.....%138..158............#...........*....323. ......$............/.................586%.........825.....*....................318......@...260.................618..229...865....353...*... .............834.......68*981................606..*.....432............870...............................749....*...........#.........215... ......886....*...325...................18.25*.....977...................../.......385.........$.......95*......182./........................ ............773........................*................165...+....+816........*...*...........391..................439............@........ ........................682..........249...................*.435............400...261..119.....................................921..630..... .......-.......92*744....*....................115.......780........205....................*...347.152......950..592&.152....@.....*......... .....789.949..............530.248.149.............................*....*957............957.....&..*.......#..........#.....572.............. ...........*.601.766..112.......*......113..@.....529...736.+...656.837........320...............518.120.........125..............900....... 83......434.....*.....*.../...224.....*....235..............498............175...*.930.......................+......*................*880... ...*296...............118.328........405.............../801................*...804....*.......................590...770.........276......... 297..............726.............................966............*997......165..........25.983............669.............&..992*.......966.. ...........92....*........%.........108.............@.475....769..................897......@.........792................123.......122....... ...........*...&..579......811..708...&.................*........................*....767.......386...........558............708.....=...... ........230..161...............*................#....177.........940...903./...706.......*785..=.....93..381..%.................*........... ...621.............652..886...157........$....204............418....*....%..62......422.............*.....=........555.537.............+479. .....%............*.....*.............499............96.........*....656..............*...751..293...759.....174..........%..265..32%....... ...............610....105.416.........................%........242.........*.......746.......*....=...........*..259@....................... ............#................*591........./.-.......................653.103..62=.............585.............567...........586...+....216... ..840/....612.......588.................676..202...................&................@..............................301............632..*.... ......................*.........=392.............667..%..........-...............457...134*....................165*.....................728. .339&.*74.........402.581............518&.......*....823.....874..102..678.74..............219....114..................836..915..245.-...... ..........38.....*........612...628..............90......513...*............*...........59......+..../....799..268....*.....*.........370... ..........$........./........*.....*.......$...................8.......684=.577..209.........550.............#.....#...529.240.............. .236..............153......163........*.414...........................................549........432............919............81.....-337.. ....*.................604......-...631..........879........240.......97...............*.....315....&...720..........610...530............... .....856...214..236....*.....159.%......738.....-......826....&.272.*.......36.....465.........../.....*...587.......*....*......548..699... .............*........36..........743.=.../...............*......*..424.................580.#...897.448....*.......833...633.....*...*...... .............963......................542........734.....901...914..........843.............523..........818..................691.....833..."""
0
Kotlin
0
0
660d1a5733dd533aff822f0e10166282b8e4bed9
22,322
AOC2023
Creative Commons Zero v1.0 Universal
src/main/kotlin/dev/shtanko/algorithms/leetcode/LetterCasePermutation.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.util.LinkedList import java.util.Queue /** * 784. Letter Case Permutation * @see <a href="https://leetcode.com/problems/letter-case-permutation/">Source</a> */ fun interface LetterCasePermutation { operator fun invoke(s: String): List<String> } class LetterCasePermutationBFS : LetterCasePermutation { override operator fun invoke(s: String): List<String> { if (s.isBlank()) { return LinkedList() } val queue: Queue<String> = LinkedList() queue.offer(s) for (i in s.indices) { if (Character.isDigit(s[i])) continue val size: Int = queue.size for (j in 0 until size) { val cur: String = queue.poll() val chs = cur.toCharArray() chs[i] = chs[i].uppercaseChar() queue.offer(String(chs)) chs[i] = chs[i].lowercaseChar() queue.offer(String(chs)) } } return LinkedList(queue) } } class LetterCasePermutationDFS : LetterCasePermutation { override operator fun invoke(s: String): List<String> { if (s.isBlank()) { return LinkedList() } val res: MutableList<String> = LinkedList() helper(s.toCharArray(), res, 0) return res } fun helper(chs: CharArray, res: MutableList<String>, pos: Int) { if (pos == chs.size) { res.add(String(chs)) return } if (chs[pos] in '0'..'9') { helper(chs, res, pos + 1) return } chs[pos] = chs[pos].lowercaseChar() helper(chs, res, pos + 1) chs[pos] = chs[pos].uppercaseChar() helper(chs, res, pos + 1) } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,393
kotlab
Apache License 2.0
src/net/sheltem/aoc/y2022/Day18.kt
jtheegarten
572,901,679
false
{"Kotlin": 178521}
package net.sheltem.aoc.y2022 import net.sheltem.aoc.y2022.D3Direction.BACKWARD import net.sheltem.aoc.y2022.D3Direction.DOWN import net.sheltem.aoc.y2022.D3Direction.FORWARD import net.sheltem.aoc.y2022.D3Direction.LEFT import net.sheltem.aoc.y2022.D3Direction.RIGHT import net.sheltem.aoc.y2022.D3Direction.UP suspend fun main() { Day18().run() } class Day18 : Day<Long>(64, 58) { override suspend fun part1(input: List<String>): Long = input.toMatrix().countEmptyEdges() override suspend fun part2(input: List<String>): Long = input.toMatrix().countSurfaceEdges() } private fun List<String>.toMatrix() = map { Point(it.split(",").map(String::toInt)) }.toSet() private fun Set<Point>.countEmptyEdges(): Long = sumOf { it.neighbours().filter { neighbour -> neighbour !in this }.size }.toLong() private fun Set<Point>.countSurfaceEdges(): Long { val minx = minOf { it.x } - 1 val miny = minOf { it.y } - 1 val minz = minOf { it.z } - 1 val maxx = maxOf { it.x } + 1 val maxy = maxOf { it.y } + 1 val maxz = maxOf { it.z } + 1 val surface = mutableSetOf<Point>() val pointsToCheck = mutableListOf(Point(minx, miny, minz)) while (pointsToCheck.isNotEmpty()) { val pointToCheck = pointsToCheck.removeLast() if (pointToCheck in this) continue if (pointToCheck.x !in minx..maxx || pointToCheck.y !in miny..maxy || pointToCheck.z !in minz..maxz) continue if (surface.add(pointToCheck)) pointsToCheck.addAll(pointToCheck.neighbours()) } return sumOf { it.neighbours().filter { neighbour -> neighbour in surface }.size }.toLong() } private data class Point(var x: Int, var y: Int, var z: Int) { constructor(list: List<Int>) : this(list[0], list[1], list[2]) fun neighbours() = listOf(move(UP), move(DOWN), move(FORWARD), move(BACKWARD), move(RIGHT), move(LEFT)) fun move(dir: D3Direction) = Point(x + dir.x, y + dir.y, z + dir.z) } private enum class D3Direction(val x: Int, val y: Int, val z: Int) { UP(0, 0, 1), DOWN(0, 0, -1), FORWARD(0, 1, 0), BACKWARD(0, -1, 0), RIGHT(1, 0, 0), LEFT(-1, 0,0); }
0
Kotlin
0
0
ac280f156c284c23565fba5810483dd1cd8a931f
2,135
aoc
Apache License 2.0
advent-of-code-2022/src/main/kotlin/eu/janvdb/aoc2022/day18/Cubes.kt
janvdbergh
318,992,922
false
{"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335}
package eu.janvdb.aoc2022.day18 data class Cubes(val cubes: Set<Cube>) { val uniqueSides: Set<Side> by lazy { cubes .flatMap(Cube::getSides) .groupingBy { it } .eachCount() .filterValues { it == 1 } .keys } fun isLinkedTo(other: Cubes) = uniqueSides.intersect(other.uniqueSides).isNotEmpty() fun join(other: Cubes) = Cubes(cubes + other.cubes) fun findAirPockets(): Cubes { fun getAllCubesInRange() = cubes.rangeOver(Cube::x).flatMap { x -> cubes.rangeOver(Cube::y).flatMap { y -> cubes.rangeOver(Cube::z).map { z -> Cube(x, y, z) } } } fun combineLinkedCubes(unusedCubes: Collection<Cube>): List<Cubes> { val possibleAirPockets = unusedCubes.map(::setOf).map(::Cubes).toMutableList() val allPockets = mutableListOf<Cubes>() while (possibleAirPockets.isNotEmpty()) { val possibleAirPocket = possibleAirPockets.removeAt(0) val linked = mutableSetOf(possibleAirPocket) var linkedResult = possibleAirPocket possibleAirPockets.forEach { if (linkedResult.isLinkedTo(it)) { linked += it linkedResult = linkedResult.join(it) } } if (linked.size == 1) { allPockets += possibleAirPocket } else { possibleAirPockets -= linked possibleAirPockets += linkedResult } } return allPockets } val unusedCubes = getAllCubesInRange() - cubes val allPockets = combineLinkedCubes(unusedCubes) return allPockets .filter { it.uniqueSides.minus(uniqueSides).isEmpty() } .fold(Cubes(setOf()), Cubes::join) } } fun Collection<Cube>.toCubes(): Cubes = Cubes(toSet())
0
Java
0
0
78ce266dbc41d1821342edca484768167f261752
1,587
advent-of-code
Apache License 2.0
AoC2022/src/main/kotlin/xyz/danielstefani/Day3.kt
OpenSrcerer
572,873,135
false
{"Kotlin": 14185}
package xyz.danielstefani import java.util.stream.IntStream import kotlin.streams.asSequence val priorityMap = mutableMapOf<Int, Int>() fun main() { // Prep fillMapWithPriorities(97, 122, 1) fillMapWithPriorities(65, 90, 27) val splitRucksacks = object {}.javaClass .classLoader .getResource("Day3Input.in") ?.readText() ?.split("\n") ?.map { twoRucksacks -> listOf(twoRucksacks.substring(0, twoRucksacks.length / 2).toCharSet(), twoRucksacks.substring(twoRucksacks.length / 2).toCharSet()) } // Part 1 val splitRucksacksCommonItemsSum = splitRucksacks?.sumOf { priorityMap[it[0].intersect(it[1]).elementAt(0)]!! } // Part 2 val groupedBy3CommonItemsSum = splitRucksacks ?.map { twoRuckSacks -> twoRuckSacks[0].union(twoRuckSacks[1]) } ?.chunked(3) ?.sumOf { groupOfThree -> priorityMap[groupOfThree.reduce { acc, set -> acc.intersect(set) }.elementAt(0)]!! as Int } println(splitRucksacksCommonItemsSum) println(groupedBy3CommonItemsSum) } fun fillMapWithPriorities(lowerInclusive: Int, upperInclusive: Int, foldInit: Int) { IntStream.range(lowerInclusive, upperInclusive + 1) .asSequence() .fold(foldInit) { acc, code -> priorityMap[code] = acc acc + 1 } } fun String.toCharSet(): Set<Int> { return this.chars().collect({ mutableSetOf() }, { s, c -> s.add(c) }, { s1, s2 -> s1.addAll(s2) }) }
0
Kotlin
0
3
84b9b62e15c70a4a17f8b2379dc29f9daa9f4be3
1,535
aoc-2022
The Unlicense
src/main/kotlin/Puzzle10.kt
namyxc
317,466,668
false
null
import java.math.BigInteger object Puzzle10 { @JvmStatic fun main(args: Array<String>) { val input = Puzzle10::class.java.getResource("puzzle10.txt").readText() val count1and3diffInInput = count1and3diffInInput(input) println(count1and3diffInInput.first * count1and3diffInInput.second) val countAvailableConfigurations = countAvailableConfigurations(input) println(countAvailableConfigurations) } fun count1and3diffInInput(input: String): Pair<Int, Int> { val orderedNumbers = inputToSortedList(input) var diff1 = 0 var diff3 = 0 for ( i in 1 until orderedNumbers.count()){ val diff = orderedNumbers[i] - orderedNumbers[i-1] if (diff == 1) diff1 ++ if (diff == 3) diff3 ++ } return Pair(diff1, diff3) } private fun inputToSortedList(input: String): List<Int> { val numbers = input.split("\n").map(String::toInt) val numbersWithStartAndEnd = numbers + 0 + (numbers.maxOrNull()!! + 3) return numbersWithStartAndEnd.sorted() } fun countAvailableConfigurations(input: String): BigInteger { val orderedNumbers = inputToSortedList(input) val parentsMap = HashMap<Int, MutableList<Int>>() for ( i in orderedNumbers) { for (j in 1..3) { val parent = i - j if (orderedNumbers.contains(parent)) { if (!parentsMap.containsKey(i)) { parentsMap[i] = ArrayList() } parentsMap[i]!!.add(parent) } } } val parentCount = HashMap<Int, BigInteger>() for (num in orderedNumbers){ val parents = parentsMap[num] if (parents == null){ parentCount[num] = BigInteger.ONE }else{ parentCount[num] = parents.map{ parentCount[it]!!}.sumOf { it } } } val maxValue = orderedNumbers.maxOrNull()!! return parentCount[maxValue]!! } }
0
Kotlin
0
0
60fa6991ac204de6a756456406e1f87c3784f0af
2,102
adventOfCode2020
MIT License
hackerrank/the-grid-search/Solution.kts
shengmin
5,972,157
false
null
import java.util.*; import java.util.concurrent.* import java.util.function.* import java.util.regex.* import java.util.stream.* import kotlin.collections.* import kotlin.comparisons.* import kotlin.io.* import kotlin.jvm.* import kotlin.jvm.functions.* import kotlin.jvm.internal.* import kotlin.ranges.* import kotlin.sequences.* import kotlin.text.* class CompressedRow(val nodes: List<Node>) { data class Node(val start: Int, val end: Int, val value: Char) { val size: Int = end - start } companion object { fun fromString(rowString: String): CompressedRow { val nodes = mutableListOf<Node>() var lastChar = rowString[0] var lastStart = 0 for (i in 1 until rowString.length) { val char = rowString[i] if (char == lastChar) { continue } nodes.add(Node(lastStart, i, lastChar)) lastStart = i lastChar = char } nodes.add(Node(lastStart, rowString.length, lastChar)) return CompressedRow(nodes) } fun fromArray(grid: Array<String>): List<CompressedRow> { return grid.map { row -> fromString(row) } } } override fun toString(): String { return nodes.flatMap { node -> (1..node.end - node.start).map { node.value } }.joinToString("") } fun startingIndices(pattern: CompressedRow): Set<Int> { val indices = mutableSetOf<Int>() if (pattern.nodes.size == 1) { val patternNode = pattern.nodes[0] for (gridNode in nodes) { if (gridNode.value == patternNode.value && gridNode.size >= patternNode.size) { for (i in gridNode.start..gridNode.end - patternNode.size) { indices.add(i) } } } return indices } loop@ for (startingIndex in 0..nodes.size - pattern.nodes.size) { for (i in 0 until pattern.nodes.size) { val patternNode = pattern.nodes[i] val gridNode = nodes[startingIndex + i] if (patternNode.value != gridNode.value) { // It's not the same sequence of chars, so it cannot match continue@loop } if (patternNode.size > gridNode.size) { // Pattern has more chars in the sequence continue@loop } if (i != 0 && i != pattern.nodes.size - 1 && patternNode.size != gridNode.size) { // Unless it's the prefix/suffix we're matching, the # of chars need to match continue@loop } } indices.add(nodes[startingIndex].end - pattern.nodes[0].size) } return indices } } // Complete the gridSearch function below. fun gridSearch(g: Array<String>, p: Array<String>): String { val grid = CompressedRow.fromArray(g) val pattern = CompressedRow.fromArray(p) val startingIndices = Array<Set<Int>>(p.size) { emptySet<Int>() } for (gridStartRowIndex in 0..g.size - p.size) { for (i in 0 until p.size) { val gridRow = grid[gridStartRowIndex + i] val patternRow = pattern[i] startingIndices[i] = gridRow.startingIndices(patternRow) } val isMatch = startingIndices[0].any { index -> startingIndices.all { s -> s.contains(index) } } if (isMatch) { return "YES" } } return "NO" } fun main(args: Array<String>) { val scan = Scanner(System.`in`) val t = scan.nextLine().trim().toInt() for (tItr in 1..t) { val RC = scan.nextLine().split(" ") val R = RC[0].trim().toInt() val C = RC[1].trim().toInt() val G = Array<String>(R, { "" }) for (i in 0 until R) { val GItem = scan.nextLine() G[i] = GItem } val rc = scan.nextLine().split(" ") val r = rc[0].trim().toInt() val c = rc[1].trim().toInt() val P = Array<String>(r, { "" }) for (i in 0 until r) { val PItem = scan.nextLine() P[i] = PItem } val result = gridSearch(G, P) println(result) } } main(arrayOf())
0
Java
18
20
08e65546527436f4bd2a2014350b2f97ac1367e7
3,906
coding-problem
MIT License
src/main/kotlin/io/github/clechasseur/adventofcode2021/Day5.kt
clechasseur
435,726,930
false
{"Kotlin": 315943}
package io.github.clechasseur.adventofcode2021 import io.github.clechasseur.adventofcode2021.data.Day5Data import io.github.clechasseur.adventofcode2021.util.Pt object Day5 { private val data = Day5Data.data private val linesRegex = """^(\d+),(\d+) -> (\d+),(\d+)$""".toRegex() private val lines: List<Pair<Pt, Pt>> = data.lines().map { val match = linesRegex.matchEntire(it) ?: error("Wrong line format: $it") val (x1, y1, x2, y2) = match.destructured Pt(x1.toInt(), y1.toInt()) to Pt(x2.toInt(), y2.toInt()) } fun part1(): Int = hotPoints(false) fun part2(): Int = hotPoints(true) private fun hotPoints(diag: Boolean): Int { val points = mutableMapOf<Pt, Int>() lines.forEach { line -> linePoints(line, diag).forEach { pt -> points[pt] = points.getOrDefault(pt, 0) + 1 } } return points.count { it.value > 1 } } private fun linePoints(line: Pair<Pt, Pt>, diag: Boolean): Sequence<Pt> = if (line.first.y == line.second.y) { if (line.first.x <= line.second.x) { generateSequence(line.first) { if (it.x < line.second.x) Pt(it.x + 1, it.y) else null } } else { linePoints(line.second to line.first, diag) } } else if (line.first.x == line.second.x) { linePoints(Pt(line.first.y, line.first.x) to Pt(line.second.y, line.second.x), diag).map { Pt(it.y, it.x) } } else if (!diag) { emptySequence() } else if (line.first.x < line.second.x) { if (line.first.y < line.second.y) { linePoints(Pt(line.first.x, line.first.y) to Pt(line.second.x, line.first.y), false).mapIndexed { i, pt -> Pt(pt.x, pt.y + i) } } else { linePoints(Pt(line.first.x, line.second.y) to Pt(line.second.x, line.first.y), true).mapIndexed { i, pt -> Pt(pt.x, line.first.y - i) } } } else { linePoints(line.second to line.first, true) } }
0
Kotlin
0
0
4b893c001efec7d11a326888a9a98ec03241d331
2,060
adventofcode2021
MIT License
numeriko-core/src/main/kotlin/tomasvolker/numeriko/core/primitives/Extensions.kt
TomasVolker
114,266,369
false
null
package tomasvolker.numeriko.core.primitives import tomasvolker.numeriko.core.config.NumerikoConfig import kotlin.math.abs infix fun Int.modulo(other: Int) = ((this % other) + other) % other infix fun Long.modulo(other: Long) = ((this % other) + other) % other infix fun Float.modulo(other: Float) = ((this % other) + other) % other infix fun Double.modulo(other: Double) = ((this % other) + other) % other fun Int.squared(): Int = this * this fun Long.squared(): Long = this * this fun Float.squared(): Float = this * this fun Double.squared(): Double = this * this fun Int.cubed(): Int = this * this * this fun Long.cubed(): Long = this * this * this fun Float.cubed(): Float = this * this * this fun Double.cubed(): Double = this * this * this infix fun Double.numericEqualsTo( other: Double ): Boolean = numericEqualsTo(other, NumerikoConfig.defaultTolerance) fun Double.numericEqualsTo( other: Double, tolerance: Double ): Boolean = abs(other - this) <= tolerance fun sqrt(value: Int): Float = kotlin.math.sqrt(value.toFloat()) fun sqrt(value: Long): Double = kotlin.math.sqrt(value.toDouble()) fun Boolean.indicative() = if(this) 1.0 else 0.0 fun pow2(power: Int): Int { var x = 1 repeat(power){ x *= 2 } return x } tailrec fun Int.isPowerOf2(): Boolean = when { this == 0 -> false this == 1 -> true else -> if (this % 2 != 0) false else (this / 2).isPowerOf2() } fun Int.isEven(): Boolean = this % 2 == 0 fun Int.isOdd(): Boolean = this % 2 == 1 fun Long.isEven(): Boolean = this % 2 == 0L fun Long.isOdd(): Boolean = this % 2 == 1L inline fun sumDouble(indices: IntProgression, value: (i: Int)->Double): Double { var result = 0.0 for (i in indices) { result += value(i) } return result } inline fun sumDouble( indices0: IntProgression, indices1: IntProgression, value: (i0: Int, i1: Int)->Double ): Double { var result = 0.0 for (i0 in indices0) { for (i1 in indices1) { result += value(i0, i1) } } return result } inline fun sumInt(indices: IntProgression, value: (i: Int)->Int): Int = indices.sumBy(value) inline fun sumInt( indices0: IntProgression, indices1: IntProgression, value: (i0: Int, i1: Int)->Int ): Int = indices0.sumBy { i0 -> indices1.sumBy { i1 -> value(i0, i1) } }
8
Kotlin
1
3
1e9d64140ec70b692b1b64ecdcd8b63cf41f97af
2,504
numeriko
Apache License 2.0
src/main/kotlin/aoc22/Day20.kt
tom-power
573,330,992
false
{"Kotlin": 254717, "Shell": 1026}
package aoc22 import aoc22.Day20Domain.Mixer import aoc22.Day20Solution.part1Day20 import aoc22.Day20Solution.part2Day20 import aoc22.Day20Parser.toMixer import aoc22.Day20Runner.coordinates import aoc22.Day20Runner.decrypt import common.Year22 object Day20: Year22 { fun List<String>.part1(): Long = part1Day20() fun List<String>.part2(): Long = part2Day20() } object Day20Solution { fun List<String>.part1Day20(): Long = toMixer(key = 1L) .decrypt(times = 1) .coordinates() fun List<String>.part2Day20(): Long = toMixer(key = 811589153L) .decrypt(times = 10) .coordinates() } object Day20Runner { fun List<Mixer>.decrypt(times: Int, mixers: MutableList<Mixer> = this.toMutableList()): List<Mixer> = when (times) { 0 -> mixers else -> decrypt(times - 1, this.decryptWith(mixers).toMutableList()) } private fun List<Mixer>.decryptWith(mixers: MutableList<Mixer>): List<Mixer> = foldIndexed(mixers) { originalIndex, acc, mixer -> val index = acc.indexOfFirst { it.originalIndex == originalIndex } acc.apply { removeAt(index) add((index + mixer.value).mod(acc.size), mixer) } } fun List<Mixer>.coordinates(): Long = indexOfFirst { it.value == 0L }.let { zero -> listOf(1000, 2000, 3000).sumOf { this[(zero + it).mod(size)].value } } } object Day20Domain { data class Mixer(val originalIndex: Int, val value: Long) } object Day20Parser { fun List<String>.toMixer(key: Long): List<Mixer> = mapIndexed { index, s -> Mixer( originalIndex = index, value = s.toLong() * key ) } }
0
Kotlin
0
0
baccc7ff572540fc7d5551eaa59d6a1466a08f56
1,806
aoc
Apache License 2.0
src/Day11.kt
buczebar
572,864,830
false
{"Kotlin": 39213}
import java.lang.IllegalArgumentException private fun parseMonkey(monkeyData: String): Monkey { return Monkey.build { monkeyData.lines().forEach { line -> with(line.trim()) { when { startsWith("Monkey") -> { id = getAllInts().first() } startsWith("Starting items:") -> { items = getAllInts().map { it.toLong() }.toMutableList() } startsWith("Operation") -> { operation = "\\w+ [*+-/]? \\w+".toRegex().find(this)?.value.orEmpty() } startsWith("Test:") -> { testDivisor = getAllInts().first().toLong() } startsWith("If true:") -> { idIfTrue = getAllInts().first() } startsWith("If false:") -> { idIfFalse = getAllInts().first() } } } } } } private fun parseInput(name: String) = readGroupedInput(name).map { parseMonkey(it) } fun main() { fun simulate(monkeys: List<Monkey>, rounds: Int, reduceOperation: (Long) -> Long): List<Long> { val inspectionCounters = MutableList(monkeys.size) { 0L } repeat(rounds) { monkeys.forEach { monkey -> monkey.items.forEach { item -> val newItemValue = reduceOperation(monkey.calculate(item)) monkeys[monkey.getMonkeyIdToPass(newItemValue)].items.add(newItemValue) inspectionCounters[monkey.id]++ } monkey.items.clear() } } return inspectionCounters } fun monkeyBusiness(inspections: List<Long>) = inspections .sortedDescending() .take(2) .factorial() fun part1(monkeys: List<Monkey>) = monkeyBusiness(simulate(monkeys, 20) { it / 3 }) fun part2(monkeys: List<Monkey>) = monkeyBusiness( simulate(monkeys, 10_000) { it % monkeys.map { monkey -> monkey.testDivisor }.factorial() } ) check(part1(parseInput("Day11_test")) == 10605L) check(part2(parseInput("Day11_test")) == 2713310158L) println(part1(parseInput("Day11"))) println(part2(parseInput("Day11"))) } private data class Monkey( val id: Int, val items: MutableList<Long> = mutableListOf(), private val operation: String, val testDivisor: Long, private val idIfTrue: Int, private val idIfFalse: Int ) { private constructor(builder: Builder) : this( builder.id, builder.items, builder.operation, builder.testDivisor, builder.idIfTrue, builder.idIfFalse ) fun getMonkeyIdToPass(value: Long) = idIfTrue.takeIf { value % testDivisor == 0L } ?: idIfFalse fun calculate(value: Long): Long { val (_, type, second) = operation.takeIf { it.isNotEmpty() }?.splitWords() ?: return -1L val arg = if (second == "old") value else second.toLong() return when (type) { "+" -> value + arg "-" -> value - arg "*" -> value * arg "/" -> value / arg else -> throw IllegalArgumentException("wrong operation type $operation") } } companion object { inline fun build(block: Builder.() -> Unit) = Builder().apply(block).build() } class Builder { var id = 0 var items: MutableList<Long> = mutableListOf() var operation: String = "" var testDivisor: Long = 0L var idIfTrue: Int = 0 var idIfFalse: Int = 0 fun build() = Monkey(this) } }
0
Kotlin
0
0
cdb6fe3996ab8216e7a005e766490a2181cd4101
3,851
advent-of-code
Apache License 2.0
src/main/kotlin/aoc2017/SporificaVirus.kt
komu
113,825,414
false
{"Kotlin": 395919}
package komu.adventofcode.aoc2017 import komu.adventofcode.utils.Direction import komu.adventofcode.utils.Point import komu.adventofcode.utils.nonEmptyLines fun sporificaVirus1(input: String): Int { val infectedPoints = VirusMap(input.nonEmptyLines()) var point = Point.ORIGIN var dir = Direction.UP var infections = 0 repeat(10000) { if (infectedPoints[point] == VirusState.INFECTED) { dir = dir.right infectedPoints[point] = VirusState.CLEAN } else { dir = dir.left infectedPoints[point] = VirusState.INFECTED infections++ } point += dir } return infections } fun sporificaVirus2(input: String): Int { val infectedPoints = VirusMap(input.nonEmptyLines()) var point = Point.ORIGIN var dir = Direction.UP var infections = 0 repeat(10000000) { val state = infectedPoints[point] dir = when (state) { VirusState.CLEAN -> dir.left VirusState.WEAKENED -> dir VirusState.INFECTED -> dir.right VirusState.FLAGGED -> dir.opposite } infectedPoints[point] = state.next if (state.next == VirusState.INFECTED) infections++ point += dir } return infections } private enum class VirusState { CLEAN, WEAKENED, INFECTED, FLAGGED; val next: VirusState get() = values()[(ordinal + 1) % 4] } private class VirusMap(lines: List<String>) { private val infectedPoints = mutableMapOf<Point, VirusState>() init { val dy = lines.size / 2 val dx = lines[0].length / 2 lines.forEachIndexed { y, line -> line.forEachIndexed { x, c -> if (c == '#') infectedPoints[Point(x - dx, y - dy)] = VirusState.INFECTED } } } operator fun get(point: Point) = infectedPoints[point] ?: VirusState.CLEAN operator fun set(point: Point, state: VirusState) { infectedPoints[point] = state } }
0
Kotlin
0
0
8e135f80d65d15dbbee5d2749cccbe098a1bc5d8
2,064
advent-of-code
MIT License
src/questions/TwoSumII.kt
realpacific
234,499,820
false
null
package questions import _utils.UseCommentAsDocumentation import algorithmdesignmanualbook.print import utils.assertIterableSame /** * Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, * find two numbers such that they add up to a specific target number. * Return the indices of the two numbers, index1 and index2, as an integer array [index1, index2] of length 2. * * The tests are generated such that there is exactly one solution. You may not use the same element twice. * * [Source](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/) */ @UseCommentAsDocumentation fun twoSum(numbers: IntArray, target: Int): IntArray { for (i in 0..numbers.lastIndex) { val requiredInt = target - numbers[i] val indexOfRequired = binarySearch(numbers, low = 0, high = numbers.size, target = requiredInt, ignoreIndex = i) if (indexOfRequired != null) { return intArrayOf(i + 1, indexOfRequired + 1).sortedArray() } } return intArrayOf() } private fun binarySearch(numbers: IntArray, low: Int, high: Int, target: Int, ignoreIndex: Int): Int? { // can't have <= as the [target] may occur at the middle if (high < low) return null val mid = (low + high) / 2 // [ignoreIndex] to satisfy condition that "You may not use the same element twice." val midNumber = numbers.getOrNull(mid) return if (midNumber == null) null else if (midNumber == target && ignoreIndex != mid) mid else if (midNumber < target) binarySearch(numbers, mid + 1, high, target = target, ignoreIndex = ignoreIndex) else binarySearch(numbers, low, mid - 1, target = target, ignoreIndex = ignoreIndex) } fun main() { assertIterableSame( intArrayOf(3, 42).toList(), twoSum( numbers = intArrayOf( 12, 83, 104, 129, 140, 184, 199, 300, 306, 312, 321, 325, 341, 344, 349, 356, 370, 405, 423, 444, 446, 465, 471, 491, 500, 506, 508, 530, 539, 543, 569, 591, 606, 607, 612, 614, 623, 627, 645, 662, 670, 685, 689, 726, 731, 737, 744, 747, 764, 773, 778, 787, 802, 805, 811, 819, 829, 841, 879, 905, 918, 918, 929, 955, 997, ), target = 789 ).toList().print() ) assertIterableSame( intArrayOf(1, 2).toList(), twoSum(numbers = intArrayOf(0, 0, 3, 4), target = 0).toList().print() ) assertIterableSame( intArrayOf(2, 3).toList(), twoSum(numbers = intArrayOf(5, 25, 75), target = 100).toList().print() ) assertIterableSame( intArrayOf(1, 2).toList(), twoSum(numbers = intArrayOf(2, 7, 11, 15), target = 9).toList().print() ) assertIterableSame( intArrayOf(1, 3).toList(), twoSum(numbers = intArrayOf(2, 3, 4), target = 6).toList().print() ) assertIterableSame( intArrayOf(1, 2).toList(), twoSum(numbers = intArrayOf(-1, 0), target = -1).toList().print() ) }
4
Kotlin
5
93
22eef528ef1bea9b9831178b64ff2f5b1f61a51f
3,942
algorithms
MIT License
src/nativeMain/kotlin/com.qiaoyuang.algorithm/special/Questions82.kt
qiaoyuang
100,944,213
false
{"Kotlin": 338134}
package com.qiaoyuang.algorithm.special fun test82() { printlnResult(intArrayOf(2, 2, 2, 4, 3, 3), 8) } /** * Questions 82: Given an IntArray that contain the same integers possibly. And, given a value, * please find all subsets that the sum of subset equals this value, integers just could appear once in one subset */ private infix fun IntArray.findSubsets(sum: Int): List<List<Int>> = buildList { backTrack(this, mutableListOf(), sum, 0) } private fun IntArray.backTrack(results: MutableList<List<Int>>, subset: MutableList<Int>, sum: Int, index: Int) { if (sum == 0) { results.add(listOf()) return } if (sum < 0) return val sumOfSubset = subset.sum() when { sumOfSubset > sum -> return sumOfSubset == sum -> { results.add(ArrayList(subset)) return } } if (index >= size) return backTrack(results, subset, sum, getNext(index)) subset.add(this[index]) backTrack(results, subset, sum, index + 1) subset.removeLast() } private infix fun IntArray.getNext(i: Int): Int { for (j in i + 1 ..< size) if (this[i] != this[j]) return j return size } private fun printlnResult(nums: IntArray, sum: Int) = println("The all subsets in ${nums.toList()} that sum equals $sum are ${nums findSubsets sum}")
0
Kotlin
3
6
66d94b4a8fa307020d515d4d5d54a77c0bab6c4f
1,350
Algorithm
Apache License 2.0
kotlin/0329-longest-increasing-path-in-a-matrix.kt
neetcode-gh
331,360,188
false
{"JavaScript": 473974, "Kotlin": 418778, "Java": 372274, "C++": 353616, "C": 254169, "Python": 207536, "C#": 188620, "Rust": 155910, "TypeScript": 144641, "Go": 131749, "Swift": 111061, "Ruby": 44099, "Scala": 26287, "Dart": 9750}
class Solution { fun longestIncreasingPath(matrix: Array<IntArray>): Int { val m = matrix.size val n = matrix[0].size val memo = Array<IntArray>(m){IntArray(n)} val dirs = arrayOf(intArrayOf(-1,0),intArrayOf(1,0),intArrayOf(0,1),intArrayOf(0,-1)) var res = 1 for (i in 0..m-1) { for (j in 0..n-1) { val len = dfs(matrix, i, j, dirs, memo) res = Math.max(res, len) } } return res } fun dfs(matrix: Array<IntArray>, row: Int, col: Int, dirs: Array<IntArray>, memo: Array<IntArray>): Int { val m = matrix.size val n = matrix[0].size if (memo[row][col] != 0) return memo[row][col] var len = 1 for (dir in dirs) { val x = dir[0] + row val y = dir[1] + col if (x < 0 || x == m || y < 0 || y == n || matrix[row][col] >= matrix[x][y]) continue len = Math.max(len, 1+dfs(matrix, x, y, dirs, memo)) } memo[row][col] = len return len } }
337
JavaScript
2,004
4,367
0cf38f0d05cd76f9e96f08da22e063353af86224
1,111
leetcode
MIT License
src/Day11.kt
MickyOR
578,726,798
false
{"Kotlin": 98785}
class Monke { var items = MutableList(0) { mutableListOf<Pair<Int, Int>>() } var operation: (Int) -> Int = { a -> a } var trueMonke: Int = 0 var falseMonke: Int = 0 var inspectCount: Long = 0 } fun main() { fun part1(input: List<String>): Long { var monkes = mutableListOf<Monke>() var rules = mutableListOf<Int>() for (i in 0 until input.size step 7) { val vs = input[i+3].split(" ") val modulo = vs[5].toInt() rules.add(modulo) } for (i in 0 until input.size step 7) { var monke = Monke() var vs = input[i+1].split(" ").map { if (it.isNotEmpty() && it[it.length-1] == ',') it.substring(0, it.length-1) else it } for (j in 4 until vs.size) { var v = vs[j].toInt() var itemList = mutableListOf<Pair<Int, Int>>() for (k in 0 until rules.size) { itemList.add(Pair(v, rules[k])) } monke.items.add(itemList) } vs = input[i+2].split(" ") if (vs[vs.size-1] == "old") { monke.operation = if (vs[vs.size-2] == "+") { a -> a + a } else { a -> a * a } } else { var opValue = vs[vs.size - 1].toInt() monke.operation = if (vs[vs.size - 2] == "+") { a -> a + opValue } else { a -> a * opValue } } vs = input[i+4].split(" ") monke.trueMonke = vs[vs.size-1].toInt() vs = input[i+5].split(" ") monke.falseMonke = vs[vs.size-1].toInt() monkes.add(monke) } val rounds = 20 for (ite in 1 .. rounds) { for (idx in 0 until monkes.size) { var monke = monkes[idx] var trueItems = MutableList(0) { mutableListOf<Pair<Int, Int>>() } var falseItems = MutableList(0) { mutableListOf<Pair<Int, Int>>() } monke.inspectCount += monke.items.size for (item in monke.items) { var itemWithRules = mutableListOf<Pair<Int, Int>>() for (pair in item) { var newPair: Pair<Int, Int> = Pair(monke.operation(pair.first) / 3, pair.second) itemWithRules.add(newPair) } if (itemWithRules[0].first % rules[idx] == 0) { trueItems.add(itemWithRules) } else { falseItems.add(itemWithRules) } } monke.items.clear() monkes[monke.trueMonke].items.addAll(trueItems) monkes[monke.falseMonke].items.addAll(falseItems) } } var auxVec = mutableListOf<Long>() for (monke in monkes) { auxVec.add(monke.inspectCount) } auxVec.sortDescending() return auxVec[0] * auxVec[1] } fun part2(input: List<String>): Long { var monkes = mutableListOf<Monke>() var rules = mutableListOf<Int>() for (i in 0 until input.size step 7) { val vs = input[i+3].split(" ") val modulo = vs[5].toInt() rules.add(modulo) } for (i in 0 until input.size step 7) { var monke = Monke() var vs = input[i + 1].split(" ") .map { if (it.isNotEmpty() && it[it.length - 1] == ',') it.substring(0, it.length - 1) else it } for (j in 4 until vs.size) { var v = vs[j].toInt() var itemList = mutableListOf<Pair<Int, Int>>() for (k in 0 until rules.size) { itemList.add(Pair(v % rules[k], rules[k])) } monke.items.add(itemList) } vs = input[i + 2].split(" ") if (vs[vs.size - 1] == "old") { monke.operation = if (vs[vs.size - 2] == "+") { a -> a + a } else { a -> a * a } } else { var opValue = vs[vs.size - 1].toInt() monke.operation = if (vs[vs.size - 2] == "+") { a -> a + opValue } else { a -> a * opValue } } vs = input[i + 4].split(" ") monke.trueMonke = vs[vs.size - 1].toInt() vs = input[i + 5].split(" ") monke.falseMonke = vs[vs.size - 1].toInt() monkes.add(monke) } val rounds = 10000 for (ite in 1 .. rounds) { for (idx in 0 until monkes.size) { var monke = monkes[idx] var trueItems = MutableList(0) { mutableListOf<Pair<Int, Int>>() } var falseItems = MutableList(0) { mutableListOf<Pair<Int, Int>>() } monke.inspectCount += monke.items.size for (item in monke.items) { var itemWithRules = mutableListOf<Pair<Int, Int>>() for (pair in item) { var newPair: Pair<Int, Int> = Pair(monke.operation(pair.first) % pair.second, pair.second) itemWithRules.add(newPair) } if (itemWithRules[idx].first == 0) { trueItems.add(itemWithRules) } else { falseItems.add(itemWithRules) } } monke.items.clear() monkes[monke.trueMonke].items.addAll(trueItems) monkes[monke.falseMonke].items.addAll(falseItems) } } var auxVec = mutableListOf<Long>() for (monke in monkes) { auxVec.add(monke.inspectCount) } auxVec.sortDescending() return auxVec[0] * auxVec[1] } val input = readInput("Day11") part1(input).println() part2(input).println() }
0
Kotlin
0
0
c24e763a1adaf0a35ed2fad8ccc4c315259827f0
5,911
advent-of-code-2022-kotlin
Apache License 2.0
src/main/kotlin/nl/jackploeg/aoc/_2023/calendar/day03/Day03.kt
jackploeg
736,755,380
false
{"Kotlin": 318734}
package nl.jackploeg.aoc._2023.calendar.day03 import nl.jackploeg.aoc.generators.InputGenerator.InputGeneratorFactory import nl.jackploeg.aoc.utilities.readStringFile import javax.inject.Inject class Day03 @Inject constructor( private val generatorFactory: InputGeneratorFactory, ) { fun partOne(fileName: String): Int { val partNumbers: MutableList<PartNumber> = mutableListOf() readSchematic(fileName, partNumbers) return partNumbers.filter { it.hasSymbolNeighbour() }.sumOf { it.value } } fun partTwo(fileName: String): Int { val symbols: MutableList<Symbol> = mutableListOf() readSchematic(fileName, symbols = symbols) return symbols .filter { it.char == '*' && it.neighbours.size==2 } .sumOf { it.neighbours[0].value * it.neighbours[1].value} } fun readSchematic( fileName: String, partNumbers: MutableList<PartNumber> = mutableListOf(), symbols: MutableList<Symbol> = mutableListOf() ) { val engineSchema = readStringFile(fileName) for (lineNo in engineSchema.indices) { val line = engineSchema[lineNo] var lastDigitProcessed = -1 for (pos in line.indices) { if (line[pos].isDigit() && pos > lastDigitProcessed) { lastDigitProcessed = pos while (lastDigitProcessed < line.length && line[lastDigitProcessed].isDigit()) lastDigitProcessed++ val value = line.substring(pos, lastDigitProcessed).toInt() partNumbers.add(PartNumber(lineNo, pos, value)) } } } for (lineNo in engineSchema.indices) { val line = engineSchema[lineNo] for (pos in line.indices) { if (!line[pos].isDigit() && line[pos] != '.') { val symbol = Symbol(lineNo, pos, line[pos]) if (lineNo > 0) { partNumbers.filter { it.top == lineNo - 1 && it.left <= pos + 1 && it.right >= pos - 1 } .forEach { it.bottomChars.add(line[pos]) symbol.neighbours.add(it) } } if (lineNo < engineSchema.size - 1) { partNumbers.filter { it.top == lineNo + 1 && it.left <= pos + 1 && it.right >= pos - 1 } .forEach { it.topChars.add(line[pos]) symbol.neighbours.add(it) } } partNumbers.filter { it.top == lineNo && it.left == pos + 1 } .forEach { it.leftChars.add(line[pos]) symbol.neighbours.add(it) } partNumbers.filter { it.top == lineNo && it.right == pos - 1 } .forEach { it.rightChars.add(line[pos]) symbol.neighbours.add(it) } symbols.add(symbol) } } } } data class PartNumber( val top: Int, val left: Int, val value: Int, val topChars: MutableList<Char> = mutableListOf(), val bottomChars: MutableList<Char> = mutableListOf(), val leftChars: MutableList<Char> = mutableListOf(), val rightChars: MutableList<Char> = mutableListOf() ) { val right: Int get() = left + value.toString().length - 1 fun hasSymbolNeighbour(): Boolean = topChars.size > 0 || bottomChars.size > 0 || leftChars.size > 0 || rightChars.size > 0 } data class Symbol( val top: Int, val left: Int, val char: Char, val neighbours: MutableList<PartNumber> = mutableListOf() ) }
0
Kotlin
0
0
f2b873b6cf24bf95a4ba3d0e4f6e007b96423b76
3,423
advent-of-code
MIT License
src/com/kingsleyadio/adventofcode/y2022/day03/Solution.kt
kingsleyadio
435,430,807
false
{"Kotlin": 134666, "JavaScript": 5423}
package com.kingsleyadio.adventofcode.y2022.day03 import com.kingsleyadio.adventofcode.util.readInput fun main() { part1() part2() } fun part1() { var result = 0 readInput(2022, 3).forEachLine { line -> val first = line.substring(0, line.length / 2) val second = line.substring(line.length / 2) val array = BooleanArray(52) for (char in first) array[valueOfChar(char) - 1] = true for (char in second) { val value = valueOfChar(char) if (array[value - 1]) { result += value array[value - 1] = false } } } println(result) } fun part2() { var result = 0 readInput(2022, 3).useLines { lines -> lines.windowed(3, 3).forEach { (first, second, third) -> val array = IntArray(52) for (char in first) array[valueOfChar(char) - 1] = 1 for (char in second) { val value = valueOfChar(char) if (array[value - 1] == 1) array[value - 1] = 2 } for (char in third) { val value = valueOfChar(char) if (array[value - 1] == 2) { result += value array[value - 1] = 0 } } } } println(result) } fun valueOfChar(char: Char) = when { char.isUpperCase() -> char - 'A' + 27 else -> char - 'a' + 1 }
0
Kotlin
0
1
9abda490a7b4e3d9e6113a0d99d4695fcfb36422
1,451
adventofcode
Apache License 2.0
leetcode/src/offer/middle/Offer48.kt
zhangweizhe
387,808,774
false
null
package offer.middle fun main() { // 剑指 Offer 48. 最长不含重复字符的子字符串 // https://leetcode.cn/problems/zui-chang-bu-han-zhong-fu-zi-fu-de-zi-zi-fu-chuan-lcof/ println(lengthOfLongestSubstring("abba")) } fun lengthOfLongestSubstring(s: String): Int { // 滑动窗口,左开右闭,所以 left 初始化为 -1 var left = -1 val map = HashMap<Char, Int>() var max = 0 var right = 0 while (right < s.length) { if (map.containsKey(s[right])) { // 左边界要取 (原左边界left, 重复字符出现的位置map[s[right]]) 中的最大值,因为重复字符可能出现在【原左边界】左边 // 比如 abba,当遍历到第二个 b 时,左边界 left 更新为 1; // 接着遍历到第二个 a,此时 map['a'] 是 0,重复字符的位置在左边界的左边 left = Math.max(left, map[s[right]]!!) } // 更新字符对应的索引,不管是否重复 // 如果重复了,可以理解为更新为最新(最大)的索引 map[s[right]] = right max = Math.max(max, right - left) right++ } return max }
0
Kotlin
0
0
1d213b6162dd8b065d6ca06ac961c7873c65bcdc
1,191
kotlin-study
MIT License
common/src/main/kotlin/combo/math/Cholesky.kt
rasros
148,620,275
false
null
package combo.math import kotlin.math.absoluteValue import kotlin.math.sqrt /** * Perform cholesky decomposition downdate with vector x, such that A = L'*L - x*x' * The matrix is modified inline. * Ported from fortran dchdd. */ fun Matrix.choleskyDowndate(x: VectorView): Float { val L = this val p = x.size val s = vectors.zeroVector(p) val c = vectors.zeroVector(p) // Solve the system L.T*s = x s[0] = x[0] / L[0, 0] if (p > 1) { for (j in 1 until p) { var sum = 0f for (i in 0 until j) sum += L[i, j] * s[i] s[j] = x[j] - sum s[j] = s[j] / L[j, j] } } var norm = s.norm2() return if (norm > 0f && norm < 1f) { var alpha = sqrt(1 - norm * norm) for (ii in 0 until p) { val i = p - ii - 1 val scale = alpha + s[i].absoluteValue val a = alpha / scale val b = s[i] / scale norm = sqrt(a * a + b * b) c[i] = a / norm s[i] = b / norm alpha = scale * norm } for (j in 0 until p) { var xx = 0f for (ii in 0..j) { val i = j - ii val t = c[i] * xx + s[i] * L[i, j] L[i, j] = c[i] * L[i, j] - s[i] * xx xx = t } } 0f } else norm } fun Matrix.cholesky(): Matrix { val N = rows val L = vectors.zeroMatrix(N) for (i in 0 until N) { for (j in 0..i) { var sum = 0.0f for (k in 0 until j) sum += L[i, k] * L[j, k] if (i == j) L[i, i] = sqrt(this[i, i] - sum) else L[i, j] = 1.0f / L[j, j] * (this[i, j] - sum) } if (L[i, i] <= 0 || L[i, i].isNaN()) L[i, i] = 1e-5f //error("Matrix not positive definite") } return L }
0
Kotlin
1
2
2f4aab86e1b274c37d0798081bc5500d77f8cd6f
1,912
combo
Apache License 2.0
jvm/src/main/kotlin/io/prfxn/aoc2021/day25.kt
prfxn
435,386,161
false
{"Kotlin": 72820, "Python": 362}
// <NAME> (https://adventofcode.com/2021/day/25) package io.prfxn.aoc2021 fun main() { val v = 'v' val gt = '>' val lines = textResourceReader("input/25.txt").readLines() val numRows = lines.size val numCols = lines.first().length val (gts, vs) = lines.indices .flatMap { r -> lines[r].indices.mapNotNull { c -> val char = lines[r][c] if (char == v || char == gt) char to (r to c) else null } } .groupBy({ it.first }) { it.second } .let { it[gt]!!.toSet() to it[v]!!.toSet() } fun step(gts: MutableSet<CP>, vs: MutableSet<CP>): Int = sequenceOf(gts, vs).sumOf { cps -> cps.asSequence() .map { (r, c) -> (r to c) to when (cps) { gts -> (r to (c + 1) % numCols) else -> ((r + 1) % numRows to c) } } .filter { (_, to) -> to !in gts && to !in vs } .toList() .map { (from, to) -> cps.remove(from) cps.add(to) } .count() } val gtms = gts.toMutableSet() val vms = vs.toMutableSet() println( generateSequence(1) { if (step(gtms, vms) > 0) it + 1 else null }.last() ) }
0
Kotlin
0
0
148938cab8656d3fbfdfe6c68256fa5ba3b47b90
1,537
aoc2021
MIT License
src/Day11.kt
l8nite
573,298,097
false
{"Kotlin": 105683}
class Monkey( private val items: MutableList<Long>, val operation: ((Long) -> Long), val divisor: Long, private val trueTarget: Int, private val falseTarget: Int, var worry: ((Long) -> (Long))? = null ) { var inspected: Long = 0L fun inspect(monkeys: List<Monkey>) { items.forEach { var item = operation(it) item = worry?.invoke(item) ?: item if (item % divisor == 0L) { monkeys[trueTarget].items.add(item) } else { monkeys[falseTarget].items.add(item) } } inspected += items.size items.clear() } // fun report(idx: Int) { // println("Monkey $idx:") // println(" Items: $items") // println(" Divisor: $divisor") // println(" Worry: $worry") // println(" Targets: [$trueTarget, $falseTarget]") // println(" Inspected: $inspected") // } } fun parseMonkey(input: List<String>): Monkey { val items = parseItems(input[1]) val operation = parseOperation(input[2]) val divisor = parseTestDivisor(input[3]) val (trueTarget, falseTarget) = parseTrueFalseTargets(input[4], input[5]) return Monkey( items, operation, divisor, trueTarget, falseTarget ) { n -> n / 3L } } fun parseItems(input: String): MutableList<Long> { val itemsRegex = "^\\s*Starting items: (.+)+$".toRegex() val (itemString) = itemsRegex.matchEntire(input)!!.destructured return itemString.split(", ".toRegex()).map(String::toLong).toMutableList() } fun parseOperation(input: String): ((Long) -> Long) { val operationRegex = "^\\s*Operation: new = (.+?) ([*+]) (.+?)$".toRegex() val (l, o, r) = operationRegex.matchEntire(input)!!.destructured return fun (n: Long): Long { val left = if (l == "old") n else l.toLong() val right = if (r == "old") n else r.toLong() return when (o) { "+" -> left + right "*" -> left * right else -> throw Exception("Unknown operation: $o") } } } fun parseTestDivisor(input: String): Long { val testRegex = "^\\s*Test: divisible by (\\d+)$".toRegex() val (divisor) = testRegex.matchEntire(input)!!.destructured return divisor.toLong() } fun parseTrueFalseTargets(trueInput: String, falseInput: String): Pair<Int,Int> { val throwTargetRegex = "^\\s*If (?:true|false): throw to monkey (\\d+)$".toRegex() val (trueTarget) = throwTargetRegex.matchEntire(trueInput)!!.destructured val (falseTarget) = throwTargetRegex.matchEntire(falseInput)!!.destructured return Pair(trueTarget.toInt(), falseTarget.toInt()) } fun main() { fun part1(input: List<String>): Long { val monkeys = input.chunked(7).map { parseMonkey(it) } repeat(20) { monkeys.forEach { it.inspect(monkeys) } } val top2 = monkeys.map { it.inspected }.sortedDescending().take(2) return top2[0] * top2[1] } fun part2(input: List<String>): Long { val monkeys = input.chunked(7).map { parseMonkey(it) } val lcm = monkeys.map { it.divisor }.reduce { acc, n -> acc * n } val function = { n: Long -> n % lcm } monkeys.forEach { it.worry = function } repeat(10000) { monkeys.forEach { it.inspect(monkeys) } } val top2 = monkeys.map { it.inspected }.sortedDescending().take(2) return top2[0] * top2[1] } // test if implementation meets criteria from the description, like: 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
f74331778fdd5a563ee43cf7fff042e69de72272
3,798
advent-of-code-2022
Apache License 2.0
year2021/day16/bits/src/main/kotlin/com/curtislb/adventofcode/year2021/day16/bits/BitsPacketType.kt
curtislb
226,797,689
false
{"Kotlin": 2146738}
package com.curtislb.adventofcode.year2021.day16.bits import com.curtislb.adventofcode.common.number.product /** * A type of packet included as part of a BITS transmission. * * @param id An integer ID that uniquely defines this packet type. */ enum class BitsPacketType(val id: Int) { /** * A packet whose value is the sum of the values of its sub-packets. */ SUM(id = 0), /** * A packet whose value is result of multiplying together the values of its sub-packets. */ PRODUCT(id = 1), /** * A packet whose value is the minimum of the values of its sub-packets. */ MINIMUM(id = 2), /** * A packet whose value is the maximum of the values of its sub-packets. */ MAXIMUM(id = 3), /** * A packet that represents a literal value and contains no sub-packets. */ LITERAL(id = 4), /** * A packet whose value is 1 if the value of the first sub-packet is greater than the value of * the second sub-packet; otherwise, its value is 0. */ GREATER_THAN(id = 5), /** * A packet whose value is 1 if the value of the first sub-packet is less than the value of the * second sub-packet; otherwise, its value is 0. */ LESS_THAN(id = 6), /** * A packet whose value is 1 if the value of the first sub-packet is equal to the value of the * second sub-packet; otherwise, its value is 0. */ EQUAL_TO(id = 7); /** * Returns the result of applying the operation represented by this packet type to a list of * sub-packet [values]. * * @throws UnsupportedOperationException If this packet type has no associated operation. */ fun applyOperation(values: List<Long>): Long = when (this) { SUM -> values.sum() PRODUCT -> values.product() MINIMUM -> values.minOrNull() ?: 0L MAXIMUM -> values.maxOrNull() ?: 0L LITERAL -> throw UnsupportedOperationException("Not supported for packet type: $this") GREATER_THAN -> { checkBinaryOperatorValues(values) if (values[0] > values[1]) 1L else 0L } LESS_THAN -> { checkBinaryOperatorValues(values) if (values[0] < values[1]) 1L else 0L } EQUAL_TO -> { checkBinaryOperatorValues(values) if (values[0] == values[1]) 1L else 0L } } /** * Checks that a given list of sub-packet [values] is valid for a binary operator packet type. * * @throws IllegalArgumentException If a binary operator can't be applied to [values]. */ private fun checkBinaryOperatorValues(values: List<Long>) { require(values.size == 2) { "$this operation requires exactly 2 values: $values" } } companion object { /** * Returns the [BitsPacketType] corresponding to the given [id]. * * @throws IllegalArgumentException If [id] has no corresponding [BitsPacketType]. */ fun fromID(id: Int): BitsPacketType = entries.find { it.id == id } ?: throw IllegalArgumentException("No packet type for ID: $id") } }
0
Kotlin
1
1
6b64c9eb181fab97bc518ac78e14cd586d64499e
3,164
AdventOfCode
MIT License
kmath-core/src/commonMain/kotlin/scientifik/kmath/operations/Algebra.kt
schakalakka
254,950,505
true
{"Kotlin": 217723}
package scientifik.kmath.operations interface SpaceOperations<T> { /** * Addition operation for two context elements */ fun add(a: T, b: T): T /** * Multiplication operation for context element and real number */ fun multiply(a: T, k: Number): T //Operation to be performed in this context operator fun T.unaryMinus(): T = multiply(this, -1.0) operator fun T.plus(b: T): T = add(this, b) operator fun T.minus(b: T): T = add(this, -b) operator fun T.times(k: Number) = multiply(this, k.toDouble()) operator fun T.div(k: Number) = multiply(this, 1.0 / k.toDouble()) operator fun Number.times(b: T) = b * this } /** * A general interface representing linear context of some kind. * The context defines sum operation for its elements and multiplication by real value. * One must note that in some cases context is a singleton class, but in some cases it * works as a context for operations inside it. * * TODO do we need non-commutative context? */ interface Space<T> : SpaceOperations<T> { /** * Neutral element for sum operation */ val zero: T } interface RingOperations<T> : SpaceOperations<T> { /** * Multiplication for two field elements */ fun multiply(a: T, b: T): T operator fun T.times(b: T): T = multiply(this, b) } /** * The same as {@link Space} but with additional multiplication operation */ interface Ring<T> : Space<T>, RingOperations<T> { /** * neutral operation for multiplication */ val one: T // operator fun T.plus(b: Number) = this.plus(b * one) // operator fun Number.plus(b: T) = b + this // // operator fun T.minus(b: Number) = this.minus(b * one) // operator fun Number.minus(b: T) = -b + this } /** * All ring operations but without neutral elements */ interface FieldOperations<T> : RingOperations<T> { fun divide(a: T, b: T): T operator fun T.div(b: T): T = divide(this, b) } /** * Four operations algebra */ interface Field<T> : Ring<T>, FieldOperations<T> { operator fun Number.div(b: T) = this * divide(one, b) }
0
null
0
0
e52cfcaafe7eb1149170838d9910e54851ba1a92
2,114
kmath
Apache License 2.0
src/main/kotlin/main.kt
zsr2531
354,633,269
false
null
import kotlin.math.max import kotlin.math.min import kotlin.random.Random fun minimax(board: Board): Int { // First, we check if the game is over, and return the score accordingly. if (board.isFinished) { return when (board.winner) { Side.Cross -> 1 Side.Circle -> -1 null -> 0 } } // If the game isn't over yet, we loop over all possible moves from // the current position and try to find the best "value". var value: Int if (board.sideToMove == Side.Cross) { // Cross always tries to get the biggest score. value = -1000 // Effectively negative infinity, as the score of any position is in the set { -1, 0, 1 }. for (move in board.emptySlots()) // If the score is bigger than anything we found previously, set the best score to the newly found one. value = max(value, minimax(board.makeMove(move)!!)) } else { // Circle always tries to get the smallest score. value = 1000 // Effectively infinity, as the score of any position is in the set { -1, 0, 1 }. for (move in board.emptySlots()) // If the score is lower than anything we found previously, set the best score to the newly found one. value = min(value, minimax(board.makeMove(move)!!)) } // And now we return the score. return value } fun bestMove(board: Board): Int? { // There is no best move if the game is over... duh. if (board.isFinished) return null // Assume there is no best move yet. var best: Int? = null val moves = MutableList(0) { 0 } // We loop over every possible move. for (move in board.emptySlots()) { // Calculate the score of the move using our minimax function. val score = minimax(board.makeMove(move)!!) // If there isn't a move yet, we don't need to check if // it's better than anything we found previously. if (best == null) { best = score moves.add(move) continue } // Check whether the current score is better than the best // score we found so far. val isBetter = when (board.sideToMove) { Side.Cross -> best < score Side.Circle -> best > score } // Set `best` accordingly. best = when { // If we have a new best score, clear the `moves` and add the newly found best move. isBetter -> { moves.clear() moves.add(move) score } // If the move is as good as the `best` score, add it as an alternative. best == score -> { moves.add(move) best } // Otherwise (the move is worse), don't do anything. else -> { best } } } // Return one of the best moves that we found. return moves[Random.nextInt(moves.size)] } fun main() { val side: Side while (true) { print("Cross or circle? [x/o] ") val input = readLine() ?: continue if (input != "x" && input != "o") continue side = when (input) { "x" -> Side.Cross "o" -> Side.Circle else -> throw Exception("Unreachable.") } break } var game = Board(Side.Cross) while (!game.isFinished) { var move: Int if (game.sideToMove != side) { move = bestMove(game)!! } else { println(game.toString()) while (true) { print("What's your move? ") val input = readLine() ?: continue val num = input.toIntOrNull() if (num is Int) { move = num break } } } val new = game.makeMove(move) if (new == null) { println("That's an invalid move!") } else { game = new } } println(game.toString()) println( when (game.winner) { Side.Cross -> "Cross wins!" Side.Circle -> "Circle wins!" null -> "It's a draw!" } ) }
0
Kotlin
1
0
5260b0996b776d6f6da737b9dbe60eaa1b4a59cf
4,280
ticwactoe
MIT License
src/main/kotlin/com/sk/leetcode/kotlin/121. Best Time to Buy and Sell Stock.kt
sandeep549
262,513,267
false
{"Kotlin": 530613}
package leetcode.kotlin.array.easy import kotlin.math.max import kotlin.math.min fun main() { check(maxProfit(intArrayOf(7, 1, 5, 3, 6, 4)) == 5) check(maxProfit(intArrayOf(7, 6, 4, 3, 1)) == 0) check(maxProfit3(intArrayOf(7, 1, 5, 3, 6, 4)) == 5) check(maxProfit3(intArrayOf(7, 6, 4, 3, 1)) == 0) check(maxProfit4(intArrayOf(7, 1, 5, 3, 6, 4)) == 5) check(maxProfit4(intArrayOf(7, 6, 4, 3, 1)) == 0) } /** * Try with buy stock on each day and check the profit if we sell it on * every right side of it, retaining max profit found so far. */ private fun maxProfit(prices: IntArray): Int { var max = 0 for (i in 0 until prices.lastIndex) { for (j in i + 1 until prices.lastIndex + 1) { (prices[j] - prices[i]).run { if (this > max) max = this } } } return max } /** * Iterate from left to right, try selling at every point retaining max profit found so far, * and min found so far. */ private fun maxProfit3(arr: IntArray): Int { var min_price_so_far = arr[0] var max_profit_so_far = 0 for (i in 1..arr.lastIndex) { max_profit_so_far = max(max_profit_so_far, arr[i] - min_price_so_far) min_price_so_far = min(min_price_so_far, arr[i]) } return max_profit_so_far } /** * Iterate from left to right, maintain 2 variables min price found so far and max profit found so far. */ private fun maxProfit4(arr: IntArray): Int { var min_price_so_far = arr[0] var max_profit_so_far = 0 for (i in 1..arr.lastIndex) { if (arr[i] < min_price_so_far) { min_price_so_far = arr[i] } else if (arr[i] - min_price_so_far > max_profit_so_far) { max_profit_so_far = arr[i] - min_price_so_far } } return max_profit_so_far }
1
Kotlin
0
0
cf357cdaaab2609de64a0e8ee9d9b5168c69ac12
1,816
leetcode-kotlin
Apache License 2.0
src/day16/second/Solution.kt
verwoerd
224,986,977
false
null
package day16.second import tools.timeSolution import kotlin.math.abs import kotlin.math.min fun main() = timeSolution { val input = readLine()!!.toCharArray().map { (it - '0').toLong() } val offset = input.take(7).joinToString("").toInt() val work = generateInput(input).drop(offset).take(10_000 * input.size - offset).toList() val results = fft(work, offset) println(results.take(8).joinToString("")) } fun generateInput(input: List<Long>) = sequence { var index = -1 while (true) yield(input[++index % input.size]) } // Observation, numbers are only depend on number following them, so no point calculating the ones before them // we can re-use partial sums // Note this code only works for offsets in the second half of the list fun fft(input: List<Long>, position: Int): List<Long> { var result: List<Long> = input.toCollection(mutableListOf()) var phase = 0 while (phase < 100) { var start = 0 var step = position var sum = 0L var sign = 1L while (start < result.size) { sum += result.subList(start, min(start + step, result.size)).sum() * sign start += 2 * position sign *= -1 } result = result.indices.map { index -> if (index != 0) { // Does not deal with the minus part for the first half of the list sum -= result[index - 1] sum += result.subList(min(result.size, step), min(result.size, index + step)).sum() } step++ abs(sum) % 10 } phase++ } return result }
0
Kotlin
0
0
554377cc4cf56cdb770ba0b49ddcf2c991d5d0b7
1,506
AoC2019
MIT License
src/Day08_part2_optimal.kt
rosyish
573,297,490
false
{"Kotlin": 51693}
fun main() { val lines = readInput("Day08_input") val rows = lines.size val cols = lines[0].length val heights = Array(rows) { i -> Array(cols) { j -> lines[i][j] - '0' } } val score = Array(rows) { Array(cols) { 1 } } val outerBounds = listOf(0 until rows, 0 until rows, 0 until cols, 0 until cols) val innerBounds = listOf(0 until cols, cols-1 downTo 0 , 0 until rows, rows - 1 downTo 0) val rowFirst = listOf(true, true, false, false) outerBounds.zip(innerBounds).zip(rowFirst).forEach { val (outer, inner) = it.first val rowFirst = it.second for (i in outer) { // Store tree height and the number of trees that came before strictly smaller than it val stack : ArrayDeque<Pair<Int, Int>> = ArrayDeque(0) for (j in inner) { val r = if (rowFirst) i else j var c = if (rowFirst) j else i var popped = 0 while (stack.isNotEmpty() && stack.last().first < heights[r][c]) { popped += 1 + stack.last().second stack.removeLast() } if (stack.isNotEmpty()) { score[r][c] *= (popped + 1) } else { score[r][c] *= popped } stack.add(Pair(heights[r][c], popped)) } } } println(score.flatten().max()) }
0
Kotlin
0
2
43560f3e6a814bfd52ebadb939594290cd43549f
1,439
aoc-2022
Apache License 2.0
src/main/kotlin/days/Day17.kt
hughjdavey
225,440,374
false
null
package days import common.IntcodeComputer import common.stackOf class Day17 : Day(17) { private fun program() = inputString.split(",").map { it.trim().toLong() }.toMutableList() override fun partOne(): Any { val image = getImage() return getIntersections(image).map { it.alignment }.sum() } override fun partTwo(): Any { val image = getImage() val code = getCode(image) val program = program() program[0] = 2 val computer = IntcodeComputer(program) computer.runWithIO(stackOf(*code.main.toTypedArray())) computer.runWithIO(stackOf(*code.a.toTypedArray())) computer.runWithIO(stackOf(*code.b.toTypedArray())) computer.runWithIO(stackOf(*code.c.toTypedArray())) val out = computer.runWithIO(stackOf(*toAscii("n\n").toTypedArray())) return out.last() } fun getImage(cameraOutput: List<Long> = emptyList()): String { val output = if (cameraOutput.isNotEmpty()) cameraOutput else { val computer = IntcodeComputer(program()) computer.runWithIO(stackOf()) } return output.fold("") { acc, elem -> acc + elem.toChar() } } fun withIntersections(image: String): String { val rows = image.split('\n') val intersections = getIntersections(image) return rows.mapIndexed { y, row -> row.mapIndexed { x, char -> if (intersections.find { it.coord == x to y } != null) 'O' else char }.joinToString("") }.joinToString("\n") } fun getIntersections(image: String): List<Intersection> { val rows = image.split('\n') return rows.foldIndexed(listOf()) { y, intersections, row -> if (y == 0 || y == row.lastIndex) intersections else { val matches = row.windowed(3).mapIndexed { w, s -> if (s.all { it == '#' } && rows[y - 1][w + 1] == '#' && rows[y + 1][w + 1] == '#') Intersection(w + 1 to y) else null }.filterNotNull() intersections.plus(matches) } } } fun getScaffoldPath(image: String): String { val array: Array<Array<Char>> = image.split('\n').filterNot { it.isEmpty() }.map { it.toList().toTypedArray() }.toTypedArray() var robot = Robot(RobotDirection.UP, 0 to 0) var scaffoldEnd = 0 to 0 array.forEachIndexed { y, row -> row.forEachIndexed { x, char -> if (char == '#' && getNeighbours(x, y, array).filterNot { it == '.' } == listOf('#')) { scaffoldEnd = x to y } if (RobotDirection.values().map { it.value }.contains(char)) { robot = Robot(RobotDirection.fromValue(char), x to y) } } } val path = StringBuilder() while (robot.position != scaffoldEnd) { val lrIndices = when (robot.direction) { RobotDirection.UP -> 0 to 1 RobotDirection.DOWN -> 1 to 0 RobotDirection.LEFT -> 3 to 2 RobotDirection.RIGHT -> 2 to 3 } val neighbours = getNeighbours(robot.position.first, robot.position.second, array) val (left, right) = listOf(neighbours[lrIndices.first], neighbours[lrIndices.second]) val goLeft = left == '#' robot.turn(goLeft) val steps = robot.goUntilTurn(array) path.append(if (goLeft) 'L' else 'R').append(',').append(steps).append(',') } return path.toString().dropLast(1) } fun getCode(image: String): RobotCode { // hardcoded from manual solving - todo make it work for any input // scaffoldPath was L,12,L,12,R,12,L,12,L,12,R,12,L,8,L,8,R,12,L,8,L,8,L,10,R,8,R,12,L,10,R,8,R,12,L,12,L,12,R,12,L,8,L,8,R,12,L,8,L,8,L,10,R,8,R,12,L,12,L,12,R,12,L,8,L,8,R,12,L,8,L,8 return RobotCode("A,A,B,C,C,A,B,C,A,B", "L,12,L,12,R,12", "L,8,L,8,R,12,L,8,L,8", "L,10,R,8,R,12") } private fun getNeighbours(x: Int, y: Int, array: Array<Array<Char>>): List<Char> { val left = if (x == 0) '.' else array[y][x - 1] val right = if (x == array[0].lastIndex) '.' else array[y][x + 1] val up = if (y == 0) '.' else array[y - 1][x] val down = if (y == array.lastIndex) '.' else array[y + 1][x] return listOf(left, right, up, down) } companion object { fun toAscii(code: String, addNewline: Boolean = true): List<Long> { val ascii = code.toList().map { it.toLong() } return if (addNewline) ascii.plus(10) else ascii } } class RobotCode(main: String, a: String, b: String, c: String) { val main = toAscii(main) val a = toAscii(a) val b = toAscii(b) val c = toAscii(c) } data class Robot(var direction: RobotDirection, var position: Pair<Int, Int>) { fun goUntilTurn(array: Array<Array<Char>>): Int { var next = nextPosition() var count = 0 while (array[next.second][next.first] == '#') { position = next count++ next = nextPosition() if (next.first < 0 || next.first > array[0].lastIndex || next.second < 0 || next.second > array.lastIndex) { break } } return count } fun turn(left: Boolean) { direction = if (left) direction.turnLeft() else direction.turnRight() } private fun nextPosition(): Pair<Int, Int> { return when (direction) { RobotDirection.UP -> position.first to position.second - 1 RobotDirection.DOWN -> position.first to position.second + 1 RobotDirection.LEFT -> position.first - 1 to position.second RobotDirection.RIGHT -> position.first + 1 to position.second } } } enum class RobotDirection(val value: Char) { UP('^'), DOWN('v'), LEFT('<'), RIGHT('>'); fun turnLeft(): RobotDirection { return when (this) { UP -> LEFT DOWN -> RIGHT LEFT -> DOWN RIGHT -> UP } } fun turnRight(): RobotDirection { return when (this) { UP -> RIGHT DOWN -> LEFT LEFT -> UP RIGHT -> DOWN } } companion object { fun fromValue(value: Char): RobotDirection = values().find { it.value == value } ?: throw IllegalArgumentException("Bad robot state: $value") } } data class Intersection(val coord: Pair<Int, Int>, val alignment: Int = coord.first * coord.second) }
0
Kotlin
0
1
84db818b023668c2bf701cebe7c07f30bc08def0
6,762
aoc-2019
Creative Commons Zero v1.0 Universal
src/Day01.kt
kent10000
573,114,356
false
{"Kotlin": 11288}
fun main() { fun getElfCalories(input: List<String>): List<Int> { val elfCalories = mutableListOf(0) for (value in input) { if (value.isBlank()) { elfCalories.add(0) continue } elfCalories[elfCalories.size - 1] += value.toInt() } return elfCalories } fun part1(input: List<String>): Int { val elfCalories = getElfCalories(input) return elfCalories.max() } fun part2(input: List<String>): Int { val elfCalories = getElfCalories(input).sortedByDescending { it } return elfCalories.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
c128d05ab06ecb2cb56206e22988c7ca688886ad
911
advent-of-code-2022
Apache License 2.0
src/Day08.kt
janbina
112,736,606
false
null
package day08 import getInput import kotlin.test.assertEquals data class Instruction( val name: String, val operation: (Int) -> Int, val condName: String, val condition: (Int) -> Boolean ) { companion object { fun fromString(input: String): Instruction { val parts = input.split(Regex("\\s+")) val condition: (Int) -> Boolean = when (parts[5]) { "<" -> { a -> a < parts[6].toInt() } ">" -> { a -> a > parts[6].toInt() } "<=" -> { a -> a <= parts[6].toInt() } ">=" -> { a -> a >= parts[6].toInt() } "==" -> { a -> a == parts[6].toInt() } "!=" -> { a -> a != parts[6].toInt() } else -> throw IllegalArgumentException("Invalid condition operator: ${parts[5]}") } val operation: (Int) -> Int = when (parts[1]) { "inc" -> { a -> a + parts[2].toInt() } "dec" -> { a -> a - parts[2].toInt() } else -> throw IllegalArgumentException("Invalid operator: ${parts[1]}") } return Instruction(parts[0], operation, parts[4], condition) } } } fun main(args: Array<String>) { val input = getInput(8).readLines().map { Instruction.fromString(it) } val result = execute(input) assertEquals(5215, result.first) assertEquals(6419, result.second) } fun execute(input: List<Instruction>): Pair<Int, Int> { val registers = mutableMapOf<Int, Int>() var maxValue = 0 for (inst in input) { val condValue = registers.getOrDefault(inst.condName.hashCode(), 0) val targetValue = registers.getOrDefault(inst.name.hashCode(), 0) if (inst.condition(condValue)) { val newValue = inst.operation(targetValue) registers.put(inst.name.hashCode(), newValue) if (newValue > maxValue) { maxValue = newValue } } } val endMax = registers.values.max() ?: 0 return endMax to maxValue }
0
Kotlin
0
0
71b34484825e1ec3f1b3174325c16fee33a13a65
2,074
advent-of-code-2017
MIT License
src/main/kotlin/days/impl/Day3.kt
errob37
726,532,024
false
{"Kotlin": 29748, "Shell": 408}
package days.impl import days.model.* class Day3() : AdventOfCodeDayImpl(3, 4361L, 467835L) { override fun partOne(input: List<String>): Long { val engineSchematic = extractEngineSchematic(input) val (numbers, symbols) = extractPosition(engineSchematic) return symbols .map { numbers.filter { n -> n.areaCovered.contains(it) } } .flatten() .toSet() .sumOf(NumberPosition::number) } override fun partTwo(input: List<String>): Long { val engineSchematic = extractEngineSchematic(input) val (numbers, symbols) = extractPosition(engineSchematic) val gears = symbols.filter { it.isGear } return gears .map { numbers.filter { n -> n.areaCovered.contains(it) } } .filter { it.size == 2 } .sumOf { it[0].number * it[1].number } } internal fun extractPosition(engineSchematic: List<SchematicEngineRow>) = Pair( engineSchematic .mapIndexed { i, it -> extractNumberFromRow(i, it.schematicInformations) } .flatten(), engineSchematic .mapIndexed { i, it -> extractSymbolFromRow(i, it.schematicInformations) } .flatten() ) internal fun extractEngineSchematic(input: List<String>) = input.mapIndexed(this::extractEngineSchematicRow) internal fun extractEngineSchematicRow(rowNumber: Int, row: String): SchematicEngineRow { val infos = row.asSequence().mapIndexed(this::toEngineSchematicInformation).toList() return SchematicEngineRow(rowNumber, infos) } internal fun extractSymbolFromRow(rowNumber: Int, infos: List<SchematicInformation>): List<SymbolPosition> = infos.mapIndexedNotNull { i, it -> if (it.informationType in listOf(InformationType.SYMBOL)) { SymbolPosition(it.value, rowNumber, i) } else { null } } internal fun extractNumberFromRow(rowNumber: Int, infos: List<SchematicInformation>): List<NumberPosition> { var currentNumber: String? = null var startRange = 0 val numbers = mutableListOf<NumberPosition>() infos.mapIndexed { index, schematicInformation -> if (schematicInformation.informationType == InformationType.DIGIT) { if (currentNumber == null) { currentNumber = schematicInformation.value.toString() startRange = index if (index + 1 == infos.size) { numbers.add(NumberPosition(currentNumber!!.toLong(), rowNumber, IntRange(startRange, index))) currentNumber = null } } else { currentNumber += schematicInformation.value.toString() if (index + 1 == infos.size) { numbers.add(NumberPosition(currentNumber!!.toLong(), rowNumber, IntRange(startRange, index))) currentNumber = null } } } else { if (currentNumber != null) { numbers.add(NumberPosition(currentNumber!!.toLong(), rowNumber, IntRange(startRange, index - 1))) currentNumber = null } } } return numbers } internal fun toEngineSchematicInformation(column: Int, value: Char): SchematicInformation = SchematicInformation( column, when { value.isDigit() -> InformationType.DIGIT '.' == value -> InformationType.PERIOD else -> InformationType.SYMBOL }, value ) }
0
Kotlin
0
0
79db6f0f56d207b68fb89425ad6c91667a84d60f
3,795
adventofcode-2023
Apache License 2.0
src/day3/Code.kt
fcolasuonno
225,219,560
false
null
package day3 import isDebug import java.io.File import kotlin.math.abs fun main() { val name = if (isDebug()) "test.txt" else "input.txt" System.err.println(name) val dir = ::main::class.java.`package`.name val input = File("src/$dir/$name").readLines() val parsed = parse(input) println("Part 1 = ${part1(parsed)}") println("Part 2 = ${part2(parsed)}") } data class Movement(val d: Char, val steps: Int) { fun points(point: Point): List<Point> = (1..steps).map { when (d) { 'U' -> point.copy(y = point.y - it) 'D' -> point.copy(y = point.y + it) 'L' -> point.copy(x = point.x - it) else -> point.copy(x = point.x + it) } } } data class Point(val x: Int, val y: Int) fun parse(input: List<String>) = input.map { it.split(',').map { Movement(it.first(), it.substring(1).toInt()) } .fold(mutableListOf(Point(0, 0)) as List<Point>) { path, movement -> path + movement.points(path.last()) } }.requireNoNulls().let { (path1, path2) -> Pair(path1, path2) } fun part1(input: Pair<List<Point>, List<Point>>) = input.let { (path1, path2) -> path1.intersect(path2).map { abs(it.x) + abs(it.y) }.filterNot { it == 0 }.min() } fun part2(input: Pair<List<Point>, List<Point>>) = input.let { (path1, path2) -> val otherPath = path2.toSet() path1.asSequence().withIndex().filter { it.value in otherPath }.map { intersection -> intersection.index + path2.indexOf(intersection.value) }.filterNot { it == 0 }.min() }
0
Kotlin
0
0
d1a5bfbbc85716d0a331792b59cdd75389cf379f
1,541
AOC2019
MIT License
src/main/kotlin/adventofcode2018/Day04ReposeRecord.kt
n81ur3
484,801,748
false
{"Kotlin": 476844, "Java": 275}
package adventofcode2018 import java.time.LocalDateTime import java.time.format.DateTimeFormatter class Day04ReposeRecord data class Guard(val id: Int) data class SleepPeriod(val start: LocalDateTime, val stop: LocalDateTime) sealed class ShiftEntry( val dateTime: LocalDateTime, val guard: Guard = Guard(-1), val awake: Boolean = false, val asleep: Boolean = false ) { companion object { val dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm") fun fromString(input: String): ShiftEntry { val dateTime = LocalDateTime.parse(input.substring(1).substringBefore("] "), dateFormatter) return when { input.contains("Guard") -> NewGuardEntry( dateTime, Guard(input.substringAfter("#").substringBefore(" ").toInt()) ) input.contains("asleep") -> AsleepEntry(dateTime) else -> AwakeEntry(dateTime) } } } override fun toString(): String { return "ShiftEntry(dateTime=$dateTime, guard=$guard, awake=$awake, asleep=$asleep)" } } class NewGuardEntry(dateTime: LocalDateTime, guard: Guard) : ShiftEntry(dateTime, guard, awake = true) class AsleepEntry(dateTime: LocalDateTime) : ShiftEntry(dateTime, asleep = true) class AwakeEntry(dateTime: LocalDateTime) : ShiftEntry(dateTime, awake = true) class ShiftPlan(input: List<String>) { val entries: List<ShiftEntry> var currentGuard = Guard(-1) var currentStartSleep = LocalDateTime.now() val guardRecords = mutableMapOf<Guard, MutableList<SleepPeriod>>() var guardSleeping = false init { entries = input.map { ShiftEntry.fromString(it) }.sortedBy { it.dateTime } } fun scheduleShifts() { entries.forEach { entry -> when (entry) { is NewGuardEntry -> { if (guardRecords[entry.guard] == null) { guardRecords[entry.guard] = mutableListOf() } if (guardSleeping) { recordSleep(entry.dateTime.minusMinutes(1)) guardSleeping = false } currentGuard = entry.guard } is AsleepEntry -> { currentStartSleep = entry.dateTime guardSleeping = true } is AwakeEntry -> { recordSleep(entry.dateTime.minusMinutes(1)) guardSleeping = false } } } } private fun recordSleep(endSleep: LocalDateTime) { guardRecords[currentGuard]?.add(SleepPeriod(currentStartSleep, endSleep)) } fun findBestGuardAndMinute(): Pair<Guard, Int> { val bestGuard = findBestGuard() val bestMinute = findBestMinute(bestGuard) return bestGuard to bestMinute } private fun findBestGuard(): Guard { val sleepTimes = guardRecords.map { records -> val totalSleep = records.value.sumOf { it.stop.minute - it.start.minute } records.key to totalSleep } return sleepTimes.maxBy { it.second }.first } private fun findBestMinute(guard: Guard): Int { var result = 0 guardRecords[guard]?.let { result = getMostFrequentMinute(it).first } return result } fun findBestGuardMostFrequentMinute(): Pair<Guard, Int> { val groupedEntries = guardRecords .filter { it.value.size > 0 } .map { it.key to getMostFrequentMinute(it.value) } val maxEntry = groupedEntries.maxBy { it.second.second } return maxEntry.first to maxEntry.second.first } private fun getMostFrequentMinute(sleepPeriods: List<SleepPeriod>): Pair<Int, Int> { val minutes = mutableListOf<Int>() sleepPeriods.forEach { sleepPeriod -> (sleepPeriod.start.minute..sleepPeriod.stop.minute).forEach { minutes.add(it) } } val sleepMinutesGroups = minutes.groupBy { it } val result = sleepMinutesGroups.maxByOrNull { it.value.size } return result?.let { result.key to result.value.size } ?: (-1 to 0) } }
0
Kotlin
0
0
fdc59410c717ac4876d53d8688d03b9b044c1b7e
4,326
kotlin-coding-challenges
MIT License
src/main/kotlin/se/saidaspen/aoc/aoc2021/Day17.kt
saidaspen
354,930,478
false
{"Kotlin": 301372, "CSS": 530}
package se.saidaspen.aoc.aoc2021 import se.saidaspen.aoc.util.* fun main() = Day17.run() object Day17 : Day(2021, 17) { var ints = ints(input) private var xRange = IntRange(ints[0], ints[1]) private var yRange = IntRange(ints[2], ints[3]) override fun part1() = (0..250).flatMap { x -> (-250..500).map { y-> P(x, y) }}.map { shoot(it) }.filter { it.first }.maxOf { it.second } override fun part2()= (0..250).flatMap { x -> (-250..500).map { y-> P(x, y) }}.map { shoot(it) }.count { it.first } private fun shoot(vStart: Pair<Int, Int>) : Pair<Boolean, Int> { var pos = P(0,0) var v = vStart var maxHeight = Int.MIN_VALUE val yMin = yRange.minOrNull()!! while(pos.y > yMin) { pos += v maxHeight = maxHeight.coerceAtLeast(pos.y) if (pos.first in xRange && pos.second in yRange) { return P(true, maxHeight) } v = P(if (v.first > 0) v.first-1 else if (v.first< 0) v.first+1 else 0, v.second-1) } return P(false, maxHeight) } }
0
Kotlin
0
1
be120257fbce5eda9b51d3d7b63b121824c6e877
1,095
adventofkotlin
MIT License
src/main/kotlin/days/Day6.kt
mstar95
317,305,289
false
null
package days import util.groupByEmpty class Day6 : Day(6) { override fun partOne(): Any { val groups: List<List<String>> = groupByEmpty(inputList) val forms = flatten(groups) val answers = forms.map { form -> form.distinct().size } return answers.fold(0, {sum, elem -> sum + elem}); } override fun partTwo(): Any { val groups: List<List<String>> = groupByEmpty(inputList) val answers = groups.map { countCommon(it) } print(answers) return answers.fold(0, {sum, elem -> sum + elem}); } } private fun countCommon(group: List<String>): Int { return group.map { it.toSet() } .reduce { acc, set -> acc.intersect(set) } .size } private fun flatten(groups: List<List<String>>): List<List<String>> { return groups.map { group -> group.flatMap { letters -> letters.map { it.toString() } } } }
0
Kotlin
0
0
ca0bdd7f3c5aba282a7aa55a4f6cc76078253c81
936
aoc-2020
Creative Commons Zero v1.0 Universal
AdventOfCode/Challenge2023Day11.kt
MartinWie
702,541,017
false
{"Kotlin": 90565}
import org.junit.Test import java.io.File import kotlin.math.abs import kotlin.test.assertEquals class Challenge2023Day11 { private fun solve1(lines: List<String>): Int { val map = mutableListOf<String>() // First lets expand the map for (line in lines) { map.add(line) // If the line does not contain any galaxies we can conveniently use it to add it to the expanded map if (line.replace(".", "").isEmpty()) map.add(line) } val columnsToExpand = (0 until map[0].length).map { columnIndex -> map.all { row -> row[columnIndex] == '.' } } val expandedMap = map.map { row -> row.mapIndexed { index, char -> if (columnsToExpand[index]) "$char$char" else char }.joinToString("") } // Implement Galaxy numeration (use currentGalaxyAmount) // More efficient would be to also do the galaxy enumeration in the former steps. // (Decision here readability > performance) // The list "finalMap" is currently not necessary, but I will keep it for now var currentGalaxyAmount = 0 val finalMap = mutableListOf<String>() val galaxyCords = mutableListOf<Pair<Int, Int>>() for ((y, line) in expandedMap.withIndex()) { val newLine = StringBuilder() for ((x, char) in line.withIndex()) { if (char == '#') { newLine.append(currentGalaxyAmount) currentGalaxyAmount++ galaxyCords.add(x to y) } else { newLine.append(char) } } finalMap.add(newLine.toString()) } // Implement path calculation val pathsHashMap = HashMap<Pair<Pair<Int, Int>, Pair<Int, Int>>, Int>() for (pos1 in galaxyCords) { for (pos2 in galaxyCords) { if (pathsHashMap[pos1 to pos2] == null && pathsHashMap[pos2 to pos1] == null) { pathsHashMap[pos1 to pos2] = (abs(pos1.first - pos2.first) + abs(pos1.second - pos2.second)) } } } return pathsHashMap.values.sum() } @Test fun test() { val lines = File("./AdventOfCode/Data/Day11-1-Test-Data.txt").bufferedReader().readLines() val exampleSolution1 = solve1(lines) println("Example solution 1: $exampleSolution1") assertEquals(374, exampleSolution1) val realLines = File("./AdventOfCode/Data/Day11-1-Data.txt").bufferedReader().readLines() val solution1 = solve1(realLines) println("Solution 1: $solution1") assertEquals(9623138, solution1) } }
0
Kotlin
0
0
47cdda484fabd0add83848e6000c16d52ab68cb0
2,793
KotlinCodeJourney
MIT License
src/day13/Day13.kt
GrzegorzBaczek93
572,128,118
false
{"Kotlin": 44027}
package day13 import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.int import readInput import utils.multiply import utils.withStopwatch fun main() { val testInput = readInput("input13_test") withStopwatch { println(part1(testInput)) } withStopwatch { println(part2(testInput + listOf("[[2]]", "[[6]]"))) } val input = readInput("input13") withStopwatch { println(part1(input)) } withStopwatch { println(part2(input + listOf("[[2]]", "[[6]]"))) } } private fun part1(input: List<String>) = input.windowed(2, 3) .mapIndexed { index, data -> index + 1 to compare(data) } .filter { it.second == 1 } .sumOf { it.first } private fun part2(input: List<String>) = input.asSequence().filter { it.isNotBlank() } .map { decode(it) } .sorted() .mapIndexed { index, node -> index + 1 to node } .filter { it.second == Node.NodeList(listOf(Node.NodeList(listOf(Node.NodeValue(2))))) || it.second == Node.NodeList(listOf(Node.NodeList(listOf(Node.NodeValue(6))))) } .map { it.first }.toList() .multiply() private fun compare(input: List<String>): Int { val (first, second) = input return decode(first).compare(decode(second)) } private fun decode(input: String): Node = parseJson(Json.parseToJsonElement(input)) private fun parseJson(jsonElement: JsonElement): Node { return when (jsonElement) { is JsonArray -> Node.NodeList(jsonElement.map { parseJson(it) }) is JsonPrimitive -> Node.NodeValue(jsonElement.int) else -> error("Unknown element") } }
0
Kotlin
0
0
543e7cf0a2d706d23c3213d3737756b61ccbf94b
1,725
advent-of-code-kotlin-2022
Apache License 2.0
year2020/day18/part2/src/main/kotlin/com/curtislb/adventofcode/year2020/day18/part2/Year2020Day18Part2.kt
curtislb
226,797,689
false
{"Kotlin": 2146738}
/* --- Part Two --- You manage to answer the child's questions and they finish part 1 of their homework, but get stuck when they reach the next section: advanced math. Now, addition and multiplication have different precedence levels, but they're not the ones you're familiar with. Instead, addition is evaluated before multiplication. For example, the steps to evaluate the expression 1 + 2 * 3 + 4 * 5 + 6 are now as follows: 1 + 2 * 3 + 4 * 5 + 6 3 * 3 + 4 * 5 + 6 3 * 7 * 5 + 6 3 * 7 * 11 21 * 11 231 Here are the other examples from above: - 1 + (2 * 3) + (4 * (5 + 6)) still becomes 51. - 2 * 3 + (4 * 5) becomes 46. - 5 + (8 * 3 + 9 + 3 * 4 * 3) becomes 1445. - 5 * 9 * (7 * 3 * 3 + 9 * 3 + (8 + 6 * 4)) becomes 669060. - ((2 + 4 * 9) * (6 + 9 * 8 + 6) + 6) + 2 + 4 * 2 becomes 23340. What do you get if you add up the results of evaluating the homework problems using these new rules? */ package com.curtislb.adventofcode.year2020.day18.part2 import com.curtislb.adventofcode.year2020.day18.expression.evaluateAdvanced import java.nio.file.Path import java.nio.file.Paths /** * Returns the solution to the puzzle for 2020, day 18, part 2. * * @param inputPath The path to the input file for this puzzle. */ fun solve(inputPath: Path = Paths.get("..", "input", "input.txt")): Long { val file = inputPath.toFile() var total = 0L file.forEachLine { total += evaluateAdvanced(it) } return total } fun main() { println(solve()) }
0
Kotlin
1
1
6b64c9eb181fab97bc518ac78e14cd586d64499e
1,510
AdventOfCode
MIT License
arrays/RemoveDuplicatesFromSortedArray/kotlin/Solution.kt
YaroslavHavrylovych
78,222,218
false
{"Java": 284373, "Kotlin": 35978, "Shell": 2994}
/** * Given a sorted array nums, remove the duplicates in-place such * that each element appears only once and returns the new length. * Do not allocate extra space for another array, you must * do this by modifying the input array in-place with O(1) extra memory. * Clarification: * Confused why the returned value is an integer but your answer is an array? * Note that the input array is passed in by reference, which means * a modification to the input array will be known to the caller as well. * Internally you can think of this: * // nums is passed in by reference. (i.e., without making a copy) * int len = removeDuplicates(nums); * * // any modification to nums in your function would be known by the caller. * // using the length returned by your function, * //it prints the first len elements. * for (int i = 0; i < len; i++) { * print(nums[i]); * } * <br/> * https://leetcode.com/problems/remove-duplicates-from-sorted-array/ */ class Solution { fun removeDuplicates(a: IntArray): Int { var i = 0 var j = 1 while(j < a.size) { if(a[i] != a[j]) { if(i + 1 != j) a[i + 1] = a[j] i += 1 } j += 1 } return i + 1 } } fun main() { println("Remove Duplicates from Sorted Array: test is not implemented") }
0
Java
0
2
cb8e6f7e30563e7ced7c3a253cb8e8bbe2bf19dd
1,362
codility
MIT License
src/main/kotlin/se/saidaspen/aoc/aoc2017/Day10.kt
saidaspen
354,930,478
false
{"Kotlin": 301372, "CSS": 530}
package se.saidaspen.aoc.aoc2017 import se.saidaspen.aoc.util.Day import se.saidaspen.aoc.util.ints import kotlin.streams.toList fun main() = Day10.run() object Day10 : Day(2017, 10) { private val ropeLen = 256 override fun part1(): String { val rope = generateSequence(0) { it + 1 }.take(ropeLen).toMutableList() var currPos = 0 val lenSeq: MutableList<Int> = ints(input).toMutableList() for ((skipSize, n) in lenSeq.withIndex()) { val tmp = mutableListOf<Int>() val indexes = (0 until n).map { (it + currPos) % rope.size }.toList() for (j in indexes) tmp.add(rope[j]) for (k in indexes) rope[k] = tmp.removeLast() currPos = (currPos + n + skipSize) % rope.size } return (rope[0] * rope[1]).toString() } override fun part2(): String { return KnotHasher(ropeLen).hash(input) } } class KnotHasher(val len: Int) { fun hash(inp: String): String { val rope = generateSequence(0) { it + 1 }.take(len).toMutableList() var currPos = 0 var skipSize = 0 val lenSeq: MutableList<Int> = inp.chars().toList().toMutableList() lenSeq.addAll(listOf(17, 31, 73, 47, 23)) for (i in 0 until 64) { for (n in lenSeq) { val tmp = mutableListOf<Int>() val indexes = (0 until n).map { (it + currPos) % rope.size }.toList() for (j in indexes) tmp.add(rope[j]) for (k in indexes) rope[k] = tmp.removeLast() currPos = (currPos + n + skipSize) % rope.size skipSize++ } } return dense(rope) } private fun dense(rope: List<Int>): String { return rope.chunked(16) .map { it.reduce { acc, i -> acc.xor(i) } } .joinToString("") { "%02x".format(it) } } }
0
Kotlin
0
1
be120257fbce5eda9b51d3d7b63b121824c6e877
1,898
adventofkotlin
MIT License
src/main/kotlin/puzzle7/WhaleBuster.kt
tpoujol
436,532,129
false
{"Kotlin": 47470}
package puzzle7 import kotlin.math.abs import kotlin.math.floor import kotlin.math.roundToInt import kotlin.system.measureTimeMillis fun main() { val whaleBuster = WhaleBuster() val time = measureTimeMillis { println("Minimal fuel consumption is: ${whaleBuster.findCrabAlignment()}") println("Total fuel consumption with cost increased by distance is: ${whaleBuster.findCrabAlignmentWithCostProblems()}") } println("Time: ${time}ms") } class WhaleBuster { private val input = WhaleBuster::class.java.getResource("/input/puzzle7.txt") ?.readText() ?.split(",") ?.map { it.toInt() } ?: listOf() fun findCrabAlignment(): Int { val distanceValues = (0..input.maxOf { it }).associateWith { position -> input.sumOf { crabPosition -> abs(crabPosition - position) } } println(distanceValues) val inputNumber = input.size val sortedInput = input.sorted() val median = if (inputNumber % 2 == 1) { sortedInput[floor(inputNumber / 2.0).toInt()] } else { (sortedInput[inputNumber / 2] + sortedInput[inputNumber / 2]) / 2 } println("median is: $median") return sortedInput.sumOf { abs(it - median) } } fun findCrabAlignmentWithCostProblems(): Int { val distanceValues = (0..input.maxOf { it }).associateWith { position -> input.sumOf { crabPosition -> val distance = abs(crabPosition - position) (distance * (distance + 1) / 2.0).roundToInt() } } val optimalPosition = distanceValues.minByOrNull { it.value } println("Optimal Position is: $optimalPosition") return optimalPosition?.value ?: 0 } }
0
Kotlin
0
1
6d474b30e5204d3bd9c86b50ed657f756a638b2b
1,815
aoc-2021
Apache License 2.0
src/Day22.kt
kpilyugin
572,573,503
false
{"Kotlin": 60569}
fun main() { val up = Vec2(-1, 0) val right = Vec2(0, 1) val down = Vec2(1, 0) val left = Vec2(0, -1) val dirs = listOf(right, down, left, up) data class Input(val table: List<String>, val commands: List<String>) fun parseInput(input: String): Input { val (tableStr, cmds) = input.split("\n\n") val table = tableStr.lines().toMutableList() val maxLength = table.maxOf { it.length } for (i in table.indices) { table[i] = table[i] + " ".repeat(maxLength - table[i].length) } val commands = Regex("([0-9]+)([^[0-9]])?+") .findAll(cmds) .flatMap { match -> match.groupValues.drop(1).filter { it.isNotEmpty() } } .toList() return Input(table, commands) } fun score(i: Int, j: Int, dir: Vec2) = 1000 * (i + 1) + 4 * (j + 1) + dirs.indexOf(dir) fun part1(input: String): Int { val (table, commands) = parseInput(input) var i = 0 var j = table[0].indexOfFirst { it == '.' } var dir = right fun go(steps: Int) { repeat(steps) { if (dir.x != 0) { var nextI = i + dir.x if (nextI !in table.indices || table[nextI][j] == ' ') { nextI = if (dir.x == 1) { table.indexOfFirst { it[j] != ' ' } } else { table.indexOfLast { it[j] != ' ' } } } if (table[nextI][j] != '#') { i = nextI } else return } else { var nextJ = j + dir.y val row = table[i] if (nextJ !in row.indices || row[nextJ] == ' ') { nextJ = if (dir.y == 1) row.indexOfFirst { it != ' ' } else row.indexOfLast { it != ' ' } } if (row[nextJ] != '#') { j = nextJ } else return } } } for (command in commands) { when (command) { "L" -> dir = dirs[(dirs.indexOf(dir) - 1).mod(4)] "R" -> dir = dirs[(dirs.indexOf(dir) + 1).mod(4)] else -> go(command.toInt()) } } return score(i, j, dir) } data class Vec3(val x: Int, val y: Int, val z: Int) { operator fun unaryMinus(): Vec3 = Vec3(-x, -y, -z) override fun toString() = "($x, $y, $z)" } class Side(val normal: Vec3) { lateinit var texturePos: Vec2 lateinit var textureDown: Vec3 fun isNotWrapped() = !this::texturePos.isInitialized } fun start(table: List<String>): Vec2 { for (i in table.indices) { for (j in table[0].indices) { if (table[i][j] != ' ') return Vec2(i, j) } } throw IllegalStateException() } fun rotateVector(vec: Vec3, sin: Int, normal: Vec3): Vec3 { val (x, y, z) = normal val m0 = intArrayOf(x * x, x * y - z * sin, z + y * sin) val m1 = intArrayOf(x * y + z * sin, y * y , y * z - x * sin) val m2 = intArrayOf(x * z - y * sin, y * z + x * sin, z * z) return Vec3( m0[0] * vec.x + m0[1] * vec.y + m0[2] * vec.z, m1[0] * vec.x + m1[1] * vec.y + m1[2] * vec.z, m2[0] * vec.x + m2[1] * vec.y + m2[2] * vec.z ) } fun part2(input: String, sideSize: Int): Int { val (table, commands) = parseInput(input) val sides = listOf( Side(Vec3(0, 0, 1)), Side(Vec3(0, 0, -1)), Side(Vec3(0, 1, 0)), Side(Vec3(0, -1, 0)), Side(Vec3(1, 0, 0)), Side(Vec3(-1, 0, 0)), ) fun wrap(side: Side, pos: Vec2, down: Vec3) { println("Wrap: side normal = ${side.normal}, pos = $pos, down = $down") side.texturePos = pos side.textureDown = down for ((flatDir, rotation) in listOf( Vec2(0, 1) to 1, Vec2(0, -1) to -1, Vec2(1, 0) to 0 )) { val newPos = pos + flatDir * sideSize if (newPos.x in table.indices && newPos.y in table[0].indices && table[newPos.x][newPos.y] != ' ') { val sideDir = if (rotation != 0) rotateVector(down, rotation, side.normal) else down val newSide = sides.first { it.normal == sideDir } if (newSide.isNotWrapped()) { var newDown = -side.normal if (rotation != 0) newDown = rotateVector(newDown, -rotation, newSide.normal) wrap(newSide, newPos, newDown) } } } } wrap(sides[0], start(table), Vec3(0, -1, 0)) var side = sides[0] var pos = side.texturePos var dir = right var dir3d = rotateVector(side.textureDown, 1, side.normal) fun Side.findTextureDir(dir: Vec3): Vec2 { var res = down var current = textureDown repeat(5) { if (current == dir) { return res } res = dirs[(dirs.indexOf(res) + 1).mod(4)] current = rotateVector(current, -1, normal) } throw IllegalStateException() } fun positionOnSide(): Int { val relX = pos.x - side.texturePos.x val relY = pos.y - side.texturePos.y return when (dir) { left -> sideSize - 1 - relX right -> relX up -> relY down -> sideSize - 1 - relY else -> throw IllegalStateException() } } fun fromPositionOnSide(linePos: Int, dir: Vec2): Vec2 { return when (dir) { left -> Vec2(linePos, sideSize - 1) right -> Vec2(sideSize - 1 - linePos, 0) up -> Vec2(sideSize - 1, sideSize - 1 - linePos) down -> Vec2(0, linePos) else -> throw IllegalStateException() } } fun go(steps: Int) { repeat(steps) { step -> var nextPos = pos + dir var nextSide = side var nextDir = dir var nextDir3d = dir3d val startX = side.texturePos.x val startY = side.texturePos.y if (nextPos.x !in startX until startX + sideSize || nextPos.y !in startY until startY + sideSize) { nextSide = sides.first { it.normal == dir3d } nextDir3d = -side.normal nextDir = nextSide.findTextureDir(nextDir3d) val linePos = sideSize - 1 - positionOnSide() // println("Switch: dir = $dir, nextDir = $nextDir, linePos = $linePos") nextPos = fromPositionOnSide(linePos, nextDir) nextPos += nextSide.texturePos } if (table[nextPos.x][nextPos.y] != '#') { side = nextSide pos = nextPos dir = nextDir dir3d = nextDir3d } else return // println("After step $step: x = ${pos.x}, y = ${pos.y}, side = ${side.normal}, dir = $dir, dir3d = $dir3d") } } for (command in commands) { when (command) { "L" -> { dir = dirs[(dirs.indexOf(dir) - 1).mod(4)] dir3d = rotateVector(dir3d, 1, side.normal) } "R" -> { dir = dirs[(dirs.indexOf(dir) + 1).mod(4)] dir3d = rotateVector(dir3d, -1, side.normal) } else -> go(command.toInt()) } // println("After command $command: x = ${pos.x}, y = ${pos.y}, side = ${side.normal}, dir = $dir, dir3d = $dir3d") } return score(pos.x, pos.y, dir) } val testInput = readInput("Day22_test") check(part1(testInput), 6032) check(part2(testInput, 4), 5031) val input = readInput("Day22") println(part1(input)) println(part2(input, 50)) }
0
Kotlin
0
1
7f0cfc410c76b834a15275a7f6a164d887b2c316
8,481
Advent-of-Code-2022
Apache License 2.0
src/Day06.kt
winnerwinter
573,917,144
false
{"Kotlin": 20685}
fun main() { fun part1(): Int { val testInput = readInput("Day06_test") val test_ans = testInput.map { naive(it, 4) } check(test_ans == listOf(7,5,6,10,11)) val input = readInput("Day06") val ans = naive(input.single(), 4) return ans } fun part2(): Int { val testInput = readInput("Day06_test") val test_ans = testInput.map { naive(it, 14) } check(test_ans == listOf(19,23,23,29,26)) val input = readInput("Day06") val ans = naive(input.single(), 14) return ans } println(part1()) println(part2()) } fun naive(input: String, size: Int): Int = input.windowed(size = size, step = 1).indexOfFirst { it.toList().size == it.toSet().size } + size
0
Kotlin
0
0
a019e5006998224748bcafc1c07011cc1f02aa50
772
advent-of-code-22
Apache License 2.0
LeetCode/Kotlin/GenerateParentheses.kt
vale-c
177,558,551
false
null
/** * 22. Generate Parentheses * https://leetcode.com/problems/generate-parentheses/ */ class Solution { val combinations = mutableListOf<String>() fun generateParentheses(n: Int): List<String> { generateParentheses(n, n, "") return combinations } private fun generateParentheses(open: Int, closed: Int, combination: String) { if (open == 0 && closed == 0) { combinations.add(combination) } else { if (open > 0) { generateParentheses(open - 1, closed, "$combination(") } if (closed > 0 && closed > open) { generateParentheses(open, closed - 1, "$combination)") } } } //works but not in leetcode's desired order fun generateParenthesesIterative(n: Int): List<String> { if (n == 0) { return listOf("") } /** * add parentheses from left side, right side and around * for each of the current combinations */ var combinations = setOf("()") var count = 1 while(count < n) { combinations = combinations.flatMap { linkedSetOf("($it)", "$it()", "()$it") }.toSet() count++ } return combinations.toList() } }
0
Java
5
9
977e232fa334a3f065b0122f94bd44f18a152078
1,333
CodingInterviewProblems
MIT License
src/main/kotlin/aoc2019/UniversalOrbitMap.kt
komu
113,825,414
false
{"Kotlin": 395919}
package komu.adventofcode.aoc2019 import komu.adventofcode.utils.nonEmptyLines private typealias OrbitalObject = String private typealias OrbitMap = Map<OrbitalObject, OrbitalObject> fun universalOrbitMap1(input: String): Int { val map = parseOrbitMap(input) return map.keys.sumBy { map.stepsToCenterOfMass(it).size } } fun universalOrbitMap2(input: String): Int { val map = parseOrbitMap(input) val myRoute = map.stepsToCenterOfMass("YOU") val santaRoute = map.stepsToCenterOfMass("SAN") for ((i, node) in myRoute.withIndex()) { val santaSteps = santaRoute.indexOf(node) if (santaSteps != -1) return i + santaSteps - 2 } error("no common ancestor") } private fun OrbitMap.stepsToCenterOfMass(start: OrbitalObject): List<String> { val steps = mutableListOf<OrbitalObject>() var node = start while (node != "COM") { steps += node node = this[node] ?: error("no parent for '$node'") } return steps } private val orbitRegex = Regex("""(.+)\)(.+)""") private fun parseOrbitMap(input: String): Map<String, String> = input.nonEmptyLines() .associate { (orbitRegex.matchEntire(it) ?: error("no match for '$it'")).groupValues.let { g -> g[2] to g[1] } }
0
Kotlin
0
0
8e135f80d65d15dbbee5d2749cccbe098a1bc5d8
1,266
advent-of-code
MIT License
src/main/kotlin/cloud/dqn/leetcode/NumberOfIslandsKt.kt
aviuswen
112,305,062
false
null
package cloud.dqn.leetcode /** * https://leetcode.com/problems/number-of-islands/description/ * Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. Example 1: 11110 11010 11000 00000 Answer: 1 Example 2: 11000 11000 00100 00011 Answer: 3 */ class NumberOfIslandsKt { /** copy char array for each grid { if grid == '1' { change self and all surrounding to 'x' add one to count } } */ class Solution { companion object { val LAND = '1' private val MARKED = 'x' } private fun inRange(row: Int, col: Int, grid: Array<CharArray>): Boolean { return row >= 0 && col >= 0 && row < grid.size && col < grid[row].size } private fun convertToX(row: Int, col: Int, grid: Array<CharArray>) { if (inRange(row, col, grid)) { val value = grid[row][col] if (value == LAND) { grid[row][col] = MARKED // upper convertToX(row - 1, col, grid) // left convertToX(row, col - 1, grid) // right convertToX(row, col + 1, grid) // bottom convertToX(row + 1, col, grid) } } } private fun charArrCopy(grid: Array<CharArray>): Array<CharArray> { return Array(grid.size, { row -> CharArray(grid[row]!!.size, { col -> grid[row][col] }) }) } fun numIslands(grid: Array<CharArray>): Int { val gridCopy = charArrCopy(grid) var count = 0 gridCopy.forEachIndexed { rowIndex, row -> row.forEachIndexed { colIndex, charAt -> if (charAt == LAND) { count++ convertToX(rowIndex, colIndex, gridCopy) } } } return count } } }
0
Kotlin
0
0
23458b98104fa5d32efe811c3d2d4c1578b67f4b
2,446
cloud-dqn-leetcode
No Limit Public License
app/src/main/java/my/github/dstories/core/model/AbilityScores.kt
horseunnamed
515,286,546
false
{"Kotlin": 116710}
package my.github.dstories.core.model import kotlin.math.max enum class AbilityScore { Str, Dex, Con, Int, Wis, Cha } data class AbilityScoreValue( val base: Int, val raceBonus: Int = 0 ) { val modifier: Int get() = (base - 10).floorDiv(2) val total: Int get() = base + raceBonus val costOfIncrease: Int get() = pointBuyCost(base + 1) val currentCost: Int get() = pointBuyCost(base) val isMax: Boolean get() = base >= 15 val isMin: Boolean get() = base <= 8 companion object { fun pointBuyCost(value: Int): Int = when { value < 9 -> 0 value in (9..13) -> value - 8 value in (14..15) -> (value - 8) + (value - 13) else -> Int.MAX_VALUE } } } data class AbilityScoresValues( val strength: AbilityScoreValue, val dexterity: AbilityScoreValue, val constitution: AbilityScoreValue, val intelligence: AbilityScoreValue, val wisdom: AbilityScoreValue, val charisma: AbilityScoreValue ) { private val pointsCost: Int get() = AbilityScore.values().sumOf { abilityScore -> this[abilityScore].currentCost } val freePoints: Int get() = max(27 - pointsCost, 0) fun canIncrease(abilityScore: AbilityScore) = !this[abilityScore].isMax && freePoints > this[abilityScore].costOfIncrease fun canDecrease(abilityScore: AbilityScore) = !this[abilityScore].isMin fun increase(abilityScore: AbilityScore) = update(abilityScore) { if (canIncrease(abilityScore)) { copy(base = base + 1) } else { this } } fun decrease(abilityScore: AbilityScore) = update(abilityScore) { if (canDecrease(abilityScore)) { copy(base = base - 1) } else { this } } fun applyRaceBonuses(raceBonuses: Map<AbilityScore, Int>): AbilityScoresValues { return AbilityScore.values().scan(this) { abilityScoreValues, abilityScore -> abilityScoreValues.update(abilityScore) { copy(raceBonus = raceBonuses[abilityScore] ?: 0) } }.last() } private fun update( abilityScore: AbilityScore, updateValue: AbilityScoreValue.() -> AbilityScoreValue ): AbilityScoresValues { return when (abilityScore) { AbilityScore.Str -> copy(strength = updateValue(strength)) AbilityScore.Dex -> copy(dexterity = updateValue(dexterity)) AbilityScore.Con -> copy(constitution = updateValue(constitution)) AbilityScore.Int -> copy(intelligence = updateValue(intelligence)) AbilityScore.Wis -> copy(wisdom = updateValue(wisdom)) AbilityScore.Cha -> copy(charisma = updateValue(charisma)) } } operator fun get(abilityScore: AbilityScore): AbilityScoreValue { return when (abilityScore) { AbilityScore.Str -> strength AbilityScore.Dex -> dexterity AbilityScore.Con -> constitution AbilityScore.Int -> intelligence AbilityScore.Wis -> wisdom AbilityScore.Cha -> charisma } } companion object { val Default = AbilityScoresValues( strength = AbilityScoreValue(8, 0), dexterity = AbilityScoreValue(8, 0), constitution = AbilityScoreValue(8, 0), intelligence = AbilityScoreValue(8, 0), wisdom = AbilityScoreValue(8, 0), charisma = AbilityScoreValue(8, 0) ) } }
6
Kotlin
0
0
e431340467993b839e5db0b6d64972cee6d379c6
3,621
Dungeon-Stories
MIT License