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
app/src/main/kotlin/com/simplemobiletools/calculator/helpers/StatFunctions.kt
ModestosV
116,624,977
true
{"Java": 84718, "Kotlin": 79549}
package com.simplemobiletools.calculator.helpers fun updateStats(results: ArrayList<String>){ getMean(results) getMedian(results) getMode(results) getRange(results) } fun getMean(results: ArrayList<String>): String{ var avg = 0.0 for(r in results) { if(r.isEmpty()) return "" avg += r.replace(",","").toDouble() } avg /= results.size return String.format(java.util.Locale.US,"%.2f", avg) } fun getMedian(results: ArrayList<String>): String{ for(r in results) { if (r.isEmpty()) return "" } val listOfSortedResults = sortListOfStringsOfDoubles(results) return if(listOfSortedResults.size % 2 == 0) { ((listOfSortedResults[listOfSortedResults.size / 2] + listOfSortedResults[listOfSortedResults.size / 2 - 1]) / 2).toString() } else { (listOfSortedResults[listOfSortedResults.size / 2]).toString() } } fun getMode(results: ArrayList<String>): String{ for(r in results) { if (r.isEmpty()) return "" } val storeValues = hashMapOf<String, Int>() val listOfModes = arrayListOf<String>() var highestCount = 0 //Get count of each occurrence for(r in results){ if(storeValues[r] == null) storeValues[r] = 1 else{ val count = storeValues[r] storeValues[r] = count!! + 1 } } //Store highest count for(s in storeValues){ if(highestCount < s.value) highestCount = s.value } //Every number with an equal highest count is added to return list for(s in storeValues){ if(s.value == highestCount) listOfModes.add(s.key) } val listOfSortedModes = sortListOfStringsOfDoubles(listOfModes) return listOfSortedModes.toString() } fun getRange(results: ArrayList<String>): String { for(r in results) { if (r.isEmpty()) return "" } val listOfSortedModes = sortListOfStringsOfDoubles(results) return (listOfSortedModes.last() - listOfSortedModes.first()).toString() } private fun sortListOfStringsOfDoubles(listOfStringOfDoubles: ArrayList<String>): ArrayList<Double> { val listOfDoubles = ArrayList<Double>() for(l in listOfStringOfDoubles){ listOfDoubles.add(l.replace(",","").toDouble()) } listOfDoubles.sort() return listOfDoubles }
10
Java
4
0
3b7b7ebd44d3307ff27e47c7c8724ffba4d5a6f8
2,392
Simple-Calculator-DreamTeam
Apache License 2.0
src/Day10.kt
lsimeonov
572,929,910
false
{"Kotlin": 66434}
fun main() { fun part1(input: List<String>): Int { var clock = 0 var registry = 1 var total = 0 input.forEach { l -> var calculated = false if (l == "noop") { clock++ } else { for (i in 1..2) { clock++ if ((clock == 20 || ((clock - 20) % 40) == 0) && clock <= 220) { total += clock * registry calculated = true } } registry += l.split(" ").last().toInt() } if (!calculated && ((clock == 20 || ((clock - 20) % 40) == 0) && clock <= 220)) { total += clock * registry } } return total } fun draw(sprite: IntRange, clock: Int): Int { if (sprite.contains(clock)) { print('#') } else { print(' ') } if (clock % 40 == 0) { println() // Reset clock return 0 } return clock } fun part2(input: List<String>): Int { var clock = 0 var crtClock = 0 var registry = 1 var sprite = 0..3 input.forEach { l -> var drawn = false if (l == "noop") { clock++ crtClock++ } else { for (i in 1..2) { clock++ crtClock++ crtClock = draw(sprite, crtClock) drawn = true } registry += l.split(" ").last().toInt() sprite = registry..registry + 2 } if (!drawn) { draw(sprite, crtClock) } } return 0 } // test if implementation meets criteria from the description, like: val testInput = readInput("Day10_test") check(part1(testInput) == 13140) part2(testInput) val input = readInput("Day10") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
9d41342f355b8ed05c56c3d7faf20f54adaa92f1
2,102
advent-of-code-2022
Apache License 2.0
src/test/kotlin/dev/shtanko/algorithms/leetcode/SimilarStringGroupsTest.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.stream.Stream import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.extension.ExtensionContext import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.Arguments import org.junit.jupiter.params.provider.ArgumentsProvider import org.junit.jupiter.params.provider.ArgumentsSource abstract class SimilarStringGroupsTest<out T : SimilarStringGroups>(private val strategy: T) { private class InputArgumentsProvider : ArgumentsProvider { override fun provideArguments(context: ExtensionContext?): Stream<out Arguments> = Stream.of( Arguments.of(arrayOf(""), 1), Arguments.of(arrayOf("a"), 1), Arguments.of(arrayOf("one"), 1), Arguments.of(arrayOf("tars", "rats", "arts", "star"), 2), Arguments.of(arrayOf("omv", "ovm"), 1), Arguments.of(arrayOf("abc", "bac", "cab", "xyz", "yzx", "zxy"), 4), Arguments.of(arrayOf("abc", "bac", "cab", "xyz", "yzx", "zxy", "def", "edf", "fde"), 5), Arguments.of( arrayOf("abc", "bad", "cda", "xyz", "yzx", "zxy"), 6, ), Arguments.of( arrayOf("abc", "abc", "abc", "xyz", "xyz", "xyz"), 2, ), Arguments.of( arrayOf("abcdefghijklmnopqrstuvwxyza", "bcdefghijklmnopqrstuvwxyzab", "cdefghijklmnopqrstuvwxyzabc"), 3, ), Arguments.of( arrayOf( "abc", "bcdefghijklmnopqrstuvwxyzab", "cdefghijklmnopqrstuvwxyzabc", "defghijklmnopqrstuvwxyzabcd", ), 4, ), ) } @ParameterizedTest @ArgumentsSource(InputArgumentsProvider::class) fun `num similar groups test`(strings: Array<String>, expected: Int) { val actual = strategy.numSimilarGroups(strings) assertEquals(expected, actual) } } class SimilarStringGroupsBFSTest : SimilarStringGroupsTest<SimilarStringGroups>(SimilarStringGroupsBFS()) class SimilarStringGroupsDFSTest : SimilarStringGroupsTest<SimilarStringGroups>(SimilarStringGroupsDFS()) class SimilarStringGroupsUnionFindTest : SimilarStringGroupsTest<SimilarStringGroups>(SimilarStringGroupsUnionFind()) class SimilarStringGroupsDSUTest : SimilarStringGroupsTest<SimilarStringGroups>(SimilarStringGroupsDSU())
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,117
kotlab
Apache License 2.0
src/main/kotlin/days/aoc2022/Day3.kt
bjdupuis
435,570,912
false
{"Kotlin": 537037}
package days.aoc2022 import days.Day class Day3 : Day(2022, 3) { override fun partOne(): Any { return calculatePartOne(inputList) } override fun partTwo(): Any { return calculatePartTwo(inputList) } fun calculatePartOne(inputList: List<String>): Int { return inputList .map { line -> findCommonProperty(line) } .sumOf { property -> priority(property) } } private fun findCommonProperty(input: String): Char { val front = input.substring(0, input.length / 2) val back = input.substring(input.length / 2) return front.first { current -> back.contains(current) } } private fun priority(input: Char): Int { return when(input) { in 'a'..'z' -> input - 'a' + 1 in 'A'..'Z' -> input - 'A' + 27 else -> throw IllegalStateException() } } fun calculatePartTwo(inputList: List<String>): Int { return findBadgesInGroups(inputList) .sumOf { badge -> priority(badge) } } private fun findBadgesInGroups(input: List<String>): List<Char> { return input.chunked(3) .map { group -> group.first().first { badge -> group[1].contains(badge) && group[2].contains(badge) } } } }
0
Kotlin
0
1
c692fb71811055c79d53f9b510fe58a6153a1397
1,347
Advent-Of-Code
Creative Commons Zero v1.0 Universal
Kotlin/src/SubsetsII.kt
TonnyL
106,459,115
false
null
/** * Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set). * * Note: The solution set must not contain duplicate subsets. * * For example, * If nums = [1,2,2], a solution is: * * [ * [2], * [1], * [1,2,2], * [2,2], * [1,2], * [] * ] * * Accepted. */ class SubsetsII { fun subsetsWithDup(nums: IntArray): List<List<Int>> { if (nums.isEmpty()) { return emptyList() } val lists = mutableListOf<List<Int>>() if (nums.size == 1) { // Add the empty list. lists.add(emptyList()) lists.add(listOf(nums[0])) return lists } nums.sort() for (list in subsetsWithDup(nums.copyOfRange(0, nums.size - 1))) { val l = mutableListOf(nums[nums.size - 1]) l.addAll(list) if (!lists.contains(l)) { lists.add(l) } if (!lists.contains(list)) { lists.add(list) } } return lists } }
1
Swift
22
189
39f85cdedaaf5b85f7ce842ecef975301fc974cf
1,091
Windary
MIT License
src/main/kotlin/days/Day24.kt
andilau
429,557,457
false
{"Kotlin": 103829}
package days @AdventOfCodePuzzle( name = "It Hangs in the Balance", url = "https://adventofcode.com/2015/day/24", date = Date(day = 24, year = 2015) ) class Day24(private val weights: List<Int>) : Puzzle { override fun partOne() = findBest(weights, 3)?.quantumEntanglement() ?: error("Not found") override fun partTwo() = findBest(weights, 4)?.quantumEntanglement() ?: error("Not found") private fun findBest(weights: List<Int>, size: Int): Set<Int>? { if (size < 1) return null if (size == 1) return weights.toSet() val targetSum = weights.sum() / size val groups = weights.combinationsFit(targetSum).map { it.toSet() }.toList() groups .sortedWith(compareBy<Set<Int>> { it.size }.then(compareBy { it.quantumEntanglement() })) .forEach { best -> val candidates = groups.filter { group -> best.none { it in group } } if (candidates.canPartitionBy(size - 1)) return best } return null } private fun Collection<Set<Int>>.canPartitionBy(parts: Int): Boolean { if (parts == 1) return isNotEmpty() return firstOrNull { group -> filter { complement -> complement.none { it in group } } .canPartitionBy(parts - 1) } != null } private fun Iterable<Int>.quantumEntanglement(): Long = fold(1L) { product, number -> product * number } }
0
Kotlin
0
0
55932fb63d6a13a1aa8c8df127593d38b760a34c
1,441
advent-of-code-2015
Creative Commons Zero v1.0 Universal
src/test/kotlin/days/y2022/Day07Test.kt
jewell-lgtm
569,792,185
false
{"Kotlin": 161272, "Jupyter Notebook": 103410, "TypeScript": 78635, "JavaScript": 123}
package days.y2022 import days.Day import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.core.Is.`is` import org.junit.jupiter.api.Test class Day07 : Day(2022, 7) { private lateinit var rootDir: FSNode override fun partOne(input: String): Any { parseInput(input) return rootDir.childNodesWhere { it.size() < 100000 }.sumOf { it.size() } } override fun partTwo(input: String): Any { parseInput(input) val unusedSpace = (70000000 - rootDir.size()) val neededSpace = 30000000 - unusedSpace val dirsToDelete = rootDir.childNodesWhere { it.size() >= neededSpace } val dirToDelete = dirsToDelete.minBy { it.size() } return dirToDelete.size() } private fun parseInput(input: String) { rootDir = FSNode.from("..", null) val lines = input.lines().drop(1) // first command is $ cd / var currNode = rootDir for (line in lines) { if (line == "$ ls") { continue } if (line.startsWith("$ cd ")) { val dirName = line.split(" ").last() currNode = if (dirName == ".." ) { currNode.parent!! } else { currNode.child(dirName) } continue } if (line.startsWith("dir ")) { val dirName = line.split(" ").last() currNode.children.add(FSNode.from(dirName, currNode)) continue } if (line[0].isDigit()) { val (size, name) = line.split(" ") currNode.files.add(FSFile(name, size.toInt())) continue } error("Unknown format: $line") } } data class FSFile(val name: String, val size: Int) data class FSNode( val name: String, val files: MutableSet<FSFile>, val children: MutableSet<FSNode>, val parent: FSNode? ) { fun size(): Int = files.sumOf { it.size } + children.sumOf { it.size() } fun childNodesWhere(function: (node: FSNode) -> Boolean): Set<FSNode> { val result = mutableSetOf<FSNode>() children.forEach { child -> if (function(child)) { result.add(child) } result.addAll(child.childNodesWhere(function)) } return result } fun child(dirName: String): FSNode = this.children.find { it.name == dirName }!! companion object { fun from(name: String, parent: FSNode?): FSNode = FSNode(name, mutableSetOf(), mutableSetOf(), parent) } } } class Day07Test { private val exampleInput = """ ${'$'} cd / ${'$'} ls dir a 14848514 b.txt 8504156 c.dat dir d ${'$'} cd a ${'$'} ls dir e 29116 f 2557 g 62596 h.lst ${'$'} cd e ${'$'} ls 584 i ${'$'} cd .. ${'$'} cd .. ${'$'} cd d ${'$'} ls 4060174 j 8033020 d.log 5626152 d.ext 7214296 k """.trimIndent() @Test fun testExampleOne() { assertThat( Day07().partOne(exampleInput), `is`(95437) ) } @Test fun testPartOne() { assertThat(Day07().partOne(), `is`(1915606)) } @Test fun testExampleTwo() { assertThat( Day07().partTwo(exampleInput).toString(), `is`(24933642.toString()) ) } @Test fun testPartTwo() { assertThat(Day07().partTwo(), `is`(5025657)) } }
0
Kotlin
0
0
b274e43441b4ddb163c509ed14944902c2b011ab
3,703
AdventOfCode
Creative Commons Zero v1.0 Universal
src/org/prime/util/DerivationBuilder.kt
miloserdova-l
433,512,408
true
{"Kotlin": 18468}
package org.prime.util import org.prime.util.machines.LinearBoundedAutomaton import org.prime.util.machines.TuringMachine interface DerivationBuilder { fun buildDerivation(input: List<String>, grammar: Grammar): MutableList<String> } /** * Derivation builder uses TuringMachine to get accumulated used deltas to build derivations */ class DerivationBuilderT0(private val turingMachine: TuringMachine) : DerivationBuilder { override fun buildDerivation(input: List<String>, grammar: Grammar): MutableList<String> { var currentWord = mutableListOf(turingMachine.startState) val productions = grammar.productions input.forEach { currentWord.add(getBracketSymbol(it, it)) } repeat(input.size) { currentWord.add(getBracketSymbol(Constants.EPSILON, "_")) } repeat(input.size + 2) { currentWord.add(0, getBracketSymbol(Constants.EPSILON, "_")) } val result = mutableListOf(currentWord.toPrettyWord()) for (d in turingMachine.usedDeltas) { for (p in productions.filter { p -> p.leftSymbols.contains(d.currentState) && p.rightSymbols.contains(d.nextState) }) { val prodResult = p.apply(currentWord)?.toMutableList() if (prodResult != null) { result.add(prodResult.toPrettyWord()) currentWord = prodResult break } } } val finishProductions = productions.filter { p -> p.leftSymbols.contains(turingMachine.acceptState) && p.rightSymbols.size != 1 } val acceptEps = productions.find { it.leftSymbols.contains(turingMachine.acceptState) && it.rightSymbols.size == 1 }!! while (true) { var changed = false finishProductions.forEach { val newWord = it.apply(currentWord) if (newWord != null) { result.add(newWord.toPrettyWord()) currentWord = newWord.toMutableList() changed = true } } if (!changed) break } while (true) { var changed = false val newWord = acceptEps.apply(currentWord) if (newWord != null) { result.add(newWord.toPrettyWord()) currentWord = newWord.toMutableList() changed = true } if (!changed) break } return result } private fun getBracketSymbol(left: String, right: String) = "($left|$right)" private fun List<String>.toPrettyWord() = toString().replace("[", "").replace("]", "") } class DerivationBuilderT1(val lba: LinearBoundedAutomaton) : DerivationBuilder { override fun buildDerivation(input: List<String>, grammar: Grammar): MutableList<String> { TODO("Not yet implemented") } }
0
Kotlin
1
0
f912a88f65458effce107318efc0a2a82ece45aa
2,985
primary-numbers-grammar
MIT License
src/main/kotlin/day4/Day4.kt
Mee42
433,459,856
false
{"Kotlin": 42703, "Java": 824}
package dev.mee42.day4 import dev.mee42.* fun main() { val inputRaw = input(day = 4, year = 2021) val (bingoNumbers, boardsSplit) = inputRaw .split("\n", limit = 2) .twoElements() .manipulateTuple { bingoNumbers, boards -> bingoNumbers.ints() to boards.split("\n\n").map { it.trim() } } data class Board(val squares: List<List<Int>>) { val transposed = squares.transpose() } val boards = boardsSplit.map { Board(it.trim().split("\n").map { line -> line.split(Regex("""\s+""")).filter { x -> x.isNotEmpty() }.map { number -> number.toInt() } }) }.toMutableList() val called = mutableListOf<Int>() var sol = 0 var part1 = true outer@ for(bingoNumber in bingoNumbers) { called.add(bingoNumber) val iterator = boards.listIterator() for(board in iterator) { val win = (0 until 5).any { index -> board.squares[index].all { it in called } || board.transposed[index].all { it in called} } if(win) { iterator.remove() val sumOfUnmarked = board.squares.flatten().filter { it !in called }.sum() sol = sumOfUnmarked * bingoNumber // For part one, exit early here // For part two, continue til the last board is removed (comment the line out) if(part1) { println("Part one: $sol") part1 = false } } } } println("Part two: $sol") }
0
Kotlin
0
0
db64748abc7ae6a92b4efa8ef864e9bb55a3b741
1,647
aoc-2021
MIT License
src/main/kotlin/g1601_1700/s1610_maximum_number_of_visible_points/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1601_1700.s1610_maximum_number_of_visible_points // #Hard #Array #Math #Sorting #Sliding_Window #Geometry // #2023_06_15_Time_1343_ms_(100.00%)_Space_101_MB_(100.00%) import kotlin.math.atan class Solution { fun visiblePoints(points: List<List<Int>>, angle: Int, location: List<Int>): Int { var max = 0 var count = 0 val angles: MutableList<Double> = ArrayList(points.size) for (point in points) { val a = calculateAngle(location, point) if (a == 360.0) { count++ } else { angles.add(a) } } angles.sort() var s = 0 var e = 0 var size: Int val n = angles.size while (s < n && max < n) { while (true) { val index = (e + 1) % n if (s == index || (360 + angles[index] - angles[s]) % 360 > angle) { break } e = index } size = if (e >= s) e - s + 1 else n - s + e + 1 max = max.coerceAtLeast(size) if (e == s) { e++ } s++ } return max + count } private fun calculateAngle(location: List<Int>, point: List<Int>): Double { val x1 = location[0] val y1 = location[1] val x2 = point[0] val y2 = point[1] if (x1 == x2) { if (y2 > y1) { return 90.0 } return if (y2 < y1) { 270.0 } else 360.0 } var angle = Math.toDegrees(atan((y2 - y1).toDouble() / (x2 - x1))) if (x2 > x1) { angle = (angle + 360.0) % 360.0 } else { angle += 180.0 } return angle } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,827
LeetCode-in-Kotlin
MIT License
modules/fathom/src/main/kotlin/silentorb/mythic/fathom/surfacing/MergeVertices.kt
silentorb
227,508,449
false
null
package silentorb.mythic.fathom.surfacing import silentorb.mythic.spatial.Vector3 tailrec fun groupNearbyVertices(distanceTolerance: Float, remaining: List<Vector3>, groups: List<List<Vector3>>): List<List<Vector3>> = if (remaining.size < 2) groups else { val next = remaining.first() val nearby = remaining.filter { it != next && it.distance(next) < distanceTolerance } val nextRemaining = remaining .drop(1) val nextGroups = if (nearby.any()) { val newGroup = listOf(next).plus(nearby) // if (groups.none { group -> group.containsAll(newGroup) }) val overlaps = groups.filter { group -> group.any { newGroup.contains(it) } } if (overlaps.any()) groups.minus(overlaps).plusElement(overlaps.flatten().plus(newGroup).distinct()) else groups.plusElement(newGroup) } else groups groupNearbyVertices(distanceTolerance, nextRemaining, nextGroups) } fun groupNearbyVertices(distanceTolerance: Float, edges: List<Edge>): List<List<Vector3>> = groupNearbyVertices(distanceTolerance, getVerticesFromEdges(edges), listOf()) fun mergeNearbyEdgeVertices(distanceTolerance: Float, edges: List<Edge>): List<Edge> { val clumps = groupNearbyVertices(distanceTolerance, edges) val vertexMap = clumps.flatMap { points -> val center = points.reduce { a, b -> a + b } / points.size.toFloat() points.map { point -> Pair(point, center) } } .associate { it } val result = edges.mapNotNull { edge -> val first = vertexMap[edge.first] ?: edge.first val second = vertexMap[edge.second] ?: edge.second if (first.distance(second) > distanceTolerance) edge.copy( first = vertexMap[edge.first] ?: edge.first, second = vertexMap[edge.second] ?: edge.second ) else null } return result }
0
Kotlin
0
2
74462fcba9e7805dddec1bfcb3431665df7d0dee
1,921
mythic-kotlin
MIT License
src/Day06.kt
orirabi
574,124,632
false
{"Kotlin": 14153}
fun main() { fun CharArray.isDistinct(i: Int, requiredCount: Int): Boolean { if (i < requiredCount - 1) { return false } return generateSequence(i to this[i]) { it.first - 1 to this[it.first - 1] } .take(requiredCount) .map { it.second } .distinct() .count() == requiredCount } fun CharArray.isMarker(i: Int): Boolean = isDistinct(i, 4) fun CharArray.isMessage(i: Int): Boolean = isDistinct(i, 14) fun getFirstMarkerEnd(input: String): Int { val chars = input.toCharArray() for (i in chars.indices) { if (chars.isMarker(i)) return i + 1 } throw IllegalStateException() } fun getFirstMessageEnd(input: String): Int { val chars = input.toCharArray() for (i in chars.indices) { if (chars.isMessage(i)) return i + 1 } throw IllegalStateException() } val input = readInput("Day06").single() println(getFirstMarkerEnd(input)) println(getFirstMessageEnd(input)) }
0
Kotlin
0
0
41cb10eac3234ae77ed7f3c7a1f39c2f9d8c777a
1,080
AoC-2022
Apache License 2.0
src/main/kotlin/adventofcode/year2017/Day15DuelingGenerators.kt
pfolta
573,956,675
false
{"Kotlin": 199554, "Dockerfile": 227}
package adventofcode.year2017 import adventofcode.Puzzle import adventofcode.PuzzleInput class Day15DuelingGenerators(customInput: PuzzleInput? = null) : Puzzle(customInput) { private val generators by lazy { input.lines().map { it.split(" ").last().toLong() }.zipWithNext().first() } override fun partOne() = generateSequence(generators) { (a, b) -> a.next(A_FACTOR) to b.next(B_FACTOR) } .take(ROUNDS_PART_1) .count { (a, b) -> a.toBinary().takeLast(BITS_TO_COMPARE) == b.toBinary().takeLast(BITS_TO_COMPARE) } override fun partTwo() = generateSequence(generators) { (a, b) -> a.next(A_FACTOR, A_MULTIPLE_OF) to b.next(B_FACTOR, B_MULTIPLE_OF) } .take(ROUNDS_PART_2) .count { (a, b) -> a.toBinary().takeLast(BITS_TO_COMPARE) == b.toBinary().takeLast(BITS_TO_COMPARE) } companion object { private const val BITS_TO_COMPARE = 16 private const val ROUNDS_PART_1 = 40_000_000 private const val ROUNDS_PART_2 = 5_000_000 private const val A_FACTOR = 16807 private const val B_FACTOR = 48271 private const val DIVISOR = 2147483647 private const val A_MULTIPLE_OF = 4 private const val B_MULTIPLE_OF = 8 private fun Long.next(factor: Int) = this * factor % DIVISOR private tailrec fun Long.next(factor: Int, multipleOf: Int): Long { val next = this.next(factor) return when (next % multipleOf) { 0L -> next else -> next.next(factor, multipleOf) } } private fun Long.toBinary() = this.toString(2).padStart(BITS_TO_COMPARE, '0') } }
0
Kotlin
0
0
72492c6a7d0c939b2388e13ffdcbf12b5a1cb838
1,655
AdventOfCode
MIT License
src/main/kotlin/models/Coord3d.kt
aormsby
571,002,889
false
{"Kotlin": 80084}
package models import kotlin.math.abs import kotlin.math.pow import kotlin.math.sqrt data class Coord3d( var x: Int, var y: Int, var z: Int ) { operator fun plus(c: Coord3d) = Coord3d(x = x + c.x, y = y + c.y, z = z + c.z) operator fun minus(c: Coord3d) = Coord3d(x = x - c.x, y = y - c.y, z = z - c.z) fun opposite(): Coord3d = Coord3d(x * -1, y * -1, z * -1) fun diffWith(c: Coord3d): Coord3d = Coord3d(c.x - x, c.y - y, c.z - z) fun euclideanDistanceTo(c: Coord3d): Float = sqrt( ((x - c.x).toFloat()).pow(2) + ((y - c.y).toFloat()).pow(2) + ((z - c.z).toFloat()).pow(2) ) fun manhattanDistanceTo(c: Coord3d): Int = with(diffWith(c)) { abs(this.x) + abs(this.y) + abs(this.z) } fun toInts(): List<Int> = listOf(x, y, z) fun pairWith(c: Coord3d) = listOf( x to c.x, y to c.y, z to c.z, ) fun adjacentNeighbors(xLimit: Int = -1, yLimit: Int = -1, zLimit: Int = -1): List<Coord3d> { var adjs = listOf( Coord3d(x, y + 1, z), Coord3d(x, y - 1, z), Coord3d(x + 1, y, z), Coord3d(x - 1, y, z), Coord3d(x, y, z + 1), Coord3d(x, y, z - 1), ) if (xLimit > -1) adjs = adjs.filter { it.x in 0..xLimit } if (yLimit > -1) adjs = adjs.filter { it.y in 0..yLimit } if (zLimit > -1) adjs = adjs.filter { it.z in 0..zLimit } return adjs } fun diagonalNeighbors(xLimit: Int = -1, yLimit: Int = -1, zLimit: Int = -1): List<Coord3d> { var diags = listOf( Coord3d(x - 1, y - 1, z), Coord3d(x - 1, y + 1, z), Coord3d(x + 1, y - 1, z), Coord3d(x + 1, y + 1, z), Coord3d(x + 1, y, z + 1), Coord3d(x + 1, y, z - 1), ) if (xLimit > -1) diags = diags.filter { it.x in 0..xLimit } if (yLimit > -1) diags = diags.filter { it.y in 0..yLimit } if (zLimit > -1) diags = diags.filter { it.z in 0..zLimit } return diags } fun allNeighbors(xLimit: Int = -1, yLimit: Int = -1, zLimit: Int = -1): List<Coord3d> { return adjacentNeighbors(xLimit, yLimit) + diagonalNeighbors(xLimit, yLimit) } override fun toString(): String = "($x, $y, $z)" }
0
Kotlin
0
0
1bef4812a65396c5768f12c442d73160c9cfa189
2,386
advent-of-code-2022
MIT License
app/src/main/java/com/arya/matrixcalculator/logic/InverseOperation.kt
arryaaas
300,893,861
false
{"Kotlin": 36162}
package com.arya.matrixcalculator.logic object InverseOperation { // const val N = 3 // Function to get cofactor of A[p][q] in temp[][]. n is current // dimension of A[][] private fun getCofactor(A: Array<Array<Float>>, temp: Array<Array<Float>>, p: Int, q: Int, n: Int) { var i = 0 var j = 0 // Looping for each element of the matrix for (row in 0 until n) { for (col in 0 until n) { // Copying into temporary matrix only those element // which are not in given row and column if (row != p && col != q) { temp[i][j++] = A[row][col] // Row is filled, so increase row index and // reset col index if (j == n - 1) { j = 0 i++ } } } } } /* Recursive function for finding determinant of matrix. n is current dimension of A[][]. */ private fun determinant(A: Array<Array<Float>>, n: Int): Float { val x = A.size var d = 0F // Initialize result // Base case : if matrix contains single element if (n == 1) return A[0][0] val temp: Array<Array<Float>> // To store cofactors temp = Array(x) {Array(x) {0f} } //Array(N) { FloatArray(N) } var sign = 1 // To store sign multiplier // Iterate for each element of first row for (f in 0 until n) { // Getting Cofactor of A[0][f] getCofactor( A, temp, 0, f, n ) d += sign * A[0][f] * determinant( temp, n - 1 ) // terms are to be added with alternate sign sign = -sign } return d } // Function to get adjoint of A[N][N] in adj[N][N]. private fun adjoint(A: Array<Array<Float>>, adj: Array<Array<Float>>) { val n = A.size if (n == 1) { adj[0][0] = 1F return } // temp is used to store cofactors of A[][] var sign: Int val temp = Array(n) {Array(n) {0f} } for (i in 0 until n) { for (j in 0 until n) { // Get cofactor of A[i][j] getCofactor( A, temp, i, j, n ) // sign of adj[j][i] positive if sum of row // and column indexes is even. sign = if ((i + j) % 2 == 0) 1 else -1 // Interchanging rows and columns to get the // transpose of the cofactor matrix adj[j][i] = sign * determinant( temp, n - 1 ) } } } // Function to calculate and store inverse, returns false if // matrix is singular private fun inverse( A: Array<Array<Float>>, inverse: Array<Array<Float>> ): Boolean { // Find determinant of A[][] val n = A.size val det = determinant(A, n) if (det == 0F) { print("Singular matrix, can't find its inverse") return false } // Find adjoint val adj = Array(n) {Array(n) {0f} }//Array(N) { IntArray(N) } adjoint(A, adj) // Find Inverse using formula "inverse(A) = adj(A)/det(A)" for (i in 0 until n) for (j in 0 until n) inverse[i][j] = adj[i][j] / det return true } fun mainInverse( matrix1: Array<Array<Float>>, matrixResult: Array<Array<Float>> ) { val n = matrix1.size val adj = Array(n) {Array(n) {0f} } // To store adjoint of A[][] val inv = Array(n) {Array(n) {0f} } // To store inverse of A[][] adjoint(matrix1, adj) if (inverse( matrix1, inv ) ) for (i: Int in inv.indices) for (j: Int in inv[0].indices) matrixResult[i][j] = inv[i][j] } }
0
Kotlin
0
1
393d2e9ff271bd5aceabc2074be1ac7a96d8a271
4,236
Matrix-Calculator
MIT License
src/main/kotlin/adventofcode2020/Day19MonsterMessage.kt
n81ur3
484,801,748
false
{"Kotlin": 476844, "Java": 275}
package adventofcode2020 class Day19MonsterMessage data class MessageRule( var ruleExpression: String = "", ) { val fullRule: String get() = ruleExpression override fun toString(): String = (ruleExpression).replace(" ", "") val isEvaluated: Boolean get() { val regex = "[ab |()]*".toRegex() return (regex.matches(ruleExpression)) } fun substituteRule(ruleNumber: String, rule: String) { val regex = " $ruleNumber ".toRegex() ruleExpression = ruleExpression.replace(regex, " ( " + rule + " ) ") ruleExpression = ruleExpression.replace(regex, " ( " + rule + " ) ") } fun matches(message: String): Boolean { val regex = (ruleExpression.replace(" ", "")).toRegex() return regex.matches(message) } } class RulesChecker { val rules = mutableMapOf<Int, MessageRule>() fun buildRulesFromLines(rules: List<String>) { rules.forEach { rule -> this.rules.put( rule.substringBefore(":").toInt(), MessageRule(rule.substringAfter(":").replace("\"", "").replace("\"", "") + " ") ) } buildRulesFromRawRules() } private fun buildRulesFromRawRules() { var evaluatedRules = mapOf<Int, MessageRule>() val substitutedRules = mutableListOf<Int>() do { evaluatedRules = rules.filter { (_, messageRule) -> messageRule.isEvaluated } if (evaluatedRules.isNotEmpty()) { val rulesToReplace = evaluatedRules.entries.filter { (ruleNumber, _) -> ruleNumber !in substitutedRules } if (rulesToReplace.isNotEmpty()) { rulesToReplace.forEach { nextRuleToReplace -> rules.values.forEach { it.substituteRule( nextRuleToReplace.key.toString(), nextRuleToReplace.value.fullRule ) } substitutedRules.add(nextRuleToReplace.key) } } } } while (evaluatedRules.size != rules.size) } fun evaluateMessage(message: String): Boolean { return rules.get(0)?.matches(message) ?: false } }
0
Kotlin
0
0
fdc59410c717ac4876d53d8688d03b9b044c1b7e
2,351
kotlin-coding-challenges
MIT License
domain/src/main/kotlin/io/exflo/domain/extensions/ListExt.kt
41north
237,284,768
false
null
/* * Copyright (c) 2020 41North. * * 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 io.exflo.domain.extensions /** * Returns a list of triple built from the elements of `this` collection and the [one] and [two] lists with the same index. * The returned list has length of the shortest collection. */ fun <T, R, V> List<T>.zip(one: List<R>, two: List<V>): List<Triple<T, R, V>> = zip(one, two) { t1, t2, t3 -> Triple(t1, t2, t3) } /** * Returns a list of values built from the elements of `this` collection, the [one] and [two] lists with the same index * using the provided [transform] function applied to each group of elements. * The returned list has length of the shortest collection. */ inline fun <T, R, P, V> List<T>.zip(one: List<R>, two: List<P>, transform: (a: T, b: R, c: P) -> V): List<V> { val arraySize = minOf(one.size, two.size) val list = ArrayList<V>(minOf(size, arraySize)) var i = 0 for (element in this) { if (i >= arraySize) break list.add(transform(element, one[i], two[i])) i++ } return list }
16
Kotlin
7
17
218d6f83db11268d8e5cb038e96f1d3fcd0a6cc0
1,574
besu-exflo
Apache License 2.0
src/advent/of/code/TwelvethPuzzle.kt
1nco
725,911,911
false
{"Kotlin": 112713, "Shell": 103}
package advent.of.code import java.util.* class TwelvethPuzzle { companion object { private const val DAY = "12"; private var input: MutableList<String> = arrayListOf(); private var result = 0L; private var resultSecond = 0L; private var resultThird = 0L; private var results = arrayListOf<Long>() var alreadyCheckedPerms = mutableMapOf<String, Boolean>(); var validArrangementCounts: MutableMap<String, Long> = mutableMapOf(); fun solve() { val startingTime = Date(); input.addAll(Reader.readInput(DAY)); first(); second(); println(startingTime); println(Date()); } private fun first() { var lineNum = 0; input.forEach { line -> result += possibleArrangements(line); lineNum++; } println(result) } private fun possibleArrangements(line: String): Long { val arrangement = line.split(" ")[0]; val parts = line.split(" ")[1].split(",").map { c -> c.toLong() }.toList(); val permutations = arrayListOf<String>(); getAllPermutations(arrangement, permutations); var valid = 0L; permutations.forEach { permutation -> val groups = permutation.split(".").filter { p -> p.contains("#") } var isPermValid = true; if (groups.size == parts.size) { for (i in 0..parts.size - 1) { if (getOccurencesOfAChar(groups[i], '#') == parts[i]) { // isPermValid = true } else { isPermValid = false; }; } } else { isPermValid = false; } if (isPermValid) { valid++ } } return valid; } private fun possibleArrangementsForPartTwo(line: String) { alreadyCheckedPerms = mutableMapOf<String, Boolean>(); var arrangement = line.split(" ")[0]; var parts: MutableList<Long> = line.split(" ")[1].split(",").map { c -> c.toLong() }.toMutableList(); val originalArrangement = arrangement; val originalParts = arrayListOf<Long>(); originalParts.addAll(parts) val CONCAT_COUNT = 2; // val CONCAT_COUNT = 2; for (i in 0..<CONCAT_COUNT - 1) { arrangement += "?" + originalArrangement; parts.addAll(originalParts); } validArrangementCounts.set(arrangement, 0L); println("") println("") println("") println(line); println(Date()) getAllPermutationsForPartTwo(arrangement, parts, arrangement); val withoutConcat = possibleArrangements(line); var withConcat = validArrangementCounts[arrangement]!!; var res = 0L; if (withConcat < withoutConcat || withConcat % withoutConcat != 0L) { println("valami van a levegoben"); for (i in 0..< 3 - CONCAT_COUNT) { arrangement += "?" + originalArrangement; parts.addAll(originalParts); } validArrangementCounts.set(arrangement, 0L); getAllPermutationsForPartTwo(arrangement, parts, arrangement); withConcat = validArrangementCounts[arrangement]!!; res = withConcat; } else { val multiplier = withConcat / withoutConcat; res = withoutConcat * multiplier * multiplier * multiplier * multiplier; } println("withoutConcat: $withoutConcat") println("withConcat: $withConcat") println("res: $res"); println(Date()) resultSecond += res; } private fun checkPermutation(permutation: String, parts: List<Long>): Boolean { val groups = permutation.split(".").filter { p -> p.contains("#") } var isPermValid = true; if (groups.size == parts.size) { for (i in 0..parts.size - 1) { if (getOccurencesOfAChar(groups[i], '#') == parts[i]) { } else { isPermValid = false; }; } } else { isPermValid = false; } return isPermValid; } private fun getAllPermutationsForPartTwo(arrangement: String, parts: List<Long>, originalArrangement: String) { if (arrangement.contains("?")) { var arr1 = arrangement.replaceFirst("?", ".") var arr2 = arrangement.replaceFirst("?", "#") if (checkHalfDonePermutation(arr1, parts)) { getAllPermutationsForPartTwo(arr1, parts, originalArrangement); } if (checkHalfDonePermutation(arr2, parts)) { getAllPermutationsForPartTwo(arr2, parts, originalArrangement); } } else { if (checkPermutation(arrangement, parts)) { validArrangementCounts[originalArrangement] = validArrangementCounts[originalArrangement]!! + 1L } } } private fun checkHalfDonePermutation(arrangement: String, parts: List<Long>): Boolean { val groups = arrangement.split(".").filter { a -> a != "" } var canBeValid = true; var breakFor = false; var i = 0; while (canBeValid && !breakFor && i < parts.size) { if (i < groups.size) { if (groups[i].contains("?")) { // if (getOccurencesOfAChar( // groups[i].split("?")[0], // '#' // ) == parts[i] && groups[i].length > parts[i] && groups[i][parts[i].toInt()] == '?' // ) { // canBeValid = true; // } else if (getOccurencesOfAChar(groups[i], '#') > parts[i] && getOccurencesOfAChar(groups[i], '?') < parts[i] // ) { // canBeValid = false // } breakFor = true; } if (!groups[i].contains("?")) { if (getOccurencesOfAChar(groups[i], '#') == parts[i]) { } else { canBeValid = false; breakFor = true; }; } } i++; } return canBeValid; } private fun getOccurencesOfAChar(value: String, char: Char): Long { var count = 0L; for (i in 0 until value.length) { if (value[i] == char) { count++ } } return count; } private fun getAllPermutations(arrangement: String, permutations: MutableList<String>) { if (arrangement.contains("?")) { var arr1 = arrangement.replaceFirst("?", ".") var arr2 = arrangement.replaceFirst("?", "#") getAllPermutations(arr1, permutations); getAllPermutations(arr2, permutations); } else { permutations.add(arrangement); } } private fun second() { var lineNum = 0; input.forEach { line -> possibleArrangementsForPartTwo(line); lineNum++; } println("") println("") println("") println("") println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!") println("") println("") println("") println("") println("second: $resultSecond") } } }
0
Kotlin
0
0
0dffdeba1ebe0b44d24f94895f16f0f21ac8b7a3
8,380
advent-of-code
Apache License 2.0
src/main/kotlin/adventofcode2020/solution/Day8.kt
lhess
320,667,380
false
null
package adventofcode2020.solution import adventofcode2020.Solution import adventofcode2020.resource.PuzzleInput class Day8(puzzleInput: PuzzleInput<String>) : Solution<String, Int>(puzzleInput) { override fun runPart1() = CPU(puzzleInput).run { runCPU() check(state == CPU.State.HALTED) accumulator.apply { check(this == 1941) } } override fun runPart2() = puzzleInput.indices .mapNotNull { when (puzzleInput[it].take(3)) { "jmp" -> it to puzzleInput[it].replace("jmp", "nop") "nop" -> it to puzzleInput[it].replace("nop", "jmp") else -> null } } .map { (pos, instruction) -> CPU(puzzleInput.toMutableList().apply { this[pos] = instruction }.toList()).run { runCPU() to accumulator } } .firstOrNull { it.first == CPU.State.DONE } .run { check(this != null) check(first == CPU.State.DONE) check(second == 2096) second } class CPU(private val instructions: List<String>) : Iterable<CPU.State> { init { check(instructions.isNotEmpty()) } enum class State { IDLE, HALTED, RUNNING, DONE } private abstract class Instruction { abstract fun runInstruction(cpu: CPU): Int? class Acc(private val value: Int) : Instruction() { override fun runInstruction(cpu: CPU): Int? { cpu.accumulator += value return null } } class Jmp(private val value: Int) : Instruction() { override fun runInstruction(cpu: CPU) = value } class Nop() : Instruction() { override fun runInstruction(cpu: CPU): Int? = null } companion object { fun of(command: String, argument: Int?) = when (command) { "acc" -> argument?.run(::Acc) ?: error("acc needs one argument") "jmp" -> argument?.run(::Jmp) ?: error("jmp needs one argument") "nop" -> Nop() else -> error("unknown command $command") } } } private var _state = State.IDLE private var _accumulator = 0 private val executed = mutableSetOf<Int>() private var instructionPointer: Int = 0 var accumulator: Int get() = _accumulator private set(value) { _accumulator = value } var state: State get() = _state private set(state) { _state = state } override fun iterator(): Iterator<State> = object : Iterator<State> { override fun hasNext() = instructionPointer == 0 || state == State.RUNNING override fun next(): State = run() } private fun run(): State { if (state in listOf(State.IDLE, State.RUNNING)) { state = if (executed.add(instructionPointer)) { instructions[instructionPointer] .run(::decode) .runInstruction(this) .let { (it ?: 1) + instructionPointer } .takeIf { it <= instructions.size } ?.let { if (it == instructions.size) State.DONE else { instructionPointer = it State.RUNNING } } ?: error("instruction no. $instructionPointer leads to invalid position") } else State.HALTED } return state } private fun decode(input: String): Instruction = input.splitAtIndex(3).let { (instruction, argument) -> Instruction.of(instruction, argument?.toInt()) } private fun String.splitAtIndex(index: Int) = take(index) to if (index + 1 in 0..length) substring(index + 1) else null } private fun CPU.runCPU(): CPU.State = first { it != CPU.State.RUNNING } }
0
null
0
1
cfc3234f79c27d63315994f8e05990b5ddf6e8d4
4,460
adventofcode2020
The Unlicense
src/Day01.kt
mnajborowski
573,619,699
false
{"Kotlin": 7975}
fun main() { fun part1(input: List<String>): Int { var mostCalories = 0 input.fold(0) { acc, item -> if (item.isBlank()) { if (acc > mostCalories) mostCalories = acc 0 } else acc + item.toInt() } return mostCalories } fun part2(input: List<String>): Int { val totalCaloriesPerElf = mutableListOf<Int>() input.fold(0) { acc, item -> if (item.isBlank()) { totalCaloriesPerElf.add(acc) 0 } else acc + item.toInt() } return totalCaloriesPerElf.sortedDescending().take(3).sum() } val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
e54c13bc5229c6cb1504db7e3be29fc9b9c4d386
810
advent-of-code-2022
Apache License 2.0
src/main/kotlin/com/bajdcc/util/intervalTree/IntervalNode.kt
bajdcc
32,624,604
false
{"Kotlin": 1131761, "HTML": 42480, "CSS": 37889, "JavaScript": 2703}
package com.bajdcc.util.intervalTree import java.util.* /** * The Node class contains the interval tree information for one single node * * @author <NAME> */ class IntervalNode<Type>(intervalList: List<Interval<Type>>) { private var intervals: SortedMap<Interval<Type>, MutableList<Interval<Type>>> = TreeMap() var center: Long = 0 var left: IntervalNode<Type>? = null var right: IntervalNode<Type>? = null init { val endpoints = TreeSet<Long>() intervalList.forEach { interval -> endpoints.add(interval.start) endpoints.add(interval.end) } val median = getMedian(endpoints)!! center = median val left = mutableListOf<Interval<Type>>() val right = mutableListOf<Interval<Type>>() intervalList.forEach { interval -> when { interval.end < median -> left.add(interval) interval.start > median -> right.add(interval) else -> { val posting = intervals.computeIfAbsent(interval) { _ -> mutableListOf() } posting.add(interval) } } } if (left.size > 0) this.left = IntervalNode(left) if (right.size > 0) this.right = IntervalNode(right) } /** * Perform a stabbing query on the node * * @param time the time to query at * @return all intervals containing time */ fun stab(time: Long): List<Interval<Type>> { val result = mutableListOf<Interval<Type>>() for ((key, value) in intervals) { if (key.contains(time)) result.addAll(value) else if (key.start > time) break } if (time < center && left != null) result.addAll(left!!.stab(time)) else if (time > center && right != null) result.addAll(right!!.stab(time)) return result } /** * Perform an interval intersection query on the node * * @param target the interval to intersect * @return all intervals containing time */ fun query(target: Interval<*>): List<Interval<Type>> { val result = mutableListOf<Interval<Type>>() for ((key, value) in intervals) { if (key.intersects(target)) result.addAll(value) else if (key.start > target.end) break } if (target.start < center && left != null) result.addAll(left!!.query(target)) if (target.end > center && right != null) result.addAll(right!!.query(target)) return result } /** * @param set the set to look on * @return the median of the set, not interpolated */ private fun getMedian(set: SortedSet<Long>): Long? { val middle = set.size / 2 return set .asSequence() .filterIndexed { i, _ -> i == middle } .firstOrNull() } override fun toString(): String { val sb = StringBuilder() sb.append(center).append(": ") intervals.forEach { (key, value) -> sb.append("[").append(key.start).append(",").append(key.end).append("]:{") value.forEach { interval -> sb.append("(").append(interval.start).append(",").append(interval.end).append(",").append(interval.data).append(")") } sb.append("} ") } return sb.toString() } }
0
Kotlin
20
65
90b19af98da99b53bba5b3269ad5666df7c05e49
3,540
jMiniLang
MIT License
2022/src/day01/day01.kt
Bridouille
433,940,923
false
{"Kotlin": 171124, "Go": 37047}
package day01 import readInput fun List<String>.toElvesCalories(): List<Int> { val elves = mutableListOf<Int>() foldIndexed(0) { idx, acc, value -> if (value.isEmpty() || idx == size - 1) { 0.also { elves.add(acc) } } else { acc + value.toInt() } } return elves } fun part1(input: List<String>) = input.toElvesCalories().sortedDescending().first() fun part2(input: List<String>) = input.toElvesCalories().sortedDescending().let { it[0] + it[1] + it[2] } fun main() { val testInput = readInput("day01_example.txt", false) println("part1 example = " + part1(testInput)) println("part2 example = " + part2(testInput)) val input = readInput("day01.txt", false) println("part1 input = " + part1(input)) println("part2 input = " + part2(input)) }
0
Kotlin
0
2
8ccdcce24cecca6e1d90c500423607d411c9fee2
840
advent-of-code
Apache License 2.0
year2021/day21/part2/src/main/kotlin/com/curtislb/adventofcode/year2021/day21/part2/Year2021Day21Part2.kt
curtislb
226,797,689
false
{"Kotlin": 2146738}
/* --- Part Two --- Now that you're warmed up, it's time to play the real game. A second compartment opens, this time labeled Dirac dice. Out of it falls a single three-sided die. As you experiment with the die, you feel a little strange. An informational brochure in the compartment explains that this is a quantum die: when you roll it, the universe splits into multiple copies, one copy for each possible outcome of the die. In this case, rolling the die always splits the universe into three copies: one where the outcome of the roll was 1, one where it was 2, and one where it was 3. The game is played the same as before, although to prevent things from getting too far out of hand, the game now ends when either player's score reaches at least 21. Using the same starting positions as in the example above, player 1 wins in 444356092776315 universes, while player 2 merely wins in 341960390180808 universes. Using your given starting positions, determine every possible outcome. Find the player that wins in more universes; in how many universes does that player win? */ package com.curtislb.adventofcode.year2021.day21.part2 import com.curtislb.adventofcode.year2021.day21.dice.DiceGameState import com.curtislb.adventofcode.year2021.day21.dice.dirac.DiracDice import com.curtislb.adventofcode.year2021.day21.dice.dirac.DiracDiceGame import java.nio.file.Path import java.nio.file.Paths /** * Returns the solution to the puzzle for 2021, day 21, part 2. * * @param inputPath The path to the input file for this puzzle. * @param diceCount The number of [DiracDice] a player must roll on their turn. * @param dieSidesCount The number of sides on each of the [DiracDice]. * @param winningScore The minimum score a player needs to win the game. */ fun solve( inputPath: Path = Paths.get("..", "input", "input.txt"), diceCount: Int = 3, dieSidesCount: Int = 3, winningScore: Int = 21 ): Long { // Count all possible winning states of the game val initialState = DiceGameState.fromFile(inputPath.toFile()) val dice = DiracDice(diceCount, dieSidesCount) val game = DiracDiceGame(initialState, dice) val stateCounts = game.countPossibleEndStates(winningScore) // Count the universes in which each player wins val playerWinCounts = LongArray(initialState.players.size) for ((state, count) in stateCounts.entries) { playerWinCounts[state.getWinner(winningScore)] += count } return playerWinCounts.max() } fun main() { println(solve()) }
0
Kotlin
1
1
6b64c9eb181fab97bc518ac78e14cd586d64499e
2,522
AdventOfCode
MIT License
src/Day01.kt
palex65
572,937,600
false
{"Kotlin": 68582}
fun List<String>.toCalories() = splitBy { it.isEmpty() } // List<List<String>> .map { it.map { it.toInt() }.sum() } // List<Int> fun part1(calories: List<Int>) = calories.max() fun part2(calories: List<Int>) = calories.sorted().takeLast(3).sum() fun main() { val testCalories = readInput("Day01_test").toCalories() check(part1(testCalories) == 24000) check(part2(testCalories) == 45000) val calories = readInput("Day01").toCalories() println(part1(calories)) // 69795 println(part2(calories)) // 208437 }
0
Kotlin
0
2
35771fa36a8be9862f050496dba9ae89bea427c5
562
aoc2022
Apache License 2.0
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[69]x 的平方根.kt
maoqitian
175,940,000
false
{"Kotlin": 354268, "Java": 297740, "C++": 634}
//实现 int sqrt(int x) 函数。 // // 计算并返回 x 的平方根,其中 x 是非负整数。 // // 由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。 // // 示例 1: // // 输入: 4 //输出: 2 // // // 示例 2: // // 输入: 8 //输出: 2 //说明: 8 的平方根是 2.82842..., //  由于返回类型是整数,小数部分将被舍去。 // // Related Topics 数学 二分查找 // 👍 730 👎 0 //leetcode submit region begin(Prohibit modification and deletion) class Solution { fun mySqrt(x: Int): Int { //二分查找 //时间复杂度 O(logn) if(x == 0 || x == 1) return x var left = 0 var right = x var res = -1 while(left <= right){ val mid = left + (right - left)/2 //如果当前值得平方小于等于 x 说明找到相近的 if (mid * mid.toLong() <= x){ res = mid left = mid+1 }else{ //太大继续缩小范围 right = mid -1 } } return res } } //leetcode submit region end(Prohibit modification and deletion)
0
Kotlin
0
1
8a85996352a88bb9a8a6a2712dce3eac2e1c3463
1,202
MyLeetCode
Apache License 2.0
src/org/prime/util/Converter.kt
miloserdova-l
433,512,408
true
{"Kotlin": 31409}
package org.prime.util import org.prime.util.machines.Direction import org.prime.util.machines.TapeMachine interface Converter { fun machineToGrammar(machine: TapeMachine): Grammar } object Constants { const val EPSILON = "epsilon" const val RIGHT = ">" const val COMMENT = "//" const val BLANK = "_" const val COMMA_DELIM = "," } class ConverterT0 : Converter { override fun machineToGrammar(machine: TapeMachine): Grammar { val sigmaStrings = machine.sigma val initStr = machine.startState val gammaStrings = machine.gamma val acceptStr = machine.acceptState val nonTerminals = ArrayList<String>() (sigmaStrings + listOf(Constants.EPSILON)).forEach { X -> gammaStrings.forEach { Y -> nonTerminals.add(getBracketSymbol(X, Y)) } } nonTerminals.addAll(listOf("A1", "A2", "A3")) nonTerminals.addAll(machine.states) val productions = ArrayList<Production>() // following Martynenko: https://core.ac.uk/download/pdf/217165386.pdf // (1) productions.add(Production(listOf("A1"), listOf(initStr, "A2"))) // (2) sigmaStrings.forEach { productions.add(Production(listOf("A2"), listOf(getBracketSymbol(it, it), "A2"))) } // (3) productions.add(Production(listOf("A2"), listOf("A3"))) // (4) productions.add(Production(listOf("A3"), listOf(getBracketSymbol(Constants.EPSILON, Constants.BLANK), "A3"))) // (5) productions.add(Production(listOf("A3"), listOf(Constants.EPSILON))) val (deltasRight, deltasLeft) = machine.deltaTransitions.partition { it.direction == Direction.RIGHT } // (6) deltasRight.forEach { delta -> (sigmaStrings + listOf(Constants.EPSILON)).forEach { productions.add(Production(listOf(delta.currentState, getBracketSymbol(it, delta.readSymbol)), listOf(getBracketSymbol(it, delta.writeSymbol), delta.nextState))) } } // (7) deltasLeft.forEach { delta -> (sigmaStrings + listOf(Constants.EPSILON)).forEach { a -> (sigmaStrings + listOf(Constants.EPSILON)).forEach { b -> gammaStrings.forEach { E -> productions.add(Production(listOf(getBracketSymbol(b, E), delta.currentState, getBracketSymbol(a, delta.readSymbol)), listOf(delta.nextState, getBracketSymbol(b, E), getBracketSymbol(a, delta.writeSymbol)))) } } } } // (8) (sigmaStrings + listOf(Constants.EPSILON)).forEach { a -> gammaStrings.forEach { C -> productions.add( Production(listOf(getBracketSymbol(a, C), acceptStr), listOf(acceptStr, a, acceptStr)) ) productions.add( Production(listOf(acceptStr, getBracketSymbol(a, C)), listOf(acceptStr, a, acceptStr)) ) productions.add( Production(listOf(acceptStr), listOf(Constants.EPSILON)) ) } } return Grammar(sigmaStrings, "A1", productions.distinct()) } private fun getBracketSymbol(left: String, right: String) = "($left|$right)" } class ConverterT1 : Converter { override fun machineToGrammar(machine: TapeMachine): Grammar { val sigmaStrings = machine.sigma val initStr = machine.startState val gammaStrings = machine.gamma val acceptStr = machine.acceptState val productions = ArrayList<Production>() for (sigma in sigmaStrings) { productions.add(Production(listOf("A1"), listOf("($initStr|_|$sigma|$sigma|_)"))) productions.add(Production(listOf("A1"), listOf("($initStr|_|$sigma|$sigma)", "A2"))) productions.add(Production(listOf("A2"), listOf("($sigma|$sigma)", "A2"))) productions.add(Production(listOf("A2"), listOf("($sigma|$sigma|_)"))) } for (delta in machine.deltaTransitions) { for (sigma in sigmaStrings) { if (delta.direction == Direction.RIGHT) { if (delta.readSymbol == "_") { for (e in gammaStrings) { productions.add( Production( listOf("(" + delta.currentState + "|_|" + e + "|" + sigma + "|_)"), listOf("(_|" + delta.nextState + "|" + e + "|" + sigma + "|_)") ) ) } } else { productions.add( Production( listOf("(_|" + delta.currentState + "|" + delta.readSymbol + "|" + sigma + "|_)"), listOf("(_|" + delta.writeSymbol + "|" + sigma + "|" + delta.nextState + "|_)") ) ) } } else { if (delta.readSymbol == "_") { for (gamma in gammaStrings) { productions.add( Production( listOf("(_|" + gamma + "|" + sigma + "|" + delta.currentState + "|_)"), listOf("(_|" + delta.nextState + "|" + gamma + "|" + sigma + "|_)") ) ) } } else { productions.add( Production( listOf("(_|" + delta.currentState + "|" + delta.readSymbol + "|" + sigma + "|_)"), listOf("(" + delta.nextState + "|_|" + delta.writeSymbol + "|" + sigma + "|_)") ) ) } } } } for (sigma in sigmaStrings) { for (gamma in gammaStrings) { productions.add(Production(listOf("($acceptStr|_|$gamma|$sigma|_)"), listOf(sigma))) productions.add(Production(listOf("(_|$acceptStr|$gamma|$sigma|_)"), listOf(sigma))) productions.add(Production(listOf("(_|$gamma|$sigma|$acceptStr|_)"), listOf(sigma))) } } for (delta in machine.deltaTransitions) { for (sigma in sigmaStrings) { if (delta.direction == Direction.RIGHT) { if (delta.readSymbol == "_") { for (gamma in gammaStrings) { productions.add( Production( listOf("(" + delta.currentState + "|_|" + gamma + "|" + sigma + ")"), listOf("(_|" + delta.nextState + "|" + gamma + "|" + sigma + ")") ) ) } } else { for (gamma in gammaStrings) { for (s1 in sigmaStrings) { productions.add( Production( listOf("(_|" + delta.currentState + "|" + delta.readSymbol + "|" + sigma + ")", "($gamma|$s1)"), listOf("(_|" + delta.writeSymbol + "|" + sigma + ")", "(" + delta.nextState + "|" + gamma + "|" + s1 + ")") ) ) productions.add( Production( listOf("(_|" + delta.currentState + "|" + delta.readSymbol + "|" + sigma + ")", "($gamma|$s1|_)"), listOf("(_|" + delta.writeSymbol + "|" + sigma + ")", "(" + delta.nextState + "|" + gamma + "|" + s1 + "_)") ) ) } } } } else { productions.add( Production( listOf("(_|" + delta.currentState + "|" + delta.readSymbol + "|" + sigma + ")"), listOf("(" + delta.nextState + "|_|" + delta.writeSymbol + "|" + sigma + ")") ) ) } } } for (delta in machine.deltaTransitions) { for (s1 in sigmaStrings) { for (s2 in sigmaStrings) { if (delta.direction == Direction.RIGHT) { for (gamma in gammaStrings) { productions.add( Production( listOf("(" + delta.currentState + "|" + delta.readSymbol + "|" + s1 + ")", "($gamma|$s2)"), listOf("(" + delta.writeSymbol + "|" + s1 + ")", "(" + delta.nextState + "|" + gamma + "|" + s2 + ")") ) ) productions.add( Production( listOf("(" + delta.currentState + "|" + delta.readSymbol + "|" + s1 + ")", "($gamma|$s2|_)"), listOf("(" + delta.writeSymbol + "|" + s1 + ")", "(" + delta.nextState + "|" + gamma + "|" + s2 + "|_)") ) ) } } else { for (gamma in gammaStrings) { productions.add( Production( listOf("($gamma|$s2)", "(" + delta.currentState + "|" + delta.readSymbol + "|" + s1 + ")"), listOf("(" + delta.nextState + "|" + gamma + "|" + s2 + ")", "(" + delta.writeSymbol + "|" + s1 + ")") ) ) productions.add( Production( listOf("(_|$gamma|$s2)", "(" + delta.currentState + "|" + delta.readSymbol + "|" + s1 + ")"), listOf("(_|" + delta.nextState + "|" + gamma + "|" + s2 + ")", "(" + delta.writeSymbol + "|" + s1 + ")") ) ) } } } } } for (delta in machine.deltaTransitions) { for (sigma in sigmaStrings) { if (delta.direction == Direction.RIGHT) { productions.add( Production( listOf("(" + delta.currentState + "|" + delta.readSymbol + "|" + sigma + "|_)"), listOf("(" + delta.writeSymbol + "|" + sigma + "|" + delta.nextState + "|_)") ) ) } else { if (delta.readSymbol == "_") { for (gamma in gammaStrings) { productions.add( Production( listOf("(" + gamma + "|" + sigma + "|" + delta.currentState + "|_)"), listOf("(" + delta.nextState + "|" + gamma + "|" + sigma + "|_)") ) ) } } else { for (gamma in gammaStrings) { for (s1 in sigmaStrings) { productions.add( Production( listOf("(" + gamma + "|" + s1 + ")", "(" + delta.currentState + "|" + delta.readSymbol + "|" + sigma + "|_)"), listOf("(" + delta.nextState + "|" + gamma + "|" + s1 + "_)", "(" + delta.writeSymbol + "|" + sigma + "|_)") ) ) } } } } } } for (sigma in sigmaStrings) { for (gamma in gammaStrings) { productions.add( Production(listOf("(" + acceptStr + "|_|" + gamma + "|" + sigma + ")"), listOf(sigma)) ) productions.add( Production(listOf("(_|" + acceptStr + "|" + gamma + "|" + sigma + ")"), listOf(sigma)) ) productions.add( Production(listOf("(" + acceptStr + "|" + gamma + "|" + sigma + ")"), listOf(sigma)) ) productions.add( Production(listOf("(" + acceptStr + "|" + gamma + "|" + sigma + "|_)"), listOf(sigma)) ) productions.add( Production(listOf("(" + gamma + "|" + sigma + "|" + acceptStr + "|_)"), listOf(sigma)) ) } } for (s1 in sigmaStrings) { for (s2 in sigmaStrings) { for (gamma in gammaStrings) { productions.add( Production(listOf(s1, "(" + gamma + "|" + s2 + ")"), listOf(s1, s2)) ) productions.add( Production(listOf(s1, "(" + gamma + "|" + s2 + "|_)"), listOf(s1, s2)) ) productions.add( Production(listOf("(" + gamma + "|" + s1 + ")", s2), listOf(s1, s2)) ) productions.add( Production(listOf("(_|" + gamma + "|" + s1 + ")", s2), listOf(s1, s2)) ) } } } return Grammar(sigmaStrings,"A1", productions.distinct()) } }
0
Kotlin
0
0
f912a88f65458effce107318efc0a2a82ece45aa
14,376
primary-numbers-grammar
MIT License
src/Day06.kt
fercarcedo
573,142,185
false
{"Kotlin": 60181}
private const val START_OF_PACKET_MARKER_LENGTH = 4 private const val START_OF_MESSAGE_MARKER_LENGTH = 14 private const val MARKER_NOT_FOUND = -1 fun main() { fun play(input: List<String>, markerLength: Int): Int { val line = input[0] for (i in 0 until line.length - markerLength) { val possibleMarker = line.substring(i, i + markerLength) if (possibleMarker.toSet().size == possibleMarker.length) { return i + markerLength } } return MARKER_NOT_FOUND } fun part1(input: List<String>) = play(input, START_OF_PACKET_MARKER_LENGTH) fun part2(input: List<String>) = play(input, START_OF_MESSAGE_MARKER_LENGTH) val testInput = readInput("Day06_test") check(part1(testInput) == 7) check(part2(testInput) == 19) val testInput2 = readInput("Day06_test2") check(part1(testInput2) == 5) check(part2(testInput2) == 23) val testInput3 = readInput("Day06_test3") check(part1(testInput3) == 6) check(part2(testInput3) == 23) val testInput4 = readInput("Day06_test4") check(part1(testInput4) == 10) check(part2(testInput4) == 29) val testInput5 = readInput("Day06_test5") check(part1(testInput5) == 11) check(part2(testInput5) == 26) val input = readInput("Day06") println(part1(input)) // 1804 println(part2(input)) // 2508 }
0
Kotlin
0
0
e34bc66389cd8f261ef4f1e2b7f7b664fa13f778
1,395
Advent-of-Code-2022-Kotlin
Apache License 2.0
src/Day25.kt
frungl
573,598,286
false
{"Kotlin": 86423}
fun main() { fun Long.toSnafu(): String { var s = "" var n = this while (n > 0L) { val rem = n % 5L var res = n / 5L if (rem < 3L) s += rem.toString() else { if (rem == 3L) s += "=" else s += "-" res++ } n = res } return s.reversed() } fun String.fromSnafu(): Long { var n = 0L var m = 1L this.reversed().forEach { n += when (it) { '=' -> m * -2L '-' -> m * -1L else -> m * it.toString().toLong() } m *= 5L } return n } fun part1(input: List<String>): String { val sum = input.sumOf { it.fromSnafu() } return sum.toSnafu() } fun part2(input: List<String>): Int { return 0 } val testInput = readInput("Day25_test") check(part1(testInput) == "2=-1=0") check(part2(testInput) == 0) val input = readInput("Day25") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d4cecfd5ee13de95f143407735e00c02baac7d5c
1,180
aoc2022
Apache License 2.0
src/main/kotlin/leetcode/kotlin/dp/hard/85. Maximal Rectangle.kt
sandeep549
251,593,168
false
null
package leetcode.kotlin.dp.hard private fun maximalRectangle(matrix: Array<CharArray>): Int { /** * Consider all rectangle which has top left corner at r,c index. * For every row, find max area with minimum column size which has all 1 in it. * Traverse every row top to down and keep track of minimum column length found so far which has all 1. * At every row calculate max area with current row distance and minimum column size distance and keep track of max so far. */ fun maxAreaAt(i: Int, j: Int): Int { var max = 0 if (matrix[i][j] == '0') return max var minC = Int.MAX_VALUE for (r in i..matrix.lastIndex) { var c = j while (c < matrix[0].size && matrix[r][c] == '1') c++ minC = minOf(minC, c - 1) var currArea = (r - i + 1) * (minC - j + 1) max = maxOf(max, currArea) } return max } var ans = 0 for (r in matrix.indices) { for (c in matrix[0].indices) { ans = maxOf(ans, maxAreaAt(r, c)) } } return ans } private fun maximalRectangle2(matrix: Array<CharArray>): Int { if (matrix.isEmpty()) return 0 var r = matrix.size var c = matrix[0].size var left = IntArray(c) { 0 } // init left with leftmost boundary var right = IntArray(c) { c } // init right with rightmost boundary var height = IntArray(c) var max = 0 for (i in 0 until r) { var cur_left = 0 // rightmost occurrence of zero encountered var cur_right = c // update height for (j in 0 until c) { if (matrix[i][j] == '1') height[j]++ else height[j] = 0 } // update left for (j in 0 until c) { if (matrix[i][j] == '1') left[j] = maxOf(left[j], cur_left) else { left[j] = 0 cur_left = j + 1 } } // update right for (j in c - 1 downTo 0) { if (matrix[i][j] == '1') right[j] = minOf(right[j], cur_right) else { right[j] = c cur_right = j } } // update area for (j in 0 until c) { max = maxOf(max, ((right[j] - left[j]) * height[j])) } } return max }
0
Kotlin
0
0
9cf6b013e21d0874ec9a6ffed4ae47d71b0b6c7b
2,330
kotlinmaster
Apache License 2.0
Android Kotlin/KotlinFunny/app/src/main/kotlin/ru/guar7387/kotlinfunny/features/collections.kt
ArturVasilov
34,915,513
false
{"Java": 5837467, "Kotlin": 29850}
package ru.guar7387.kotlinfunny.features import java.util.ArrayList import java.util.HashMap public fun listTest() { val immutableList = listOf(1, 2, 3, 4, 5) val list = ArrayList<Int>() for (value in immutableList) { list.add(value) } assert(list.size() == 5) assert(list.sum() == 15) assert(list.min() == 1) assert(list.max() == 5) assert(list[3] == 4) list[3] = 5; } public fun mapTest() { val immutableMap = mapOf(1 to "Vasya", 2 to "Kolya", 3 to "Oleg") val map = HashMap<Int, String>() for ((key, value) in immutableMap) { map.put(key, value) } assert(map.size() == 3) assert(map[1] == "Vasya") map[2] = "Olezhka" } public fun collectionsWithLambdas() { val list = listOf(1, 2, 3, 4, 5) list.forEach { print(it) } //list.forEach( { print(it) } ) val filtered = list.filter { it >= 3 } assert(filtered[1] == 4) val map = list.toMap { it * 31 } assert(map[31] == 1) val partitioned = list.partition { it % 2 == 1 } assert(partitioned.first[1] == 1) assert(partitioned.second[0] == 2) val sum = list.reduce { sum, value -> sum + value } assert(sum == list.sum()) } public fun maps() { val map = mapOf(1 to "Vasya", 2 to "Kolya", 3 to "Oleg") map.forEach { print(it.getKey().toString() + ":" + it.getValue()) } val keys = map.keySet() val values = map.values() val filtered = map.filter { it.getValue().length() > 4 } assert(filtered.size() == 2) }
0
Java
0
3
3a6483468c896fc97080680918e90d61983d3c23
1,525
AndroidCourses
Apache License 2.0
FineMedianSortedArrays.kt
linisme
111,369,586
false
null
class FindMedianSortedArraysSolution { fun findMedianSortedArrays(nums1: IntArray, nums2: IntArray): Double { var i1 = 0 var i2 = 0 var length1 = nums1.size var length2 = nums2.size var sortedSize = length1 + length2 var sortedArray = IntArray(sortedSize) var k = 0 while (i1 < length1 || i2 < length2) { var e1 = if (i1 < length1)nums1[i1] else null var e2 = if (i2 < length2)nums2[i2] else null if (e2 == null || (e1 != null && e1 < e2)) { sortedArray[k] = e1!! i1++ } else { sortedArray[k] = e2 i2++ } k++ } if (sortedSize > 1 && sortedSize % 2 == 0) { return (sortedArray[sortedSize / 2] + sortedArray[sortedSize / 2 - 1]) / 2.0 } else { return sortedArray[sortedSize / 2].toDouble() } } } fun main(args: Array<String>) { println(FindMedianSortedArraysSolution().findMedianSortedArrays(intArrayOf(), intArrayOf(2,3))) }
0
Kotlin
1
0
4382afcc782da539ed0d535c0a5b3a257e0c8097
1,013
LeetCodeInKotlin
MIT License
src/main/kotlin/homework5/ParserTree.kt
martilut
342,898,976
false
{"Kotlin": 107965}
package homework5 interface ParserTreeNode { fun calculate(): Int fun outputValue(height: Int): String } class OperandNode(private val value: Int) : ParserTreeNode { override fun calculate(): Int = value override fun outputValue(height: Int): String = ".".repeat(height) + this.value.toString() + "\n" } class OperatorNode( private val operator: String?, private var leftChild: ParserTreeNode, private var rightChild: ParserTreeNode ) : ParserTreeNode { override fun calculate(): Int { return when (operator) { OperationType.PLUS.value -> leftChild.calculate() + rightChild.calculate() OperationType.MINUS.value -> leftChild.calculate() - rightChild.calculate() OperationType.MULTIPLY.value -> leftChild.calculate() * rightChild.calculate() OperationType.DIVIDE.value -> { val leftValue = leftChild.calculate() val rightValue = rightChild.calculate() if (rightValue == 0) { throw IllegalArgumentException("Division by zero") } else { leftValue / rightValue } } else -> throw IllegalArgumentException("Your expression is incorrect") } } override fun outputValue(height: Int): String { return ".".repeat(height) + this.operator + "\n" + this.leftChild.outputValue(height * 2) + this.rightChild.outputValue(height * 2) } } class ParserTree(inputExpression: List<String>) { private val root = parseExpression(inputExpression).treeRoot fun getResult(): Int = root.calculate() fun getOutputTree(): String = root.outputValue(1) data class ParserData(val treeRoot: ParserTreeNode, val currentList: List<String>) private fun parseExpression(expression: List<String>): ParserData { return when { expression.first().toIntOrNull() != null -> { ParserData(OperandNode(expression.first().toInt()), expression.drop(1)) } else -> { val operator = expression.first() if (operationContains(operator) == null) { throw IllegalArgumentException("Your operators or operands are incorrect") } var currentData = parseExpression(expression.drop(1)) val left = currentData.treeRoot currentData = parseExpression(currentData.currentList) val right = currentData.treeRoot return ParserData(OperatorNode(operator, left, right), currentData.currentList) } } } }
0
Kotlin
0
0
091a57cbca3fca8869ea5b61d2e0f2f77ccdb792
2,692
spbu_2021_kotlin_homeworks
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/DivideArrayWithMaxDifference.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2024 <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 /** * 2966. Divide Array Into Arrays With Max Difference * @see <a href="https://leetcode.com/problems/divide-array-into-arrays-with-max-difference">Source</a> */ fun interface DivideArrayWithMaxDifference { operator fun invoke(nums: IntArray, k: Int): Array<IntArray> } class DivideArrayWithMaxDifferenceSort : DivideArrayWithMaxDifference { override fun invoke(nums: IntArray, k: Int): Array<IntArray> { nums.sort() val ans = Array(nums.size / 3) { IntArray(3) } var i = 0 while (i < nums.size) { if (nums[i + 2] - nums[i] > k) { return Array(0) { IntArray(0) } } ans[i / 3] = intArrayOf(nums[i], nums[i + 1], nums[i + 2]) i += 3 } return ans } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,419
kotlab
Apache License 2.0
day13/src/Day13.kt
simonrules
491,302,880
false
{"Kotlin": 68645}
import java.io.File class Day13(path: String) { private val size = 2000 private val map = BooleanArray(size * size) private val folds = mutableListOf<Pair<Char, Int>>() private var width = 0 private var height = 0 init { File(path).forEachLine { if (it.contains(",")) { // dot val coord = it.split(",") val x = coord[0].toInt() val y = coord[1].toInt() if (x > width) { width = x } if (y > height) { height = y } setMapAt(x, y, true) } else if (it.contains("=")) { // fold val fold = it.split("=") folds.add(Pair(fold[0].last(), fold[1].toInt())) } } width++ height++ } private fun getMapAt(x: Int, y: Int): Boolean { return map[y * size + x] } private fun setMapAt(x: Int, y: Int, value: Boolean) { map[y * size + x] = value } private fun printMap(w: Int, h: Int) { for (i in 0 until h) { for (j in 0 until w) { print(if (getMapAt(j, i)) '#' else '.') } println() } println() } private fun countDots(w: Int, h: Int): Int { var count = 0 for (i in 0 until h) { for (j in 0 until w) { if (getMapAt(j, i)) { count++ } } } return count } private fun doFold(fold: Pair<Char, Int>) { val axis = fold.first val v = fold.second if (axis == 'x') { var jj = v - 1 for (j in v + 1 until width) { for (i in 0 until height) { val value = getMapAt(j, i) if (value) { setMapAt(jj, i, true) } } jj-- } width = v } else if (axis == 'y') { var ii = v - 1 for (i in v + 1 until height) { for (j in 0 until width) { val value = getMapAt(j, i) if (value) { setMapAt(j, ii, true) } } ii-- } height = v } } fun part1(): Int { val fold = folds[0] doFold(fold) return countDots(width, height) } fun part2(): Int { folds.forEach { doFold(it) } printMap(width, height) return 0 } } fun main() { val aoc = Day13("day13/input.txt") println(aoc.part1()) println(aoc.part2()) }
0
Kotlin
0
0
d9e4ae66e546f174bcf66b8bf3e7145bfab2f498
2,810
aoc2021
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/NumOfWaysGrid.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import dev.shtanko.algorithms.MOD /** * 1411. Number of Ways to Paint N × 3 Grid * @see <a href="https://leetcode.com/problems/number-of-ways-to-paint-n-3-grid">Source</a> */ fun interface NumOfWaysGrid { operator fun invoke(n: Int): Int } class NumOfWaysGridDP : NumOfWaysGrid { override operator fun invoke(n: Int): Int { val dp = Array(2) { LongArray(2) { 6 } } for (i in 1 until n) { dp[i % 2][0] = (dp[(i - 1) % 2][0] * 3 + dp[(i - 1) % 2][1] * 2) % MOD dp[i % 2][1] = (dp[(i - 1) % 2][0] * 2 + dp[(i - 1) % 2][1] * 2) % MOD } return ((dp[(n - 1) % 2][0] + dp[(n - 1) % 2][1]) % MOD).toInt() } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,317
kotlab
Apache License 2.0
year2021/day09/part2/src/main/kotlin/com/curtislb/adventofcode/year2021/day09/part2/Year2021Day09Part2.kt
curtislb
226,797,689
false
{"Kotlin": 2146738}
/* --- Part Two --- Next, you need to find the largest basins so you know what areas are most important to avoid. A basin is all locations that eventually flow downward to a single low point. Therefore, every low point has a basin, although some basins are very small. Locations of height 9 do not count as being in any basin, and all other locations will always be part of exactly one basin. The size of a basin is the number of locations within the basin, including the low point. The example above has four basins. The top-left basin, size 3: ``` 21........ 3......... .......... .......... .......... ``` The top-right basin, size 9: ``` .....43210 ......4.21 .........2 .......... .......... ``` The middle basin, size 14: ``` .......... ..878..... .85678.... 87678..... .8........ ``` The bottom-right basin, size 9: ``` .......... .......... .......8.. ......678. .....65678 ``` Find the three largest basins and multiply their sizes together. In the above example, this is 9 * 14 * 9 = 1134. What do you get if you multiply together the sizes of the three largest basins? */ package com.curtislb.adventofcode.year2021.day09.part2 import com.curtislb.adventofcode.common.comparison.takeLargest import com.curtislb.adventofcode.common.number.product import com.curtislb.adventofcode.year2021.day09.basin.HeightMap import java.nio.file.Path import java.nio.file.Paths /** * Returns the solution to the puzzle for 2021, day 9, part 2. * * @param inputPath The path to the input file for this puzzle. * @param basinCount How many of the largest basin sizes should be multiplied to get the result. */ fun solve(inputPath: Path = Paths.get("..", "input", "input.txt"), basinCount: Int = 3): Int { val heightMap = HeightMap(inputPath.toFile().readText()) return heightMap.findBasinSizes().takeLargest(basinCount).product() } fun main() { println(solve()) }
0
Kotlin
1
1
6b64c9eb181fab97bc518ac78e14cd586d64499e
1,891
AdventOfCode
MIT License
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[1078]Bigram 分词.kt
maoqitian
175,940,000
false
{"Kotlin": 354268, "Java": 297740, "C++": 634}
//给出第一个词 first 和第二个词 second,考虑在某些文本 text 中可能以 "first second third" 形式出现的情况,其中 se //cond 紧随 first 出现,third 紧随 second 出现。 // // 对于每种这样的情况,将第三个词 "third" 添加到答案中,并返回答案。 // // // // 示例 1: // // //输入:text = "alice is a good girl she is a good student", first = "a", second = //"good" //输出:["girl","student"] // // // 示例 2: // // //输入:text = "we will we will rock you", first = "we", second = "will" //输出:["we","rock"] // // // // // 提示: // // // 1 <= text.length <= 1000 // text 由小写英文字母和空格组成 // text 中的所有单词之间都由 单个空格字符 分隔 // 1 <= first.length, second.length <= 10 // first 和 second 由小写英文字母组成 // // Related Topics 字符串 // 👍 51 👎 0 //leetcode submit region begin(Prohibit modification and deletion) class Solution { fun findOcurrences(text: String, first: String, second: String): ArrayList<String> { //暴力求解 时间复杂度 O(n) var splitArray = text.split(" ") var resList = ArrayList<String>() for (i in 0 until splitArray.size-2){ if (splitArray[i] == first && splitArray[i+1] == second){ resList.add(splitArray[i+2]) } } return resList } } //leetcode submit region end(Prohibit modification and deletion)
0
Kotlin
0
1
8a85996352a88bb9a8a6a2712dce3eac2e1c3463
1,505
MyLeetCode
Apache License 2.0
archive/src/main/kotlin/com/grappenmaker/aoc/year22/Day15.kt
770grappenmaker
434,645,245
false
{"Kotlin": 409647, "Python": 647}
package com.grappenmaker.aoc.year22 import com.grappenmaker.aoc.* import com.grappenmaker.aoc.Direction.* fun PuzzleSet.day15() = puzzle { val scanners = inputLines.map { l -> val ints = l.splitInts() Scanner(Point(ints[0], ints[1]), Point(ints[2], ints[3])) } fun Point.isValid() = scanners.none { it.loc manhattanDistanceTo this <= it.distance } val min = scanners.minOf { it.loc.x - it.distance } val max = scanners.maxOf { it.loc.x + it.distance } partOne = (min..max).count { !Point(it, 2000000).isValid() }.s() val range = 0..4000000 val directions = listOf(DOWN + LEFT, DOWN + RIGHT, UP + LEFT, UP + RIGHT) val (x, y) = scanners.asSequence().flatMap { scan -> val away = scan.distance + 1 (0..away).flatMap { dx -> val dy = away - dx directions.map { (Point(dx, dy) * it) + scan.loc } }.filter { (x, y) -> x in range && y in range } }.first { it.isValid() } partTwo = (x.toLong() * 4000000 + y.toLong()).s() } data class Scanner(val loc: Point, val beacon: Point) { val distance = loc manhattanDistanceTo beacon }
0
Kotlin
0
7
92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585
1,139
advent-of-code
The Unlicense
solutions/src/CutTreeEdge.kt
JustAnotherSoftwareDeveloper
139,743,481
false
{"Kotlin": 305071, "Java": 14982}
/** * https://www.hackerrank.com/challenges/cut-the-tree/problem * * The problem made it seem like a tree, but was actually an undirected graph. * I decided to just call it a day on this one */ class CutTreeEdge { fun cutTheTree(data: Array<Int>, edges: Array<Array<Int>>): Int { val totalSum = data.sum() val edgeMap = mutableMapOf<Pair<Int,Int>,Int>() val edgeToEnding = mutableMapOf<Int,Pair<Int,Int>>() val edgeSums = mutableMapOf<Pair<Int,Int>,Int>() val connectionsForward = mutableMapOf<Int,MutableList<Int>>() val connectionsReversed = mutableMapOf<Int,Int>() edges.forEachIndexed { index, ints -> edgeMap[Pair(ints[0],ints[1])] = index+1 connectionsForward.computeIfAbsent(ints[0]-1){ mutableListOf()}.add(ints[1]-1) connectionsReversed[ints[1]-1] = ints[0]-1 } val queue = mutableListOf<Int>() for (i in data.indices) { if (!connectionsForward.containsKey(i)) { queue.add(i) } } while (queue.isNotEmpty()) { val current = queue.removeAt(0) if (connectionsReversed[current] != null) { val currentEdge = Pair(connectionsReversed[current]!!,current) val newSum = data[current] + connectionsForward.getOrDefault(current, mutableListOf()).map { edgeSums.getOrDefault(Pair(current,it),0) }.sum() edgeSums[currentEdge] = newSum queue.add(connectionsReversed[current]!!) } } var minPair = Pair(-1,-1) var minDifference = Int.MAX_VALUE for (edge in edgeSums.keys) { val difference = Math.abs(totalSum - edgeSums[edge]!!*2) if (difference < minDifference) { minDifference = difference minPair = edge } } return minDifference } }
0
Kotlin
0
0
fa4a9089be4af420a4ad51938a276657b2e4301f
1,936
leetcode-solutions
MIT License
src/kotlin2022/Day03.kt
egnbjork
571,981,366
false
{"Kotlin": 18156}
package kotlin2022 import readInput fun main() { val gameInput = readInput("Day03_test") println("task1 ${gameInput.sumOf { getCharPriority(findCommonChar(it)) }}") println("task2 ${gameInput.chunked(3).sumOf{ getCharPriority(findCommonChar(it)) }}") } fun findCommonChar(items: List<String>): Char { return items[0].toSet().intersect(items[1].toSet()).intersect(items[2].toSet()).first() } fun findCommonChar(items: String): Char { val string1CharSet = items.take(items.length/2).toSet() val string2CharSet = items.substring(items.length/2, items.length).toSet() return string1CharSet.intersect(string2CharSet).first() } fun getCharPriority(char: Char): Int { val asciiCode = char.code return if(asciiCode > 91) asciiCode - 96 else asciiCode - 65 + 27 }
0
Kotlin
0
0
1294afde171a64b1a2dfad2d30ff495d52f227f5
802
advent-of-code-kotlin
Apache License 2.0
src/main/kotlin/g0101_0200/s0200_number_of_islands/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0101_0200.s0200_number_of_islands // #Medium #Top_100_Liked_Questions #Top_Interview_Questions #Array #Depth_First_Search // #Breadth_First_Search #Matrix #Union_Find // #Algorithm_II_Day_6_Breadth_First_Search_Depth_First_Search // #Graph_Theory_I_Day_1_Matrix_Related_Problems #Level_1_Day_9_Graph/BFS/DFS #Udemy_Graph // #Big_O_Time_O(M*N)_Space_O(M*N) #2022_09_09_Time_252_ms_(95.41%)_Space_52.4_MB_(86.52%) class Solution { fun numIslands(grid: Array<CharArray>): Int { var islands = 0 if (grid.isNotEmpty() && grid[0].isNotEmpty()) { for (i in grid.indices) { for (j in grid[0].indices) { if (grid[i][j] == '1') { dfs(grid, i, j) islands++ } } } } return islands } private fun dfs(grid: Array<CharArray>, x: Int, y: Int) { if (x < 0 || grid.size <= x || y < 0 || grid[0].size <= y || grid[x][y] != '1') { return } grid[x][y] = 'x' dfs(grid, x + 1, y) dfs(grid, x - 1, y) dfs(grid, x, y + 1) dfs(grid, x, y - 1) } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,193
LeetCode-in-Kotlin
MIT License
src/main/aoc2015/Day14.kt
nibarius
154,152,607
false
{"Kotlin": 963896}
package aoc2015 import kotlin.math.min class Day14(input: List<String>) { data class Reindeer(val Name: String, val speed: Int, val duration: Int, val rest: Int) { var score = 0 var currentDistance = 0 private set private var currentTime = 0 private fun isMoving(): Boolean { val timeIntoCurrentCycle = currentTime % (duration + rest) // 0 means last second in the cycle while the reindeer is still resting return timeIntoCurrentCycle in 1..duration } fun tick() { currentTime++ if (isMoving()) currentDistance += speed } fun distanceAfter(seconds: Int): Int { val fullCycles = seconds / (duration + rest) val remainingTime = seconds % (duration + rest) val lastFlyTime = min(duration, remainingTime) return fullCycles * duration * speed + lastFlyTime * speed } } val reindeers = parseInput(input) private fun parseInput(input: List<String>): List<Reindeer> { return input.map { val parts = it.split(" ") Reindeer(parts.first(), parts[3].toInt(), parts[6].toInt(), parts[13].toInt()) } } fun solvePart1(seconds: Int = 2503): Int { return reindeers.maxOf { it.distanceAfter(seconds) } } private fun race(time: Int): Int { repeat(time) { reindeers.forEach { it.tick() } val leadingDistance = reindeers.maxByOrNull { it.currentDistance }!!.currentDistance reindeers.filter { it.currentDistance == leadingDistance } .forEach { it.score++ } } return reindeers.maxByOrNull { it.score }!!.score } fun solvePart2(seconds: Int = 2503): Int { return race(seconds) } }
0
Kotlin
0
6
f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22
1,841
aoc
MIT License
y2019/src/main/kotlin/adventofcode/y2019/Day07.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2019 import adventofcode.io.AdventSolution import adventofcode.language.intcode.IntCodeProgram import adventofcode.util.collections.cycle import adventofcode.util.collections.permutations fun main() = Day07.solve() object Day07 : AdventSolution(2019, 7, "Amplification Circuit") { override fun solvePartOne(input: String) = solve(input, 0L..4L) override fun solvePartTwo(input: String) = solve(input, 5L..9L) private fun solve(input: String, phases: LongRange) = phases.permutations() .map { permutation -> setupPrograms(input, permutation) } .map { programs -> runLoop(programs) } .maxOrNull() private fun setupPrograms(data: String, permutation: List<Long>): List<IntCodeProgram> = permutation.map { phase -> IntCodeProgram.fromData(data).apply { input(phase) } } private fun runLoop(programs: List<IntCodeProgram>): Long = programs.cycle() .takeWhile { it.state != IntCodeProgram.State.Halted } .fold(0L) { power, program -> program.input(power) program.execute() program.output()!! } }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
1,153
advent-of-code
MIT License
src/day02/Day02.kt
robin-schoch
572,718,550
false
{"Kotlin": 26220}
package day02 import AdventOfCodeSolution fun main() { Day02.run() } sealed class Shape { abstract val points: Int abstract fun losses(): Shape abstract fun wins(): Shape private fun draws() = this infix fun plays(opponent: Shape) = when (this) { opponent.draws() -> DRAW opponent.losses() -> WON opponent.wins() -> LOST else -> throw IllegalStateException("illegal shape") } fun shapeFromResult(result: Int): Shape = when (result) { DRAW -> this.draws() WON -> this.losses() LOST -> this.wins() else -> throw IllegalStateException("illegal game outcome") } companion object { const val DRAW = 3 const val WON = 6 const val LOST = 0 fun findShape(c: Char) = when (c) { 'A', 'X' -> Rock 'B', 'Y' -> Paper 'C', 'Z' -> Scissors else -> throw IllegalStateException("unknown figure") } fun findResult(c: Char) = when (c) { 'X' -> LOST 'Y' -> DRAW 'Z' -> WON else -> throw IllegalStateException("unsupported game outcome") } } } object Rock : Shape() { override val points = 1 override fun losses() = Paper override fun wins() = Scissors } object Scissors : Shape() { override val points = 3 override fun losses() = Rock override fun wins() = Paper } object Paper : Shape() { override val points = 2 override fun losses() = Scissors override fun wins() = Rock } object Day02 : AdventOfCodeSolution<Int, Int> { override val testSolution1 = 15 override val testSolution2 = 12 override fun part1(input: List<String>) = input.sumOf { val evilShape = Shape.findShape(it[0]) val myShape = Shape.findShape(it[2]) (myShape plays evilShape) + myShape.points } override fun part2(input: List<String>) = input.sumOf { val evilShape = Shape.findShape(it[0]) val result = Shape.findResult(it[2]) val myShape = evilShape.shapeFromResult(result) myShape.points + result } }
0
Kotlin
0
0
fa993787cbeee21ab103d2ce7a02033561e3fac3
2,142
aoc-2022
Apache License 2.0
src/main/kotlin/day11.kt
Gitvert
725,292,325
false
{"Kotlin": 97000}
import kotlin.math.abs const val EXPANSION_TIMES = 999999L fun day11 (lines: List<String>) { day11part1(lines) day11part2(lines) } fun day11part1(lines: List<String>) { val expanded = expandUniverse(lines) val positions = findGalaxyPositions(expanded) val totalManhattan = findManhattanDistance(positions) println("Day 11 part 1: $totalManhattan") } fun day11part2(lines: List<String>) { val positions = findGalaxyPositions(lines) val emptyRows = findEmptyRows(lines) val emptyCols = findEmptyCols(lines) val totalManhattan = findManhattanDistanceWithExpansions(positions, emptyRows, emptyCols) println("Day 11 part 2: $totalManhattan") println() } fun findManhattanDistanceWithExpansions(positions: List<GalaxyPosition>, emptyRows: List<Int>, emptyCols: List<Int>): Long { var totalManhattan = 0L for (i in positions.indices) { for (j in i+1..<positions.size) { val manhattan = abs(positions[j].x - positions[i].x) + abs(positions[j].y - positions[i].y) val crossedEmptyRows = emptyRows.filter { positions[i].y < it && positions[j].y > it }.size var crossedEmptyCols = 0 crossedEmptyCols = if (positions[i].x > positions[j].x) { emptyCols.filter { positions[j].x < it && positions[i].x > it}.size } else { emptyCols.filter { positions[i].x < it && positions[j].x > it}.size } totalManhattan += (manhattan + (crossedEmptyRows * EXPANSION_TIMES) + (crossedEmptyCols * EXPANSION_TIMES)) } } return totalManhattan } fun findEmptyRows(lines: List<String>): List<Int> { val emptyRows = mutableListOf<Int>() lines.forEachIndexed { index, line -> if (!line.contains("#")) { emptyRows.add(index) } } return emptyRows } fun findEmptyCols(lines: List<String>): List<Int> { val emptyCols = mutableListOf<Int>() val galaxyColCount = mutableListOf<Int>() lines.forEach { _ -> galaxyColCount.add(0) } lines.forEach { line -> line.forEachIndexed { index, cell -> if (cell == '#') { galaxyColCount[index]++ } } } galaxyColCount.forEachIndexed { index, it -> if (it == 0) { emptyCols.add(index) } } return emptyCols } fun findManhattanDistance(positions: List<GalaxyPosition>): Int { var totalManhattan = 0 for (i in positions.indices) { for (j in i+1..<positions.size) { val manhattan = abs(positions[j].x - positions[i].x) + abs(positions[j].y - positions[i].y) totalManhattan += manhattan } } return totalManhattan } fun findGalaxyPositions(expanded: List<String>): List<GalaxyPosition> { val positions = mutableListOf<GalaxyPosition>() expanded.forEachIndexed { y, row -> row.forEachIndexed { x, cell -> if (cell == '#') { positions.add(GalaxyPosition(x, y)) } } } return positions } fun expandUniverse(lines: List<String>): List<String> { val expanded = mutableListOf<String>() val galaxyColCount = mutableListOf<Int>() lines.forEach {line -> galaxyColCount.add(0) expanded.add(line) if (!line.contains("#")) { expanded.add(line) } } lines.forEach { line -> line.forEachIndexed { index, cell -> if (cell == '#') { galaxyColCount[index]++ } } } expanded.forEachIndexed {i, line -> var newLine = "" line.forEachIndexed { j, cell -> newLine += cell if (galaxyColCount[j] == 0) { newLine += '.' } } expanded[i] = newLine } return expanded } data class GalaxyPosition(val x: Int, val y: Int)
0
Kotlin
0
0
f204f09c94528f5cd83ce0149a254c4b0ca3bc91
4,025
advent_of_code_2023
MIT License
src/Day14.kt
erwinw
572,913,172
false
{"Kotlin": 87621}
@file:Suppress("MagicNumber") import kotlin.math.sign private const val DAY = "14" private const val PART1_CHECK = 24 private const val PART2_CHECK = 93 private enum class Rego { START, ROCK, SAND } private fun printGrid(grid: List<List<Rego?>>) { val withInit = grid.map { it.toMutableList() } withInit[0][500] = Rego.START val indents = withInit.map { line -> line.indexOfFirst { it != null } }.filterNot { it < 0 } val indent = indents.min() val outdents = withInit.map { line -> line.indexOfLast { it != null } }.filterNot { it < 0 } val outdent = 699 - outdents.max() withInit.forEach { line -> line.drop(indent).dropLast(outdent).forEach { item -> when (item) { null -> print(".") Rego.START -> print("+") Rego.ROCK -> print("#") Rego.SAND -> print("o") } } println("") } } private fun fillWithSand(grid: List<MutableList<Rego?>>): Int { val maxY = grid.size - 1 var settledCount = 0 var settled: Boolean var sy: Int do { sy = 0 var sx = 500 settled = false while (!settled && sy < maxY) { // println("Sand? $sx x $sy") when { grid[sy + 1][sx] == null -> { sy += 1 } grid[sy + 1][sx - 1] == null -> { sy += 1 sx -= 1 } grid[sy + 1][sx + 1] == null -> { sy += 1 sx += 1 } else -> settled = true } } // println("Grain done: $settled") if (settled) { settledCount += 1 grid[sy][sx] = Rego.SAND } // printGrid(grid) // println("\n--------\n") } while (settled && sy>0) return settledCount } fun main() { fun part1(input: List<String>): Int { var grid = List(200) { MutableList<Rego?>(700) { null } } input.forEach { line -> val steps = line.split(" -> ") .map { tuple -> val (x, y) = tuple.split(',').map(String::toInt) Pair(x, y) }.toMutableList() var (cx, cy) = steps.removeFirst() grid[cy][cx] = Rego.ROCK steps.forEach { (x, y) -> val dx = sign(x.toDouble() - cx).toInt() val dy = sign(y.toDouble() - cy).toInt() while (cx != x || cy != y) { cx += dx cy += dy grid[cy][cx] = Rego.ROCK } } } grid = grid .dropLastWhile { line -> line.all { it == null } } return fillWithSand(grid) } fun part2(input: List<String>): Int { var grid = List(200) { MutableList<Rego?>(700) { null } } input.forEach { line -> val steps = line.split(" -> ") .map { tuple -> val (x, y) = tuple.split(',').map(String::toInt) Pair(x, y) }.toMutableList() var (cx, cy) = steps.removeFirst() grid[cy][cx] = Rego.ROCK steps.forEach { (x, y) -> val dx = sign(x.toDouble() - cx).toInt() val dy = sign(y.toDouble() - cy).toInt() while (cx != x || cy != y) { cx += dx cy += dy grid[cy][cx] = Rego.ROCK } } } // put in the floor val bottom = grid.indexOfLast { line -> line.any { it != null } } println("bottom! $bottom") val indents = grid.map { line -> line.indexOfFirst { it != null } }.filterNot { it < 0 } val indent = indents.min() val outdents = grid.map { line -> line.indexOfLast { it != null } }.filterNot { it < 0 } val outdent = outdents.max() for (x in (indent + 1 - bottom)..(outdent+bottom)) { grid[bottom + 2][x] = Rego.ROCK } grid = grid .dropLastWhile { line -> line.all { it == null } } printGrid(grid) return fillWithSand(grid) // return input.size } println("Day $DAY") // test if implementation meets criteria from the description, like: val testInput = readInput("Day${DAY}_test") check(part1(testInput).also { println("Part1 output: $it") } == PART1_CHECK) check(part2(testInput).also { println("Part2 output: $it") } == PART2_CHECK) val input = readInput("Day$DAY") println("Part1 final output: ${part1(input)}") println("Part2 final output: ${part2(input)}") }
0
Kotlin
0
0
57cba37265a3c63dea741c187095eff24d0b5381
4,851
adventofcode2022
Apache License 2.0
src/main/kotlin/eu/michalchomo/adventofcode/year2023/Day06.kt
MichalChomo
572,214,942
false
{"Kotlin": 56758}
package eu.michalchomo.adventofcode.year2023 import eu.michalchomo.adventofcode.Day import eu.michalchomo.adventofcode.main object Day06 : Day { override val number: Int = 6 override fun part1(input: List<String>): String = input.let { val times = it[0].getNumbers() val distances = it[1].getNumbers() val zip = times.zip(distances) zip.map { (raceTime, recordDistance) -> (1..<raceTime).count { hold -> hold * (raceTime - hold) > recordDistance } } .reduce(Int::times) }.toString() override fun part2(input: List<String>): String = input.let { val raceTime = it[0].getNumber() val recordDistance = it[1].getNumber() (1..<raceTime).count { hold -> hold * (raceTime - hold) > recordDistance } }.toString() private fun String.getNumbers(): List<Int> = this.split(":", " ").drop(1).filter { it.isNotEmpty() }.map { it.trim().toInt() } private fun String.getNumber(): Long = this.split(":", " ").drop(1).filter { it.isNotEmpty() }.reduce { acc, s -> acc + s }.toLong() } fun main() { main(Day06) }
0
Kotlin
0
0
a95d478aee72034321fdf37930722c23b246dd6b
1,187
advent-of-code
Apache License 2.0
src/main/kotlin/LambdasCollections.kt
ersushantsood
191,845,135
false
null
fun main() { val li = listOf<Int>(1,2,3,4) println(li.filter({i:Int -> i%2 ==0})) //Map operation println (li.map { it * 2 }) val lstNumbers = listOf<Number>(Number("one",1),Number("two",2),Number("three",3)) println("Numbers:"+lstNumbers.map { it.name }) //Find and groupBy val list = listOf(1,2,3,4) //The function find returns the first element of the collection that satisfies the condition set in the lambda. // It is the same function as firstOrNull, which is a longer but also clearer name println("Finding the first match as per the lambda condition: "+list.find { it % 2 ==0 }) println("Finding the last match as per the lambda condition: "+list.findLast { it % 2 == 0 }) val animal_collection = listOf(Animal("Lion","carnivore"),Animal("Tiger","carnivore"), Animal("Elephant","herbivore"),Animal("Rabbit","herbivore")) val animal_groups = animal_collection.groupBy { it.type } println("Group of Herbivores and Carnivores:"+animal_groups) //Fold Operation //In the previous example, the first time we start with 0 and added all elements until the end. // In the second case, with start with 15 and subtracted alle elements. // Basically, the provided value is used as argument for start in the first cycle, then start becomes the value returned by the previous cycle. var items_list = listOf<Int>(5,10,25) println("Folding the collection:"+items_list.fold(0, {start,element -> element+start})) println("Folding the collection by Subtracting the items: "+items_list.fold(25,{start,element -> start-element})) //So, in the first case the function behaves like this: // //start = 0, element = 5 -> result 5 //start = 5, element = 10 -> result 15 //start = 15, element = 25 -> result 40 //flatten operation : The function flatten creates one collection from a supplied list of collections. var lists = listOf<List<Int>>(listOf(1,2), listOf(4,5)) var flattened_list = lists.flatten() println("Flattened List: "+flattened_list) //Flatmap operation : flatMap use the provided lambda to map each element of the initial collection to a new collection, // then it merges all the collections into one collection. val lists_numbers = listOf<Number>(Number("one",1),Number("two",2),Number("three",3)) println(lists_numbers.flatMap { listOf(it.value) }) //In this example, we create one list with all the values of the property value of each element of type Number. These are the steps to arrive to this result: // //each element is mapped to a new collection, with these three new lists //listOf(1) //listOf(2) //listOf(3) //then the these three lists are merged in one list, listOf(3,3,5) //Notice that the initial collection does not affect the kind of collection that is returned. That is to say, even if you start with a set you end up with a generic collection } data class Number(val name: String, val value : Int) data class Animal(val name: String, val type: String)
0
Kotlin
0
0
94aab4e4334f8ed24947f4551362d6fc8cfd8154
3,080
kotlinSamples
Apache License 2.0
src/main/kotlin/twentytwentytwo/Day13.kt
JanGroot
317,476,637
false
{"Kotlin": 80906}
package twentytwentytwo import kotlinx.serialization.decodeFromString import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.JsonPrimitive import kotlin.math.sign fun main() { val input = {}.javaClass.getResource("input-13.txt")!!.readText().split("\n\n"); val day = Day13(input) println(day.part1()) println(day.part2()) } class Day13(private val input: List<String>) { fun part1(): Int { return input.mapIndexedNotNull { index, s -> val (a, b) = s.lines().also { println(it) } if (matches(a, b) <= 0) index + 1 else null }.also { print(it) }.sum() } fun part2(): Int { val markers = listOf("[[2]]", "[[6]]") var extended = input.filter { it.isNotEmpty() }.map{it.lines()}.flatten() + markers extended = extended.filter{it.isNotEmpty()} extended.forEach { println(it) } extended = extended.sortedWith { a, b -> matches(a, b)} return (extended.indexOf(markers.first()) + 1) * (extended.indexOf(markers.last()) + 1) } fun matches(a: String, b: String): Int { return matches(Json.decodeFromString<JsonArray>(a), Json.decodeFromString<JsonArray>(b)) } fun matches(x: JsonElement, y: JsonElement) : Int{ println("comparing $x with $y") return when { (x is JsonPrimitive && y is JsonArray) -> matches(JsonArray(listOf(x)),y) (x is JsonArray && y is JsonPrimitive) -> matches(x,JsonArray(listOf(y))) (x is JsonArray && y is JsonArray) -> { (0 until minOf( x.size, y.size)).forEach { val dif = matches(x[it], y[it]) if (dif != 0) return dif } return (x.size - y.size).sign } (x is JsonPrimitive && y is JsonPrimitive) -> (x.content.toInt() - y.content.toInt()).sign else -> {-1} } } }
0
Kotlin
0
0
04a9531285e22cc81e6478dc89708bcf6407910b
2,024
aoc202xkotlin
The Unlicense
src/Day4/Day4.kt
tomashavlicek
571,148,715
false
{"Kotlin": 23780}
package Day4 import readInput import containsFull fun main() { fun part1(input: List<String>): Int { return input.map { elfPair -> elfPair.split(',').map { elf -> val parts = elf.split('-') IntRange(parts[0].toInt(), parts[1].toInt()) } }.count { parts -> return@count parts.first().containsFull(parts.last()) || parts.last().containsFull(parts.first()) } } fun part2(input: List<String>): Int { return input.map { elfPair -> elfPair.split(',').map { elf -> val parts = elf.split('-') IntRange(parts[0].toInt(), parts[1].toInt()) } }.count { parts -> return@count parts.first().intersect(parts.last()).isNotEmpty() } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day4/Day4_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("Day4/Day4") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
899d30e241070903fe6ef8c4bf03dbe678310267
1,104
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/day17.kt
Gitvert
433,947,508
false
{"Kotlin": 82286}
import kotlin.math.abs fun day17() { val lines: List<String> = readFile("day17.txt") day17part1(lines) day17part2(lines) } fun day17part1(lines: List<String>) { val xPos = lines[0].split(",")[0].split("=")[1].split("..") val yPos = lines[0].split(",")[1].split("=")[1].split("..") val xPair = Pair(Integer.valueOf(xPos[0]), Integer.valueOf(xPos[1])) val yPair = Pair(Integer.valueOf(yPos[0]), Integer.valueOf(yPos[1])) var highestHit = 0 for (i in 1..xPair.second) { for (j in 0..abs(yPair.first)) { val attempt = findHighestPositionWhileReachingTarget(xPair, yPair, i, j) if (attempt > highestHit) { highestHit = attempt } } } val answer = highestHit println("17a: $answer") } fun day17part2(lines: List<String>) { val xPos = lines[0].split(",")[0].split("=")[1].split("..") val yPos = lines[0].split(",")[1].split("=")[1].split("..") val xPair = Pair(Integer.valueOf(xPos[0]), Integer.valueOf(xPos[1])) val yPair = Pair(Integer.valueOf(yPos[0]), Integer.valueOf(yPos[1])) var noOfHits = 0 for (i in 1..xPair.second * 2) { for (j in yPair.first..abs(yPair.first)) { val attempt = findHighestPositionWhileReachingTarget(xPair, yPair, i, j) if (attempt > -1) { noOfHits++ } } } val answer = noOfHits println("17b: $answer") } fun findHighestPositionWhileReachingTarget(xPair: Pair<Int, Int>, yPair: Pair<Int, Int>, xStartVelocity: Int, yStartVelocity: Int): Int { var xPosition = 0 var yPosition = 0 var xVelocity = xStartVelocity var yVelocity = yStartVelocity var maxY = 0 while (true) { xPosition += xVelocity yPosition += yVelocity if (xVelocity > 0) { xVelocity-- } yVelocity-- if (yPosition > maxY) { maxY = yPosition } if (xPosition >= xPair.first && xPosition <= xPair.second && yPosition >= yPair.first && yPosition <= yPair.second) { return maxY } else if (xPosition > xPair.second || yPosition < yPair.first) { return -1 } } }
0
Kotlin
0
0
02484bd3bcb921094bc83368843773f7912fe757
2,230
advent_of_code_2021
MIT License
src/Day04.kt
sungi55
574,867,031
false
{"Kotlin": 23985}
fun main() { val day = "Day04" fun getRanges(input: List<String>) = input.map { set -> set.split(",") .map { ranges -> ranges.split("-").map { it.toInt() } } .map { (it.component1()..it.component2()).toList() } } fun part1(input: List<String>): Int = getRanges(input) .count { (firstElf, secondElf) -> firstElf.containsAll(secondElf) || secondElf.containsAll(firstElf) } fun part2(input: List<String>): Int = getRanges(input) .count { (firstElves, secondElves) -> firstElves.intersect(secondElves.toSet()).isNotEmpty() } val testInput = readInput(name = "${day}_test") val input = readInput(name = day) check(part1(testInput) == 2) check(part2(testInput) == 4) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
2a9276b52ed42e0c80e85844c75c1e5e70b383ee
909
aoc-2022
Apache License 2.0
fuzzywuzzy_kotlin/src/main/java/com/frosch2010/fuzzywuzzy_kotlin/algorithms/Utils.kt
jens-muenker
695,555,771
false
{"Kotlin": 88201}
package com.frosch2010.fuzzywuzzy_kotlin.algorithms import java.util.Arrays import java.util.Collections import java.util.PriorityQueue object Utils { fun tokenize(`in`: String): List<String> { return Arrays.asList(*`in`.split("\\s+".toRegex()).dropLastWhile { it.isEmpty() } .toTypedArray()) } fun tokenizeSet(`in`: String): Set<String> { return HashSet(tokenize(`in`)) } fun sortAndJoin(col: List<String?>, sep: String?): String { val sortedList = col.sortedWith(Comparator { a, b -> when { a == null && b == null -> 0 a == null -> -1 b == null -> 1 else -> a.compareTo(b) } }) return join(sortedList, sep) } fun join(strings: List<String?>, sep: String?): String { val buf = StringBuilder(strings.size * 16) for (i in strings.indices) { if (i < strings.size) { buf.append(sep) } buf.append(strings[i]) } return buf.toString().trim { it <= ' ' } } fun sortAndJoin(col: Set<String?>?, sep: String?): String { return sortAndJoin(ArrayList(col), sep) } fun <T : Comparable<T>?> findTopKHeap(arr: List<T>, k: Int): List<T> { val pq = PriorityQueue<T>() for (x in arr) { if (pq.size < k) pq.add(x) else if (x!!.compareTo(pq.peek()) > 0) { pq.poll() pq.add(x) } } val res: MutableList<T> = ArrayList() for (i in k downTo 1) { val polled = pq.poll() if (polled != null) { res.add(polled) } } return res } fun <T : Comparable<T>?> max(vararg elems: T): T? { if (elems.size == 0) return null var best = elems[0] for (t in elems) { if (t!!.compareTo(best) > 0) { best = t } } return best } }
0
Kotlin
0
0
da452a7027069e9c6adb6b11a430e125a50ce0ca
2,023
fuzzywuzzy-kotlin
The Unlicense
app/src/main/kotlin/me/mataha/misaki/solutions/adventofcode/aoc2015/d03/Day.kt
mataha
302,513,601
false
{"Kotlin": 92734, "Gosu": 702, "Batchfile": 104, "Shell": 90}
package me.mataha.misaki.solutions.adventofcode.aoc2015.d03 import me.mataha.misaki.domain.NoOpParser import me.mataha.misaki.domain.adventofcode.AdventOfCode import me.mataha.misaki.domain.adventofcode.AdventOfCodeDay import me.mataha.misaki.util.extensions.next /** See the puzzle's full description [here](https://adventofcode.com/2015/day/3). */ @AdventOfCode("Perfectly Spherical Houses in a Vacuum", 2015, 3) class PerfectlySphericalHouses : AdventOfCodeDay<String, Int>(), NoOpParser { override fun solvePartOne(input: String): Int { var current = Position(0, 0) val grid = mutableSetOf(current) for (direction in input) { val new = current.next(direction) grid += new current = new } return grid.size } override fun solvePartTwo(input: String): Int { val map = mutableMapOf(Turn.SANTA to Position(0, 0), Turn.ROBOT to Position(0, 0)) var turn = Turn.SANTA val grid = mutableSetOf(map.getValue(turn)) for (direction in input) { val new = map.getValue(turn).next(direction) grid += new map[turn] = new turn = if (direction.isDirection) turn.next() else turn } return grid.size } } private enum class Turn { SANTA, ROBOT } private data class Position(val x: Int, val y: Int) { fun next(direction: Char): Position = when (direction) { '^' -> Position(x, y + 1) 'v' -> Position(x, y - 1) '>' -> Position(x + 1, y) '<' -> Position(x - 1, y) else -> this } } private const val DIRECTIONS = "^>v<" private val Char.isDirection: Boolean get() = this in DIRECTIONS
0
Kotlin
0
0
748a5b25a39d01b2ffdcc94f1a99a6fbc8a02685
1,717
misaki
MIT License
src/main/kotlin/com/sherepenko/leetcode/solutions/LongestCommonSubsequence.kt
asherepenko
264,648,984
false
null
package com.sherepenko.leetcode.solutions import com.sherepenko.leetcode.Solution import kotlin.math.max class LongestCommonSubsequence( private val text1: String, private val text2: String ) : Solution { companion object { fun longestCommonSubsequence(text1: String, text2: String): Int { val m = text1.length val n = text2.length val dp = Array(m + 1) { IntArray(n + 1) } for (i in 0..m) { for (j in 0..n) { dp[i][j] = if (i == 0 || j == 0) { 0 } else if (text1[i - 1] == text2[j - 1]) { dp[i - 1][j - 1] + 1 } else { max(dp[i - 1][j], dp[i][j - 1]) } } } return dp[m][n] } } override fun resolve() { val result = longestCommonSubsequence(text1, text2) println( "Longest Common Subsequence: \n" + " Input: $text1, $text2; \n" + " Result: $result \n" ) } }
0
Kotlin
0
0
49e676f13bf58f16ba093f73a52d49f2d6d5ee1c
1,164
leetcode
The Unlicense
solutions/aockt/y2022/Y2022D13.kt
Jadarma
624,153,848
false
{"Kotlin": 435090}
package aockt.y2022 import aockt.y2022.Y2022D13.PacketData.* import io.github.jadarma.aockt.core.Solution object Y2022D13 : Solution { /** An element in a [Packet]. */ private sealed interface PacketData : Comparable<PacketData> { /** Contains a single positive integer literal.*/ @JvmInline value class NumberData(val value: Int) : PacketData { init { require(value >= 0) { "Negative values are not allowed." } } override fun toString() = value.toString() override fun compareTo(other: PacketData) = when (other) { is NumberData -> value compareTo other.value is ListData -> ListData(listOf(this)) compareTo other } } /** Contains a list of zero or more packets. */ @JvmInline value class ListData(private val data: List<PacketData>) : PacketData, List<PacketData> by data { override fun toString() = data.joinToString(prefix = "[", postfix = "]", separator = ",") override fun compareTo(other: PacketData): Int = when (other) { is NumberData -> this compareTo ListData(listOf(other)) is ListData -> { val p1 = this.data val p2 = other.data (0 until maxOf(p1.size, p2.size)).forEach { index -> val left = p1.getOrNull(index) ?: return -1 val right = p2.getOrNull(index) ?: return 1 val comparison = left compareTo right if (comparison != 0) return comparison } 0 } } } } /** A distress signal packet. */ @JvmInline private value class Packet(val data: ListData) : Comparable<Packet> { override fun compareTo(other: Packet): Int = data.compareTo(other.data) override fun toString() = data.toString() companion object { /** Decode the [input] into a [Packet] or throw if invalid. */ fun parse(input: String): Packet { val stream = input.iterator() require(stream.nextChar() == '[') { "Expected beginning of list." } fun parseList(): ListData { val data = mutableListOf<PacketData>() while (stream.hasNext()) { when (val char = stream.nextChar()) { ',' -> require(data.isNotEmpty()) { "Encountered list separator before first element." } '[' -> parseList().also(data::add) ']' -> return ListData(data) in '0'..'9' -> { var number = char.digitToInt() var nextDigit = stream.nextChar() while (nextDigit.isDigit()) { number = number * 10 + nextDigit.digitToInt() nextDigit = stream.nextChar() } data.add(NumberData(number)) if (nextDigit == ']') return ListData(data) if (nextDigit != ',') throw IllegalArgumentException("Illegal character '$char' encountered.") } else -> throw IllegalArgumentException("Illegal character '$char' encountered.") } } throw IllegalArgumentException("Reached end of input with an opened list.") } return Packet(parseList()) } } } /** Parse the [input] and return the sequence of packets in the input, ignoring whitespace.. */ private fun parseInput(input: String): Sequence<Packet> = input .splitToSequence("\n\n") .flatMap { pair -> pair.split('\n').also { require(it.size == 2) } } .map(Packet::parse) override fun partOne(input: String) = parseInput(input) .chunked(2) { (left, right) -> left < right } .withIndex() .sumOf { (index, isInRightOrder) -> if (isInRightOrder) index + 1 else 0 } override fun partTwo(input: String): Int { val dividerPackets = listOf(Packet.parse("[[2]]"), Packet.parse("[[6]]")) return parseInput(input) .plus(dividerPackets) .sorted() .run { dividerPackets.map { indexOf(it) + 1 }.reduce(Int::times) } } }
0
Kotlin
0
3
19773317d665dcb29c84e44fa1b35a6f6122a5fa
4,662
advent-of-code-kotlin-solutions
The Unlicense
src/main/aoc2018/Day19.kt
nibarius
154,152,607
false
{"Kotlin": 963896}
package aoc2018 class Day19(val input: List<String>) { private val registers = MutableList(6) { 0 } fun solvePart1(): Long { val elf = ElfCode(input) elf.runProgram() return elf.registers[0] } private fun theProgram() { // init part (line 1 + 17 - 35) registers[2] += 2 // line 17 registers[2] *= registers[2] // line 18 registers[2] *= 19 // line 19 registers[2] *= 11 // line 20 registers[1] += 6 // line 21 registers[1] *= 22 // line 22 registers[1] += 18 // line 23 registers[2] += registers[1] // line 24 if (registers[0] == 1) { // line 25 - 26 registers[1] = 27 registers[1] *= 28 registers[1] += 29 registers[1] *= 30 registers[1] *= 14 registers[1] *= 32 registers[2] += registers[1] } /* // Below part calculates the sum of all factorials of registers[2] and put it in registers[0] registers[5] = 1 //line 1 var a = registers[0] var b = registers[1] val c = registers[2] var d = registers[3] //var e = registers[4] var f = registers[5] do { // a = sum of all factors of of c d = 1 //line 2 do { b = f * d // line 3 if (b == c) { // line 4-7 a += f } d++ // line 8 } while (d <= c) // line 9-11 f++ // line 12 } while (f <= c) // line 13-15 registers[0] = a registers[1] = b registers[2] = c registers[3] = d //registers[4] = e registers[5] = f return //line 16*/ // Do the calculation in a more efficient way registers[0] = sumOfFactors(registers[2]) } private fun sumOfFactors(number: Int): Int { return (1..number) .filter { number % it == 0 } .sum() } fun solvePart2(): Int { registers[0] = 1 theProgram() return registers[0] } }
0
Kotlin
0
6
f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22
2,128
aoc
MIT License
kotlin/src/katas/kotlin/hackerrank/NonDivisibleSubset.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.hackerrank import datsok.shouldEqual import org.junit.Test // https://www.hackerrank.com/challenges/non-divisible-subset class NonDivisibleSubset { @Test fun `example from the task description`() { nonDivisibleSubset(k = 4, array = arrayOf(19, 10, 12, 10, 24, 25, 22)) shouldEqual 3 } @Test fun `basic example`() { nonDivisibleSubset(k = 3, array = arrayOf(1, 7, 2, 4)) shouldEqual 3 } } fun nonDivisibleSubset(k: Int, array: Array<Int>): Int = frequenciesOfNonDivisibleSubset(k, array).values.sum() fun frequenciesOfNonDivisibleSubset(k: Int, array: Array<Int>): Map<Int, Int> { // Use reminder of dividing all values by "k" because this doesn't affect how they add up to "k". val map = array.fold(HashMap<Int, Int>()) { map, it -> val n = it % k map[n] = map.getOrDefault(n, 0) + 1 map } if (map.containsKey(0)) map[0] = 1 if ((k % 2 == 0) && map.containsKey(k / 2)) map[k / 2] = 1 val result = HashMap<Int, Int>() map.forEach { (key, value) -> // By choosing a value we always rule out only one other value, which is called "complement" here. val complementKey = k - key val complementValue = map[complementKey] ?: -1 if (!result.containsKey(key) && !result.containsKey(complementKey)) { if (value > complementValue) result[key] = value else result[complementKey] = complementValue } } return result }
7
Roff
3
5
0f169804fae2984b1a78fc25da2d7157a8c7a7be
1,493
katas
The Unlicense
src/main/kotlin/aoc22/Day21.kt
tom-power
573,330,992
false
{"Kotlin": 254717, "Shell": 1026}
package aoc22 import aoc22.Day21Domain.HumanMonkey import aoc22.Day21Domain.MathMonkey import aoc22.Day21Domain.Monkey import aoc22.Day21Domain.NumberMonkey import aoc22.Day21Domain.Operator import aoc22.Day21Domain.Operator.* import aoc22.Day21Parser.toMonkeys import aoc22.Day21Parser.toRootMonkey import aoc22.Day21Runner.yellEquals import aoc22.Day21Solution.part1Day21 import aoc22.Day21Solution.part2Day21 import common.Year22 object Day21: Year22 { fun List<String>.part1(): Long = part1Day21() fun List<String>.part2(): Long = part2Day21() } object Day21Solution { fun List<String>.part1Day21(): Long = toMonkeys() .toRootMonkey() .yell() fun List<String>.part2Day21(): Long = toMonkeys() .yellEquals() } object Day21Runner { fun List<Monkey>.yellEquals(): Long = (toRootMonkey() as MathMonkey) .let { it to it.pathToHuman() } .let { (rootMonkey, pathToHuman) -> listOf(rootMonkey.left, rootMonkey.right) .partition { it in pathToHuman } .let { (humanSide, monkeySide) -> humanSide.first().findEquals(monkeySide.first().yell(), pathToHuman) } } } object Day21Domain { interface Monkey { val name: String fun yell(): Long fun pathToHuman(): Set<Monkey> fun findEquals(incoming: Long, pathToHuman: Set<Monkey>): Long } enum class Operator { Plus, Minus, Divide, Multiply } data class MathMonkey( override val name: String, val left: Monkey, val right: Monkey, val operator: Operator, ) : Monkey { override fun yell(): Long = left.yell() operate right.yell() private infix fun Long.operate(other: Long): Long = when (operator) { Plus -> this + other Minus -> this - other Divide -> this / other Multiply -> this * other } override fun pathToHuman(): Set<Monkey> = listOf( left.pathToHuman(), right.pathToHuman() ).filter { it.isNotEmpty() } .flatMap { it + this } .toSet() override fun findEquals(incoming: Long, pathToHuman: Set<Monkey>): Long = listOf(left, right) .single { it in pathToHuman } .let { it.findEquals(negate(it, incoming), pathToHuman) } private fun negate(monkey: Monkey, incoming: Long): Long = when (monkey) { left -> incoming leftNegate right.yell() right -> incoming rightNegate left.yell() else -> error("monkey mismatch") } private infix fun Long.leftNegate(other: Long): Long = when (operator) { Plus -> this - other Minus -> this + other Multiply -> this / other Divide -> this * other } private infix fun Long.rightNegate(other: Long): Long = when (operator) { Plus -> this - other Minus -> other - this Multiply -> this / other Divide -> other / this } } data class NumberMonkey( override val name: String, val number: Long, ) : Monkey { override fun yell(): Long = number override fun pathToHuman(): Set<Monkey> = emptySet() override fun findEquals(incoming: Long, pathToHuman: Set<Monkey>): Long = number } data class HumanMonkey( override val name: String, val number: Long, ) : Monkey { override fun yell(): Long = number override fun pathToHuman(): Set<Monkey> = setOf(this) override fun findEquals(incoming: Long, pathToHuman: Set<Monkey>): Long = incoming } } private typealias NamedMonkey = Pair<String, String> object Day21Parser { private fun String.toOperator(): Operator = mapNotNull { it.toOperator() }.first() private fun Char.toOperator(): Operator? = when (this) { '+' -> Plus '-' -> Minus '/' -> Divide '*' -> Multiply else -> null } private fun String.toLeftName(): String = filter { it.isLetter() }.take(4) private fun String.toRightName(): String = filter { it.isLetter() }.takeLast(4) private fun List<NamedMonkey>.getMonkeyBy(name: String): Monkey = this.first { it.first == name }.toMonkey() private fun List<String>.toNamedMonkeys(): List<NamedMonkey> = map { row -> row.split(":").let { Pair(it[0], it[1]) } } context(List<NamedMonkey>) private fun NamedMonkey.toMonkey(): Monkey = this.let { (name, rest) -> val number = rest.filter { it.isDigit() } when { number.isNotEmpty() -> when (name) { "humn" -> HumanMonkey(name, number.toLong()) else -> NumberMonkey(name, number.toLong()) } else -> MathMonkey( name = name, operator = rest.toOperator(), left = this@List.getMonkeyBy(rest.toLeftName()), right = this@List.getMonkeyBy(rest.toRightName()), ) } } fun List<String>.toMonkeys(): List<Monkey> = toNamedMonkeys().run { this.map { it.toMonkey() } } fun List<Monkey>.toRootMonkey(): Monkey = first { it.name == "root" } }
0
Kotlin
0
0
baccc7ff572540fc7d5551eaa59d6a1466a08f56
5,628
aoc
Apache License 2.0
src/main/kotlin/day19/Day19.kt
alxgarcia
435,549,527
false
{"Kotlin": 91398}
package day19 import java.io.File import kotlin.math.absoluteValue typealias Position = Triple<Int, Int, Int> typealias Transformation = (Triple<Int, Int, Int>) -> Triple<Int, Int, Int> private operator fun Position.plus(offset: Position): Position = Position(first + offset.first, second + offset.second, third + offset.third) private operator fun Position.minus(other: Position) = Position(first - other.first, second - other.second, third - other.third) data class Scanner(val beacons: List<Position>) { val distanceMatrix: Array<Array<Position>> get() = beacons.map { position -> beacons.map { (position - it) }.toTypedArray() }.toTypedArray() fun transform(t: Transformation): Scanner = this.copy(beacons = beacons.map(t)) } fun parseInput(lines: List<String>): List<Scanner> { fun parseBeacon(line: String): Position { val (x, y, z) = line.split(",").map(String::toInt) return Position(x, y, z) } val scanners = mutableListOf<Scanner>() val beacons = mutableListOf<Position>() for (line in lines) { when { line.isBlank() -> scanners.add(Scanner(beacons.toList())) line.startsWith("--- ") -> beacons.clear() else -> beacons.add(parseBeacon(line)) } } if (beacons.isNotEmpty()) scanners.add(Scanner(beacons.toList())) return scanners } /* Orientations over Z x y z y -x z -x -y z -y x z Orientations over -Z x -y -z -y -x -z -x y -z y x -z Orientations over X -z y x -y -z x z -y x y z x Orientations over -X z y -x y -z -x -z -y -x -y z -x Orientations over Y x -z y -z -x y -x z y z x y Orientations over -Y x z -y z -x -y -x -z -y -z x -y */ val orientations = listOf<Transformation>( // Orientations over Z { (x, y, z) -> Triple(x, y, z) }, { (x, y, z) -> Triple(y, -x, z) }, { (x, y, z) -> Triple(-x, -y, z) }, { (x, y, z) -> Triple(-y, x, z) }, // Orientations over -Z { (x, y, z) -> Triple(x, -y, -z) }, { (x, y, z) -> Triple(-y, -x, -z) }, { (x, y, z) -> Triple(-x, y, -z) }, { (x, y, z) -> Triple(y, x, -z) }, // Orientations over X { (x, y, z) -> Triple(-z, y, x) }, { (x, y, z) -> Triple(-y, -z, x) }, { (x, y, z) -> Triple(z, -y, x) }, { (x, y, z) -> Triple(y, z, x) }, // Orientations over -X { (x, y, z) -> Triple(z, y, -x) }, { (x, y, z) -> Triple(y, -z, -x) }, { (x, y, z) -> Triple(-z, -y, -x) }, { (x, y, z) -> Triple(-y, z, -x) }, // Orientations over Y { (x, y, z) -> Triple(x, -z, y) }, { (x, y, z) -> Triple(-z, -x, y) }, { (x, y, z) -> Triple(-x, z, y) }, { (x, y, z) -> Triple(z, x, y) }, // Orientations over -Y { (x, y, z) -> Triple(x, z, -y) }, { (x, y, z) -> Triple(z, -x, -y) }, { (x, y, z) -> Triple(-x, -z, -y) }, { (x, y, z) -> Triple(-z, x, -y) }, ) /* * For scanner s1, for every beacon compute the distance with the others * For scanner s2, apply one of the rotations and compute the distance matrix too * For each pair of matrix, check if for one row in s1 there's a matching row in s2 with at least minOverlap matching distances * If so, we got a pair of overlapping scanners given a certain orientation. * Subtracting both positions will return the distance between the position of the two scanners */ fun determineScannerLocation(s1: Scanner, s2: Scanner, minOverlaps: Int): Pair<Position, Scanner>? { val matrix1 = s1.distanceMatrix for (orientation in orientations) { val matrix2 = s2.transform(orientation).distanceMatrix val matchingBeacons = matrix1.mapIndexed { index, beaconDistances -> index to matrix2.indexOfFirst { distances -> beaconDistances.count { distances.contains(it) } >= minOverlaps } }.filterNot { it.second == -1 } if (matchingBeacons.size < minOverlaps) continue val (b1, b2) = matchingBeacons.first() val s2Center = s1.beacons[b1] - orientation(s2.beacons[b2]) // compute the discrepancy between the two positions of the same beacon val transformation = { position: Position -> orientation(position) + s2Center } // transforming to the PoV of scanner s1 return s2Center to s2.transform(transformation) } return null } /* * Returns the positions of the scanners and the position of the beacons from the PoV of the first scanner */ fun locateScannersAndBeacons(scanners: List<Scanner>, minOverlaps: Int): Pair<Set<Position>, Set<Position>> { val scannerPositions = mutableSetOf(Position(0, 0, 0)) // assuming the first scanner is at (0, 0, 0) val beaconPositions = scanners.first().beacons.toMutableSet() val recognisedScanners = mutableListOf(scanners.first()) val unrecognisedScanners = scanners.drop(1).toMutableList() while (unrecognisedScanners.isNotEmpty()) { val scanner = recognisedScanners.removeFirst() val scannersToCheck = unrecognisedScanners.listIterator() while (scannersToCheck.hasNext()) { val unrecognised = scannersToCheck.next() determineScannerLocation(scanner, unrecognised, minOverlaps)?.let { (position, transformedScanner) -> scannersToCheck.remove() recognisedScanners.add(transformedScanner) scannerPositions.add(position) beaconPositions.addAll(transformedScanner.beacons) } } } return scannerPositions to beaconPositions } private fun euclideanDistance(one: Position, other: Position): Int = (one.first - other.first).absoluteValue + (one.second - other.second).absoluteValue + (one.third - other.third).absoluteValue private fun findMaxEuclideanDistance(positions: Iterable<Position>): Int = positions.maxOf { p1 -> positions.maxOf { p2 -> euclideanDistance(p1, p2) } } fun findMaxEuclideanDistance(scanners: List<Scanner>, minOverlaps: Int): Int { val (centers, _) = locateScannersAndBeacons(scanners, minOverlaps) return findMaxEuclideanDistance(centers) } fun main() { File("./input/day19.txt").useLines { lines -> val scanners = parseInput(lines.toList()) val (scannerPositions, beaconPositions) = locateScannersAndBeacons(scanners, 12) println(beaconPositions.size) println(findMaxEuclideanDistance(scannerPositions)) } }
0
Kotlin
0
0
d6b10093dc6f4a5fc21254f42146af04709f6e30
6,144
advent-of-code-2021
MIT License
src/main/kotlin/com/github/davio/aoc/y2020/Day6.kt
Davio
317,510,947
false
{"Kotlin": 405939}
package com.github.davio.aoc.y2020 import com.github.davio.aoc.general.Day import com.github.davio.aoc.general.call import com.github.davio.aoc.general.getInputAsSequence fun main() { Day6.getResult() } object Day6 : Day() { /* * --- Day 6: Custom Customs --- As your flight approaches the regional airport where you'll switch to a much larger plane, * customs declaration forms are distributed to the passengers. The form asks a series of 26 yes-or-no questions marked a through z. * All you need to do is identify the questions for which anyone in your group answers "yes". * Since your group is just you, this doesn't take very long. However, the person sitting next to you seems to be experiencing a language barrier and asks if you can help. * For each of the people in their group, you write down the questions for which they answer "yes", one per line. For example: abcx abcy abcz In this group, there are 6 questions to which anyone answered "yes": a, b, c, x, y, and z. * (Duplicate answers to the same question don't count extra; each question counts at most once.) Another group asks for your help, then another, and eventually you've collected answers from every group on the plane * (your puzzle input). Each group's answers are separated by a blank line, * and within each group, each person's answers are on a single line. For example: abc a b c ab ac a a a a b This list represents answers from five groups: The first group contains one person who answered "yes" to 3 questions: a, b, and c. The second group contains three people; combined, they answered "yes" to 3 questions: a, b, and c. The third group contains two people; combined, they answered "yes" to 3 questions: a, b, and c. The fourth group contains four people; combined, they answered "yes" to only 1 question, a. The last group contains one person who answered "yes" to only 1 question, b. In this example, the sum of these counts is 3 + 3 + 3 + 1 + 1 = 11. For each group, count the number of questions to which anyone answered "yes". What is the sum of those counts? * * --- Part Two --- As you finish the last group's customs declaration, you notice that you misread one word in the instructions: You don't need to identify the questions to which anyone answered "yes"; you need to identify the questions to which everyone answered "yes"! Using the same example as above: abc a b c ab ac a a a a b This list represents answers from five groups: In the first group, everyone (all 1 person) answered "yes" to 3 questions: a, b, and c. In the second group, there is no question to which everyone answered "yes". In the third group, everyone answered yes to only 1 question, a. Since some people did not answer "yes" to b or c, they don't count. In the fourth group, everyone answered yes to only 1 question, a. In the fifth group, everyone (all 1 person) answered "yes" to 1 question, b. In this example, the sum of these counts is 3 + 0 + 1 + 1 + 1 = 6. For each group, count the number of questions to which everyone answered "yes". What is the sum of those counts? */ fun getResult() { var activeGroup = Group() (getInputAsSequence().sumOf { line: String -> if (line.isBlank()) { val yesAnswerCount = activeGroup.getAllYesAnswerCount() activeGroup = Group() yesAnswerCount } else { parseAnswerLine(line, activeGroup) 0 } } + activeGroup.getAllYesAnswerCount()).call { println(it) } } private fun parseAnswerLine(line: String, group: Group) { group.addYesAnswers(line) } class Group { private val yesAnswers: MutableList<String> = arrayListOf() fun addYesAnswers(answers: String) { yesAnswers.add(answers) } fun getAllYesAnswerCount() = yesAnswers .flatMap { it.asSequence() }.toSet() .filter { c -> yesAnswers.all { it.contains(c) } }.size } }
1
Kotlin
0
0
4fafd2b0a88f2f54aa478570301ed55f9649d8f3
4,157
advent-of-code
MIT License
src/leetcode_study_badge/data_structure/Day2.kt
faniabdullah
382,893,751
false
null
package leetcode_study_badge.data_structure import java.util.* class Day2 { fun sortColors(nums: IntArray) { var one = 0 var two = 0 var insertPosition = -1 repeat(nums.count()) { if (nums[it] == 0) { insertPosition++ nums[insertPosition] = 0 } else if (nums[it] == 1) { one++ } else { two++ } } repeat(one) { insertPosition++ nums[insertPosition] = 1 } repeat(two) { insertPosition++ nums[insertPosition] = 2 } } fun merge(intervals: Array<IntArray>): Array<IntArray> { Arrays.sort( intervals ) { a: IntArray, b: IntArray -> a[0].compareTo(b[0]) } val merged = mutableListOf<IntArray>() // [0, 3][0, 1][0, 2][1, 9][2, 5][10, 11][12, 20][19, 20] for (interval in intervals) { println(interval.contentToString()) if (merged.isEmpty() || merged.last()[1] < interval[0]) { merged.add(interval) } else { merged.last()[1] = maxOf(merged.last()[1], interval[1]) } } return merged.toTypedArray() } } class MyHashMap() { /** Initialize your data structure here. */ private val data = arrayOfNulls<Int>(1000001) /** value will always be non-negative. */ fun put(key: Int, value: Int) { data[key] = value } /** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */ fun get(key: Int): Int { return data[key] ?: -1 } /** Removes the mapping of the specified value key if this map contains a mapping for the key */ fun remove(key: Int) { data[key] = null } } fun main() { val intArray = intArrayOf(2, 0, 2, 1, 1, 0) Day2().sortColors(intArray) val intArrayIntervals = arrayOf( intArrayOf(1, 4), intArrayOf(0, 4) ) val result = Day2().merge(intArrayIntervals) result.forEach { print(it.contentToString()) } println(intArray.contentToString()) }
0
Kotlin
0
6
ecf14fe132824e944818fda1123f1c7796c30532
2,220
dsa-kotlin
MIT License
src/main/kotlin/io/array/SubarraySumEqualsK.kt
jffiorillo
138,075,067
false
{"Kotlin": 434399, "Java": 14529, "Shell": 465}
package io.array import io.utils.runTests // https://leetcode.com/explore/featured/card/30-day-leetcoding-challenge/531/week-4/3307/ class SubarraySumEqualsK { fun execute(input: IntArray, target: Int): Int { var result = 0 val stack = input.map { elem -> elem.also { if (elem == target) result++ } }.toMutableList() for (offset in 1 until input.size) { var index = 0 while (index + offset < input.size) { stack[index] += input[index + offset] result += if (stack[index] == target) 1 else 0 index++ } } return result } } fun main() { runTests(listOf( Triple(intArrayOf(1, 1, 2, 1, 2, 1, 1, 1, 1), 2, 6), Triple(intArrayOf(1, 1, 1), 2, 2), Triple(intArrayOf(-1, -1, 1), 0, 1), Triple(intArrayOf(1, 2, 3, 4, 5, 6, 7, 1, 23, 21, 3, 1, 2, 1, 1, 1, 1, 1, 12, 2, 3, 2, 3, 2, 2), 6, 5), Triple(intArrayOf(-1, -1, 1), 1, 1), Triple(intArrayOf(-92, -63, 75, -86, -58, 22, 31, -16, -66, -67, 420), 100, 1) )) { (input, target, value) -> value to SubarraySumEqualsK().execute(input, target) } }
0
Kotlin
0
0
f093c2c19cd76c85fab87605ae4a3ea157325d43
1,095
coding
MIT License
src/Day03.kt
li-xin-yi
573,617,763
false
{"Kotlin": 23422}
fun main() { fun solvePart1(input: List<String>): Int { var res = 0 for (line in input) { val length = line.length val first = line.substring(0, length / 2).toSet() val second = line.substring(length / 2).toSet() val item = first.intersect(second).first() res += if (item.isUpperCase()) (item - 'A' + 27) else (item - 'a' + 1) } return res } fun solvePart2(input: List<String>): Int { var res = 0 for (i in 0 until input.size step 3) { val first = input[i].toSet() val second = input[i + 1].toSet() val third = input[i + 2].toSet() val item = first.intersect(second).intersect(third).first() res += if (item.isUpperCase()) (item - 'A' + 27) else (item - 'a' + 1) } return res } val testInput = readInput("input/Day03_test") println(solvePart1(testInput)) println(solvePart2(testInput)) }
0
Kotlin
0
1
fb18bb7e462b8b415875a82c5c69962d254c8255
1,002
AoC-2022-kotlin
Apache License 2.0
leetcode2/src/leetcode/ValidParentheses.kt
hewking
68,515,222
false
null
package leetcode import java.util.* /** * 有效的括号 栈相关 * https://leetcode-cn.com/problems/valid-parentheses/ * Created by test * Date 2019/5/18 15:36 * Description * 给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。 有效字符串需满足: 左括号必须用相同类型的右括号闭合。 左括号必须以正确的顺序闭合。 注意空字符串可被认为是有效字符串。 示例 1: 输入: "()" 输出: true 示例 2: 输入: "()[]{}" 输出: true 示例 3: 输入: "(]" 输出: false 示例 4: 输入: "([)]" 输出: false 示例 5: 输入: "{[]}" 输出: true */ class Solution { /** * 思路: * 1.通过栈来解决 * 2.遇到左括号则入栈 * 3.遇到右括号则出栈 * 4.如果不匹配false * 5.最终stack不为空false */ fun isValid(s: String): Boolean { val p = arrayOf('{','(','[') val stack = Stack<Char>() for (i in 0 until s.length) { if (stack.size == 0) { stack.push(s[i]) } else if (isSymmetric(stack.peek(),s[i])) { stack.pop() } else { stack.push(s[i]) } } return stack.isEmpty() } fun isSymmetric(l : Char ,r : Char) : Boolean { return l == '(' && r == ')' || l == '{' && r == '}' || l == '[' && r == ']' } } object ValidParentheses{ @JvmStatic fun main(args : Array<String>) { Solution().isValid("(])") } }
0
Kotlin
0
0
a00a7aeff74e6beb67483d9a8ece9c1deae0267d
1,562
leetcode
MIT License
marathons/atcoder/ahc21_toyota2023_pyramidSorting/pyramidSorting.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package marathons.atcoder.ahc21_toyota2023_pyramidSorting import kotlin.random.Random private fun solve(f: List<IntArray>) { val answers = mutableListOf<List<String>>() for (mode in 0 until 5 + 12) { answers.add(solveGreedy(f.map { it.clone() }, mode)) } val ans = answers.minBy { it.size } println("" + ans.size + "\n" + ans.joinToString("\n")) System.err.println(answers.map { it.size }) } private fun solveGreedy(f: List<IntArray>, mode: Int): List<String> { val n = f.size val ans = mutableListOf<String>() fun makeMove(y: Int, x: Int, d: Int) { val yy = y + DY[d]; val xx = x + DX[d] ans.add("$y $x $yy $xx") val t = f[y][x]; f[y][x] = f[yy][xx]; f[yy][xx] = t } val penaltyLarge = when (mode % 4) { 0 -> 10 1 -> 100 2 -> 10_000 else -> 0 } val penaltyRandom = when (mode / 4 % 3) { 0 -> 50 1 -> 500 else -> 0 } val random = Random(mode) val dp = List(n) { IntArray(it + 1) } val dpHow = List(n) { IntArray(it + 1) } while (true) { var maxScore = Int.MIN_VALUE var bestMove: Triple<Int, Int, Int>? = null for (y in 0 until n) for (x in 0..y) for (d in 1..2) { val yy = y + DY[d]; val xx = x + DX[d] if (yy < 0 || yy >= n || xx < 0 || xx > yy) continue val v = f[y][x] val vv = f[yy][xx] val diff = v - vv if (diff < 0) continue val score = when (mode) { 0 -> diff 1 -> v 2 -> vv 3 -> -v else -> -vv } * 1000 + diff if (score > maxScore) { maxScore = score bestMove = Triple(y, x, d) } } if (maxScore == Int.MIN_VALUE) break val (yBest, xBest, dBest) = bestMove!! if (mode < 5) { makeMove(yBest, xBest, dBest) continue } val y0 = yBest + DY[dBest] val x0 = xBest + DX[dBest] dp[y0].fill(-1) dp[y0][x0] = 0 for (y in y0 - 1 downTo 0) { var x1 = -1 for (x in 0..y) { dp[y][x] = -1 if (f[y][x] < f[y0][x0]) continue var scoreHere = f[y][x] if (penaltyLarge > 0) { for (d in 0..5) { val yy = y + DY[d]; val xx = x + DX[d] if (yy < 0 || yy >= n || xx < 0 || xx > yy) continue if (f[yy][xx] < f[y][x]) scoreHere += penaltyLarge } } if (penaltyRandom > 0) { scoreHere += random.nextInt(penaltyRandom) } for (d in 1..2) { val yy = y + DY[d]; val xx = x + DX[d] if (dp[yy][xx] == -1) continue val new = dp[yy][xx] + scoreHere if (new > dp[y][x]) { dp[y][x] = new dpHow[y][x] = d } } if (dp[y][x] == -1) continue var found = true for (d in 4..5) { val yy = y + DY[d]; val xx = x + DX[d] if (yy >= 0 && xx in 0..yy && f[yy][xx] > f[y0][x0]) found = false } if (found) { if (x1 == -1 || dp[y][x] > dp[y][x1]) x1 = x } } if (x1 != -1) { fun moveTo(yDest: Int, xDest: Int) { if (yDest == y0) return val d = dpHow[yDest][xDest] moveTo(yDest + DY[d], xDest + DX[d]) makeMove(yDest, xDest, d) } moveTo(y, x1) break } } } return ans } private val DY = intArrayOf(0, 1, 1, 0, -1, -1) private val DX = intArrayOf(1, 0, 1, -1, 0, -1) private fun solve(n: Int = 30) = solve(List(n) { readInts().toIntArray() }) fun main() = solve() private fun readLn() = readLine()!! private fun readStrings() = readLn().split(" ") private fun readInts() = readStrings().map { it.toInt() }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
3,292
competitions
The Unlicense
src/main/kotlin/io/undefined/IsBalanceParentheses.kt
jffiorillo
138,075,067
false
{"Kotlin": 434399, "Java": 14529, "Shell": 465}
package io.undefined import io.undefined.IsBalanceParentheses.Parameter class IsBalanceParentheses { data class Parameter( val input: String, val bruteForceSolution: String, val stackSolution: String, val backAndForthSolution: String, val debug: Boolean = false ) fun balanceBruceForce(input: String, debug: Boolean = false): String { val shouldKeep: MutableList<Boolean> = input.map { false }.toMutableList() input.mapIndexed { index, value -> if (value == '(') { var j = index while (j < input.length) { if (input[j] == ')' && !shouldKeep[j]) { shouldKeep[index] = true shouldKeep[j] = true break } j++ } } if (debug) { println("index $index value $value $shouldKeep") } } val result = StringBuilder() if (debug) { println(shouldKeep) } input.mapIndexed { index, value -> if (shouldKeep[index] || value.isLetter()) { result.append(value) } } return result.toString() } fun balanceStack(input: String, debug: Boolean = false): String { val stack = mutableListOf<Int>() val temp: MutableList<Char> = input.mapIndexed { index, value -> when (value) { '(' -> value.also { stack.add(index) } ')' -> if (stack.isNotEmpty()) value.also { stack.removeLast() } else '*' else -> value }.also { result -> if (debug) println("index $index value $value stack $stack result $result") } }.toMutableList() if (debug) println("stack $stack temp $temp") stack.forEach { temp[it] = '*' } return temp.fold("") { acc, value -> if (value == '*') acc else acc + value } } fun balanceBackAndForth(input: String, debug: Boolean = false): String { var countExtraParentheses = 0 val temp: MutableList<Char> = input.map { value -> when (value) { '(' -> value.also { countExtraParentheses++ } ')' -> if (countExtraParentheses == 0) '*' else value.also { countExtraParentheses-- } else -> value }.also { result -> if (debug) println("value $value countExtraParentheses $countExtraParentheses result $result") } }.toMutableList() if (debug) println("balanceBackAndForth: first round: temp $temp countExtraParentheses $countExtraParentheses") countExtraParentheses = 0 return temp.asReversed().map { value -> if (debug) println("checking $value") when (value) { ')' -> value.also { countExtraParentheses++ } '(' -> if (countExtraParentheses == 0) '*'.also { if (debug) println("balanceBackAndForth: second round: removing $value in $temp") } else value.also { countExtraParentheses-- } else -> value } }.asReversed().fold("") { acc, value -> if (value == '*') acc else acc + value } } } fun main() { listOf( Parameter("()", "()", "()", "()"), Parameter("a(b)c)", "a(b)c", "a(b)c", "a(b)c"), Parameter("(((((", "", "", ""), Parameter("(()()(", "(())", "()()", "()()"), Parameter(")(())(", "(())", "(())", "(())"), Parameter(")())(()()(", "()(())", "()()()", "()()()"), ).map { (input, bruteForceSolution, stackSolution, backAndForthSolution, debug) -> IsBalanceParentheses().apply { if (balanceBruceForce(input) == bruteForceSolution) { println("balanceBruceForce: '$input' is valid") } else { println( "balanceBruceForce: '$input' expected '$bruteForceSolution' but got '${ balanceBruceForce( input, debug ) }' instead." ) } if (balanceStack(input) == stackSolution) { println("balanceStack: '$input' is valid") } else { println( "balanceStack: '$input' expected '$stackSolution' but got '${ balanceStack( input, debug ) }' instead." ) } if (balanceBackAndForth(input) == backAndForthSolution) { println("balanceBackAndForth: '$input' is valid") } else { println( "balanceBackAndForth: '$input' expected '$backAndForthSolution' but got '${ balanceBackAndForth( input, debug ) }' instead." ) } println("----------") } } }
0
Kotlin
0
0
f093c2c19cd76c85fab87605ae4a3ea157325d43
4,433
coding
MIT License
src/main/kotlin/de/tek/adventofcode/y2022/util/math/Graph.kt
Thumas
576,671,911
false
{"Kotlin": 192328}
package de.tek.adventofcode.y2022.util.math class Graph<T>(edges: List<Edge<T>>) { private val neighbourMap = edges.groupBy(Edge<T>::from) { it } constructor(edges: Set<Pair<T, T>>) : this(edges.map { Edge(it, 1) }) fun vertices(): Set<T> = neighbourMap.keys fun toPath(vertices: List<T>): List<Edge<T>> { if (vertices.size < 2) return emptyList() return vertices.zip(vertices.drop(1)).map { (from, to) -> neighbourMap[from]?.firstOrNull { it.to == to } ?: throw IllegalArgumentException("Vertices $from and $to do not form an edge ein the graph.") } } /** * Finds a shortest path between the given vertices in the graph. If there is no path, an empty list is returned. * Otherwise, returns a list of consecutive edges from start to end. */ fun findShortestPath(start: T, end: T): List<Edge<T>> { val distances = mutableMapOf(start to 0) val predecessor = mutableMapOf<T, Edge<T>?>(start to null) val verticesToVisit = mutableListOf(start) while (verticesToVisit.isNotEmpty()) { val vertex = verticesToVisit.removeFirst() val distance = distances[vertex] ?: throw IllegalStateException("Vertex $vertex should have a distance at this point.") val outgoingEdges = neighbourMap[vertex] ?: emptyList() for (edge in outgoingEdges) { val neighbour = edge.to val oldDistance = distances[neighbour] if (oldDistance == null || oldDistance > distance + 1) { distances[neighbour] = distance + edge.weight predecessor[neighbour] = edge verticesToVisit.add(neighbour) } } } val lastEdge = predecessor[end] ?: return emptyList() return generateSequence(lastEdge) { edge -> predecessor[edge.from] }.toList().reversed() } } data class Edge<T>(val from: T, val to: T, val weight: Int) { constructor(vertices: Pair<T, T>, weight: Int) : this(vertices.first, vertices.second, weight) override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Edge<*>) return false if (from != other.from) return false if (to != other.to) return false return true } override fun hashCode(): Int { var result = from?.hashCode() ?: 0 result = 31 * result + (to?.hashCode() ?: 0) return result } }
0
Kotlin
0
0
551069a21a45690c80c8d96bce3bb095b5982bf0
2,545
advent-of-code-2022
Apache License 2.0
src/aoc2017/kot/Day10.kt
Tandrial
47,354,790
false
null
package aoc2017.kot import itertools.chunksOfSize import toHexString import toIntList import java.io.File object Day10 { fun hashRound(input: List<Int>, rep: Int = 1): List<Int> { var mem = (0..255).toList() var pos = 0 var skipS = 0 repeat(rep) { for (len in input) { // reverse subList of mem pos..(pos+len) if (pos + len < mem.size) { // do wrapping mem = mem.subList(0, pos).plus(mem.subList(pos, pos + len).reversed()).plus(mem.subList(pos + len, mem.size)) } else { // wrapping - move subList pos..(mem.size) to the front, reverse 0..len and move back mem = mem.subList(pos, mem.size).plus(mem.subList(0, pos)) mem = mem.subList(0, len).reversed().plus(mem.subList(len, mem.size)) mem = mem.subList(mem.size - pos, mem.size).plus(mem.subList(0, mem.size - pos)) } pos = (pos + len + skipS++) % mem.size } } return mem } fun partTwo(input: List<Int>, rounds: Int): List<Int> = hashRound(input, rounds).chunksOfSize(16).map { it.reduce { a, b -> a.xor(b) } }.toList() } fun main(args: Array<String>) { val input = File("./input/2017/Day10_input.txt").readText().toIntList(",".toPattern()) var result = Day10.hashRound(input) println("Part One = ${result[0] * result[1]}") val input2 = File("./input/2017/Day10_input.txt").readText().toCharArray().map { it.toInt() } + listOf(17, 31, 73, 47, 23) result = Day10.partTwo(input2, 64) println("Part Two = ${result.toHexString()}") }
0
Kotlin
1
1
9294b2cbbb13944d586449f6a20d49f03391991e
1,540
Advent_of_Code
MIT License
src/day08/Day08_Part1.kt
m-jaekel
570,582,194
false
{"Kotlin": 13764}
package day08 import readInput import java.util.* fun main() { fun part1(input: List<String>): Int { val treeMap: List<List<Tree>> = input.map { row -> row.chunked(1).map { Tree(it.toInt(), UUID.randomUUID()) } } val transposedTreeMap = treeMap.mapIndexed { index, row -> List(row.size) { innerIndex -> treeMap[innerIndex][index] } } val visibleTrees: MutableSet<UUID> = mutableSetOf() checkTreeVisibility(treeMap, visibleTrees) checkTreeVisibility(treeMap.map { it.reversed() }, visibleTrees) checkTreeVisibility(transposedTreeMap, visibleTrees) checkTreeVisibility(transposedTreeMap.map { it.reversed() }, visibleTrees) return visibleTrees.size } val testInput = readInput("day08/test_input") check(part1(testInput) == 21) val input = readInput("day08/input") println(part1(input)) } private fun checkTreeVisibility( treeMap: List<List<Tree>>, visibleTrees: MutableSet<UUID>, ) { var maxTreeHeight: Int treeMap.forEachIndexed { _, trees: List<Tree> -> maxTreeHeight = -1 trees.forEachIndexed { _, tree -> if (tree.height > maxTreeHeight) { maxTreeHeight = tree.height visibleTrees.add(tree.id) } } } maxTreeHeight = -1 } data class Tree(val height: Int, val id: UUID)
0
Kotlin
0
1
07e015c2680b5623a16121e5314017ddcb40c06c
1,467
AOC-2022
Apache License 2.0
src/Day21.kt
andrikeev
574,393,673
false
{"Kotlin": 70541, "Python": 18310, "HTML": 5558}
fun main() { fun part1(input: List<String>): Long { val monkeys = buildMap { input.forEach { val (name, job) = MonkeyJob.parse(it) put(name, job) } } fun MonkeyJob.Calculate.firstMonkey() = monkeys.getValue(monkey1) fun MonkeyJob.Root.firstMonkey() = monkeys.getValue(monkey1) fun MonkeyJob.Calculate.secondMonkey() = monkeys.getValue(monkey2) fun MonkeyJob.Root.secondMonkey() = monkeys.getValue(monkey2) fun MonkeyJob.getValue(): Long { return when (this) { is MonkeyJob.Calculate -> { val monkey1Value = firstMonkey().getValue() val monkey2Value = secondMonkey().getValue() when (op) { MonkeyJob.Op.Plus -> monkey1Value + monkey2Value MonkeyJob.Op.Minus -> monkey1Value - monkey2Value MonkeyJob.Op.Multiply -> monkey1Value * monkey2Value MonkeyJob.Op.Divide -> monkey1Value / monkey2Value } } is MonkeyJob.Yell -> this.value is MonkeyJob.Root -> firstMonkey().getValue() + secondMonkey().getValue() } } return monkeys.getValue("root").getValue() } fun part2(input: List<String>): Long { val me = "humn" val monkeys = buildMap { input.forEach { val (name, job) = MonkeyJob.parse(it) put(name, job) } } fun MonkeyJob.Calculate.firstMonkey() = monkeys.getValue(monkey1) fun MonkeyJob.Root.firstMonkey() = monkeys.getValue(monkey1) fun MonkeyJob.Calculate.secondMonkey() = monkeys.getValue(monkey2) fun MonkeyJob.Root.secondMonkey() = monkeys.getValue(monkey2) fun MonkeyJob.getValue(): Long { return when (this) { is MonkeyJob.Calculate -> { val monkey1Value = firstMonkey().getValue() val monkey2Value = secondMonkey().getValue() when (op) { MonkeyJob.Op.Plus -> monkey1Value + monkey2Value MonkeyJob.Op.Minus -> monkey1Value - monkey2Value MonkeyJob.Op.Multiply -> monkey1Value * monkey2Value MonkeyJob.Op.Divide -> monkey1Value / monkey2Value } } is MonkeyJob.Yell -> this.value is MonkeyJob.Root -> firstMonkey().getValue() + secondMonkey().getValue() } } fun MonkeyJob.findMe(): Boolean { return when (this) { is MonkeyJob.Calculate -> monkey1 == me || monkey2 == me || firstMonkey().findMe() || secondMonkey().findMe() is MonkeyJob.Yell -> false is MonkeyJob.Root -> false } } fun MonkeyJob.Calculate.getMyValue(correctValue: Long): Long { if (monkey1 == me) { val secondValue = secondMonkey().getValue() return when (op) { MonkeyJob.Op.Plus -> correctValue - secondValue MonkeyJob.Op.Minus -> correctValue + secondValue MonkeyJob.Op.Multiply -> correctValue / secondValue MonkeyJob.Op.Divide -> correctValue * secondValue } } else if (monkey2 == me) { val firstValue = firstMonkey().getValue() return when (op) { MonkeyJob.Op.Plus -> correctValue - firstValue MonkeyJob.Op.Minus -> firstValue - correctValue MonkeyJob.Op.Multiply -> correctValue / firstValue MonkeyJob.Op.Divide -> firstValue / correctValue } } else { val firstMonkey = firstMonkey() val secondMonkey = secondMonkey() return if (firstMonkey.findMe()) { val secondValue = secondMonkey.getValue() val newCorrectValue = when (op) { MonkeyJob.Op.Plus -> correctValue - secondValue MonkeyJob.Op.Minus -> correctValue + secondValue MonkeyJob.Op.Multiply -> correctValue / secondValue MonkeyJob.Op.Divide -> correctValue * secondValue } (firstMonkey as MonkeyJob.Calculate).getMyValue(newCorrectValue) } else { val firstValue = firstMonkey.getValue() val newCorrectValue = when (op) { MonkeyJob.Op.Plus -> correctValue - firstValue MonkeyJob.Op.Minus -> firstValue - correctValue MonkeyJob.Op.Multiply -> correctValue / firstValue MonkeyJob.Op.Divide -> firstValue / correctValue } (secondMonkey as MonkeyJob.Calculate).getMyValue(newCorrectValue) } } } return with(monkeys.getValue("root") as MonkeyJob.Root) { val firstMonkey = firstMonkey() val secondMonkey = secondMonkey() if (firstMonkey.findMe()) { val correctValue = secondMonkey.getValue() (firstMonkey as MonkeyJob.Calculate).getMyValue(correctValue) } else { val correctValue = firstMonkey.getValue() (secondMonkey as MonkeyJob.Calculate).getMyValue(correctValue) } } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day21_test") check(part1(testInput).also { println("part1 test: $it") } == 152L) check(part2(testInput).also { println("part2 test: $it") } == 301L) val input = readInput("Day21") println(part1(input)) println(part2(input)) } private sealed interface MonkeyJob { enum class Op { Plus, Minus, Multiply, Divide } data class Yell(val value: Long) : MonkeyJob data class Calculate( val monkey1: String, val monkey2: String, val op: Op, ) : MonkeyJob data class Root( val monkey1: String, val monkey2: String, ) : MonkeyJob companion object { fun parse(input: String): Pair<String, MonkeyJob> { val items = input.split(" ") val name = items.first().dropLast(1) return name to when { name == "root" -> Root( monkey1 = items[1], monkey2 = items[3], ) items.size == 4 -> Calculate( monkey1 = items[1], monkey2 = items[3], op = parseOp(items[2]), ) else -> Yell(items[1].toLong()) } } private fun parseOp(input: String): Op = when (input) { "+" -> Op.Plus "-" -> Op.Minus "*" -> Op.Multiply "/" -> Op.Divide else -> error("wrong input") } } }
0
Kotlin
0
1
1aedc6c61407a28e0abcad86e2fdfe0b41add139
7,274
aoc-2022
Apache License 2.0
Kotlin for Java Developers. Week 3/Taxi Park/Task/src/taxipark/TaxiParkTask.kt
binout
159,054,839
false
null
package taxipark import java.util.* import kotlin.math.absoluteValue /* * Task #1. Find all the drivers who performed no trips. */ fun TaxiPark.findFakeDrivers(): Set<Driver> { val driversWhoPerformedAtrip = this.trips.map { it.driver } return this.allDrivers.filter { it !in driversWhoPerformedAtrip }.toSet() } /* * Task #2. Find all the clients who completed at least the given number of trips. */ fun TaxiPark.findFaithfulPassengers(minTrips: Int): Set<Passenger> = this.allPassengers.filter { p -> this.trips.count { trip -> p in trip.passengers } >= minTrips }.toSet() /* * Task #3. Find all the passengers, who were taken by a given driver more than once. */ fun TaxiPark.findFrequentPassengers(driver: Driver): Set<Passenger> = this.allPassengers.filter { p -> this.trips.filter { trip -> p in trip.passengers }.count{ trip -> trip.driver == driver } > 1 }.toSet() /* * Task #4. Find the passengers who had a discount for majority of their trips. */ fun TaxiPark.findSmartPassengers(): Set<Passenger> { fun hasMajorityOfDiscount(p: Passenger): Boolean { val tripOfPassenger = this.trips.filter { trip -> p in trip.passengers } val noDiscountTrip = tripOfPassenger.count { it.discount == null} return !tripOfPassenger.isEmpty() && (noDiscountTrip / tripOfPassenger.size.toDouble()) < 0.5 } return this.allPassengers.filter { hasMajorityOfDiscount(it)}.toSet() } /* * Task #5. Find the most frequent trip duration among minute periods 0..9, 10..19, 20..29, and so on. * Return any period if many are the most frequent, return `null` if there're no trips. */ fun TaxiPark.findTheMostFrequentTripDurationPeriod(): IntRange? { fun dozen(duration: Int) : IntRange { val i = ((duration / 10).absoluteValue) return 10*i..(10*i+9) } val tripByDozen: Map<IntRange, List<Trip>> = this.trips.groupBy { dozen(it.duration) } return tripByDozen.maxBy { it.value.size }?.key } /* * Task #6. * Check whether 20% of the drivers contribute 80% of the income. */ fun TaxiPark.checkParetoPrinciple(): Boolean { if (this.trips.isEmpty()) return false val totalCost = this.trips.map { it.cost }.sum() val oneOfFifth = (this.allDrivers.size / 5) val costByDriver = this.trips.groupBy { it.driver }.mapValues { it.value.map { it.cost }.sum() } var sum = 0.0 val currentMap = costByDriver.toMutableMap() repeat(oneOfFifth) { _ -> val max = currentMap.maxBy { it.value } sum += max?.value ?: 0.0 currentMap.remove(max!!.key) } return sum >= totalCost * 0.8 }
0
Kotlin
1
5
40ff182f63d29443fa3c29730560d37e2325501a
2,614
coursera-kotlin
Apache License 2.0
src/main/aoc2021/Day14.kt
nibarius
154,152,607
false
{"Kotlin": 963896}
package aoc2021 /** * Very similar solution to day 6. * @see Day6 */ class Day14(input: List<String>) { private val template = input.first() // Map of conversions. Example: "NN -> C" is transformed into rules[NN]: listOf(NC, CN) private val rules = input.drop(2).map { it.split(" -> ") }.associate { (a, b) -> a to listOf("${a[0]}$b", "$b${a[1]}") } /** * Increase the value of the item under 'key' with 'howMuch' with a default value of 0 */ private fun <T> MutableMap<T, Long>.add(key: T, howMuch: Long) { this[key] = getOrDefault(key, 0) + howMuch } private fun solve(steps: Int): Long { // Initialize element pair counts based on the template val numElementPairs = template.zipWithNext() .groupingBy { (a, b) -> "$a$b" } .eachCount() .mapValues { it.value.toLong() } .toMutableMap() repeat(steps) { numElementPairs.toMap().forEach { (element, numElements) -> // The original element pair is destroyed numElementPairs.add(element, -numElements) // And two new element pairs are created instead rules[element]!!.forEach { newElement -> numElementPairs.add(newElement, numElements) } } } val numElements = mutableMapOf<Char, Long>() // The first character in each two string element contributes to character count // (the second character in the pair will be counted as the first character of the next pair) numElementPairs.forEach { (key, value) -> numElements.add(key.first(), value) } // However, this leaves out the very last character in the final polymer. But the last (and first) character // remains the same during the whole process, so we can just look at the initial template to see what the // last character is. numElements.add(template.last(), 1) return numElements.values.maxOf { it } - numElements.values.minOf { it } } fun solvePart1(): Long { return solve(10) } fun solvePart2(): Long { return solve(40) } }
0
Kotlin
0
6
f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22
2,177
aoc
MIT License
src/main/kotlin/g0101_0200/s0154_find_minimum_in_rotated_sorted_array_ii/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0101_0200.s0154_find_minimum_in_rotated_sorted_array_ii // #Hard #Array #Binary_Search #Binary_Search_II_Day_13 // #2022_10_11_Time_275_ms_(84.00%)_Space_39_MB_(56.00%) class Solution { fun findMin(nums: IntArray): Int { return if (nums.isEmpty()) { 0 } else find(0, nums.size - 1, nums) } private fun find(left: Int, right: Int, nums: IntArray): Int { if (left + 1 >= right) { return Math.min(nums[left], nums[right]) } val mid = left + (right - left) / 2 if (nums[left] == nums[right] && nums[left] == nums[mid]) { return Math.min(find(left, mid, nums), find(mid, right, nums)) } return if (nums[left] >= nums[right]) { if (nums[mid] >= nums[left]) { find(mid, right, nums) } else { find(left, mid, nums) } } else { find(left, mid, nums) } } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
970
LeetCode-in-Kotlin
MIT License
src/2023/Day11.kt
nagyjani
572,361,168
false
{"Kotlin": 369497}
package `2023` import common.Linearizer import java.io.File import java.util.* import kotlin.math.abs import kotlin.math.max import kotlin.math.min fun main() { Day11().solve() } class Day11 { val input1 = """ ...#...... .......#.. #......... .......... ......#... .#........ .........# .......... .......#.. #...#..... """.trimIndent() val input2 = """ """.trimIndent() fun print(map: String, l: Linearizer) { for (y in 0 until l.dimensions[1]) { for (x in 0 until l.dimensions[0]) { print("${map[l.toIndex(x,y)]}") } print("\n") } } fun String.expand(l: Linearizer) : Pair<String, Linearizer> { val sumlinesX = (1..l.dimensions[0]).map { '.' }.toMutableList() val sumlinesY = (1..l.dimensions[1]).map { '.' }.toMutableList() for (x in 0 until l.dimensions[0]) { for (y in 0 until l.dimensions[1]) { if (get(l.toIndex(x,y)) == '#') { sumlinesX[x] = '#' sumlinesY[y] = '#' } } } val sumlinesX1 = sumlinesX.flatMap { if (it == '.') { listOf('.', '+') } else { listOf(it) } } val sumlinesY1 = sumlinesY.flatMap { if (it == '.') { listOf('.', '+') } else { listOf(it) } } val xd1 = sumlinesX.size + sumlinesX.filter { it == '.' }.size val yd1 = sumlinesY.size + sumlinesY.filter { it == '.' }.size val l1 = Linearizer(xd1, yd1) val r = (1..xd1 * yd1).map { '.' }.toMutableList() var ix = 0 for (x in 0 until xd1) { var iy = 0 for (y in 0 until yd1) { if (sumlinesX1[x] == '+' || sumlinesY1[y] == '+') { r[l1.toIndex(x,y)] = '+' } else { r[l1.toIndex(x,y)] = get(l.toIndex(ix,iy)) ++iy } } if (sumlinesX1[x] != '+') { ++ix } } return r.joinToString ( "" ) to l1 } fun solve() { val f = File("src/2023/inputs/day11.in") val s = Scanner(f) // val s = Scanner(input1) // val s = Scanner(input2) var sum = 0 var sum1 = 0L var lineix = 0 val lines = mutableListOf<String>() val sb = StringBuilder() while (s.hasNextLine()) { lineix++ val line = s.nextLine().trim() if (line.isEmpty()) { continue } lines.add(line) sb.append(line) } val l = Linearizer(lines[0].length, lineix) val lines1 = sb.toString() print(lines1, l) print("\n") val t = lines1.expand(l) val lines2 = t.first val l2 = t.second print(lines2, l2) print("\n") val galaxies = mutableListOf<Int>() lines2.forEachIndexed{ ix, it -> if (it == '#') {galaxies.add(ix)} } val m = 1000000 for (g1 in galaxies) { for (g2 in galaxies) { if (g1 < g2) { val c1 = l2.toCoordinates(g1) val c2 = l2.toCoordinates(g2) val cXmin = min(c1[0], c2[0]) val cXmax = max(c1[0], c2[0]) val cYmin = min(c1[1], c2[1]) val cYmax = max(c1[1], c2[1]) for (x in cXmin+1 .. cXmax) { val y = cYmin if (lines2[l2.toIndex(x,y)] == '+') { sum1 += m-1 } else { ++sum1 } } for (y in cYmin+1 .. cYmax) { val x = cXmax if (lines2[l2.toIndex(x,y)] == '+') { sum1 += m-1 } else { ++sum1 } } sum += abs(c1[0] - c2[0]) + abs(c1[1] - c2[1]) } } } print("$sum $sum1\n") } }
0
Kotlin
0
0
f0c61c787e4f0b83b69ed0cde3117aed3ae918a5
4,286
advent-of-code
Apache License 2.0
AdventOfCode/2022/aoc22/src/main/kotlin/day20.kt
benhunter
330,517,181
false
{"Rust": 172709, "Python": 143372, "Kotlin": 37623, "Java": 17629, "TypeScript": 3422, "JavaScript": 3124, "Just": 1078}
import java.math.BigInteger data class ValueStartIndexPair(val value: BigInteger, val startIndex: Int) fun day20() { val day = 20 println("day $day") val startTime = System.nanoTime() val filename = "$day-input.txt" val text = getTextFromResource(filename).trim() val lines = text.split("\n").map { it.toLong() } val input = lines.mapIndexed { index, i -> ValueStartIndexPair(i.toBigInteger(), index) } val decrypted = input.toMutableList() input.forEach(rotate(decrypted)) println("part 1 ${score(decrypted)}") // 19070 println("part 1 time: ${elapsedTimeInSecondsSince(startTime)} seconds") debugln("part 2") val part2StartTime = System.nanoTime() val magic = 811589153.toBigInteger() val keyed = lines.mapIndexed { index, i -> ValueStartIndexPair(i.toBigInteger() * magic, index) } val decrypted2 = keyed.toMutableList() repeat(10) { keyed.toList().forEach(rotate(decrypted2)) } val part2 = score(decrypted2) println("part 2 $part2") // 14773357352059 if (part2 != 14773357352059.toBigInteger()) throw Exception("wrong part 2") println("part 2 time: ${elapsedTimeInSecondsSince(part2StartTime)} seconds") println("total time: ${elapsedTimeInSecondsSince(startTime)} seconds") } fun score(decrypted: List<ValueStartIndexPair>): BigInteger { val posn0 = decrypted.withIndex().find { it.value.value == 0.toBigInteger() }?.index ?: throw Exception() val sum = listOf(1000, 2000, 3000).map { decrypted[(posn0 + it) % decrypted.size].value }.sumOf { it } return sum } private fun rotate( decrypted: MutableList<ValueStartIndexPair>, ) = rotateAction@{ pair: ValueStartIndexPair -> val currentPosition = decrypted.indexOf(pair).toBigInteger() var newPosition: BigInteger if (pair.value == 0.toBigInteger()) return@rotateAction newPosition = currentPosition + pair.value newPosition %= (decrypted.size - 1).toBigInteger() if (newPosition < 1.toBigInteger()) { newPosition += (decrypted.size - 1).toBigInteger() } else if (newPosition == 0.toBigInteger()) { newPosition = (decrypted.size - 1).toBigInteger() } if (newPosition != currentPosition) { decrypted.remove(pair) decrypted.add(newPosition.toInt(), pair) } }
0
Rust
0
1
a424c12f4d95f9d6f8c844e36d6940a2ac11d61d
2,327
coding-challenges
MIT License
src/main/kotlin/sort_algorithm/quickSort.kt
korilin
347,404,763
false
null
package sort_algorithm /** * 快速排序 * 时间复杂度: * 最优时间复杂度:Ο(n*log(n)) * 平均时间复杂度:Ο(n*log(n)) * 最坏时间复杂度:Ο(n²) * 空间复杂度:Ο(1) * * Quick Sort * Time Complexity: * Optimal Time Complexity: Ο(n*log(n)) * Average Time Complexity: Ο(n*log(n)) * Worst Time Complexity: Ο(n²) * Space Complexity: Ο(1) */ fun quickSort(array: IntArray) { fun partition(left: Int, right: Int): Int { // 以最左边的值作为交换值 var pivotPreIndex = left for (index in left..right) { if (array[index] <= array[right]) { array[pivotPreIndex] = array[index].also { array[index] = array[pivotPreIndex] } pivotPreIndex += 1 } } return pivotPreIndex - 1 } fun inner(left: Int, right: Int) { if (left < right) { val p = partition(left, right) inner(left, p - 1) inner(p + 1, right) } } inner(0, array.size - 1) }
0
Kotlin
0
1
b96ba1b2998b0c6b057fc9b77f677a3183c436ed
1,065
DSA-kt
MIT License
8_eight/PaintString.kt
thalees
250,902,664
false
null
fun main() { class Ans(val a: String, val m: String) repeat(readLine()!!.toInt()) { val s = readLine()!! val n = s.length val dp = Array(n) { i -> arrayOfNulls<Ans>(i + 1) } dp[0][0] = Ans(s.substring(0, 1), "R") var best = Ans(s, "") fun updateBest(p: Ans) { if (p.a <= best.a) best = p } fun updateDP(i: Int, j: Int, p: Ans) { val cur = dp[i][j] if (cur == null || p.a < cur.a) dp[i][j] = p } for (i in 1 until n) { for (j in 0 until i) { val p = dp[i - 1][j] ?: continue updateDP(i, j, Ans(p.a + s[i], p.m + "R")) if (j >= i - j) continue if (s[i] == p.a[j]) updateDP(i, j + 1, Ans(p.a, p.m + "B")) if (s[i] < p.a[j]) updateBest(Ans(p.a, p.m + "B".repeat(n - i))) } } for (p in dp[n - 1]) if (p != null) updateBest(p) println(best.m) } }
0
Kotlin
0
0
3b499d207d366450c7b2facbd99a345c86b6eff8
997
kotlin-code-challenges
MIT License
src/leetcodeProblem/leetcode/editor/en/LongestSubstringWithoutRepeatingCharacters.kt
faniabdullah
382,893,751
false
null
//Given a string s, find the length of the longest substring without repeating //characters. // // // Example 1: // // //Input: s = "abcabcbb" //Output: 3 //Explanation: The answer is "abc", with the length of 3. // // // Example 2: // // //Input: s = "bbbbb" //Output: 1 //Explanation: The answer is "b", with the length of 1. // // // Example 3: // // //Input: s = "pwwkew" //Output: 3 //Explanation: The answer is "wke", with the length of 3. //Notice that the answer must be a substring, "pwke" is a subsequence and not a //substring. // // // Example 4: // // //Input: s = "" //Output: 0 // // // // Constraints: // // // 0 <= s.length <= 5 * 10⁴ // s consists of English letters, digits, symbols and spaces. // // Related Topics Hash Table String Sliding Window 👍 18261 👎 839 package leetcodeProblem.leetcode.editor.en class LongestSubstringWithoutRepeatingCharacters { 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 lengthOfLongestSubstring(s: String): Int { var longest = 0 var currentRunStartIndex = 0 val lastSeenIndices = IntArray(128) s.toCharArray().forEachIndexed { index, char -> with(char.toInt()) { currentRunStartIndex = maxOf(lastSeenIndices[this], currentRunStartIndex) longest = maxOf(longest, index - currentRunStartIndex + 1) lastSeenIndices[this] = index + 1 } } return longest } } //leetcode submit region end(Prohibit modification and deletion) } fun main() { }
0
Kotlin
0
6
ecf14fe132824e944818fda1123f1c7796c30532
1,770
dsa-kotlin
MIT License
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[67]二进制求和.kt
maoqitian
175,940,000
false
{"Kotlin": 354268, "Java": 297740, "C++": 634}
import java.lang.StringBuilder //给你两个二进制字符串,返回它们的和(用二进制表示)。 // // 输入为 非空 字符串且只包含数字 1 和 0。 // // // // 示例 1: // // 输入: a = "11", b = "1" //输出: "100" // // 示例 2: // // 输入: a = "1010", b = "1011" //输出: "10101" // // // // 提示: // // // 每个字符串仅由字符 '0' 或 '1' 组成。 // 1 <= a.length, b.length <= 10^4 // 字符串如果不是 "0" ,就都不含前导零。 // // Related Topics 位运算 数学 字符串 模拟 // 👍 647 👎 0 //leetcode submit region begin(Prohibit modification and deletion) class Solution { fun addBinary(a: String, b: String): String { //遍历循环相加 时间复杂度 O(max(m,n)) m n 为字符串长度 var m = a.length-1 var n = b.length-1 //进位 var carry = 0 var resSb = StringBuilder() while (m >= 0 || n >= 0){ // “0” 字符的 ASC 码为48 对应为 0 ,字符串ASE 减去零 等于对应的int值 var sum = carry if(m >=0) sum+= a[m--] -'0' if(n >=0) sum+= b[n--] -'0' //拼接当前和 resSb.append(sum%2) //计算进位 carry = sum/2 } //计算完成是否还有进位 if (carry != 0) resSb.append(carry) return resSb.reverse().toString() } } //leetcode submit region end(Prohibit modification and deletion)
0
Kotlin
0
1
8a85996352a88bb9a8a6a2712dce3eac2e1c3463
1,504
MyLeetCode
Apache License 2.0
2019/day4/part_a.kt
sergeknystautas
226,467,020
false
null
package aoc2019.day4; // import kotlin.int.rem; /* Scans a range between two 6 digit numbers and counting how many combinations meet a set of rules. */ fun Descending(digits: List<Int>) : Boolean { var prev = digits[0]; for (i in 1..digits.size - 1) { if (prev > digits[i]) { return true; } prev = digits[i]; } return false; } fun Repeating(digits: List<Int>) : Boolean { var frequencies = digits.groupingBy { it }.eachCount(); var pairs = frequencies.filter{ it -> it.value > 1}; if (pairs.size == 0) { // If no pairs, this fails. return false; } /* This logic gives 1044 which is too low var odd = frequencies.filter{ it -> it.value == 3 || it.value == 5}; if (odd.size > 0) { // If there are triples or quintuples, then fails return false; } */ pairs = frequencies.filter{ it -> it.value == 2}; if (pairs.size == 0) { // If no pairs, this fails. return false; } var text = digits.joinToString(""); println("$text groups into $frequencies"); return true; } // Scan from the start to the end. fun Scan(start: Int, end: Int): Int { var matches : Int = 0; for (i in start..end) { var num = ToArray(i); if (Descending(num)) { continue; } if (!Repeating(num)) { continue; } // println(i); matches++; } return matches; } // Break down the digits into an array for easier recursion fun ToArray(raw: Int) : List<Int> { var digits = mutableListOf<Int>(); var value = raw; // println(value); while (value > 0) { var digit = value.rem(10); digits.add(digit); value = value.div(10); } digits.reverse(); // println(digits); return digits; } fun main(args: Array<String>) { if (args.size != 2) { println("You done messed up a-a-ron"); return; } var start: Int = args[0].toInt(); var end: Int = args[1].toInt(); var possibilities = Scan(start, end); println("Possibilities $possibilities"); }
0
Kotlin
0
0
38966bc742f70122681a8885e986ed69dd505243
2,141
adventofkotlin2019
Apache License 2.0
src/day1/Day01.kt
Johnett
572,834,907
false
{"Kotlin": 9781}
package day1 import readInput fun main() { fun getCalorieList(calories: List<String>):MutableList<Int> { var totalCalories = 0 val calorieSum: MutableList<Int> = mutableListOf() calories.forEach { calorie -> if (calorie.isNotBlank()) { totalCalories += calorie.toInt() } else { if (totalCalories != 0) calorieSum.add(totalCalories) totalCalories = 0 } } if (totalCalories != 0) calorieSum.add(totalCalories) calorieSum.sort() return calorieSum } fun part1(input: List<String>): Int { return getCalorieList(input).last() } fun part2(input: List<String>): Int { return getCalorieList(input).takeLast(3).sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("day1/Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput("day1/Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
c8b0ac2184bdad65db7d2f185806b9bb2071f159
1,086
AOC-2022-in-Kotlin
Apache License 2.0
src/main/kotlin/tr/emreone/adventofcode/days/Day03.kt
EmRe-One
568,569,073
false
{"Kotlin": 166986}
package tr.emreone.adventofcode.days object Day03 { // Lowercase item types a through z have priorities 1 through 26. // Uppercase item types A through Z have priorities 27 through 52. private fun getPriority(char: Char): Int { return if (char.isLowerCase()) { char - 'a' + 1 } else { char - 'A' + 27 } } fun part1(input: List<String>): Int { return input.sumOf { val (left, right) = it.substring(0, it.length/2) to it.substring(it.length/2, it.length) val commonLetter = left.toSet().intersect(right.toSet()).first() getPriority(commonLetter) } } fun part2(input: List<String>): Int { return input.chunked(3).sumOf { val (first, second, third) = it val commonLetter = first.toSet().intersect(second.toSet()).intersect(third.toSet()).first() getPriority(commonLetter) } } }
0
Kotlin
0
0
a951d2660145d3bf52db5cd6d6a07998dbfcb316
980
advent-of-code-2022
Apache License 2.0
src/main/kotlin/com/colinodell/advent2022/Day05.kt
colinodell
572,710,708
false
{"Kotlin": 105421}
package com.colinodell.advent2022 class Day05(input: String) { private val stacks = mutableMapOf<Int, MutableList<Char>>() private val moves: List<Move> init { val (rawStacks, rawCommands) = input.split("\n\n") for (row in rawStacks.split("\n").dropLast(1)) { row.chunked(4).forEachIndexed { index, crate -> stacks.computeIfAbsent(index + 1) { ArrayDeque() } if (crate.isNotBlank()) { stacks[index + 1]!!.add(crate[1]) } } } stacks.forEach { it.value.reverse() } val moveParser = "move (\\d+) from (\\d+) to (\\d+)".toRegex() moves = rawCommands.split("\n").map { val (_, count, source, destination) = moveParser.matchEntire(it)!!.groupValues Move(count.toInt(), source.toInt(), destination.toInt()) } } fun solvePart1(): String { moves.forEach { move -> repeat(move.count) { // log to console stacks[move.destination]!!.add(stacks[move.source]!!.removeLast()) } } return getStackTops() } fun solvePart2(): String { moves.forEach { move -> val crates = List(move.count) { stacks[move.source]!!.removeLast() }.asReversed() stacks[move.destination]!!.addAll(crates) } return getStackTops() } private fun getStackTops(): String { return stacks.values.map { it.last() }.joinToString("") } private data class Move(val count: Int, val source: Int, val destination: Int) }
0
Kotlin
0
1
32da24a888ddb8e8da122fa3e3a08fc2d4829180
1,629
advent-2022
MIT License
src/main/kotlin/ru/timakden/aoc/year2016/Day09.kt
timakden
76,895,831
false
{"Kotlin": 321649}
package ru.timakden.aoc.year2016 import ru.timakden.aoc.util.measure import ru.timakden.aoc.util.readInput /** * [Day 9: Explosives in Cyberspace](https://adventofcode.com/2016/day/9). */ object Day09 { @JvmStatic fun main(args: Array<String>) { measure { val input = readInput("year2016/Day09").single().filterNot { it.isWhitespace() } println("Part One: ${part1(input)}") println("Part Two: ${part2(input)}") } } tailrec fun part1(input: String, count: Long = 0L): Long { if (input.isEmpty()) return count return if (input.first() == '(') { val markerIndex = input.indexOf(')') val marker = input.substring(1, markerIndex) val (length, times) = "\\d+".toRegex().findAll(marker).map { it.value }.map { it.toInt() }.toList() part1(input.substring(markerIndex + length + 1), count + times * length) } else part1(input.substring(1), count + 1) } fun part2(input: String, count: Long = 0L): Long { if (input.isEmpty()) return count return if (input.first() == '(') { val markerIndex = input.indexOf(')') val marker = input.substring(1, markerIndex) val (length, times) = "\\d+".toRegex().findAll(marker).map { it.value }.map { it.toInt() }.toList() part2( input.substring(markerIndex + length + 1), count + times * part2(input.substring(markerIndex + 1, markerIndex + length + 1)) ) } else part2(input.substring(1), count + 1) } }
0
Kotlin
0
3
acc4dceb69350c04f6ae42fc50315745f728cce1
1,602
advent-of-code
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/ZeroOneMatrix.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 import kotlin.math.min /** * 542. 01 Matrix * @see <a href="https://leetcode.com/problems/01-matrix/">Source</a> */ fun interface ZeroOneMatrix { operator fun invoke(mat: Array<IntArray>): Array<IntArray> } /** * Approach 2: Using BFS */ class ZeroOneMatrixBFS : ZeroOneMatrix { private val dir = intArrayOf(0, 1, 0, -1, 0) override fun invoke(mat: Array<IntArray>): Array<IntArray> { val q: Queue<IntArray> = LinkedList() initializeQueue(mat, q) while (q.isNotEmpty()) { processQueue(mat, q) } return mat } private fun initializeQueue(mat: Array<IntArray>, q: Queue<IntArray>) { for (r in mat.indices) { for (c in mat[0].indices) { if (mat[r][c] == 0) { q.offer(intArrayOf(r, c)) } else { mat[r][c] = -1 // Marked as not processed yet! } } } } private fun processQueue(mat: Array<IntArray>, q: Queue<IntArray>) { val curr: IntArray = q.poll() val r = curr[0] val c = curr[1] for (i in 0..3) { val nr: Int = r + dir[i] val nc: Int = c + dir[i + 1] val local = nr < 0 || nr == mat.size || nc < 0 || nc == mat[0].size if (local || mat[nr][nc] != -1) { continue } mat[nr][nc] = mat[r][c] + 1 q.offer(intArrayOf(nr, nc)) } } } /** * Approach 3: Dynamic Programming */ class ZeroOneMatrixDP : ZeroOneMatrix { override fun invoke(mat: Array<IntArray>): Array<IntArray> { val m: Int = mat.size val n: Int = mat.firstOrNull()?.size ?: 0 fillTopLeft(mat, m, n) fillBottomRight(mat, m, n) return mat } private fun fillTopLeft(mat: Array<IntArray>, m: Int, n: Int) { val inf = m + n for (r in 0 until m) { for (c in 0 until n) { if (mat[r][c] == 0) continue val top = if (r - 1 >= 0) mat[r - 1][c] else inf val left = if (c - 1 >= 0) mat[r][c - 1] else inf mat[r][c] = min(top, left) + 1 } } } private fun fillBottomRight(mat: Array<IntArray>, m: Int, n: Int) { val inf = m + n for (r in m - 1 downTo 0) { for (c in n - 1 downTo 0) { if (mat[r][c] == 0) continue val bottom = if (r + 1 < m) mat[r + 1][c] else inf val right = if (c + 1 < n) mat[r][c + 1] else inf mat[r][c] = min(mat[r][c], min(bottom, right) + 1) } } } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,376
kotlab
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/ValidateBinaryTreeNodes.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.LinkedList import java.util.Queue /** * 1361. Validate Binary Tree Nodes * @see <a href="https://leetcode.com/problems/validate-binary-tree-nodes">Source</a> */ fun interface ValidateBinaryTreeNodes { operator fun invoke(n: Int, leftChild: IntArray, rightChild: IntArray): Boolean } class ValidateBinaryTreeNodesDFS : ValidateBinaryTreeNodes { override fun invoke(n: Int, leftChild: IntArray, rightChild: IntArray): Boolean { val inDegree = IntArray(n) { 0 } var root = -1 for (i in leftChild.indices) { if (leftChild[i] != -1 && inDegree[leftChild[i]]++ == 1) { return false } else if (rightChild[i] != -1 && inDegree[rightChild[i]]++ == 1) { return false } } for (i in leftChild.indices) { if (inDegree[i] == 0) { if (root == -1) { root = i } else { return false } } } if (root == -1) { return false } return countNodes(leftChild, rightChild, root) == n } private fun countNodes(l: IntArray, r: IntArray, root: Int): Int { if (root == -1) { return 0 } return 1 + countNodes(l, r, l[root]) + countNodes(l, r, r[root]) } } class ValidateBinaryTreeNodesBFS : ValidateBinaryTreeNodes { override fun invoke(n: Int, leftChild: IntArray, rightChild: IntArray): Boolean { val indegree = IntArray(n) for (i in 0 until n) { if (leftChild[i] != -1 && indegree[leftChild[i]]++ == 1) return false if (rightChild[i] != -1 && indegree[rightChild[i]]++ == 1) return false } var root = -1 for (i in 0 until n) if (indegree[i] == 0) root = i if (root == -1) return false val q: Queue<Int> = LinkedList() q.offer(root) var count = 0 while (q.isNotEmpty()) { val node: Int = q.poll() ++count if (leftChild[node] != -1) q.offer(leftChild[node]) if (rightChild[node] != -1) q.offer(rightChild[node]) } return count == n } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,869
kotlab
Apache License 2.0
src/main/kotlin/leetcode/kotlin/misc/463. Island Perimeter.kt
sandeep549
251,593,168
false
null
package leetcode.kotlin.misc fun main() { println( islandPerimeter( arrayOf( intArrayOf(0, 1, 0, 0), intArrayOf(1, 1, 1, 0), intArrayOf(0, 1, 0, 0), intArrayOf(1, 1, 0, 0) ) ) ) } private fun islandPerimeter(grid: Array<IntArray>): Int { // array to keep track of seen cells var dp = Array<IntArray>(grid.size) { IntArray(grid[0].size) { 0 } } fun lcon(i: Int, j: Int) = if (j == 0 || grid[i][j - 1] == 0) 1 else 0 fun rcon(i: Int, j: Int) = if (j == grid[0].size - 1 || grid[i][j + 1] == 0) 1 else 0 fun ucon(i: Int, j: Int) = if (i == 0 || grid[i - 1][j] == 0) 1 else 0 fun bcon(i: Int, j: Int) = if (i == grid.size - 1 || grid[i + 1][j] == 0) 1 else 0 // return current cell(i,j) contribution in perimeter fun dfs(i: Int, j: Int): Int { if (i < 0 || j < 0 || // out of bound, no contribution i >= grid.size || // out of bound, no contribution j >= grid[0].size || // out of bound, no contribution grid[i][j] == 0 || // not part of island, no contribution dp[i][j] == 1 // already processed, contribution already counted ) return 0 dp[i][j] = 1 // mark as seen/contributed return lcon(i, j) + // contribution from left side rcon(i, j) + // contribution from right side ucon(i, j) + // contribution from up side bcon(i, j) + // contribution from bottom side dfs(i, j - 1) + dfs(i, j + 1) + // recur for all neighbouring cells dfs(i - 1, j) + dfs(i + 1, j) } // find first cells with 1 value, and apply dfs for (i in grid.indices) { for (j in grid[0].indices) { if (grid[i][j] == 1) return dfs(i, j) } } return 0 } private fun islandPerimeter2(grid: Array<IntArray>): Int { var ans = 0 for (i in grid.indices) { for (j in grid.first().indices) { if (grid[i][j] == 1) { if (i == 0 || grid[i - 1][j] == 0) ans++ // top if (i == grid.size - 1 || grid[i + 1][j] == 0) ans++ // bottom if (j == 0 || grid[i][j - 1] == 0) ans++ // left if (j == grid.first().size - 1 || grid[i][j + 1] == 0) ans++ // right } } } return ans }
0
Kotlin
0
0
9cf6b013e21d0874ec9a6ffed4ae47d71b0b6c7b
2,396
kotlinmaster
Apache License 2.0
src/main/kotlin/year2022/Day05.kt
forketyfork
572,832,465
false
{"Kotlin": 142196}
package year2022 import java.util.* class Day05(input: String) { data class CrateMove(val num: Int, val from: Int, val to: Int) private val lines = input.lines() private val emptyLine = lines.indexOfFirst { it.isEmpty() } private val stacks = lines.parseStacks() private val regex = Regex("\\d+") private val moves: List<CrateMove> = lines.drop(emptyLine + 1).map(::parseCrateMove) private fun List<String>.parseStacks() = MutableList<Stack<Char>>((first().length + 1) / 4) { Stack() } .also { stacks -> take(emptyLine - 1).reversed() .flatMap { it.chunked(4) } .map { it[1] } .forEachIndexed { idx, char -> if (char != ' ') { stacks[idx % stacks.size].push(char) } } } private fun parseCrateMove(command: String): CrateMove { val (num, from, to) = regex.findAll(command).map { it.value.toInt() }.toList() return CrateMove(num, from - 1, to - 1) } private fun moveAll(mover: (move: CrateMove) -> Unit): String { moves.forEach(mover) return String(stacks.map { it.pop() }.toCharArray()) } fun part1() = moveAll { move -> move.moveOneByOne() } fun part2() = moveAll { move -> move.moveAtOnce() } private fun CrateMove.moveOneByOne() = repeat(num) { stacks[to].push(stacks[from].pop()) } private fun CrateMove.moveAtOnce() = Stack<Char>().apply { repeat(num) { push(stacks[from].pop()) } repeat(num) { stacks[to].push(pop()) } } }
0
Kotlin
0
0
5c5e6304b1758e04a119716b8de50a7525668112
1,662
aoc-2022
Apache License 2.0
src/day01/Day01.kt
dusanpetren
577,801,981
false
{"Kotlin": 1685}
package day01 import println import readInput fun main() { fun part1(input: String): Int { val data = input.split("\n\n").map { elf -> elf.lines().filter { it != "" }.sumOf { it.toInt() } } return data.max() } fun part2(input: String): Int { return input.split("\n\n").map { elf -> elf.lines().filter { it != "" }.sumOf { it.toInt() } } .sortedDescending() .take(3) .sum() } val testInput = readInput(1, "smol") check(part1(testInput) == 24000) //--- Part One --- //Find the Elf carrying the most Calories. How many total Calories is that Elf carrying? val input = readInput(1, "input") part1(input).println() //--- Part Two --- //Find the top three Elves carrying the most Calories. How many Calories are those Elves carrying in total? part2(input).println() }
0
Kotlin
0
0
82a26cbd0897e2d3e841c6ed9ac4fddf497ec05a
924
AoC-2022-Kotlin
Apache License 2.0
src/Day01.kt
PascalHonegger
573,052,507
false
{"Kotlin": 66208}
fun main() { fun List<String>.splitIntoElves(): List<List<Int>> = buildList { var elf = mutableListOf<Int>() this@splitIntoElves.forEach { if (it.isBlank()) { add(elf) elf = mutableListOf() } else { elf += it.toInt() } } add(elf) } fun part1(input: List<String>): Int { return input .splitIntoElves() .maxOf { it.sum() } } fun part2(input: List<String>): Int { return input .splitIntoElves() .map { it.sum() } .sortedDescending() .take(3) .sum() } val testInput = readInput("Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
2215ea22a87912012cf2b3e2da600a65b2ad55fc
899
advent-of-code-2022
Apache License 2.0
src/Day04.kt
rounakdatta
540,743,612
false
{"Kotlin": 19962}
class Board(input: MutableList<MutableList<Pair<String, Boolean>>>, isCompleted: Boolean) { private val actualBoard = input var completed: Boolean = isCompleted var numberThatHelpedMeWin: Int = -1 fun applyNumber(numberToPlayWith: String): Board { return Board(this.actualBoard.map { it.map { itx -> when (itx.first) { numberToPlayWith -> Pair(itx.first, true) else -> itx } } .toMutableList() } .toMutableList(), this.completed ) } fun markBoardCompletion(numberToPlayWith: String) { if (this.completed) { return } // check columns // :( couldn't do this in functional style for (i in 0 until this.actualBoard.size) { val currentColumn = mutableListOf<Pair<String, Boolean>>() for (j in 0 until this.actualBoard.size) { currentColumn.add(this.actualBoard[j][i]) } this.completed = currentColumn .filter { !it.second }.isEmpty() if (this.completed) { this.numberThatHelpedMeWin = numberToPlayWith.toInt() return } } // check for rows this.completed = this.actualBoard .map { it -> it.filter { itx -> !itx.second }.size } .filter { it -> it == 0 } .isNotEmpty() if (this.completed) { this.numberThatHelpedMeWin = numberToPlayWith.toInt() } return } fun calculateSumOfUnmarkedNumbers(): Int { return this.actualBoard .map { it -> it.filter { itx -> !itx.second }.sumOf { itx -> itx.first.toInt() } } .sumOf { it } } } fun deserializeBoard(input: List<String>): MutableList<MutableList<Pair<String, Boolean>>> { // remember to throw out the first blank row return input.fold(mutableListOf<MutableList<Pair<String, Boolean>>>()) { rows, singleRow -> rows.apply { this.add( singleRow.trim().split(" ", " ") // sometimes it catches the extra spaces as a number, we gotta throw that .filter { it != "" } .map { it -> Pair(it, false) } .toMutableList() ) } } .filter { it.size != 0 } .toMutableList() } fun constructBoards(input: List<String>): MutableList<Board> { return input.chunked(6) .fold(mutableListOf<Board>()) { listOfBoards, serializedBoard -> listOfBoards.apply { this.add(Board(deserializeBoard(serializedBoard), false)) } } } fun getChosenNumbers(input: String): List<String> { return input.split(",") } fun computeFirstScore(numberJustCalled: Int, boards: List<Board>): Int { return boards.filter { it.completed }.first().calculateSumOfUnmarkedNumbers() * numberJustCalled } fun letMeWinBingo( chosenNumbers: List<String>, boards: MutableList<Board>, winnerScore: Int ): Pair<MutableList<Board>, Int> { return when (chosenNumbers.size) { 0 -> Pair(boards, winnerScore) else -> { // play with the first element val numberToPlayWith = chosenNumbers.first() val appliedBoards = boards .map { it -> it.applyNumber(numberToPlayWith).also { it.markBoardCompletion(numberToPlayWith) } } letMeWinBingo( chosenNumbers.subList(1, chosenNumbers.size), appliedBoards.toMutableList(), if (winnerScore == -1 && appliedBoards.filter { it.completed }.isNotEmpty()) { computeFirstScore(numberToPlayWith.toInt(), appliedBoards) } else { winnerScore } ) } } } fun computeSecondScore(numberJustCalled: Int, boards: List<Board>): Int { return boards.filter { it.numberThatHelpedMeWin == numberJustCalled }.first() .calculateSumOfUnmarkedNumbers() * numberJustCalled } fun letGiantSquidWinBingo( chosenNumbers: List<String>, boards: MutableList<Board>, winnerScore: Int ): Pair<MutableList<Board>, Int> { return when (chosenNumbers.size) { 0 -> Pair(boards, winnerScore) else -> { // play with the first element val numberToPlayWith = chosenNumbers.first() val appliedBoards = boards .map { it -> it.applyNumber(numberToPlayWith).also { it.markBoardCompletion(numberToPlayWith) } } letGiantSquidWinBingo( chosenNumbers.subList(1, chosenNumbers.size), appliedBoards.toMutableList(), if (winnerScore == -1 && appliedBoards.filter { it.completed }.size == boards.size) { computeSecondScore(numberToPlayWith.toInt(), appliedBoards) } else { winnerScore } ) } } } fun main() { fun part1(input: List<String>): Int { return Pair(getChosenNumbers(input[0]), constructBoards(input.subList(1, input.size))) .let { it -> letMeWinBingo(it.first, it.second, -1) }.second } fun part2(input: List<String>): Int { return Pair(getChosenNumbers(input[0]), constructBoards(input.subList(1, input.size))) .let { it -> letGiantSquidWinBingo(it.first, it.second, -1) }.second } val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
130d340aa4c6824b7192d533df68fc7e15e7e910
5,655
aoc-2021
Apache License 2.0
src/main/kotlin/io/github/raphaeltarita/days/Day8.kt
RaphaelTarita
433,468,222
false
{"Kotlin": 89687}
package io.github.raphaeltarita.days import io.github.raphaeltarita.structure.AoCDay import io.github.raphaeltarita.util.day import io.github.raphaeltarita.util.inputPath import io.github.raphaeltarita.util.intersect import io.github.raphaeltarita.util.negate import io.github.raphaeltarita.util.pow import kotlinx.datetime.LocalDate import java.util.EnumSet import kotlin.io.path.readLines object Day8 : AoCDay { private enum class Segment { UPPER, U_LEFT, U_RIGHT, MIDDLE, L_LEFT, L_RIGHT, LOWER; companion object { private val set = EnumSet.allOf(Segment::class.java) fun valueSet(): EnumSet<Segment> { return EnumSet.copyOf(set) } } } private enum class Digit(val segments: Set<Segment>, val corresponding: Int, val offSegments: Set<Segment> = segments.negate()) { ZERO(setOf(Segment.UPPER, Segment.U_LEFT, Segment.U_RIGHT, Segment.L_LEFT, Segment.L_RIGHT, Segment.LOWER), 0), ONE(setOf(Segment.U_RIGHT, Segment.L_RIGHT), 1), TWO(setOf(Segment.UPPER, Segment.U_RIGHT, Segment.MIDDLE, Segment.L_LEFT, Segment.LOWER), 2), THREE(setOf(Segment.UPPER, Segment.U_RIGHT, Segment.MIDDLE, Segment.L_RIGHT, Segment.LOWER), 3), FOUR(setOf(Segment.U_LEFT, Segment.U_RIGHT, Segment.MIDDLE, Segment.L_RIGHT), 4), FIVE(setOf(Segment.UPPER, Segment.U_LEFT, Segment.MIDDLE, Segment.L_RIGHT, Segment.LOWER), 5), SIX(setOf(Segment.UPPER, Segment.U_LEFT, Segment.MIDDLE, Segment.L_LEFT, Segment.L_RIGHT, Segment.LOWER), 6), SEVEN(setOf(Segment.UPPER, Segment.U_RIGHT, Segment.L_RIGHT), 7), EIGHT(setOf(Segment.UPPER, Segment.U_LEFT, Segment.U_RIGHT, Segment.MIDDLE, Segment.L_LEFT, Segment.L_RIGHT, Segment.LOWER), 8), NINE(setOf(Segment.UPPER, Segment.U_LEFT, Segment.U_RIGHT, Segment.MIDDLE, Segment.L_RIGHT, Segment.LOWER), 9); companion object { private val set = EnumSet.allOf(Digit::class.java) fun valueSet(): EnumSet<Digit> { return EnumSet.copyOf(set) } fun fromSegments(segments: Set<Segment>): Digit { for (d in values()) { if (d.segments == segments) return d } error("unknown segment combination: $segments") } } } override val day: LocalDate = day(8) private fun isUniqueNumberLength(pattern: String): Boolean { return pattern.length == 2 || pattern.length == 3 || pattern.length == 4 || pattern.length == 7 } private val DIGITS_LEN_5 = EnumSet.of(Digit.TWO, Digit.THREE, Digit.FIVE) private val DIGITS_LEN_6 = EnumSet.of(Digit.ZERO, Digit.SIX, Digit.NINE) private fun getInput(): List<Pair<List<String>, List<String>>> { return inputPath.readLines() .map { val (patterns, output) = it.split(Regex("\\s*\\|\\s*")) patterns.split(' ') to output.split(' ') } } override fun executePart1(): Int { return getInput().sumOf { output -> output.second.count(this::isUniqueNumberLength) } } private fun deduceSegments(from: List<String>): Map<Char, Segment> { val digitsLeft = Digit.valueSet() val possibilities = mapOf( 'a' to Segment.valueSet(), 'b' to Segment.valueSet(), 'c' to Segment.valueSet(), 'd' to Segment.valueSet(), 'e' to Segment.valueSet(), 'f' to Segment.valueSet(), 'g' to Segment.valueSet() ) fun narrow(deducedDigit: Digit, input: String) { for (c in possibilities.keys) { if (c in input) { possibilities.getValue(c).retainAll(deducedDigit.segments) } else { possibilities.getValue(c).removeAll(deducedDigit.segments) } } digitsLeft.remove(deducedDigit) } fun narrowMultiple(possibleDigits: Set<Digit>, input: String) { if (possibleDigits.size == 1) { narrow(possibleDigits.single(), input) } var possibleSegments = input.map { possibilities.getValue(it) } possibleSegments = possibleSegments.partition { segments -> possibleSegments.count { it == segments } == segments.size } .let { (fixed, other) -> other + fixed.distinct().flatten().map { EnumSet.of(it) } } val narrowed = possibleDigits.filter { digit -> digit.segments.all { segment -> possibleSegments.any { segment in it } } && possibleSegments.none { segments -> digit.offSegments.containsAll(segments) } } if (narrowed.size == 1) { narrow(narrowed.single(), input) } } val (uniqueLength, other) = from.partition(this::isUniqueNumberLength) for (segments in uniqueLength.sortedBy { it.length }) { if (possibilities.values.all { it.size == 1 }) break when (segments.length) { 2 -> narrow(Digit.ONE, segments) 3 -> narrow(Digit.SEVEN, segments) 4 -> narrow(Digit.FOUR, segments) 7 -> narrow(Digit.EIGHT, segments) } } for (segments in other.sortedBy { it.length }) { if (possibilities.values.all { it.size == 1 }) break when (segments.length) { 5 -> narrowMultiple(digitsLeft intersect DIGITS_LEN_5, segments) 6 -> narrowMultiple(digitsLeft intersect DIGITS_LEN_6, segments) } } return possibilities.mapValues { (_, v) -> v.single() } } private fun toNumber(digits: List<Digit>): Int { var res = 0 for ((idx, d) in digits.withIndex()) { res += 10.pow(digits.size - idx - 1).toInt() * d.corresponding } return res } override fun executePart2(): Int { return getInput().sumOf { line -> val segmentMap = deduceSegments(line.first) toNumber(line.second.map { segment -> Digit.fromSegments(segment.map { segmentMap.getValue(it) }.toSet()) }) } } }
0
Kotlin
0
3
94ebe1428d8882d61b0463d1f2690348a047e9a1
6,297
AoC-2021
Apache License 2.0
src/main/kotlin/dev/bogwalk/batch0/Problem2.kt
bog-walk
381,459,475
false
null
package dev.bogwalk.batch0 import dev.bogwalk.util.custom.RollingQueue /** * Problem 2: Even Fibonacci Numbers * * https://projecteuler.net/problem=2 * * Goal: Find the sum of all even numbers in the Fibonacci sequence less than N. * * Constraints: 10 <= N <= 4e16 * * e.g.: N = 44 * even fibonacci < N = {2, 8, 34} * sum = 44 */ class EvenFibonacci { /** * Uses custom class RollingQueue to reduce memory of stored fibonacci numbers as only the 2 * prior are needed to accumulate sum. Provides an easier alternative to using an array or * multiple variables as it handles value reassignment & swapping within the class. * * SPEED (WORST): 6.3e+04ns for N = 4e16 */ fun sumOfEvenFibsRolling(n: Long): Long { var sum = 0L val fibonacci = RollingQueue<Long>(2).apply { addAll(listOf(1L, 1L)) } while (true) { val nextFib = fibonacci.peek() + fibonacci.peekTail()!! if (nextFib >= n) break fibonacci.add(nextFib) if (nextFib % 2 == 0L) sum += nextFib } return sum } /** * Brute iteration over all Fibonacci terms using the formula: * * F_n = F_{n-2} + F_{n-1} * * SPEED (BETTER): 1867ns for N = 4e16 */ fun sumOfEvenFibsNaive(n: Long): Long { var sum = 0L var prev2 = 1L var prev1 = 2L while (prev1 < n) { if (prev1 and 1 == 0L) sum += prev1 val nextFib = prev1 + prev2 prev2 = prev1 prev1 = nextFib } return sum } /** * Sums every 3rd term in the sequence starting with 2, based on the observed pattern that * every 3rd Fibonacci number after 2 is even. This occurs because the sequence begins with 2 * odd numbers, the sum of which must be even, then the sum of an odd and even number, twice, * will produce 2 odd numbers, etc... * * SPEED (BETTER) 1848ns for N = 4e16 */ fun sumOfEvenFibsBrute(n: Long): Long { var sum = 0L var prev = 1L var evenFib = 2L while (evenFib < n) { sum += evenFib val next = prev + evenFib prev = next + evenFib evenFib = next + prev } return sum } /** * Sums every 3rd term in the sequence starting with 2, using the formula: * * F_n = F_{n-6} + 4F_{n-3} * * SPEED (BEST) 1237ns for N = 4e16 */ fun sumOfEvenFibsFormula(n: Long): Long { var sum = 10L val evenFibs = longArrayOf(2, 8) // [F(3), F(6)] while (true) { val nextEvenFib = evenFibs[0] + 4 * evenFibs[1] if (nextEvenFib >= n) break sum += nextEvenFib evenFibs[0] = evenFibs[1] evenFibs[1] = nextEvenFib } return sum } }
0
Kotlin
0
0
62b33367e3d1e15f7ea872d151c3512f8c606ce7
2,900
project-euler-kotlin
MIT License
src/chapter1/section4/ex25_Throwing2Eggs.kt
w1374720640
265,536,015
false
{"Kotlin": 1373556}
package chapter1.section4 import extensions.formatDouble import extensions.inputPrompt import extensions.readInt import kotlin.math.sqrt /** * 扔两个鸡蛋 * 和上一题相同的问题,但现在假设你只有两个鸡蛋,而你的成本模型则是扔鸡蛋的次数。 * 设计一种策略,最多扔2*sqrt(N)次鸡蛋即可判断出F的值,然后想办法把这个成本降低到~c*sqrt(F)次。 * 这和查找命中(鸡蛋完好无损)比未命中(鸡蛋被摔碎)的成本小得多的情形类似。 * * 解:先求出sqrt(N)的值,分别从1*sqrt(N),2*sqrt(N),3*sqrt(N)...k*sqrt(N)开始扔,直到鸡蛋摔碎 * 因为sqrt(N)*sqrt(N)=N,所以在最坏情况下,k=sqrt(N) * 然后从(k-1)*sqrt(N)开始,逐层向上扔,最坏情况下,需要扔k*sqrt(N)-(k-1)*sqrt(N)=sqrt(N)次 * 所以整体在最坏情况下需要扔2*sqrt(N)次 */ fun ex25a_Throwing2Eggs(array: IntArray): Pair<Int, Int> { val sqrt = sqrt(array.size.toDouble()) var k = 0 var count = 0 var floor: Int do { k++ count++ floor = (k * sqrt).toInt() } while (floor < array.size && array[floor] < 1) for (i in ((k - 1) * sqrt).toInt() + 1..minOf(array.size - 1, floor)) { count++ if (array[i] == 1) { return i to count } } return -1 to count } /** * 条件和上面相同,把成本(扔的次数)降低到~c*sqrt(N) * * 解:因为1+2+3+4+...+k约等于(k^2)/2 * 设Sk=1+2+3+...+k * k从1开始累加,分别在Sk层扔鸡蛋,当鸡蛋摔碎时Sk=F,需要尝试k次 * 推导出(k^2)/2=F k=sqrt(2)*sqrt(F) * 然后从S(k-1)处开始逐层向上扔,需要尝试k次 * 所以总的尝试的次数为2k=2*sqrt(2)*sqrt(F) c=2*sqrt(2) */ fun ex25b_Throwing2Eggs(array: IntArray): Pair<Int, Int> { var k = 1 var S = k var count = 0 while (S < array.size && array[S] < 1) { k++ S += k count++ } for (i in S - k + 1..minOf(array.size - 1, S)) { count++ if (array[i] == 1) { return i to count } } return -1 to count } fun main() { inputPrompt() val total = readInt("total: ") val floor = readInt("floor: ") val array = IntArray(total) { if (it < floor) 0 else 1 } val resultA = ex25a_Throwing2Eggs(array) println(array.joinToString(limit = 100)) println("ex25a index=${resultA.first} count=${resultA.second} 2*sqrt(N)=${formatDouble(2 * sqrt(total.toDouble()), 2)}") val resultB = ex25b_Throwing2Eggs(array) println("ex25a index=${resultB.first} count=${resultB.second} 2*sqrt(2)*sqrt(F)=${formatDouble(2 * sqrt(2.0) * sqrt(floor.toDouble()), 2)}") }
0
Kotlin
1
6
879885b82ef51d58efe578c9391f04bc54c2531d
2,711
Algorithms-4th-Edition-in-Kotlin
MIT License
src/main/kotlin/leetcode/advanceds/Trie2.kt
sandeep549
251,593,168
false
null
package leetcode.advanceds private class Trie2 { private class TrieNode { var end = false var children: MutableMap<Char, TrieNode?> = HashMap() } private var root = TrieNode() // Insert word into Trie fun insert(word: String) { var trieNode: TrieNode = root for (ch in word) { if (!trieNode.children.containsKey(ch)) trieNode.children[ch] = TrieNode() trieNode = trieNode.children[ch]!! } trieNode.end = true } // Find word into Trie fun find(word: String): Boolean { var trieNode: TrieNode? = root for (ch in word) { if (trieNode!!.children.containsKey(ch)) trieNode = trieNode.children[ch] else return false } return trieNode != null && trieNode.end } /** * This function will print all the words in the dictionary * that have given string as prefix. * 1. Check if prefix itself not present. * 2. Check if prefix end itself as word. * 3. Print all words that has this prefix. */ fun printSuggestions(prefix: String) { var trieNode: TrieNode? = root for (ch in prefix) { trieNode = if (trieNode!!.children.containsKey(ch)) trieNode.children[ch] else return // prefix not present } if (trieNode != null && trieNode.end) { println(prefix) return // prefix itself is word } printSuggestions(prefix, trieNode) } private fun printSuggestions(prefix: String, trieNode: TrieNode?) { if (trieNode == null) return if (trieNode.end) println(prefix) for ((key, value) in trieNode.children) { printSuggestions(prefix + key, value) } } } fun main() { val trie2 = Trie2() trie2.insert("sandeep") trie2.insert("simar") trie2.insert("daksh") println("Find sandeep=" + trie2.find("sandeep")) trie2.printSuggestions("s") trie2.insert("how are you ?") trie2.insert("how do you do ?") trie2.printSuggestions("how") }
0
Kotlin
0
0
9cf6b013e21d0874ec9a6ffed4ae47d71b0b6c7b
2,085
kotlinmaster
Apache License 2.0
src/aoc2017/kot/Day13.kt
Tandrial
47,354,790
false
null
package aoc2017.kot import java.io.File import kotlin.system.measureTimeMillis object Day13 { data class Layer(val depth: Int, val range: Int) { fun isAtStart(offset: Int): Boolean = (depth + offset) % (2 * (range - 1)) == 0 } // Sum of all layers which are at position 0 when we pass fun partOne(input: List<String>): Int = parse(input).filter { it.isAtStart(0) }.sumBy { it.depth * it.range } fun partTwo(input: List<String>): Int { val layers = parse(input) // Find the smallest time we have to wait where no layer is at position 0 when we pass return generateSequence(0) { it + 1 }.first { layers.none { layer -> layer.isAtStart(it) } } } private fun parse(input: List<String>): List<Layer> = input.map { val line = it.split(": "); Layer(line[0].toInt(), line[1].toInt()) } } fun main(args: Array<String>) { val input = File("./input/2017/Day13_input.txt").readLines() println("Part One = ${Day13.partOne(input)}") println("Part One = ${Day13.partTwo(input)}") println("Part Two = ${measureTimeMillis { Day13.partTwo(input) }}") }
0
Kotlin
1
1
9294b2cbbb13944d586449f6a20d49f03391991e
1,079
Advent_of_Code
MIT License
src/Day14.kt
amelentev
573,120,350
false
{"Kotlin": 87839}
fun main() { fun read() = readInput("Day14").map { it.toCharArray() } var map: List<CharArray> = read() fun tiltN() { for (i in map.indices) { for (j in map[i].indices) { if (map[i][j] == 'O') { map[i][j] = '.' var i1 = i while (i1 > 0 && map[i1-1][j] == '.') i1-- map[i1][j] = 'O' } } } } fun tiltS() { for (i in map.indices.reversed()) { for (j in map[i].indices) { if (map[i][j] == 'O') { map[i][j] = '.' var i1 = i while (i1+1 < map.size && map[i1+1][j] == '.') i1++ map[i1][j] = 'O' } } } } fun tiltW() { for (i in map.indices) { for (j in map[i].indices) { if (map[i][j] == 'O') { map[i][j] = '.' var j1 = j while (j1-1 >= 0 && map[i][j1-1] == '.') j1-- map[i][j1] = 'O' } } } } fun tiltE() { for (i in map.indices) { for (j in map[i].indices.reversed()) { if (map[i][j] == 'O') { map[i][j] = '.' var j1 = j while (j1+1 < map[i].size && map[i][j1+1] == '.') j1++ map[i][j1] = 'O' } } } } run { tiltN() println(map.joinToString("\n") { String(it) }) var res1 = 0 for (i in map.indices) { for (j in map[i].indices) { if (map[i][j] == 'O') res1 += map.size-i } } println(res1) } run { map = read() val prev = HashMap<String, Int>() prev[map.joinToString("\n") { String(it) }] = 0 var step = 1 while (step <= 1000000000) { tiltN() tiltW() tiltS() tiltE() step++ val cur = map.joinToString("\n") { String(it) } val previ = prev[cur] if (previ != null) { val len = step - previ val need = (1000000000 - step) step += (need / len) * len } else { prev[cur] = step } } var res1 = 0 for (i in map.indices) { for (j in map[i].indices) { if (map[i][j] == 'O') res1 += map.size-i } } println(res1) } }
0
Kotlin
0
0
a137d895472379f0f8cdea136f62c106e28747d5
2,651
advent-of-code-kotlin
Apache License 2.0
2021/src/Day21.kt
Bajena
433,856,664
false
{"Kotlin": 65121, "Ruby": 14942, "Rust": 1698, "Makefile": 454}
import kotlin.math.abs import kotlin.math.max // https://adventofcode.com/2021/day/20 fun main() { class Dice { var points = 0 var rolls = 0 fun roll() : Int { rolls++ if (points == 100) { points = 0 } points++ return points } } fun part1() { // var player1Position = 4 - 1 var player1Position = 9 - 1 var player1Score = 0 // var player2Position = 8 - 1 var player2Position = 4 - 1 var player2Score = 0 val dice = Dice() while (true) { val player1RollSum = arrayOf(dice.roll(), dice.roll(), dice.roll()).sum() player1Position = (player1Position + player1RollSum) % 10 player1Score += player1Position + 1 if (player1Score >= 1000) { break } val player2RollSum = arrayOf(dice.roll(), dice.roll(), dice.roll()).sum() player2Position = (player2Position + player2RollSum) % 10 player2Score += player2Position + 1 if (player2Score >= 1000) { break } println("Player 1 score: $player1Score, position: ${player1Position + 1}") println("Player 2 score: $player2Score, position: ${player2Position + 1}") } println("Player 1 score: $player1Score, position: $player1Position") println("Player 2 score: $player2Score, position: $player2Position") println("Rolls: ${dice.rolls}") val loserScore = if (player2Score > player1Score) player1Score else player2Score println(loserScore * dice.rolls) } var p1Wins: Long = 0 var p2Wins: Long = 0 fun move(player1Position: Int, player2Position: Int, isPlayer1Current: Boolean, player1Score: Int = 0, player2Score: Int = 0, clones: Long = 0) { val availableResults = arrayOf(3, 4, 5, 6, 7, 8, 9) // val availableResults = arrayOf(3, 4, 5, 4, 5, 6, 5, 6, 7, 4, 5, 6, 5, 6, 7, 6, 7, 8, 5, 6, 7, 6, 7, 8, 7, 8, 9) val occurences = mapOf(3 to 1, 4 to 3, 5 to 6, 6 to 7, 7 to 6, 8 to 3, 9 to 1) if (isPlayer1Current) { if (player2Score >= 21) { p2Wins+=clones val thousand: Long = 1000000 val zero: Long = 0 if (p2Wins % thousand == zero) println("P2 wins: $p1Wins") return } for (sum in availableResults) { val newPosition = (player1Position + sum) % 10 move(newPosition, player2Position, !isPlayer1Current, player1Score + newPosition + 1, player2Score, clones * occurences.get(sum)!!) } return } if (player1Score >= 21) { p1Wins+=clones val thousand: Long = 1000000 val zero: Long = 0 if (p1Wins % thousand == zero) println("P1 wins: $p1Wins") return } for (sum in availableResults) { val newPosition = (player2Position + sum) % 10 move(player1Position, newPosition, !isPlayer1Current, player1Score, player2Score + newPosition + 1, clones * occurences.get(sum)!!) } } fun part2() { // var player1Position = 4 - 1 var player1Position = 9 - 1 var player1Score = 0 // var player2Position = 8 - 1 var player2Position = 4 - 1 var player2Score = 0 move(player1Position, player2Position, true, 0, 0, 1) println(p1Wins) println(p2Wins) } // part1() part2() }
0
Kotlin
0
0
a5ca56b7ac8d9d48f82dc079c8ea0cf06d17109a
3,219
advent-of-code
Apache License 2.0
src/main/java/challenges/leetcode/AddTwoNumbers.kt
ShabanKamell
342,007,920
false
null
package challenges.leetcode /** You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. Example 1 Input: l1 = [2,4,3], l2 = [5,6,4] Output: [7,0,8] Explanation: 342 + 465 = 807. Example 2: Input: l1 = [0], l2 = [0] Output: [0] Example 3: Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9] Output: [8,9,9,9,0,0,0,1] https://leetcode.com/problems/add-two-numbers/ */ object AddTwoNumbers { class ListNode(var `val`: Int) { var next: ListNode? = null } private fun addTwoNumbers(l1: ListNode?, l2: ListNode?): ListNode? { var n1 = l1 var n2 = l2 var remaining = 0 var result: ListNode? = null var prev: ListNode? = null while (n1 != null || n2 != null) { var number = (n1?.`val` ?: 0) + remaining + (n2?.`val` ?: 0) if (number > 9) { remaining = 1 number %= 10 } else { remaining = 0 } val node = ListNode(number) if (result == null) { result = node prev = result } else { prev?.next = node prev = node } n1 = n1?.next n2 = n2?.next } if (remaining > 0) { prev?.next = ListNode(remaining) } return result } @JvmStatic fun main(args: Array<String>) { var list1 = listOf(2, 4, 3) var list2 = listOf(5, 6, 4) val result = addTwoNumbers(createListNode(list1), createListNode(list2)) var next = result while (next != null) { println(next.`val`) next = next.next } println("====================") list1 = listOf(9, 9, 9, 9, 9, 9, 9) list2 = listOf(9, 9, 9, 9) val result2 = addTwoNumbers(createListNode(list1), createListNode(list2)) var next2 = result2 while (next2 != null) { println(next2.`val`) next2 = next2.next } } private fun createListNode(list: List<Int>): ListNode? { var root: ListNode? = null var prev: ListNode? = null for (i in list) { val next = ListNode(i) if (root == null) { root = next prev = next } else { prev?.next = next prev = next } } return root } }
0
Kotlin
0
0
ee06bebe0d3a7cd411d9ec7b7e317b48fe8c6d70
2,717
CodingChallenges
Apache License 2.0