path
stringlengths
5
169
owner
stringlengths
2
34
repo_id
int64
1.49M
755M
is_fork
bool
2 classes
languages_distribution
stringlengths
16
1.68k
content
stringlengths
446
72k
issues
float64
0
1.84k
main_language
stringclasses
37 values
forks
int64
0
5.77k
stars
int64
0
46.8k
commit_sha
stringlengths
40
40
size
int64
446
72.6k
name
stringlengths
2
64
license
stringclasses
15 values
src/Day07.kt
bkosm
572,912,735
false
{"Kotlin": 17839}
typealias File = Pair<String, Int> val List<File>.totalSize: Int get() = sumOf { it.second } class ConsoleParser { private val pathToFiles = mutableMapOf<String, MutableList<File>>() private val childLinks = mutableMapOf<String, MutableSet<String>>() private var currentPath = "" val directories: List<String> get() = pathToFiles.keys.toList() fun process(line: String) { CD.matchEntire(line)?.let { val cmd = it.groups[1]!!.value doCD(cmd) } ?: FILE.matchEntire(line)?.let { match -> val sizeString = match.groups[1]!!.value val name = match.groups[2]!!.value doLSOnFile(name, sizeString) } } private fun doLSOnFile(name: String, sizeString: String) = pathToFiles[currentPath]?.let { pathToFiles[currentPath]!!.add(File(name, sizeString.toInt())) } ?: run { pathToFiles.put(currentPath, mutableListOf(File(name, sizeString.toInt()))) } private fun doCD(cmd: String) { currentPath = when { cmd.startsWith("/") -> cmd cmd == ".." -> currentPath.pathOperation { dropLast(1) } else -> currentPath.pathOperation { this + cmd } } val (current, parent) = currentPath.pathElements().run { when (size) { 0 -> "/" to null 1 -> currentPath to "/" else -> currentPath to "/" + dropLast(1).joinToString("/") } } parent?.let { _ -> childLinks[parent]?.let { childLinks[parent]!!.add(current) } ?: run { childLinks[parent] = mutableSetOf(current) } } } fun totalSizeOf(dir: String): Int { val fileSize = pathToFiles[dir]?.totalSize ?: 0 val children = childLinks[dir] ?: mutableSetOf() return fileSize + children.sumOf { totalSizeOf(it) } } private fun String.pathElements() = split("/").filter { it.isNotBlank() } private fun String.pathOperation(mapper: List<String>.() -> List<String>) = runCatching { "/" + pathElements().mapper().joinToString("/") }.fold( onSuccess = { it }, onFailure = { "/" } ) companion object { private val CD = "^\\\$ cd (.*)\$".toRegex() private val FILE = "^(\\d*) (.*)\$".toRegex() // private val DIR = "^dir (.*)\$".toRegex() } } object Day07 : DailyRunner<Int, Int> { override fun do1(input: List<String>, isTest: Boolean) = ConsoleParser().run { input.forEach { process(it) } directories.map { totalSizeOf(it) }.filter { it <= 100_000 }.sum() } override fun do2(input: List<String>, isTest: Boolean): Int = 1 } fun main() { Day07.run() }
0
Kotlin
0
1
3f9cccad1e5b6ba3e92cbd836a40207a2f3415a4
2,806
aoc22
Apache License 2.0
comet-utils/src/main/kotlin/ren/natsuyuk1/comet/utils/string/FuzzyMatch.kt
StarWishsama
173,288,057
false
{"Kotlin": 676547, "Shell": 1079, "Dockerfile": 577}
package ren.natsuyuk1.comet.utils.string import java.math.BigDecimal import java.math.RoundingMode import kotlin.math.max /** * The Levenshtein distance between two words is the minimum number of * single-character edits (insertions, deletions or substitutions) required to * change one string into the other. * * @author <NAME> * @see https://github.com/tdebatty/java-string-similarity#levenshtein */ fun levenshteinDistance(s1: String, s2: String, limit: Int = Int.MAX_VALUE): Double { if (s1 == s2) { return 0.0 } if (s1.isBlank()) { return s2.length.toDouble() } if (s2.isBlank()) { return s1.length.toDouble() } // create two work vectors of integer distances var v0 = IntArray(s2.length + 1) var v1 = IntArray(s2.length + 1) var vtemp: IntArray // initialize v0 (the previous row of distances) // this row is A[0][i]: edit distance for an empty s // the distance is just the number of characters to delete from t // initialize v0 (the previous row of distances) // this row is A[0][i]: edit distance for an empty s // the distance is just the number of characters to delete from t for (i in v0.indices) { v0[i] = i } for (i in s1.indices) { // calculate v1 (current row distances) from the previous row v0 // first element of v1 is A[i+1][0] // edit distance is delete (i+1) chars from s to match empty t v1[0] = i + 1 var minv1 = v1[0] // use formula to fill in the rest of the row for (j in s2.indices) { var cost = 1 if (s1.toCharArray()[i] == s2.toCharArray()[j]) { cost = 0 } v1[j + 1] = // Cost of insertion // Cost of remove (v1[j] + 1).coerceAtMost((v0[j + 1] + 1).coerceAtMost(v0[j] + cost)) // Cost of substitution minv1 = minv1.coerceAtMost(v1[j + 1]) } if (minv1 >= limit) { return limit.toDouble() } // copy v1 (current row) to v0 (previous row) for next iteration // System.arraycopy(v1, 0, v0, 0, v0.length); // Flip references to current and previous row vtemp = v0 v0 = v1 v1 = vtemp } return v0[s2.length].toDouble() } fun ldSimilarity(s1: String, s2: String): BigDecimal { val ld = levenshteinDistance(s1, s2) return BigDecimal.ONE.minus( BigDecimal.valueOf(ld).divide(BigDecimal.valueOf(max(s1.length, s2.length).toLong()), 2, RoundingMode.HALF_UP), ) }
19
Kotlin
21
193
19ed20ec4003a37be3bc2dfc6b55a9e2548f0542
2,596
Comet-Bot
MIT License
src/main/kotlin/_2022/Day07.kt
novikmisha
572,840,526
false
{"Kotlin": 145780}
package _2022 import readInput fun main() { fun part1(input: List<String>): Int { var node = Node(Node.dir, 0, "/", null, mutableListOf()) val groupedCommands = mutableListOf<List<String>>() var currentCommand = mutableListOf<String>() for (s in input) { if (s.startsWith("$")) { if (currentCommand.size > 0) { groupedCommands.add(currentCommand) } currentCommand = mutableListOf(s) } else { currentCommand.add(s) } } if (currentCommand.size > 0) { groupedCommands.add(currentCommand) } groupedCommands.forEach { val command = it.first() if ("\$ ls" == command) { node.addNodes(it.drop(1)) } else if (command.startsWith("\$ cd")) { val dir = command.split(" ").last() node = node.cd(dir)!! } } var sum = 0 node = node.cd("/")!! val queue = ArrayDeque<Node>() queue.add(node) do { node = queue.removeFirst() queue.addAll(node.child.filter { it.type == Node.dir }) if (node.size < 100000) { sum += node.size } } while (queue.isNotEmpty()) return sum } fun part2(input: List<String>): Int { var node = Node(Node.dir, 0, "/", null, mutableListOf()) val groupedCommands = mutableListOf<List<String>>() var currentCommand = mutableListOf<String>() for (s in input) { if (s.startsWith("$")) { if (currentCommand.size > 0) { groupedCommands.add(currentCommand) } currentCommand = mutableListOf(s) } else { currentCommand.add(s) } } if (currentCommand.size > 0) { groupedCommands.add(currentCommand) } groupedCommands.forEach { val command = it.first() if ("\$ ls" == command) { node.addNodes(it.drop(1)) } else if (command.startsWith("\$ cd")) { val dir = command.split(" ").last() node = node.cd(dir)!! } } val totalSize = 70000000 val updateSize = 30000000 node = node.cd("/")!! val freeSize = totalSize - node.size val sizeToDelete = updateSize - freeSize val bigSizes = mutableListOf<Int>() val queue = ArrayDeque<Node>() queue.add(node) do { node = queue.removeFirst() queue.addAll(node.child.filter { it.type == Node.dir }) if (node.size >= sizeToDelete) { bigSizes.add(node.size) } } while (queue.isNotEmpty()) return bigSizes.min() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day07_test") println(part1(testInput)) println(part2(testInput)) val input = readInput("Day07") println(part1(input)) println(part2(input)) } data class Node( val type: String, var size: Int, val name: String, var root: Node?, val parent: Node?, val child: MutableList<Node> ) { constructor( type: String, size: Int, name: String, parent: Node?, child: MutableList<Node> ) : this( type, size, name, null, parent, child ) { if (root == null) { root = this } } companion object FileType { val file = "file" val dir = "dir" } fun cd(name: String): Node? { if (name == "..") { return parent } if (name == "/") { return root } return child.first { it.name == name } } fun addNodes(lsOutput: List<String>) { child.addAll(lsOutput.map { var (size, name) = it.split(" ") var fileType = file if (size == dir) { size = "0" fileType = dir } Node(fileType, size.toInt(), name, root, this, mutableListOf()) }) addSizes(child.sumOf { it.size }) } private fun addSizes(sumOf: Int) { size += sumOf parent?.addSizes(sumOf) } }
0
Kotlin
0
0
0c78596d46f3a8bf977bf356019ea9940ee04c88
4,389
advent-of-code
Apache License 2.0
aoc/src/Scratch.kt
aragos
726,211,893
false
{"Kotlin": 16232}
import java.io.File import kotlin.math.pow fun main() { println(countPoints()) println(countCards()) } private fun countCards(): Int { val cardCount = (0..211).associateWith { 1 }.toMutableMap() File("inputs/scratch.txt").readLines().mapIndexed() { ix, line -> if (line.isBlank()) return@mapIndexed val winningCount = countWinningNumbers(line) val times = cardCount[ix]!! for (j in (ix + 1)..ix + winningCount) { cardCount[j] = cardCount[j]!! + times } } return cardCount.values.sum() } private fun countPoints(): Int = File("inputs/scratch.txt").readLines().map { line -> val winningCount = countWinningNumbers(line) if (winningCount == 0) 0 else 2.0.pow(winningCount - 1).toInt() }.sum() private fun countWinningNumbers(line: String): Int { val (winning, actual) = line.split(":")[1].split("|") val winningNumbers = winning.toNumbers().toSet() return actual.toNumbers().count { winningNumbers.contains(it) } } private fun String.toNumbers() = Regex("\\d+").findAll(this).map { it.value.toInt() }.toList()
0
Kotlin
0
0
7bca0a857ea42d89435adc658c0ff55207ca374a
1,069
aoc2023
Apache License 2.0
hackerrank/knightl-on-chessboard/Solution.kts
shengmin
5,972,157
false
null
import java.io.* import java.math.* import java.security.* import java.text.* import java.util.* import java.util.concurrent.* import java.util.function.* import java.util.regex.* import java.util.stream.* import kotlin.collections.* import kotlin.comparisons.* import kotlin.io.* import kotlin.jvm.* import kotlin.jvm.functions.* import kotlin.jvm.internal.* import kotlin.ranges.* import kotlin.sequences.* import kotlin.text.* // Complete the knightlOnAChessboard function below. fun knightlOnAChessboard(n: Int): Array<IntArray> { val results = Array(n - 1, {IntArray(n - 1) {0}}) for (deltaX in 1 until n) { for (deltaY in deltaX until n) { val result = computeMinMoves(n, deltaX, deltaY) results[deltaX - 1][deltaY - 1] = result // knightL(i, j) is same as knightL(j, i), so just copy over the results results[deltaY - 1][deltaX - 1] = result } } return results } data class Candidate(val x: Int, val y: Int, val moves: Int) fun computeMinMoves(n: Int, a: Int, b: Int): Int { val moves = Array(n, {IntArray(n) { -1 }}) moves[0][0] = 0 val transformations = arrayOf( arrayOf(a, b), arrayOf(a, -b), arrayOf(-a, -b), arrayOf(-a, b), arrayOf(b, a), arrayOf(b, -a), arrayOf(-b, a), arrayOf(-b, -a) ) val queue = PriorityQueue(n * n, compareBy<Candidate> {it.moves}) queue.add(Candidate(0, 0, 0)) while (!queue.isEmpty()) { val head = queue.poll()!! if (head.x == n - 1 && head.y == n - 1) { return head.moves } for (transformation in transformations) { val (deltaX, deltaY) = transformation val newX = head.x + deltaX val newY = head.y + deltaY if (newX < 0 || newY < 0 || newX >= n || newY >= n) { // out of bounds, not a valid move continue } val moveCount = moves[newX][newY] if (moveCount != -1) { // visited before continue } moves[newX][newY] = head.moves + 1 queue.add(Candidate(newX, newY, head.moves + 1)) } } return -1 } fun main(args: Array<String>) { val scan = Scanner(System.`in`) val n = scan.nextLine().trim().toInt() val result = knightlOnAChessboard(n) println(result.map{ it.joinToString(" ") }.joinToString("\n")) } main(arrayOf())
0
Java
18
20
08e65546527436f4bd2a2014350b2f97ac1367e7
2,290
coding-problem
MIT License
src/main/kotlin/g2701_2800/s2800_shortest_string_that_contains_three_strings/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2701_2800.s2800_shortest_string_that_contains_three_strings // #Medium #String #Greedy #Enumeration #2023_08_06_Time_259_ms_(100.00%)_Space_38_MB_(100.00%) class Solution { fun minimumString(a: String, b: String, c: String): String { val ar = a.toCharArray() val br = b.toCharArray() val cr = c.toCharArray() return String( getSmaller( combine(ar, br, cr), getSmaller( combine(ar, cr, br), getSmaller( combine(br, ar, cr), getSmaller( combine(br, cr, ar), getSmaller(combine(cr, ar, br), combine(cr, br, ar)) ) ) ) ) ) } private fun combine(a: CharArray, b: CharArray, c: CharArray): CharArray { return combine(combine(a, b), c) } private fun combine(a: CharArray, b: CharArray): CharArray { var insertIndex = a.size for (i in a.indices) { if (a[i] == b[0]) { var ii = i + 1 var match = 1 var j = 1 while (j < b.size && ii < a.size) { if (a[ii] == b[j]) match++ else break ii++ ++j } if (match == b.size) { return a } else if (match == a.size - i) { insertIndex = i break } } } val tmp = CharArray(b.size + insertIndex) for (i in 0 until insertIndex) tmp[i] = a[i] for (i in b.indices) tmp[i + insertIndex] = b[i] return tmp } private fun getSmaller(res: CharArray, test: CharArray): CharArray { if (res.size > test.size) return test else if (res.size < test.size) return res else { for (i in res.indices) { if (res[i] > test[i]) return test else if (res[i] < test[i]) return res } } return res } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,145
LeetCode-in-Kotlin
MIT License
src/Day07.kt
acrab
573,191,416
false
{"Kotlin": 52968}
import com.google.common.truth.Truth.assertThat fun main() { fun calculateDirectorySize( currentPath: String, iterator: Iterator<String>, directoryMap: MutableMap<String, Int> ): Int { var totalFileSize = 0 val subdirectories = mutableMapOf<String, Int>() while (iterator.hasNext()) { val command = iterator.next() if (command == "$ cd ..") { //Navigating up val totalSize = totalFileSize + subdirectories.values.sum() directoryMap[currentPath] = totalSize return totalSize } else if (command.startsWith("$ cd")) { //moving to a subdirectory val subDirectory = command.split(" ").last() subdirectories[subDirectory] = calculateDirectorySize("$currentPath/$subDirectory", iterator, directoryMap) } else { //File listing val size = command.split(" ").first() if (size.first().isDigit()) { //It's a file totalFileSize += size.toInt() } //Otherwise it's a directory, and we can skip it. } } //End of command output val totalSize = totalFileSize + subdirectories.values.sum() directoryMap[currentPath] = totalSize return totalSize } fun calculateFullRepository(input: List<String>): Map<String, Int> { val directory = mutableMapOf<String, Int>() val iterator: Iterator<String> = input.iterator() val root = iterator.next().split(" ").last() println("Setting root to $root") calculateDirectorySize(root, iterator, directory) println(directory) return directory } fun part1(input: List<String>): Int { //Path to size val directory = calculateFullRepository(input) return directory.values.filter { it <= 100000 }.sum() } fun part2(input: List<String>): Int { val maxSize = 70000000 val updateSize = 30000000 val directory = calculateFullRepository(input) val totalFileSize = directory["/"]!! val freeSpace = maxSize - totalFileSize val needToFree = updateSize - freeSpace return directory.values.filter { it >= needToFree }.minOf { it } } val testInput = readInput("Day07_test") assertThat(part1(testInput)).isEqualTo(95437) val input = readInput("Day07") println(part1(input)) assertThat(calculateFullRepository(testInput)["/"]).isEqualTo(48381165) assertThat(part2(testInput)).isEqualTo(24933642) println(part2(input)) }
0
Kotlin
0
0
0be1409ceea72963f596e702327c5a875aca305c
2,725
aoc-2022
Apache License 2.0
src/main/kotlin/com/chriswk/aoc/advent2021/Day7.kt
chriswk
317,863,220
false
{"Kotlin": 481061}
package com.chriswk.aoc.advent2021 import com.chriswk.aoc.AdventDay import com.chriswk.aoc.advent2021.Day5.Companion.diff import com.chriswk.aoc.util.report import com.chriswk.aoc.util.reportNano import org.apache.logging.log4j.LogManager import org.apache.logging.log4j.Logger typealias Crab = Int class Day7: AdventDay(2021, 7) { companion object { @JvmStatic fun main(args: Array<String>) { val day = Day7() reportNano { day.part1() } reportNano { day.part2() } report { day.minimumPositionCost(day.inputCrabs, false) } report { day.minimumPositionCost(day.inputCrabs, true) } } val logger: Logger = LogManager.getLogger() } val inputCrabs = crabs(inputAsString) val crabMap = inputCrabs.groupingBy { it }.eachCount() fun crabs(input: String): List<Int> { return input.split(",").map { it.toInt() }.sorted() } fun positionCosts(crabs: List<Crab>, gaussSum: Boolean = false): Map<Int, Int> { val crabMap = crabs.groupingBy { it }.eachCount() val min = crabs.first() val max = crabs.last() return (min..max).map { pos -> pos to (crabMap.entries.fold(0) { a, e -> val distance = pos.diff(e.key) val cost = if (gaussSum) { gaussDistance(distance) } else { distance } a + (cost * e.value) }) }.toMap() } fun minimumPositionCost(crabs: List<Crab>, gaussSum: Boolean = false): Int { val crabMap = crabs.groupingBy { it }.eachCount() val min = crabs.first() val max = crabs.last() return (min..max).minOf { pos -> crabMap.entries.fold(0) { totalCost, (crabAt, count) -> val distance = pos.diff(crabAt) val cost = if (gaussSum) { gaussDistance(distance) } else { distance } totalCost + (cost * count) } } } fun costToPoint(point: Int, crabs: Map<Int, Int>, gaussSum: Boolean = false): Int { return crabs.entries.sumOf { (crabAt, count) -> val distance = point.diff(crabAt) val costForOne = if (gaussSum) { gaussDistance(distance) } else { distance } costForOne * count } } fun targetPart1(crabs: List<Crab>): Int { return crabs[crabs.size / 2] } fun targetPart2(crabs: List<Crab>): Int { return crabs.average().toInt() } private fun gaussDistance(distance: Int): Int { return (distance * (distance+1)) / 2 } fun part1(): Int { return costToPoint(targetPart1(inputCrabs), crabMap, gaussSum = false) } fun part2(): Int { return costToPoint(targetPart2(inputCrabs), crabMap, gaussSum = true) } }
116
Kotlin
0
0
69fa3dfed62d5cb7d961fe16924066cb7f9f5985
2,919
adventofcode
MIT License
src/questions/SimplifiedFraction.kt
realpacific
234,499,820
false
null
package questions import _utils.UseCommentAsDocumentation import utils.assertIterableSameInAnyOrder import utils.shouldBe /** * Given an integer n, return a list of all simplified fractions between 0 and 1 (exclusive) * such that the denominator is less-than-or-equal-to n. The fractions can be in any order. * * [Source](https://leetcode.com/problems/simplified-fractions/) */ @UseCommentAsDocumentation private fun simplifiedFractions(n: Int): List<String> { var numerator = 1 var denumerator = 2 val result = mutableListOf<String>() while (true) { if (denumerator > n) { break } if (numerator == 1) { result.add("$numerator/$denumerator") } else if (findGCD(numerator, denumerator) == 1) { // check if [numerator] & [denumerator] can be divided result.add("$numerator/$denumerator") // add if not divisible } if (denumerator == n) { numerator++ denumerator = numerator + 1 } else { denumerator++ } } return result } fun findGCD(a: Int, b: Int): Int { var (high, low) = if (a > b) Pair(a, b) else Pair(b, a) while (high > low) { val remainder = high % low if (remainder == 0) return low high = low low = remainder } return low } fun main() { simplifiedFractions(2) shouldBe listOf("1/2") assertIterableSameInAnyOrder(actual = simplifiedFractions(3), expected = listOf("1/2", "1/3", "2/3")) assertIterableSameInAnyOrder(actual = simplifiedFractions(4), expected = listOf("1/2", "1/3", "1/4", "2/3", "3/4")) assertIterableSameInAnyOrder( actual = simplifiedFractions(6), expected = listOf("1/2", "1/3", "1/4", "1/5", "1/6", "2/3", "2/5", "3/4", "3/5", "4/5", "5/6") ) }
4
Kotlin
5
93
22eef528ef1bea9b9831178b64ff2f5b1f61a51f
1,823
algorithms
MIT License
src/Day13.kt
a-glapinski
572,880,091
false
{"Kotlin": 26602}
import utils.readInputAsText fun main() { val input = readInputAsText("day13_input") val packetPairs = input.splitToSequence("\n\n") .map { it.split("\n") } .map { (left, right) -> PacketValue(left) to PacketValue(right) } val result1 = packetPairs.mapIndexed { index, (left, right) -> index + 1 to (left compareTo right) } .sumOf { (index, result) -> if (result == -1) index else 0 } println(result1) val result2 = run { val firstDividerPacket = PacketValue("[[2]]") val secondDividerPacket = PacketValue("[[6]]") val sortedPackets = packetPairs.flatMap { it.toList() } .plus(listOf(firstDividerPacket, secondDividerPacket)).sorted() (sortedPackets.indexOf(firstDividerPacket) + 1) * (sortedPackets.indexOf(secondDividerPacket) + 1) } println(result2) } sealed interface PacketValue : Comparable<PacketValue> { companion object { operator fun invoke(input: String) = when (val i = input.toIntOrNull()) { null -> ListValue(input) else -> IntegerValue(i) } } data class IntegerValue(val value: Int) : PacketValue { override infix fun compareTo(other: PacketValue): Int = when (other) { is IntegerValue -> this.value compareTo other.value is ListValue -> ListValue(this) compareTo other } } data class ListValue(val values: List<PacketValue>) : PacketValue { constructor(vararg values: PacketValue) : this(values.toList()) override infix fun compareTo(other: PacketValue): Int = when (other) { is IntegerValue -> this compareTo ListValue(other) is ListValue -> this.values.zip(other.values) .map { (left, right) -> left compareTo right } .filterNot { it == 0 } .firstOrNull() ?: (this.values.size compareTo other.values.size) } companion object { operator fun invoke(input: String): ListValue { val content = input.substring(1 until input.lastIndex) if (content.isEmpty()) return ListValue() val values = buildList { var current = "" var level = 0 for (c in content) { when (c) { '[' -> level++ ']' -> level-- } if (c == ',' && level == 0) { add(PacketValue(current)) current = "" continue } current += c } add(PacketValue(current)) } return ListValue(values) } } } }
0
Kotlin
0
0
c830d23ffc2ab8e9a422d015ecd413b5b01fb1a8
2,851
advent-of-code-2022
Apache License 2.0
src/main/kotlin/com/jacobhyphenated/advent2022/day16/Day16.kt
jacobhyphenated
573,603,184
false
{"Kotlin": 144303}
package com.jacobhyphenated.advent2022.day16 import com.jacobhyphenated.advent2022.Day import java.util.PriorityQueue /** * Day 16: Proboscidea Volcanium * * The cave system contains several different valves connected by tunnels. * Each valve releases some amount of pressure per minute once it's been opened. * * It takes 1 minute to open a valve and 1 minute to move to an adjacent valve location. */ class Day16: Day<List<String>> { override fun getInput(): List<String> { return readInputFile("day16").lines() } /** * You have 30 minutes. Maximize how much pressure can be released in that time. * return the total pressure released */ override fun part1(input: List<String>): Int { return findMaximumPressureFromStart(listOf(30), input) } /** * You spend 4 minutes training an elephant to help you. You and the elephant move independently. * return the maximum total pressure that can be released in the remaining 26 minutes. */ override fun part2(input: List<String>): Int { return findMaximumPressureFromStart(listOf(26,26), input) } private fun findMaximumPressureFromStart(startingTimes: List<Int>, input: List<String>): Int { val (start, valves) = createGraph(input) val closedValves = valves.filter { it.pressure > 0 } val travelTimes = (closedValves + start).associate { it.name to findPathsToValves(it) } val startingPositions = startingTimes.map { Pair(start.name, it) } return maximizePressure(destinationStack = startingPositions, currentPressure = 0, closedValves = closedValves.map { it.name }.toSet(), travelTimes = travelTimes, allValves = valves.associateBy { it.name }, solutions = mutableSetOf(1000) ) } /** * Many of the valves have 0 pressure and function as pass-through locations. * Set our destinations to only the valves with pressure that we haven't already opened. * Use a DFS to recursively find the path that maximizes the total pressure released * * @param destinationStack A list of destination locations (1 for part 1, 2 for part2 and the elephant). * The destination has the valve name and the time of arrival at that location. * @param currentPressure how much pressure will be released based on the valves already opened * @param closedValves the remaining closed valves that need to be opened. * @param travelTimes a map with pre-calculated travel times to each node from each node * @param allValves Every valve as a map to easily look up a valve by name * @param solutions valid solutions for the amount of pressure released. Used to optimize and prune inefficient paths */ private fun maximizePressure(destinationStack: List<Pair<String, Int>>, currentPressure: Int, closedValves: Set<String>, travelTimes: Map<String, Map<String, Int>>, allValves: Map<String, Valve>, solutions: MutableSet<Int>): Int { if (destinationStack.isEmpty()) { solutions.add(currentPressure) return currentPressure } // Pull off the first destination we'll get to val current = destinationStack.maxBy { (_, minute) -> minute } val (valveName, minute) = current val valve = allValves.getValue(valveName) var newPressure = currentPressure val updatedClosedValves = closedValves.toMutableSet() var updatedMinute = minute // If the valve at this destination is closed, open it. if (valveName in closedValves) { updatedClosedValves.remove(valveName) updatedMinute -= 1 newPressure += updatedMinute * valve.pressure } val remainingDestinations = destinationStack.toMutableList().apply { remove(current) } val travelTimeForCurrent = travelTimes.getValue(valveName) // As intelligently as reasonable, determine if we should prune this part of the DFS // Find the next hop to a remaining valve. Pretend we turn all valves on at that time. // If this hypothetical pressure is still less than a known solution, we prune. // this is the most important step in runtime optimization. if (updatedClosedValves.size > remainingDestinations.size) { val baseline = remainingDestinations.sumOf { (node, time) -> allValves.getValue(node).pressure * (time - 1) } val others = updatedClosedValves.filter { it !in remainingDestinations.map { (n,_) -> n } } // Being more accurate than naive here is the difference from 3m runtime and 20s runtime val minTimeAtOthers = updatedMinute - others.minOf { travelTimeForCurrent.getValue(it) } val minTimeFromRemaining = remainingDestinations.maxByOrNull { (_,time) -> time }?.let {(node, time) -> val pathDistance = travelTimes.getValue(node) time - others.minOf { pathDistance.getValue(it) } } ?: 0 val otherTimeEstimate = maxOf(minTimeAtOthers, minTimeFromRemaining) val potentialMax = newPressure + baseline + others.sumOf { allValves.getValue(it).pressure * otherTimeEstimate } if (potentialMax < solutions.max()) { return 0 } } if (updatedClosedValves.isEmpty()) { solutions.add(newPressure) return newPressure } // Recursive DFS to all remaining closed valves return updatedClosedValves .map { Pair(it, travelTimeForCurrent.getValue(it)) } .filter { (node, _) -> node !in remainingDestinations.map { it.first } } .map { (node, travelTime) -> remainingDestinations.toMutableList() .apply { add(Pair(node, updatedMinute - travelTime)) } .filter { (_, time) -> time >= 0 } // We need to get to the location before time runs out } .maxOfOrNull { maximizePressure(it, newPressure, updatedClosedValves, travelTimes, allValves, solutions) } // if there are no new valid destinations, finish off the paths in the stack ?: maximizePressure(remainingDestinations, newPressure, updatedClosedValves, travelTimes, allValves, solutions) } /** * Use Dijkstra's algorithm to create a map of the distances to all other valves * @param startNode the node to measure the distances from */ private fun findPathsToValves(startNode: Valve): Map<String, Int> { val distances = mutableMapOf(startNode.name to 0) val queue = PriorityQueue<PathCost> { a, b -> a.cost - b.cost } queue.add(PathCost(startNode, 0)) var current: PathCost do { current = queue.remove() // If we already found a less expensive way to reach this position if (current.cost > (distances[current.valve.name] ?: Int.MAX_VALUE)) { continue } current.valve.adjacent.forEach { // cost is the number of steps taken, increases by 1 for each move val cost = distances.getValue(current.valve.name) + 1 // If the cost to this space is less than what was previously known, put this on the queue if (cost < (distances[it.name] ?: Int.MAX_VALUE)) { distances[it.name] = cost queue.add(PathCost(it, cost)) } } } while (queue.size > 0) return distances } private fun createGraph(input: List<String>): Pair<Valve, List<Valve>> { val valves = mutableMapOf<String, Valve>() input.forEach { line -> val (valvePart, neighborPart) = line.split("; ") val (namePart, flowRate) = valvePart.split(" has flow rate=") val valve = Valve(namePart.split(" ")[1].trim(), flowRate.trim().toInt()) valves[valve.name] = valve val knownNeighbors = neighborPart.removePrefix("tunnels lead to valves ") .removePrefix("tunnel leads to valve ") // Ugh. Not cool AoC. .trim().split(", ") .mapNotNull { valves[it] } valve.adjacent.addAll(knownNeighbors) knownNeighbors.forEach { it.adjacent.add(valve) } } return Pair(valves.getValue("AA"), valves.values.toList()) } } class Valve( val name: String, val pressure: Int, val adjacent: MutableList<Valve> = mutableListOf() ) class PathCost(val valve: Valve, val cost: Int)
0
Kotlin
0
0
9f4527ee2655fedf159d91c3d7ff1fac7e9830f7
8,795
advent2022
The Unlicense
src/main/kotlin/day03/Solution.kt
TestaDiRapa
573,066,811
false
{"Kotlin": 50405}
package day03 import java.io.File fun getItemsPriorities() = ('a'..'z').foldIndexed(mapOf<Char, Int>()) { index, acc, c -> acc + (c to index+1) } + ('A' .. 'Z').foldIndexed(mapOf()) { index, acc, c -> acc + (c to index + 27) } fun getItemsFromFile() = File("src/main/kotlin/day03/input.txt") .readLines() .fold(listOf<Pair<List<Char>, List<Char>>>()) { acc, line -> acc + Pair( line.subSequence(0, line.length/2).toList(), line.subSequence(line.length/2, line.length).toList() ) } fun findCommonItemAndSumPriorities() = getItemsFromFile() .fold(0) { acc, items -> (items.first.toSet().intersect(items.second.toSet()) .firstOrNull() ?.let { getItemsPriorities()[it] } ?: 0) + acc } fun findBadgesAndSumPriorities() = getItemsFromFile() .chunked(3) .fold(0) { acc, group -> (group.fold(emptySet<Char>()) { intersected, backpack -> intersected.ifEmpty { backpack.first.toSet() + backpack.second.toSet() }.intersect( backpack.first.toSet() + backpack.second.toSet() ) }.firstOrNull() ?.let { getItemsPriorities()[it] } ?: 0) + acc } fun main() { println("The sum of the priorities of the common items in the compartments is: ${findCommonItemAndSumPriorities()}") println("The sum of the priorities of the group badges is: ${findBadgesAndSumPriorities()}") }
0
Kotlin
0
0
b5b7ebff71cf55fcc26192628738862b6918c879
1,599
advent-of-code-2022
MIT License
src/main/kotlin/com/tecacet/komplex/DivisionAlgorithm.kt
algorythmist
135,095,131
false
{"Kotlin": 26313}
package com.tecacet.komplex /** * Division of polynomials using Euclid's algorithm * @return the quotient and remainder as a pair */ fun divide(dividend: ComplexPolynomial, divisor: ComplexPolynomial): Pair<ComplexPolynomial, ComplexPolynomial> { var quotient = ComplexPolynomial.ZERO var remainder = dividend val divisorDegree = divisor.degree var remainderDegree = remainder.degree while (!isZero(remainder) && remainderDegree >= divisorDegree) { val c = remainder[remainderDegree] / divisor[divisorDegree] val monomial = ComplexPolynomial.monomial(remainderDegree - divisorDegree, c) remainder -= (monomial * divisor) quotient += monomial remainderDegree = remainder.degree } return Pair(quotient, remainder) } /** * Greatest Common Divider of two polynomials * @param f a polynomial * @param g a polynomial * @return The largest polynomial that divides both f and g */ fun gcd(f: ComplexPolynomial, g: ComplexPolynomial): ComplexPolynomial { var gcd = ComplexPolynomial(f) var s = ComplexPolynomial(g) while (!isZero(s)) { val remainder = (gcd / s).second gcd = s s = remainder } return gcd } /** * Check if the instance is the null polynomial. * * @return true if the polynomial is null */ private fun isZero(p: ComplexPolynomial): Boolean { return p.degree == 0 && p[0].isZero(Complex.DEFAULT_TOLERANCE) }
1
Kotlin
0
2
9bf0f453d852305dd2c53ceaa0856fb8eb0d6499
1,465
komplex
MIT License
kotlin/src/main/kotlin/year2023/Day10.kt
adrisalas
725,641,735
false
{"Kotlin": 130217, "Python": 1548}
package year2023 import java.util.* fun main() { val input = readInput("Day10") Day10.part1(input).println() Day10.part2(input).println() } object Day10 { data class Pipe(val row: Int, val column: Int, val value: Char, val previousPipe: Pipe? = null) { fun getDistanceToStart(): Int { if (previousPipe == null) { return 0 } return 1 + previousPipe.getDistanceToStart() } } fun part1(input: List<String>): Int { val start = input.findStartingPosition() val visited = mutableListOf(start) val toVisit = input.findPipesConnectedToStart(start).toMutableList() while (toVisit.isNotEmpty()) { val node = toVisit.removeAt(0) visited.add(node) val newNode = input.findPipeConnectedTo(node) if (newNode != null && !visited.containsPipeWithPosition(newNode.row, newNode.column) && !toVisit.containsPipeWithPosition(newNode.row, newNode.column) ) { toVisit.add(newNode) } } return visited.maxOf { it.getDistanceToStart() } } private fun List<String>.findStartingPosition(): Pipe { this.forEachIndexed start@{ row, line -> line.forEachIndexed { column, value -> if (value == 'S') { return Pipe(row, column, value) } } } error("Not found") } private fun List<String>.findPipesConnectedToStart(start: Pipe): List<Pipe> { val (row, column) = start val values = mutableListOf<Pipe>() val charAtNorth = this.getElementAt(row - 1, column) if (charAtNorth.isLookingSouth()) { values.add(Pipe(row - 1, column, charAtNorth, start)) } val charAtSouth = this.getElementAt(row + 1, column) if (charAtSouth.isLookingNorth()) { values.add(Pipe(row + 1, column, charAtSouth, start)) } val charAtWest = this.getElementAt(row, column - 1) if (charAtWest.isLookingEast()) { values.add(Pipe(row, column - 1, charAtWest, start)) } val charAtEast = this.getElementAt(row, column + 1) if (charAtEast.isLookingWest()) { values.add(Pipe(row, column + 1, charAtEast, start)) } return values } private fun List<String>.findPipeConnectedTo(pipe: Pipe): Pipe? { if (pipe.previousPipe == null) { error("This method does not allow the starting pipe") } val (rowFrom, columnFrom) = pipe.previousPipe val row = when (pipe.value) { '|' -> if (rowFrom == pipe.row - 1) pipe.row + 1 else pipe.row - 1 'L', 'J' -> if (rowFrom == pipe.row) pipe.row - 1 else pipe.row 'F', '7' -> if (rowFrom == pipe.row) pipe.row + 1 else pipe.row else -> pipe.row } val column = when (pipe.value) { '-' -> if (columnFrom == pipe.column - 1) pipe.column + 1 else pipe.column - 1 'J', '7' -> if (columnFrom == pipe.column) pipe.column - 1 else pipe.column 'L', 'F' -> if (columnFrom == pipe.column) pipe.column + 1 else pipe.column else -> pipe.column } val value = this.getElementAt(row, column) if (value == '.') { return null } return Pipe(row, column, value, pipe) } private fun Char.isLookingSouth(): Boolean { return this == '|' || this == '7' || this == 'F' } private fun Char.isLookingNorth(): Boolean { return this == '|' || this == 'L' || this == 'J' } private fun Char.isLookingWest(): Boolean { return this == '-' || this == 'J' || this == '7' } private fun Char.isLookingEast(): Boolean { return this == '-' || this == 'L' || this == 'F' } private fun List<String>.getElementAt(row: Int, column: Int): Char { if (row < 0 || row >= this.size || column < 0 || column >= this[0].length) { return '.' } return this[row][column] } private fun List<Pipe>.containsPipeWithPosition(row: Int, column: Int): Boolean { return this.any { it.row == row && it.column == column } } fun part2(input: List<String>): Int { val start = input.findStartingPosition() val visited = mutableListOf(start) val toVisit = input.findPipesConnectedToStart(start).toMutableList() while (toVisit.isNotEmpty()) { val node = toVisit.removeAt(0) visited.add(node) val newNode = input.findPipeConnectedTo(node) if (newNode != null && !visited.containsPipeWithPosition(newNode.row, newNode.column) && !toVisit.containsPipeWithPosition(newNode.row, newNode.column) ) { toVisit.add(newNode) } } val realSymbolOfStart = input.getCharOfStart(start) /* * If we cross the "rope" we will cross through outside/inside: * . | . <--- One point will be outside, the other one inside * . F - 7 . <--- Both points are outside * . F - J . <--- One point will be outside, the other one inside * . L - J . <--- Both points are outside * . L - 7 . <--- One point will be outside, the other one inside */ return input .map { it.replace('S', realSymbolOfStart) } .mapIndexed { row, line -> val stack: Stack<Char> = Stack() var insideLoop = false var count = 0 line.forEachIndexed { column, value -> val isLoopPipe = visited.containsPipeWithPosition(row, column) when { isLoopPipe && value == '|' -> { insideLoop = !insideLoop } isLoopPipe && (value == 'F' || value == 'L') -> { stack.push(value) } isLoopPipe && value == '7' -> { val prev = stack.pop() if (prev == 'L') { insideLoop = !insideLoop } } isLoopPipe && value == 'J' -> { val prev = stack.pop() if (prev == 'F') { insideLoop = !insideLoop } } } if (isLoopPipe) { return@forEachIndexed } if (insideLoop) { count++ } } count }.sum() } private fun List<String>.getCharOfStart(start: Pipe): Char { val (row, column) = start val charAtNorth = this.getElementAt(row - 1, column) val north = charAtNorth.isLookingSouth() val charAtSouth = this.getElementAt(row + 1, column) val south = charAtSouth.isLookingNorth() val charAtWest = this.getElementAt(row, column - 1) val west = charAtWest.isLookingEast() val charAtEast = this.getElementAt(row, column + 1) val east = charAtEast.isLookingWest() return when { north && south -> '|' north && east -> 'L' north && west -> 'J' south && west -> '7' south && east -> 'F' else -> '-' } } }
0
Kotlin
0
2
6733e3a270781ad0d0c383f7996be9f027c56c0e
7,740
advent-of-code
MIT License
AdventOfCodeDay14/src/nativeMain/kotlin/Day14.kt
bdlepla
451,510,571
false
{"Kotlin": 165771}
class Day14(lines:List<String>) { private val lastChar = lines.first().last() private val template: Map<String, Long> = parseTemplate(lines.first()) private val rules: Map<String, Char> = parseRules(lines) private fun parseTemplate(input: String): Map<String, Long> = input .windowed(2) .groupingBy { it } .eachCount().mapValues { it.value.toLong() } private fun parseRules(input: List<String>): Map<String, Char> = input.drop(2).associate { it.substring(0..1) to it[6] } fun solvePart1() = solve(10) fun solvePart2() = solve(40) private fun solve(iterations: Int): Long = (0 until iterations) .fold(template) { polymer, _ -> polymer.react() } .byCharFrequency() .values .sorted() .let { it.last() - it.first() } private fun Map<String, Long>.react(): Map<String, Long> = buildMap { this@react.forEach { (pair, count) -> val inserted = rules.getValue(pair) plus("${pair.first()}$inserted", count) plus("$inserted${pair.last()}", count) } } private fun <T> MutableMap<T, Long>.plus(key: T, amount: Long) { this[key] = this.getOrDefault(key, 0L) + amount } private fun <T> Map<T, Long>.getOrDefault(key:T, amount: Long) = this.getOrElse(key){amount} private fun Map<String, Long>.byCharFrequency(): Map<Char, Long> = this .map { it.key.first() to it.value } .groupBy({ it.first }, { it.second }) .mapValues { it.value.sum() + if (it.key == lastChar) 1 else 0 } }
0
Kotlin
0
0
1d60a1b3d0d60e0b3565263ca8d3bd5c229e2871
1,711
AdventOfCode2021
The Unlicense
archive/src/main/kotlin/com/grappenmaker/aoc/year22/Day24.kt
770grappenmaker
434,645,245
false
{"Kotlin": 409647, "Python": 647}
package com.grappenmaker.aoc.year22 import com.grappenmaker.aoc.* fun PuzzleSet.day24() = puzzle { val charGrid = inputLines.asCharGrid() val from = charGrid.row(0).single { charGrid[it] == '.' } val to = charGrid.row(charGrid.height - 1).single { charGrid[it] == '.' } data class Blizard(val pos: Point, val dir: Direction) data class SearchState( val pos: Point, val time: Int = 0, val seenEnd: Boolean = false, val seenStart: Boolean = false ) fun List<Blizard>.evolve() = map { val nextIntended = it.pos + it.dir val next = if (charGrid[nextIntended] == '#') { (nextIntended + it.dir + it.dir).map { x, y -> x.mod(charGrid.width) to y.mod(charGrid.height) } } else nextIntended it.copy(pos = next) } val initialBlizards = charGrid.points .filter { charGrid[it] !in listOf('#', '.') } .map { Blizard(it, charGrid[it].toDirection()) } // Assuming 1000 is max..? // Small optimization here... could also simulate every single time again val maxTime = 1000 val states = buildList { var last = initialBlizards add(initialBlizards.map { it.pos }.toSet()) repeat(maxTime) { last = last.evolve() add(last.map { it.pos }.toSet()) } } fun Grid<Char>.adj(curr: SearchState) = (curr.pos.adjacentSides() + curr.pos).filter { this[it] != '#' && it !in states[curr.time] } fun Grid<Char>.p1() = bfs( SearchState(from), isEnd = { it.pos == to }, neighbors = { curr -> adj(curr).map { SearchState(it, curr.time + 1) } }, ).end!!.time - 1 fun Grid<Char>.p2() = bfs( SearchState(from), isEnd = { it.pos == to && it.seenEnd && it.seenStart }, neighbors = { curr -> adj(curr).map { SearchState( pos = it, time = curr.time + 1, seenEnd = curr.seenEnd || it == to, seenStart = curr.seenStart || (curr.seenEnd && it == from) ) } } ).end!!.time - 1 partOne = charGrid.p1().s() partTwo = charGrid.p2().s() }
0
Kotlin
0
7
92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585
2,229
advent-of-code
The Unlicense
src/main/kotlin/io/dmitrijs/aoc2022/Day14.kt
lakiboy
578,268,213
false
{"Kotlin": 76651}
package io.dmitrijs.aoc2022 class Day14(input: List<String>) { private val points = input .map { s -> s.toPath() } .flatMap { path -> path.toLines() } .flatMap { line -> line.toPoints() } .associateWith { false } fun puzzle1() = Board().unitsOfSand() fun puzzle2() = Board(safe = true).unitsOfSand() private fun List<Point>.toLines() = zipWithNext { a, b -> Line(a, b) } private fun String.toPath() = split(" -> ").map { Point.of(it) } private data class Line(private val a: Point, private val b: Point) { fun toPoints(): List<Point> { val direction = when { a.y == b.y -> if (a.x > b.x) Direction.LEFT else Direction.RIGHT a.x == b.x -> if (a.y > b.y) Direction.UP else Direction.DOWN else -> error("Invalid line.") } return buildList { var p = a add(a) while (p != b) { p += direction add(p) } } } } private inner class Board(private val safe: Boolean = false) { private val maxY = points.keys.maxOf { it.y }.let { if (safe) it + 2 else it } private val grid = points.toMutableMap().apply { put(start, safe) } // For safe +1 fun unitsOfSand(): Int { while (true) { findSandLocation()?.let { node -> grid[node] = true } ?: break } return grid.values.count { it } } private fun findSandLocation(): Point? { var node = start var prev: Point while (true) { prev = node val next = moves.map { move -> node.move() } // Falls to abyss unless safe. if (!safe && next.any { it.y > maxY }) { return null } // Can not move further. if (next.all { it in grid || (safe && it.y == maxY) }) { break } node = next.first { it !in grid } } return prev.takeUnless { it == start } } } companion object { private val start = Point(500, 0) private val moves = listOf<Point.() -> Point>( { this + Direction.DOWN }, { this + Direction.DOWN + Direction.LEFT }, { this + Direction.DOWN + Direction.RIGHT } ) } }
0
Kotlin
0
1
bfce0f4cb924834d44b3aae14686d1c834621456
2,502
advent-of-code-2022-kotlin
Apache License 2.0
src/main/kotlin/g1001_1100/s1048_longest_string_chain/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1001_1100.s1048_longest_string_chain // #Medium #Array #String #Hash_Table #Dynamic_Programming #Two_Pointers // #2023_05_28_Time_273_ms_(75.00%)_Space_46.5_MB_(50.00%) class Solution { fun longestStrChain(words: Array<String>): Int { val lenStr = arrayOfNulls<MutableList<String>?>(20) for (word in words) { val len = word.length if (lenStr[len] == null) { lenStr[len] = ArrayList() } lenStr[len]!!.add(word) } val longest: MutableMap<String?, Int?> = HashMap() var max = 0 for (s in words) { max = findLongest(s, lenStr, longest).coerceAtLeast(max) } return max } private fun findLongest( word: String, lenStr: Array<MutableList<String>?>, longest: MutableMap<String?, Int?> ): Int { if (longest.containsKey(word)) { return longest[word]!! } val len = word.length val words: List<String>? = lenStr[len + 1] if (words == null) { longest[word] = 1 return 1 } var max = 0 var i: Int var j: Int for (w in words) { i = 0 j = 0 while (i < len && j - i <= 1) { if (word[i] == w[j++]) { ++i } } if (j - i <= 1) { max = findLongest(w, lenStr, longest).coerceAtLeast(max) } } ++max longest[word] = max return max } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,593
LeetCode-in-Kotlin
MIT License
graph/Dijkstra.kt
wangchaohui
737,511,233
false
{"Kotlin": 36737}
class BinaryHeap<T : BinaryHeap.Item>(private val comparator: Comparator<T>) { interface Item { var binaryHeapPos: Int } private val a = mutableListOf<T>() fun add(item: T) { item.binaryHeapPos = a.size a.add(item) popUp(item.binaryHeapPos) } fun peek(): T? = a.firstOrNull() fun pop(): T? { val top = a.firstOrNull() val last = a.removeLast() if (a.isNotEmpty()) { a[0] = last.apply { binaryHeapPos = 0 } heapify(0) } return top?.apply { binaryHeapPos = -1 } } fun modify(item: T) { if (item.binaryHeapPos in a.indices) heapify(popUp(item.binaryHeapPos)) } val size get() = a.size private fun exchange(i: Int, j: Int) { val ai = a[i] a[i] = a[j].apply { binaryHeapPos = i } a[j] = ai.apply { binaryHeapPos = j } } private fun popUp(index: Int): Int { var i = index while (i > 0) { val pi = (i - 1) / 2 if (comparator.compare(a[i], a[pi]) >= 0) break exchange(i, pi) i = pi } return i } private tailrec fun heapify(i: Int) { val left = 2 * i + 1 val right = 2 * i + 2 var smallest = i if (left < a.size && comparator.compare(a[left], a[smallest]) < 0) { smallest = left } if (right < a.size && comparator.compare(a[right], a[smallest]) < 0) { smallest = right } if (smallest != i) { exchange(i, smallest) heapify(smallest) } } } class Dijkstra<T : Dijkstra.Vertex>( private val vertices: Iterable<T>, private val edges: (T) -> Iterable<Edge<T>>, ) { interface Vertex : BinaryHeap.Item { var dist: Long var prev: Vertex? } data class Edge<T : Vertex>( val v: T, val w: Long, ) fun dijkstra() { val q = BinaryHeap<T>(compareBy(Vertex::dist)) vertices.forEach(q::add) while (q.size > 0) { val u = q.pop()!! if (u.dist == Long.MAX_VALUE) break for ((v, w) in edges(u).filter { it.v.binaryHeapPos >= 0 }) { val alt = u.dist + w if (alt < v.dist) { v.dist = alt v.prev = u q.modify(v) } } } } }
0
Kotlin
0
0
241841f86fdefa9624e2fcae2af014899a959cbe
2,451
kotlin-lib
Apache License 2.0
src/Day01.kt
bjornchaudron
574,072,387
false
{"Kotlin": 18699}
fun main() { fun part1(input: List<String>): Int { return sortByTotalCalories(input).first() } fun part2(input: List<String>): Int { return sortByTotalCalories(input).subList(0, 3).sum() } // test if implementation meets criteria from the description, like: val testInput = readLines("Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readLines("Day01") println(part1(input)) println(part2(input)) } fun sortByTotalCalories(input: List<String>): List<Int> { val totalCalories = mutableListOf<Int>() var currentCalories = 0 for (index in input.indices) { val line = input[index] if (line.isEmpty()) { totalCalories.add(currentCalories) currentCalories = 0 continue } currentCalories += line.toInt() if (index == input.lastIndex) { totalCalories.add(currentCalories) } } totalCalories.sortDescending() return totalCalories.toList() }
0
Kotlin
0
0
f714364698966450eff7983fb3fda3a300cfdef8
1,060
advent-of-code-2022
Apache License 2.0
src/Day03.kt
KorneliuszBarwinski
572,677,168
false
{"Kotlin": 6042}
fun main() { fun convertToCodeInt(symbol: Char) : Int = if (symbol.isUpperCase()) symbol.hashCode() - 38 else symbol.hashCode() - 96 fun part1(input: String): Int = input.split("\r\n").sumOf { rucksack -> val firstCompartment = rucksack.substring(0, rucksack.length / 2).toSet() val secondCompartment = rucksack.substring(rucksack.length / 2).toSet() convertToCodeInt(firstCompartment.intersect(secondCompartment).first()) } fun part2(input: String): Int = input.split("\r\n").windowed(3, 3).sumOf { group -> val firstElve = group[0].toSet() val secondElve = group[1].toSet() val thirdElve = group[2].toSet() convertToCodeInt(firstElve.intersect(secondElve).intersect(thirdElve).first()) } val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d90175134e0c6482986fcf3c144282f189abc875
861
AoC_2022
Apache License 2.0
leetcode2/src/leetcode/permutations.kt
hewking
68,515,222
false
null
package leetcode import java.util.* /** * 46. 全排列 * https://leetcode-cn.com/problems/permutations/ * 给定一个没有重复数字的序列,返回其所有可能的全排列。 示例: 输入: [1,2,3] 输出: [ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ] 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/permutations 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ object Permutations { class Solution { /** * 思路: * 排列组合总数 A3 ^ 3 * * 回溯法注意三点: 1. 要对所有候选解进行遍历 * 2. 候选解不符合条件 则返回上一步,再进行下一步 * 3. 需要一个标志,结束 */ fun permute(nums: IntArray): List<List<Int>> { val list = mutableListOf<List<Int>>() if(nums.size == 1) { list.add(nums.toMutableList()) } else { backTrack(nums.size,list , nums.toList(),0) } return list } fun backTrack(n: Int,nums: MutableList<List<Int>>,list: List<Int>,first: Int) { if (n == first) { nums.add(list.toMutableList()) } else { for (i in first until n) { Collections.swap(list,first,i) backTrack(n,nums,list,first + 1) Collections.swap(list,first,i) } } } } }
0
Kotlin
0
0
a00a7aeff74e6beb67483d9a8ece9c1deae0267d
1,594
leetcode
MIT License
advent-of-code-2021/src/main/kotlin/eu/janvdb/aoc2021/day15/Day15.kt
janvdbergh
318,992,922
false
{"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335}
package eu.janvdb.aoc2021.day15 import eu.janvdb.aocutil.kotlin.Move import eu.janvdb.aocutil.kotlin.findShortestPath import eu.janvdb.aocutil.kotlin.point2d.Point2D import eu.janvdb.aocutil.kotlin.readNonSeparatedDigits const val FILENAME = "input15.txt" fun main() { runWithFactor(1) runWithFactor(5) } private fun runWithFactor(factor: Int) { val map = RiskMap.create(factor) val shortestPath = map.shortestPath() println(shortestPath) } data class RiskMap(val riskLevels: List<List<Int>>, val factor: Int) { val height = riskLevels.size val width = riskLevels[0].size fun shortestPath(): Int { val end = Point2D(factor * width - 1, factor * height - 1) return findShortestPath(Point2D(0, 0), end, { sequenceOf(it.right(), it.down(), it.left(), it.up()) .filter { (x, y) -> x >= 0 && x < factor * width && y >= 0 && y < factor * height } .map { Move(it, getRiskLevel(it)) } }, { 0 })!! } private fun getRiskLevel(point: Point2D): Int { val incrementX = point.x / width val incrementY = point.y / height return (riskLevels[point.y % height][point.x % width] + incrementX + incrementY - 1) % 9 + 1 } companion object { fun create(factor: Int = 1): RiskMap { val riskLevels = readNonSeparatedDigits(2021, FILENAME) return RiskMap(riskLevels, factor) } } }
0
Java
0
0
78ce266dbc41d1821342edca484768167f261752
1,309
advent-of-code
Apache License 2.0
src/adventofcode/blueschu/y2017/day14/solution.kt
blueschu
112,979,855
false
null
package adventofcode.blueschu.y2017.day14 import adventofcode.blueschu.y2017.day10.knotHash import java.util.* import kotlin.test.assertEquals fun input(): String = "ljoxqyyw" fun main(args: Array<String>) { assertEquals("33efeb34ea91902bb2f59c9920caa6cd", knotHash("AoC 2017")) assertEquals(8108, part1(generateDisk("flqrgnkx"))) println("Part 1: ${part1(generateDisk(input()))}") assertEquals(1242, part2(generateDisk("flqrgnkx"))) println("Part 2: ${part2(generateDisk(input()))}") } // convert hexadecimal string into a bit set // original method with byte arrays proved overtly verbose fun String.hexBits(): BitSet { val bitString = this.chunked(4).joinToString(separator = "") { it.toInt(16).toString(2).padStart(16, '0') } val bitSet = BitSet(128) // indexes have been ordered to read l-r rather than r-l for ease of debugging (0 until bitString.length) .filter { bitString[it] == '1' } .forEach { bitSet.set(it) } return bitSet } fun generateDisk(inputString: String) = Array<BitSet>(128) { knotHash(inputString + "-" + it).hexBits() } fun part1(disk: Array<BitSet>): Int { return disk.sumBy { rowBits -> (0 until rowBits.size()) .filter { rowBits[it] } // true if underlying bit == 1 .size } } // Equivalent implementation without inlined lambdas //fun part1(disk: Array<BitSet>): Int { // var usedMemorySquares = 0 // for (rowBits in disk) { // for (col in 0 until rowBits.size()) { // if (rowBits[col]) usedMemorySquares++ // } // } // return usedMemorySquares //} fun part2(disk: Array<BitSet>): Int { data class Region(val row: Int, val col: Int) val groups = mutableListOf<MutableList<Region>>() fun addToGroup(groupIndex: Int, square: Region) { if (groupIndex == groups.size) { groups.add(mutableListOf(square)) } else { groups[groupIndex].add(square) } } fun groupOf(square: Region): Int { groups.forEachIndexed() { index, members -> if (square in members) return index } throw IllegalArgumentException("square does not belong to a group: $square") } fun mergeGroups(destination: Int, others: Int) { if (destination == others) return groups[destination].addAll(groups[others]) groups.removeAt(others) } for ((row: Int, rowBits: BitSet) in disk.withIndex()) { for (col in 0 until rowBits.size()) { if (rowBits[col]) { // if the grid square is "used" val cellAbove = row != 0 && disk[row - 1][col] val cellLeft = col != 0 && disk[row][col - 1] if (cellAbove && cellLeft) { val groupAbove = groupOf(Region(row - 1, col)) val groupLeft = groupOf(Region(row, col - 1)) addToGroup(groupAbove, Region(row, col)) mergeGroups(groupAbove, groupLeft) } else { when { cellAbove -> // square above is also used // get the group of the square above groupOf(Region(row - 1, col)).let { // add the current square to the same group addToGroup(it, Region(row, col)) } cellLeft -> // square to the left is also used // get the group of the square to the left groupOf(Region(row, col - 1)).let { // add the current square to the same group addToGroup(it, Region(row, col)) } else -> // neither the square above nor the square to the left is used // add the current square to a new group addToGroup(groups.size, Region(row, col)) } } } } } return groups.size }
0
Kotlin
0
0
9f2031b91cce4fe290d86d557ebef5a6efe109ed
4,147
Advent-Of-Code
MIT License
gcj/y2020/round1a/a.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package gcj.y2020.round1a private fun solve(impossible: String = "*"): String { return List(readInt()) { readLn() }.fold("**") { s, t -> val split = listOf(s, t).map { it.split("*") } val prefix = unite(split.map { it[0] }, String::startsWith) ?: return impossible val suffix = unite(split.map { it.last() }, String::endsWith) ?: return impossible prefix + "*" + split.flatMap { it.drop(1).dropLast(1) }.joinToString("") + "*" + suffix }.replace("*", "") } fun unite(s: List<String>, f: (String, String, Boolean) -> Boolean): String? { return s.maxByOrNull { it.length }!!.takeIf { res -> s.all { f(res, it, false) } } } fun main() = repeat(readInt()) { println("Case #${it + 1}: ${solve()}") } private fun readLn() = readLine()!! private fun readInt() = readLn().toInt()
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
787
competitions
The Unlicense
src/main.kt
dasuppan
254,854,694
false
{"Kotlin": 3227}
import java.io.File const val SEPARATOR = "," val EXPECTED_FORMAT_REGEX = Regex("\\w+($SEPARATOR)\\d{1,2}") // Implements the Karmarkar-Karp algorithm // Good read: http://bit-player.org/wp-content/extras/bph-publications/AmSci-2002-03-Hayes-NPP.pdf fun main(args: Array<String>) { if (args.size != 2) throw Error("Specify the path for the file which holds the players as well as the desired number of teams!") val path = args[0]; val numberOfTeams = args[1].toInt() val players = readPlayersFromFile(path).shuffled().sortedByDescending { p -> p.skill } val initialTuples = players.map { p -> val list = mutableListOf(mutableSetOf(p)) repeat(numberOfTeams - 1) { list.add(mutableSetOf()) } list }.toMutableList() printTeams(partition(initialTuples)[0]) } fun printTeams(teams: List<Set<Player>>) { teams.forEachIndexed { i, t -> println("TEAM " + (i+1) + " - TOTAL SKILL SCORE: ${calculateSetSum(t)}\n---------------") t.forEach { p -> println(p) } println("---------------") } println("GG HF!") } fun partition(playerTuples: MutableList<MutableList<MutableSet<Player>>>): MutableList<MutableList<MutableSet<Player>>> { if (playerTuples.size == 1) return playerTuples var firstTuple = Pair(playerTuples[0], 0) var secondTuple = Pair(playerTuples[1], 0) for (tuple: MutableList<MutableSet<Player>> in playerTuples) { var max = Int.MIN_VALUE; var min = Int.MAX_VALUE for (playerSet: MutableSet<Player> in tuple) { val setSum = calculateSetSum(playerSet) if (setSum > max) max = setSum if (setSum < min) min = setSum } val maxDifference = max - min if (maxDifference > firstTuple.second && secondTuple.first != tuple) { firstTuple = Pair(tuple, maxDifference) } else if (maxDifference > secondTuple.second) { secondTuple = Pair(tuple, maxDifference) } } playerTuples.remove(firstTuple.first) playerTuples.remove(secondTuple.first) firstTuple = Pair( firstTuple.first.sortedBy { set: MutableSet<Player> -> calculateSetSum(set) }.toMutableList(), firstTuple.second ) secondTuple = Pair( secondTuple.first.sortedByDescending { set: MutableSet<Player> -> calculateSetSum(set) }.toMutableList(), secondTuple.second ) val newTuple: MutableList<MutableSet<Player>> = firstTuple.first for (i in newTuple.indices) { newTuple[i].addAll(secondTuple.first[i]) } playerTuples.add(newTuple) return partition(playerTuples) } fun calculateSetSum(set: Set<Player>): Int { return set.fold(0, { sum, p -> sum + p.skill }) } fun readPlayersFromFile(fileName: String): List<Player> { return File(fileName).readLines().mapIndexed { index, line -> if (!line.matches(EXPECTED_FORMAT_REGEX)) throw Error("Line " + (index + 1) + " is malformed! Expected format: NAME,SKILL IN RANGE 0-99") line.split(SEPARATOR).let { Player(it[0], it[1].toInt()) } } }
0
Kotlin
0
0
8c1952620eca29fc94119b2dc7baa9cf1046a676
3,096
fair-teams-matcher
MIT License
dataStructuresAndAlgorithms/src/main/java/dev/funkymuse/datastructuresandalgorithms/problems/FindIfAnyPairProducesSum.kt
FunkyMuse
168,687,007
false
{"Kotlin": 1728251}
package dev.funkymuse.datastructuresandalgorithms.problems import dev.funkymuse.datastructuresandalgorithms.search.binarySearch /** * Methods are assuming the sorted list. */ /** * O(n^2) worst time complexity */ fun findAnyPairProducesSumNaive(t: List<Int>, sum: Int): Pair<Int, Int> { t.forEachIndexed { indexA, numberA -> t.forEachIndexed { indexB, numberB -> if (indexA != indexB) if (numberA + numberB == sum) return Pair(numberA, numberB) } } return Pair(-1, -1) } /** * O(n log n) worst time complexity */ fun findAnyPairProducesSumBinarySearch(t: List<Int>, sum: Int): Pair<Int, Int> { t.forEachIndexed { index, element -> val remainder = sum - element val result = binarySearch(t, remainder) if (result != -1 && result != index) return when (index > result) { true -> Pair(t[result], element) false -> Pair(element, t[result]) } } return Pair(-1, -1) } /** * O(n) at worst */ fun findAnyPairProducesSumLinear(t: List<Int>, sum: Int): Pair<Int, Int> { var pointerLeft = 0 var pointerRight = t.size - 1 while (pointerLeft < pointerRight) { val currentSum = t[pointerLeft] + t[pointerRight] if (currentSum == sum) return Pair(t[pointerLeft], t[pointerRight]) when (sum > currentSum) { true -> pointerLeft++ false -> pointerRight-- } } return Pair(-1, -1) }
0
Kotlin
92
771
e2afb0cc98c92c80ddf2ec1c073d7ae4ecfcb6e1
1,461
KAHelpers
MIT License
archive/2022/Day20.kt
mathijs81
572,837,783
false
{"Kotlin": 167658, "Python": 725, "Shell": 57}
private const val EXPECTED_1 = 3L private const val EXPECTED_2 = 1623178306L /** * Looks like a simple problem once it's done, but I lost a lot of time before I realized that * the modulo should be N-1 instead of N and (for part 2) that there are duplicate numbers so * you need to store the original index in addition to the number itself. */ private class Day20(isTest: Boolean) : Solver(isTest) { fun part1() = decrypt(1, 1) fun part2() = decrypt(10, 811589153L) fun decrypt(rounds: Int, multiplier: Long): Any { val list = readAsLines().map { it.toInt() * multiplier }.withIndex().toMutableList() repeat(rounds) { for (originalIndex in list.indices) { val i = list.indexOfFirst { it.index == originalIndex } val newIndex = (i + list[i].value).mod(list.size - 1) list.add(newIndex, list.removeAt(i)) } } val index = list.withIndex().single { it.value.value == 0L }.index return listOf(1000, 2000, 3000).sumOf { list[(index + it) % list.size].value } } } fun main() { val testInstance = Day20(true) val instance = Day20(false) testInstance.part1().let { check(it == EXPECTED_1) { "part1: $it != $EXPECTED_1" } } println("part1 ANSWER: ${instance.part1()}") testInstance.part2().let { check(it == EXPECTED_2) { "part2: $it != $EXPECTED_2" } println("part2 ANSWER: ${instance.part2()}") } }
0
Kotlin
0
2
92f2e803b83c3d9303d853b6c68291ac1568a2ba
1,468
advent-of-code-2022
Apache License 2.0
src/main/kotlin/biz/koziolek/adventofcode/year2021/day05/day5.kt
pkoziol
434,913,366
false
{"Kotlin": 715025, "Shell": 1892}
package biz.koziolek.adventofcode.year2021.day05 import biz.koziolek.adventofcode.* fun main() { val inputFile = findInput(object {}) val strLines = inputFile.bufferedReader().readLines() val lines = parseLines(strLines) val map1 = createVentMap(lines.filter { it.isHorizontal || it.isVertical }) println(map1) println(">= 2: ${countGreaterOrEqual(map1, 2)}") val map2 = createVentMap(lines) println(map2) println(">= 2: ${countGreaterOrEqual(map2, 2)}") } fun parseLines(strLines: List<String>): List<Line> = strLines .filter { it.isNotBlank() } .map { Line.fromString(it) } fun createVentMap(lines: List<Line>): Map<Coord, Int> = lines .filter { it.isHorizontal || it.isVertical || it.isDiagonal } .flatMap { it.getCoveredPoints() } .groupingBy { it } .eachCount() fun countGreaterOrEqual(ventMap: Map<Coord, Int>, value: Int): Int = ventMap.values.count { it >= value } fun ventMapToString(ventMap: Map<Coord, Int>): String { val maxValue = ventMap.values.maxOf { it } val strLen = maxValue.toString().length return (0 until ventMap.getHeight()).joinToString(separator = "\n") { y -> (0 until ventMap.getWidth()).joinToString(separator = "") { x -> ventMap[Coord(x, y)] ?.toString() ?.padStart(strLen, ' ') ?: ".".repeat(strLen) } } }
0
Kotlin
0
0
1b1c6971bf45b89fd76bbcc503444d0d86617e95
1,455
advent-of-code
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/TallestBillboard.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 kotlin.math.abs import kotlin.math.max /** * 956. Tallest Billboard * @see <a href="https://leetcode.com/problems/tallest-billboard/">Source</a> */ fun interface TallestBillboard { operator fun invoke(rods: IntArray): Int } /** * Approach 1: Meet in the Middle */ class TallestBillboardMiddle : TallestBillboard { override operator fun invoke(rods: IntArray): Int { val n: Int = rods.size val firstHalf = helper(rods, 0, n / 2) val secondHalf = helper(rods, n / 2, n) var answer = 0 for (diff in firstHalf.keys) { if (secondHalf.containsKey(-diff)) { answer = max(answer, firstHalf[diff]!! + secondHalf[-diff]!!) } } return answer } // Helper function to collect every combination `(left, right)` private fun helper(rods: IntArray, leftIndex: Int, rightIndex: Int): Map<Int, Int> { val states: MutableSet<Pair<Int, Int>> = HashSet() states.add(Pair(0, 0)) for (i in leftIndex until rightIndex) { val r = rods[i] val newStates: MutableSet<Pair<Int, Int>> = HashSet() for (p in states) { newStates.add(Pair(p.first + r, p.second)) newStates.add(Pair(p.first, p.second + r)) } states.addAll(newStates) } val dp: MutableMap<Int, Int> = HashMap() for (p in states) { val left: Int = p.first val right: Int = p.second dp[left - right] = max(dp.getOrDefault(left - right, 0), left) } return dp } } /** * Approach 2: Dynamic Programming */ class TallestBillboardDP : TallestBillboard { override operator fun invoke(rods: IntArray): Int { // dp[taller - shorter] = taller var dp: MutableMap<Int, Int> = HashMap() dp[0] = 0 for (r in rods) { // newDp means we don't add r to these stands. val newDp: MutableMap<Int, Int> = HashMap(dp) for ((diff, taller) in dp) { val shorter = taller - diff // Add r to the taller stand, thus the height difference is increased to diff + r. val newTaller = newDp.getOrDefault(diff + r, 0) newDp[diff + r] = max(newTaller, taller + r) // Add r to the shorter stand, the height difference is expressed as abs(shorter + r - taller). val newDiff = abs(shorter + r - taller) val newTaller2 = max(shorter + r, taller) newDp[newDiff] = max(newTaller2, newDp.getOrDefault(newDiff, 0)) } dp = newDp } // Return the maximum height with 0 difference. return dp.getOrDefault(0, 0) } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,426
kotlab
Apache License 2.0
src/main/kotlin/year2023/Day04.kt
forketyfork
572,832,465
false
{"Kotlin": 142196}
package year2023 class Day04 { fun Pair<Set<Int>, Set<Int>>.wins() = first.intersect(second).size fun part1(input: String): Int { return parseCards(input) .map { 1 shl (it.wins() - 1) } .sum() } fun part2(input: String): Int { val cards = parseCards(input) val cardCounts = IntArray(cards.size) { 1 } val cardWins = IntArray(cards.size) cards.forEachIndexed { idx, card -> cardWins[idx] = card.wins() for (i in (idx + 1)..<(idx + 1 + cardWins[idx])) { cardCounts[i] += cardCounts[idx] } } return cardCounts.sum() } fun parseCards(input: String): List<Pair<Set<Int>, Set<Int>>> { return input.lines() .filter { it.isNotBlank() } .map { line -> val (winning, mine) = line.split(':')[1] .split('|') .map { it.split(' ') .filter { it.isNotBlank() } .map { it.toInt() } .toSet() } winning to mine } } }
0
Kotlin
0
0
5c5e6304b1758e04a119716b8de50a7525668112
1,207
aoc-2022
Apache License 2.0
src/main/kotlin/aoc2023/Day07.kt
j4velin
572,870,735
false
{"Kotlin": 285016, "Python": 1446}
package aoc2023 import readInput private val cardOrder = charArrayOf('2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A').reversed() private val cardOrderWithJokerRule = charArrayOf('J', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'Q', 'K', 'A').reversed() private enum class Type { FiveOfAKind, FourOfAKind, FullHouse, ThreeOfAKind, TwoPairs, OnePairs, HighCard; companion object { fun getType(cards: List<Char>): Type { val occurences = cards.groupBy { it } return when (occurences.size) { 1 -> FiveOfAKind 2 -> { // FourOfAKind or FullHouse if (occurences.values.maxOf { it.size } == 4) { FourOfAKind } else { FullHouse } } 3 -> { // ThreeOfAKind or TwoPairs if (occurences.values.maxOf { it.size } == 3) { ThreeOfAKind } else { TwoPairs } } 4 -> OnePairs 5 -> HighCard else -> throw IllegalArgumentException("something wrong this these cards: $cards (${cards.size})") } } fun getTypeWithJokerRule(cards: List<Char>): Type { val occurencesWithOutJoker = cards.filter { it != 'J' }.groupBy { it } val jokers = cards.count { it == 'J' } if (jokers == 0) return getType(cards) return when (jokers) { 5, 4 -> FiveOfAKind 3 -> { // 2 other cards if (occurencesWithOutJoker.size == 1) { // remaining is a pair FiveOfAKind } else { FourOfAKind } } 2 -> { // 3 other cards when (occurencesWithOutJoker.size) { 1 -> FiveOfAKind // all other cards are the same 2 -> FourOfAKind // one pair 3 -> ThreeOfAKind // all different else -> throw IllegalArgumentException("something wrong this these cards: $cards (${cards.size})") } } 1 -> { // 4 other cards when (occurencesWithOutJoker.size) { 1 -> FiveOfAKind // all other cards are the same 2 -> { // two pairs or 3-1 if (occurencesWithOutJoker.values.first().size == 2) { FullHouse } else { FourOfAKind } } 3 -> ThreeOfAKind // one pair 4 -> OnePairs // all different else -> throw IllegalArgumentException("something wrong this these cards: $cards (${cards.size})") } } else -> throw IllegalArgumentException("something wrong this these cards: $cards (${cards.size})") } } } } private data class Hand(val cards: List<Char>, val bid: Int, val withJokerRule: Boolean) : Comparable<Hand> { companion object { fun fromString(input: String, jokerRule: Boolean): Hand { val split = input.split(" ") return Hand(split.first().toList(), split.last().toInt(), jokerRule) } } val type = if (withJokerRule) Type.getTypeWithJokerRule(cards) else Type.getType(cards) override fun compareTo(other: Hand): Int { if (type != other.type) { return type.compareTo(other.type) } else { for (i in cards.indices) { if (cards[i] != other.cards[i]) { return if (withJokerRule) { cardOrderWithJokerRule.indexOf(cards[i]) .compareTo(cardOrderWithJokerRule.indexOf(other.cards[i])) } else { cardOrder.indexOf(cards[i]).compareTo(cardOrder.indexOf(other.cards[i])) } } } return 0 } } } object Day07 { fun part1(input: List<String>): Int { return input.map { Hand.fromString(it, false) }.sorted().reversed().withIndex() .sumOf { (rank, hand) -> (rank + 1) * hand.bid } } fun part2(input: List<String>): Int { return input.map { Hand.fromString(it, true) }.sorted().reversed().withIndex() .sumOf { (rank, hand) -> (rank + 1) * hand.bid } } } fun main() { val testInput = readInput("Day07_test", 2023) check(Day07.part1(testInput) == 6440) check(Day07.part2(testInput) == 5905) val input = readInput("Day07", 2023) println(Day07.part1(input)) println(Day07.part2(input)) }
0
Kotlin
0
0
f67b4d11ef6a02cba5b206aba340df1e9631b42b
5,104
adventOfCode
Apache License 2.0
src/test/kotlin/no/nav/eessi/pensjon/prefill/person/LongestSequenceTest.kt
navikt
358,172,246
false
{"Kotlin": 841438, "Shell": 1714, "Dockerfile": 149}
package no.nav.eessi.pensjon.prefill.person import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test data class Solution(val I: Int = 0, val N: Int = 0, val C: Char? = null) operator fun Solution.compareTo(other: Solution) = this.N.compareTo(other.N) operator fun Solution.plus(int: Int) = this.copy(N = N + int) data class Accumulator(val candidate: Solution = Solution(), val best: Solution = Solution()) fun longestSequence(charSequence: CharSequence) = charSequence.foldIndexed(Accumulator(Solution(), Solution())) { index, (candidate, best), char -> when (candidate.C) { null -> Accumulator( candidate = Solution(index, 1, char), best = Solution(index, 1, char)) char -> Accumulator( candidate = candidate + 1, best = if (candidate + 1 > best) candidate + 1 else best ) else -> Accumulator( candidate = Solution(index, 1, char), best = if (candidate > best) candidate else best ) } }.best class LongestSequenceTest { @Test fun test() { assertEquals(Solution(10, 5, 'c'), longestSequence("ddaaaacccjcccccjjj")) assertEquals(Solution(2, 3, 'a'), longestSequence("ddaaacccaaa")) assertEquals(Solution(14, 6, 'a'), longestSequence("kjsfjsfajdsfjsaaaaaasssddfddddbbbdddaaa")) assertEquals(Solution(2, 3, 'b'), longestSequence("aabbb")) assertEquals(Solution(0, 0, null), longestSequence("")) } }
3
Kotlin
0
2
7d88d2535c8a6632561109a31130d040dd458f5a
1,566
eessi-pensjon-prefill
MIT License
src/main/kotlin/day09/Day09.kt
mdenburger
317,466,663
false
null
package day09 import java.io.File fun main() { val numbers = File("src/main/kotlin/day09/day09-input.txt").readLines().map { it.toLong() }.toLongArray() val window = 25 val invalidNumber = answer1(numbers, window) println("Answer 1: $invalidNumber") println("Answer 2: " + answer2(numbers, invalidNumber)) } private fun answer1(numbers: LongArray, window: Int): Long { for (start in 0 until numbers.size - window) { val next = numbers[start + window] if (!numbers.containsSum(start, start + window, next)) { return next } } error("No answer found") } private fun LongArray.containsSum(start: Int, end: Int, sum: Long): Boolean { for (i in start until end) { val first = get(i) for (j in i + 1 until end) { val second = get(j) if (first != second && first + second == sum) { return true } } } return false } private fun answer2(numbers: LongArray, sum: Long): Long { for (start in numbers.indices) { numbers.findRangeSumsTo(start, sum)?.let { return it.minOrNull()!! + it.maxOrNull()!! } } error("No answer found") } private fun LongArray.findRangeSumsTo(start: Int, sum: Long): List<Long>? { val range = mutableListOf<Long>() var rangeSum = 0L for (i in start until size) { range += get(i) rangeSum += get(i) if (rangeSum == sum) { return range } if (rangeSum > sum) { return null } } return null }
0
Kotlin
0
0
b965f465cad30f949874aeeacd8631ca405d567e
1,634
aoc-2020
MIT License
src/main/kotlin/se/brainleech/adventofcode/aoc2022/Aoc2022Day04.kt
fwangel
435,571,075
false
{"Kotlin": 150622}
package se.brainleech.adventofcode.aoc2022 import se.brainleech.adventofcode.compute import se.brainleech.adventofcode.readLines import se.brainleech.adventofcode.verify class Aoc2022Day04 { private fun String.idleElves(intersects: Boolean = false): Int { return this.split(",") .asSequence() .chunked(2) .map { (elf, buddy) -> val (elfFirst, elfLast) = elf.split("-").map { it.toInt() } val (buddyFirst, buddyLast) = buddy.split("-").map { it.toInt() } if (elfFirst <= buddyFirst && elfLast >= buddyLast) 1 else if (buddyFirst <= elfFirst && buddyLast >= elfLast) 1 else if (intersects && (elfFirst in buddyFirst..buddyLast)) 1 else if (intersects && (elfLast in buddyFirst..buddyLast)) 1 else 0 } .sum() } fun part1(input: List<String>): Int { return input.sumOf { it.idleElves() } } fun part2(input: List<String>): Int { return input.sumOf { it.idleElves(true) } } } fun main() { val solver = Aoc2022Day04() val prefix = "aoc2022/aoc2022day04" val testData = readLines("$prefix.test.txt") val realData = readLines("$prefix.real.txt") verify(2, solver.part1(testData)) compute({ solver.part1(realData) }, "$prefix.part1 = ") verify(4, solver.part2(testData)) compute({ solver.part2(realData) }, "$prefix.part2 = ") }
0
Kotlin
0
0
0bba96129354c124aa15e9041f7b5ad68adc662b
1,480
adventofcode
MIT License
src/Day3.kt
sitamshrijal
574,036,004
false
{"Kotlin": 34366}
fun main() { fun parse(input: List<String>): List<List<String>> { return input.map { it.chunked(it.length / 2) } } fun part1(input: List<String>): Int { val rucksacks = parse(input) return rucksacks.map { rucksack -> val (compartment1, compartment2) = rucksack compartment1.first { it in compartment2 } }.sumOf { it.priority() } } fun part2(input: List<String>): Int { return input.chunked(3).map { group -> val (first, second, third) = group first.first { it in second && it in third } }.sumOf { it.priority() } } val input = readInput("input3") println(part1(input)) println(part2(input)) } fun Char.priority(): Int = if (isLowerCase()) { code - 96 } else { code - 38 }
0
Kotlin
0
0
fd55a6aa31ba5e3340be3ea0c9ef57d3fe9fd72d
817
advent-of-code-2022
Apache License 2.0
src/main/kotlin/aoc2023/Day16.kt
lukellmann
574,273,843
false
{"Kotlin": 175166}
package aoc2023 import AoCDay import aoc2023.Day16.Dir.* import util.Vec2 import util.illegalInput import util.plus // https://adventofcode.com/2023/day/16 object Day16 : AoCDay<Int>( title = "The Floor Will Be Lava", part1ExampleAnswer = 46, part1Answer = 7210, part2ExampleAnswer = 51, part2Answer = 7673, ) { private enum class Dir(val vec: Vec2) { UP(Vec2(0, -1)), DOWN(Vec2(0, 1)), RIGHT(Vec2(1, 0)), LEFT(Vec2(-1, 0)), } private fun energizedTiles(grid: List<String>, start: Vec2, startDir: Dir): Int { data class Beam(val pos: Vec2, val dir: Dir) val ys = grid.indices val xs = grid.first().indices val seen = HashSet<Beam>() var step = setOf(Beam(pos = start, dir = startDir)) while (step.isNotEmpty()) { val next = HashSet<Beam>() for ((oldPos, oldDir) in step) { val pos = oldPos + oldDir.vec if (pos.x in xs && pos.y in ys) { when (val char = grid[pos.y][pos.x]) { '.' -> next += Beam(pos, oldDir) '/' -> next += Beam( pos, dir = when (oldDir) { UP -> RIGHT DOWN -> LEFT RIGHT -> UP LEFT -> DOWN }, ) '\\' -> next += Beam( pos, dir = when (oldDir) { UP -> LEFT DOWN -> RIGHT RIGHT -> DOWN LEFT -> UP }, ) '|' -> when (oldDir) { UP, DOWN -> next += Beam(pos, oldDir) RIGHT, LEFT -> { next += Beam(pos, UP) next += Beam(pos, DOWN) } } '-' -> when (oldDir) { UP, DOWN -> { next += Beam(pos, RIGHT) next += Beam(pos, LEFT) } RIGHT, LEFT -> next += Beam(pos, oldDir) } else -> illegalInput(char) } } } next.removeAll(seen) seen.addAll(next) step = next } return seen.distinctBy(Beam::pos).size } override fun part1(input: String) = energizedTiles(grid = input.lines(), start = Vec2(-1, 0), startDir = RIGHT) override fun part2(input: String): Int { val grid = input.lines() val yLimit = grid.size val xLimit = grid.first().length var max = -1 for (y in 0..<yLimit) { max = maxOf( max, energizedTiles(grid, start = Vec2(-1, y), startDir = RIGHT), energizedTiles(grid, start = Vec2(xLimit, y), startDir = LEFT), ) } for (x in 0..<xLimit) { max = maxOf( max, energizedTiles(grid, start = Vec2(x, -1), startDir = DOWN), energizedTiles(grid, start = Vec2(x, yLimit), startDir = UP), ) } return max } }
0
Kotlin
0
1
344c3d97896575393022c17e216afe86685a9344
3,589
advent-of-code-kotlin
MIT License
src/Day25.kt
Flame239
570,094,570
false
{"Kotlin": 60685}
private fun nums(): List<String> { return readInput("Day25") } val snafuDigit = mapOf( '2' to 2, '1' to 1, '0' to 0, '-' to -1, '=' to -2 ) private fun snafu2Dec(n: String): Long { var base = 1L var res = 0L n.reversed().forEach { c -> res += base * snafuDigit[c]!! base *= 5 } return res } private fun dec2Snafu(num: Long): String { return buildString { var n = num while (n != 0L) { append("012=-"[n.mod(5)]) // (n + 2) because if we got rem 3 or 4 (= and -), then we need next digit increased by 1 n = (n + 2).floorDiv(5) } reverse() } } private fun part1(nums: List<String>): String = dec2Snafu(nums.sumOf(::snafu2Dec)) fun main() { measure { part1(nums()) } }
0
Kotlin
0
0
27f3133e4cd24b33767e18777187f09e1ed3c214
810
advent-of-code-2022
Apache License 2.0
src/main/kotlin/pl/jpodeszwik/aoc2023/Day04.kt
jpodeszwik
729,812,099
false
{"Kotlin": 55101}
package pl.jpodeszwik.aoc2023 import java.lang.Long.parseLong private fun part1(lines: List<String>) { var sum = 0L lines.forEach { line -> val parts = line.split(":") val numbers = parts[1].split("|") val winning = numbers[0].split(" ") .map { it.trim() } .filter { it.isNotBlank() } .map { parseLong(it) }.toSet() val winningCards = numbers[1].split(" ") .map { it.trim() } .filter { it.isNotBlank() } .map { parseLong(it) } .filter { winning.contains(it) } val gameValue = if (winningCards.isEmpty()) 0 else 1L shl winningCards.size - 1 sum += gameValue } println(sum) } private fun part2(lines: List<String>) { val cards = LongArray(lines.size) { _ -> 1 } lines.forEachIndexed { index, line -> val parts = line.split(":") val numbers = parts[1].split("|") val card = numbers[0].split(" ") .map { it.trim() } .filter { it.isNotBlank() } .map { parseLong(it) } .toSet() val matchingCards = numbers[1].split(" ") .map { it.trim() } .filter { it.isNotBlank() } .map { parseLong(it) } .filter { card.contains(it) } .size for (i in 0..<matchingCards) { cards[index + i + 1] += cards[index] } } println(cards.sum()) } fun main() { val lines = loadFile("/aoc2023/input4") part1(lines) part2(lines) }
0
Kotlin
0
0
2b90aa48cafa884fc3e85a1baf7eb2bd5b131a63
1,583
advent-of-code
MIT License
aoc-2015/src/main/kotlin/nl/jstege/adventofcode/aoc2015/days/Day18.kt
JStege1206
92,714,900
false
null
package nl.jstege.adventofcode.aoc2015.days import nl.jstege.adventofcode.aoccommon.days.Day import nl.jstege.adventofcode.aoccommon.utils.Point import nl.jstege.adventofcode.aoccommon.utils.extensions.transformTo import java.util.* /** * * @author <NAME> */ class Day18 : Day(title = "Like a GIF For Your Yard") { private companion object Configuration { private const val ITERATIONS = 100 } override fun first(input: Sequence<String>) = (0 until ITERATIONS) .transformTo(Grid.parse(input.toList())) { grid, _ -> grid.getTogglePoints().forEach { (x, y) -> grid[x, y] = !grid[x, y] } } .cardinality() override fun second(input: Sequence<String>) = (0 until ITERATIONS) .transformTo(Grid.parse(input.toList())) { grid, _ -> grid.getTogglePoints().asSequence() .filterNot { (x, y) -> (y == 0 || y == grid.height - 1) && (x == 0 || x == grid.width - 1) } .forEach { (x, y) -> grid[x, y] = !grid[x, y] } } .cardinality() private class Grid private constructor(val grid: BitSet, val height: Int, val width: Int) { operator fun get(x: Int, y: Int) = grid[y * width + x] operator fun set(x: Int, y: Int, value: Boolean) = grid.set(y * width + x, value) fun cardinality() = grid.cardinality() fun getTogglePoints(): Set<Point> = (0 until height) .flatMap { y -> (0 until width).map { x -> Point.of(x, y) } } .filter { (x, y) -> countNeighbours(x, y) .let { (this[x, y] && !(it == 2 || it == 3)) || (!this[x, y] && it == 3) } } .toSet() private fun countNeighbours(x: Int, y: Int): Int { var n = 0 if (x > 0) { if (y > 0) { n += if (this[x - 1, y - 1]) 1 else 0 } n += if (this[x - 1, y]) 1 else 0 if (y < height - 1) { n += if (this[x - 1, y + 1]) 1 else 0 } } if (y > 0) { n += if (this[x, y - 1]) 1 else 0 } if (y < height - 1) { n += if (this[x, y + 1]) 1 else 0 } if (x < width - 1) { if (y > 0) { n += if (this[x + 1, y - 1]) 1 else 0 } n += if (this[x + 1, y]) 1 else 0 if (y < height - 1) { n += if (this[x + 1, y + 1]) 1 else 0 } } return n } companion object Parser { fun parse(input: List<String>) = Grid( input .withIndex() .transformTo(BitSet(input.size * input.first().length)) { bs, (i, s) -> s.forEachIndexed { index, c -> bs[i * s.length + index] = c == '#' } }, input.size, input.first().length ) } } }
0
Kotlin
0
0
d48f7f98c4c5c59e2a2dfff42a68ac2a78b1e025
3,162
AdventOfCode
MIT License
src/main/kotlin/aoc2023/Day09.kt
davidsheldon
565,946,579
false
{"Kotlin": 161960}
package aoc2023 import utils.InputUtils fun main() { val testInput = """0 3 6 9 12 15 1 3 6 10 15 21 10 13 16 21 30 45""".trimIndent().split("\n") fun Iterable<Int>.differences() = zip(drop(1)).map { it.second - it.first } fun Iterable<Int>.differencesTable() = generateSequence(this) { it.differences()} .takeWhile { row -> row.any { it != 0 } } fun predictNext(firstRow: Iterable<Int>): Int { return firstRow.differencesTable() //.onEach { println(it) } .map { it.last() }.sum() } fun predictPrevious(firstRow: Iterable<Int>): Int { return firstRow.differencesTable() .map { it.first() } .toList() .reduceRight { i, acc -> i-acc } } fun part1(input: List<String>): Int { return input.map { it.listOfNumbers() } .sumOf { predictNext(it) } } fun part2(input: List<String>): Int { return input.map { it.listOfNumbers() } .sumOf { predictPrevious(it) } } // test if implementation meets criteria from the description, like: val testValue = part1(testInput) println(testValue) check(testValue == 114) println(part2(testInput)) val puzzleInput = InputUtils.downloadAndGetLines(2023, 9) val input = puzzleInput.toList() println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
5abc9e479bed21ae58c093c8efbe4d343eee7714
1,389
aoc-2022-kotlin
Apache License 2.0
src/Day01.kt
papichulo
572,669,466
false
{"Kotlin": 16864}
fun main() { fun part1(input: List<String>): Int { var maxValue = 0 var newMax = 0 input.forEachIndexed{ index, element -> if (element.isEmpty()) { if (newMax > maxValue) { maxValue = newMax } newMax = 0 } else { newMax += Integer.parseInt(element) if (index == input.lastIndex && newMax > maxValue) { maxValue = newMax } } } return maxValue } fun part2(input: List<String>): Int { val result = mutableListOf<Int>() var tempValue = 0 input.forEachIndexed{ index, element -> if (element.isEmpty()) { result.add(tempValue) tempValue = 0 } else { tempValue += Integer.parseInt(element) if (index == input.lastIndex) result.add(tempValue) } } return result.sorted().reversed().take(3).sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
e277ee5bca823ce3693e88df0700c021e9081948
1,340
aoc-2022-in-kotlin
Apache License 2.0
2021/src/test/kotlin/Day22.kt
jp7677
318,523,414
false
{"Kotlin": 171284, "C++": 87930, "Rust": 59366, "C#": 1731, "Shell": 354, "CMake": 338}
import kotlin.math.abs import kotlin.test.Test import kotlin.test.assertEquals class Day22 { data class Cuboid(val minX: Int, val maxX: Int, val minY: Int, val maxY: Int, val minZ: Int, val maxZ: Int) { val initialization get() = minX >= -50 && maxX <= 50 && minY >= -50 && maxY <= 50 && minZ >= -50 && maxZ <= 50 fun size() = abs(maxX - minX + 1L) * abs(maxY - minY + 1L) * abs(maxZ - minZ + 1L) fun normalize() = Cuboid( if (minX < maxX) minX else maxX, if (minX < maxX) maxX else minX, if (minY < maxY) minY else maxY, if (minY < maxY) maxY else minY, if (minZ < maxZ) minZ else maxZ, if (minZ < maxZ) maxZ else minZ ) infix fun intersect(other: Cuboid): Cuboid? { if (minX > other.maxX || maxX < other.minX || minY > other.maxY || maxY < other.minY || minZ > other.maxZ || maxZ < other.minZ ) return null return Cuboid( if (minX > other.minX) minX else other.minX, if (maxX < other.maxX) maxX else other.maxX, if (minY > other.minY) minY else other.minY, if (maxY < other.maxY) maxY else other.maxY, if (minZ > other.minZ) minZ else other.minZ, if (maxZ < other.maxZ) maxZ else other.maxZ ) } } data class Step(val on: Boolean, val cuboid: Cuboid) @Test fun `run part 01`() { val steps = getSteps() .filter { it.cuboid.initialization } val count = runSteps(steps) assertEquals(653798, count) } @Test fun `run part 02`() { val steps = getSteps() val count = runSteps(steps) assertEquals(1257350313518866, count) } private fun runSteps(steps: List<Step>) = steps .foldIndexed(0L) { index, acc, step -> val previouslyTurnedOn = steps .take(index) .filter { it.on } .mapNotNull { step.cuboid intersect it.cuboid } if (step.on) { acc + step.cuboid.size() - previouslyTurnedOn.effectiveSize() } else { val turnOnOrOffLater = steps .drop(index + 1) .mapNotNull { step.cuboid intersect it.cuboid } acc - previouslyTurnedOn.except(turnOnOrOffLater) } } private fun List<Cuboid>.except(other: List<Cuboid>) = this .effectiveSize() - this .flatMap { cuboid -> other.mapNotNull { cuboid intersect it } } .effectiveSize() private fun List<Cuboid>.effectiveSize(): Long = this .foldIndexed(0L) { index, acc, cuboid -> acc + cuboid.size() - this .take(index) .mapNotNull { cuboid intersect it } .effectiveSize() } private fun getSteps() = Util.getInputAsListOfString("day22-input.txt") .map { val s = it.split(' ') val r = s.last().split("=", "..", ",") Step( s.first() == "on", Cuboid(r[1].toInt(), r[2].toInt(), r[4].toInt(), r[5].toInt(), r[7].toInt(), r[8].toInt()).normalize() ) } }
0
Kotlin
1
2
8bc5e92ce961440e011688319e07ca9a4a86d9c9
3,359
adventofcode
MIT License
src/day_1/kotlin/Day1.kt
Nxllpointer
573,051,992
false
{"Kotlin": 41751}
// AOC Day 1 data class Elf(var totalCalories: Int) fun part1(elves: Collection<Elf>) { val elfWithMostCalories = elves.maxByOrNull { it.totalCalories } ?: throw IllegalArgumentException("No elf provided") val topElfTotalCalories = elfWithMostCalories.totalCalories println("Part 1: The elf with the most amount of calories carrys a total of $topElfTotalCalories calories") } fun part2(elves: Collection<Elf>) { val elvesWithMostCalories = elves.sortedByDescending { it.totalCalories }.take(3) check(elvesWithMostCalories.size >= 3) { "Not enough elves provided" } val topElvesTotalCalories = elvesWithMostCalories.sumOf { it.totalCalories } println("Part 2: The top 3 calorie carrying elves have a total of $topElvesTotalCalories calories") } fun main() { val elves = getAOCInput { rawInput -> rawInput .trim() .split("\n\n") .map { rawElfCaloriesList -> val elfCalories = rawElfCaloriesList .split("\n") .sumOf { it.toInt() } Elf(elfCalories) } } part1(elves) part2(elves) }
0
Kotlin
0
0
b6d7ef06de41ad01a8d64ef19ca7ca2610754151
1,167
AdventOfCode2022
MIT License
src/day21/Day21.kt
armanaaquib
572,849,507
false
{"Kotlin": 34114}
package day21 import readInput fun main() { data class Operation(val op1: String, val op2: String, val operator: String) data class Data(val numbers: MutableMap<String, Long> = mutableMapOf(), val operations: MutableMap<String, Operation> = mutableMapOf()) fun parseInput(input: List<String>) = input.fold(Data()) { data, it -> val (left, right) = it.split(": ") if (right.toLongOrNull() != null) { data.numbers[left] = right.toLong() } else { val (op1, operator, op2) = right.split(" ") data.operations[left] = Operation(op1, op2, operator) } data } fun calcNumber(monkey: String, numbers: MutableMap<String, Long>, operations: MutableMap<String, Operation>): Long { if (numbers[monkey] != null) { return numbers[monkey]!! } val operation = operations[monkey]!! val op1 = calcNumber(operation.op1, numbers, operations) val op2 = calcNumber(operation.op2, numbers, operations) val number = when(operation.operator) { "+" -> op1 + op2 "-" -> op1 - op2 "*" -> op1 * op2 "/" -> op1 / op2 else -> 0 } numbers[monkey] = number return number } fun part1(input: List<String>): Long { val data = parseInput(input) return calcNumber("root", data.numbers, data.operations) } fun part2(input: List<String>): Int { val data = parseInput(input) return 0 } // test if implementation meets criteria from the description, like: check(part1(readInput("Day21_test")) == 152L) println(part1(readInput("Day21"))) check(part2(readInput("Day21_test")) == 301) println(part2(readInput("Day21"))) }
0
Kotlin
0
0
47c41ceddacb17e28bdbb9449bfde5881fa851b7
1,801
aoc-2022
Apache License 2.0
src/main/kotlin/Day11.kt
teodor-vasile
573,434,400
false
{"Kotlin": 41204}
class Day11 { fun solvePart1(input: String): Int { // parse the input val monkeys = input.split("\n\n") .map { monkey -> Monkey( items = getListOfItems(monkey), operator = getOperator(monkey), worryMultiplier = getWorryMultiplier(monkey), divisibleBy = getDivisibleBy(monkey), actionIsTrue = getActionIsTrue(monkey), actionIsFalse = getActionIsFalse(monkey), operationsPerformed = 0 ) } repeat(20) {doOperations(monkeys)} monkeys.forEach { println(it) } println() return monkeys.sortedByDescending { monkey -> monkey.operationsPerformed } .take(2) .map { it.operationsPerformed } .fold(1) { acc, value -> acc * value } } private fun doOperations(monkeys: List<Monkey>) { monkeys.forEach {monkey -> if (monkey.items.isNotEmpty()) { convertWorryMultiplier(monkey) calculateWorryLevel(monkey) monkeyGetsBored(monkey) throwToMonkey(monkey, monkeys) } } } data class Monkey( var items: ArrayDeque<Int>, val operator: String, val worryMultiplier: String, val divisibleBy: Int, val actionIsTrue: Int, val actionIsFalse: Int, var operationsPerformed: Int ) private fun throwToMonkey(monkey: Monkey, monkeys: List<Monkey>) { repeat(monkey.items.count()) { if (monkeyGetsBored(monkey) % monkey.divisibleBy == 0) { monkeys[monkey.actionIsTrue].items.addLast(monkeyGetsBored(monkey)) monkey.items.removeFirst() monkey.operationsPerformed++ } else { monkeys[monkey.actionIsFalse].items.addLast(monkeyGetsBored(monkey)) monkey.items.removeFirst() monkey.operationsPerformed++ } } } private fun monkeyGetsBored(monkey: Monkey): Int { return calculateWorryLevel(monkey) / 3 } private fun convertWorryMultiplier(monkey: Monkey): Int { return if (monkey.worryMultiplier == "old") monkey.items.first() else monkey.worryMultiplier.toInt() } private fun calculateWorryLevel(monkey: Monkey): Int { return when (monkey.operator) { "*" -> monkey.items.first() * convertWorryMultiplier(monkey) "/" -> monkey.items.first() / convertWorryMultiplier(monkey) "+" -> monkey.items.first() + convertWorryMultiplier(monkey) "-" -> monkey.items.first() - convertWorryMultiplier(monkey) else -> error("invalid operation") } } private fun getListOfItems(monkey: String): ArrayDeque<Int> { val worryMultiplier = monkey.lines() .find { it.trim().startsWith("Starting") } .let { it!!.substring(18, it.length) .split(",") .map { it.trim().toInt() } } return ArrayDeque(worryMultiplier) } private fun getWorryMultiplier(monkey: String): String { val worryMultiplier = monkey.lines() .find { it.trim().startsWith("Operation") } .let { it!!.substring(25, it.length) } return worryMultiplier } private fun getOperator(monkey: String): String { val worryMultiplier = monkey.lines() .find { it.trim().startsWith("Operation") } .let { it!!.substring(23, 24) } return worryMultiplier } private fun getDivisibleBy(lines: String): Int { val regex = """Test: divisible by (\d+)""".toRegex() val divisibleBy = regex.find(lines) val (value) = divisibleBy!!.destructured return value.toInt() } private fun getActionIsTrue(lines: String): Int { val regex = """If true: throw to monkey (\d+)""".toRegex() val divisibleBy = regex.find(lines) val (value) = divisibleBy!!.destructured return value.toInt() } private fun getActionIsFalse(lines: String): Int { val regex = """If false: throw to monkey (\d+)""".toRegex() val divisibleBy = regex.find(lines) val (value) = divisibleBy!!.destructured return value.toInt() } }
0
Kotlin
0
0
2fcfe95a05de1d67eca62f34a1b456d88e8eb172
4,572
aoc-2022-kotlin
Apache License 2.0
src/com/mrxyx/algorithm/BinarySearch.kt
Mrxyx
366,778,189
false
null
package com.mrxyx.algorithm /** * 二分查找 */ class BinarySearch { /** * 二分查找 * https://leetcode-cn.com/problems/binary-search/ */ fun binarySearch(nums: IntArray, target: Int): Int { if (nums.isEmpty()) return -1 var left = 0 var right = nums.size - 1 while (left <= right) { val mid = left + (right - left) / 2 when { nums[mid] == target -> return mid nums[mid] < target -> left = mid + 1 nums[mid] > target -> right = mid - 1 } } return -1 } /** * 在排序数组中查找元素的第一个和最后一个位置 * https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/ */ fun searchRange(nums: IntArray, target: Int): IntArray { return intArrayOf(leftBound(nums, target), rightBound(nums, target)) } private fun leftBound(nums: IntArray, target: Int): Int { if (nums.isEmpty()) return -1 var left = 0 var right = nums.size - 1 var mid: Int while (left <= right) { mid = left + (right - left) / 2 when { nums[mid] > target || nums[mid] == target -> right = mid - 1 nums[mid] < target -> left = mid + 1 } } return left } private fun rightBound(nums: IntArray, target: Int): Int { if (nums.isEmpty()) return -1 var left = 0 var right = nums.size - 1 var mid: Int while (left <= right) { mid = left + (right - left) / 2 when { nums[mid] < target -> left = mid + 1 nums[mid] > target -> right = mid - 1 nums[mid] == target -> left = mid + 1 } } return right } }
0
Kotlin
0
0
b81b357440e3458bd065017d17d6f69320b025bf
1,887
algorithm-test
The Unlicense
src/test/kotlin/nl/dirkgroot/adventofcode/year2022/Day11Test.kt
dirkgroot
317,968,017
false
{"Kotlin": 187862}
package nl.dirkgroot.adventofcode.year2022 import io.kotest.core.spec.style.StringSpec import io.kotest.matchers.shouldBe import nl.dirkgroot.adventofcode.util.input import nl.dirkgroot.adventofcode.util.invokedWith private fun solution1(input: String) = solve(input, 20, 3L) private fun solution2(input: String) = solve(input, 10000, 1L) private fun solve(input: String, rounds: Int, divideBy: Long) = parseMonkeys(input).let { monkeys -> val modulo = monkeys.map { it.divisibleBy }.reduce(Long::times) repeat(rounds) { round(monkeys, divideBy, modulo) } monkeys.monkeyBusiness() } private fun parseMonkeys(input: String) = input.split("\n\n").map { monkey -> Monkey.parse(monkey) } private fun round(monkeys: List<Monkey>, divideBy: Long, modulo: Long) { monkeys.forEach { monkey -> repeat(monkey.items.size) { val (item, destination) = monkey.inspect(divideBy, modulo) monkeys[destination].items.add(item) } } } private fun List<Monkey>.monkeyBusiness() = map { it.inspectCount }.sortedDescending().take(2).reduce(Long::times) private data class Monkey( val items: MutableList<Long>, val operation: (Long) -> Long, val divisibleBy: Long, val ifTrue: Int, val ifFalse: Int, var inspectCount: Long = 0L ) { fun inspect(divideBy: Long, modulo: Long): Pair<Long, Int> { inspectCount++ val item = operation(items.removeAt(0)) / divideBy % modulo return if (item % divisibleBy == 0L) item to ifTrue else item to ifFalse } companion object { fun parse(input: String): Monkey { val lines = input.lines() return Monkey( items = lines[1].drop(18).split(", ").map { it.toLong() }.toMutableList(), operation = lines[2].drop(23).split(" ").let { if (it[1] == "old") { old: Long -> old * old } else if (it[0] == "*") it[1].toLong()::times else it[1].toLong()::plus }, divisibleBy = lines[3].drop(21).toLong(), ifTrue = lines[4].drop(29).toInt(), ifFalse = lines[5].drop(30).toInt() ) } } } //===============================================================================================\\ private const val YEAR = 2022 private const val DAY = 11 class Day11Test : StringSpec({ "example part 1" { ::solution1 invokedWith exampleInput shouldBe 10605L } "part 1 solution" { ::solution1 invokedWith input(YEAR, DAY) shouldBe 54054L } "example part 2" { ::solution2 invokedWith exampleInput shouldBe 2713310158L } "part 2 solution" { ::solution2 invokedWith input(YEAR, DAY) shouldBe 14314925001L } }) private val exampleInput = """ Monkey 0: Starting items: 79, 98 Operation: new = old * 19 Test: divisible by 23 If true: throw to monkey 2 If false: throw to monkey 3 Monkey 1: Starting items: 54, 65, 75, 74 Operation: new = old + 6 Test: divisible by 19 If true: throw to monkey 2 If false: throw to monkey 0 Monkey 2: Starting items: 79, 60, 97 Operation: new = old * old Test: divisible by 13 If true: throw to monkey 1 If false: throw to monkey 3 Monkey 3: Starting items: 74 Operation: new = old + 3 Test: divisible by 17 If true: throw to monkey 0 If false: throw to monkey 1 """.trimIndent()
1
Kotlin
1
1
ffdffedc8659aa3deea3216d6a9a1fd4e02ec128
3,639
adventofcode-kotlin
MIT License
kotlin/basics/src/main/kotlin/ElementSort.kt
suzp1984
65,159,392
false
{"C++": 29471, "Java": 26106, "Kotlin": 10984, "Scala": 9694, "JavaScript": 3248, "CMake": 442, "Swift": 171}
package io.github.suzp1984.algorithms import java.util.* import kotlin.math.min fun <T> Array<T>.swap(i : Int, j : Int) { val t = this[i] this[i] = this[j] this[j] = t } fun <T : Comparable<T>> Array<T>.selectionSort() { indices.forEach { i -> var minIndex = i (i + 1 until size) .asSequence() .filter { this[it] < this[minIndex] } .forEach { minIndex = it } swap(minIndex, i) } } fun <T : Comparable<T>> Array<T>.insertionSort() { (1 until size).forEach { i -> (i downTo 1) .asSequence() .takeWhile { this[it] < this[it - 1] } .forEach { swap(it, it - 1) } } } fun <T : Comparable<T>> Array<T>.improvedInsertionSort() { (1 until size).forEach { i -> val t = this[i] val seqIndex = (i downTo 1) .asSequence() .takeWhile { this[it-1] > t } seqIndex.forEach { this[it] = this[it-1] } val lastIndex = seqIndex.lastOrNull() if (lastIndex != null) this[lastIndex - 1] = t } } fun <T : Comparable<T>> Array<T>.bubbleSort() { (0 until size).forEach { (1 until size - it).forEach { if (this[it] < this[it-1]) { swap(it, it-1) } } } } private fun <T : Comparable<T>> Array<T>.__merge(l : Int, mid : Int, r : Int) { val aux = copyOfRange(l, r + 1) var i = l var j = mid + 1 (l until r + 1).forEach { when { i > mid -> { this[it] = aux[j-l] j++ } j > r -> { this[it] = aux[i-l] i++ } aux[i-l] < aux[j-l] -> { this[it] = aux[i-l] i++ } else -> { this[it] = aux[j-l] j++ } } } } fun <T : Comparable<T>> Array<T>.mergeSort() { fun <T : Comparable<T>> Array<T>.__mergeSort(l : Int, r : Int) { if (l >= r) return val mid = l/2 + r/2 __mergeSort(l, mid) __mergeSort(mid+1, r) __merge(l, mid, r) } __mergeSort(0, size-1) } fun <T : Comparable<T>> Array<T>.bottomUpMergeSort() { var sz = 1 while (sz <= size) { var i = 0 while (i + sz < size) { __merge(i, i + sz - 1, min(i + sz + sz - 1, size - 1)) i += sz + sz } sz += sz } } fun <T : Comparable<T>> Array<T>.quickSort() { fun <T : Comparable<T>> Array<T>.__partition(l : Int, r : Int) : Int { val t = this[l] var j = l (l+1 until r+1).forEach { if (this[it] < t) { swap(++j, it) } } swap(l, j) return j } fun <T : Comparable<T>> Array<T>.__quickSort(l : Int, r : Int) { if (l >= r) return val p = __partition(l, r) __quickSort(l, p - 1) __quickSort(p + 1, r) } __quickSort(0, size-1) } fun <T : Comparable<T>> Array<T>.quickSortRandom() { fun <T : Comparable<T>> Array<T>.__partition(l : Int, r : Int) : Int { swap(l, Random().nextInt(r - l + 1) + l) val t = this[l] var j = l (l+1 until r+1).forEach { if (this[it] < t) { swap(++j, it) } } swap(l, j) return j } fun <T : Comparable<T>> Array<T>.__quickSort(l : Int, r : Int) { if (l >= r) return val p = __partition(l, r) __quickSort(l, p - 1) __quickSort(p + 1, r) } __quickSort(0, size-1) } fun <T : Comparable<T>> Array<T>.quickSortDoublePartition() { fun <T : Comparable<T>> Array<T>.__double_partition(l : Int, r : Int) : Int { swap(l, Random().nextInt(r - l + 1) + l) val t = this[l] var i = l + 1 var j = r while (true) { while (i <= r && this[i] < t) i++ while (j >= l + 1 && this[j] > t) j-- if (i > j) break swap(i, j) i++ j-- } swap(l, j) return j } fun <T : Comparable<T>> Array<T>.__quickSort(l : Int, r : Int) { if (l >= r) return val p = __double_partition(l, r) __quickSort(l, p - 1) __quickSort(p + 1, r) } __quickSort(0, size-1) } fun <T : Comparable<T>> Array<T>.quickSortTriplePartition() { fun <T : Comparable<T>> Array<T>.__triple_partition(l : Int, r : Int) { if (l >= r) { return } swap(l, Random().nextInt(r - l + 1) + l) val t = this[l] var lt = l var gt = r + 1; var i = l + 1; while (i < gt) { if (this[i] < t) { swap(i, lt + 1) lt++ i++ } else if (this[i] > t) { swap(i, gt - 1) gt-- } else { i++ } } swap(l, lt) __triple_partition(l, lt - 1) __triple_partition(gt, r) } __triple_partition(0, size - 1) }
0
C++
0
0
ea678476a4c70e5135d31fccd8383fac989cc031
5,181
Algorithms-Collection
Apache License 2.0
kotlin/src/katas/kotlin/leetcode/bst_validation/ValidateBST.kt
dkandalov
2,517,870
false
{"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221}
package katas.kotlin.leetcode.bst_validation import katas.kotlin.leetcode.TreeNode import datsok.shouldEqual import org.junit.Test import java.util.* import kotlin.Int.Companion.MAX_VALUE import kotlin.Int.Companion.MIN_VALUE /** * ✅ https://leetcode.com/problems/validate-binary-search-tree */ class ValidateBSTTests { private fun TreeNode.isValid() = isValid_3() @Test fun `shallow trees`() { TreeNode(1).isValid() shouldEqual true TreeNode(1, TreeNode(0)).isValid() shouldEqual true TreeNode(1, null, TreeNode(2)).isValid() shouldEqual true TreeNode(1, TreeNode(2)).isValid() shouldEqual false TreeNode(1, null, TreeNode(0)).isValid() shouldEqual false TreeNode(1, TreeNode(1)).isValid() shouldEqual false TreeNode(1, null, TreeNode(1)).isValid() shouldEqual false TreeNode(0, TreeNode(MIN_VALUE), TreeNode(MAX_VALUE)).isValid() shouldEqual true TreeNode(0, TreeNode(MAX_VALUE), TreeNode(MIN_VALUE)).isValid() shouldEqual false } @Test fun `right subtree has value less than or equal to one of its parents`() { TreeNode(4, left = TreeNode(2), right = TreeNode(6, TreeNode(5), TreeNode(7)) ).isValid() shouldEqual true TreeNode(4, left = TreeNode(2), right = TreeNode(6, TreeNode(7), TreeNode(5)) ).isValid() shouldEqual false TreeNode(4, left = TreeNode(2), right = TreeNode(6, TreeNode(1), TreeNode(7)) ).isValid() shouldEqual false TreeNode(4, left = TreeNode(2), right = TreeNode(6, TreeNode(4), TreeNode(7)) ).isValid() shouldEqual false } @Test fun `left subtree has value greater than one of its parents`() { TreeNode(4, left = TreeNode(2, TreeNode(1), TreeNode(3)), right = TreeNode(6) ).isValid() shouldEqual true TreeNode(4, left = TreeNode(2, TreeNode(3), TreeNode(1)), right = TreeNode(6) ).isValid() shouldEqual false TreeNode(4, left = TreeNode(2, TreeNode(1), TreeNode(5)), right = TreeNode(6) ).isValid() shouldEqual false } } fun isValidBST(root: TreeNode?): Boolean { return root?.isValid_1() ?: true // ✅ // return root?.isValid_2() ?: true // ✅ // return root?.isValid_3() ?: true // ✅ } private fun TreeNode.isValid_1(): Boolean { val stack = LinkedList<TreeNode>() var node: TreeNode? = this var prevNode: TreeNode? = null while (stack.isNotEmpty() || node != null) { while (node != null) { stack.addLast(node) node = node.left } node = stack.removeLast() if (prevNode != null && node!!.value <= prevNode.value) return false prevNode = node node = node.right } return true } private class Ref<T>(var value: T? = null) private fun TreeNode.isValid_2(last: Ref<TreeNode> = Ref()): Boolean { if (left != null && !left!!.isValid_2(last)) return false if (last.value != null && last.value!!.value >= value) return false last.value = this if (right != null && !right!!.isValid_2(last)) return false return true } private fun TreeNode.isValid_3(min: Int? = null, max: Int? = null): Boolean { if (min != null && value <= min) return false if (max != null && value > max) return false if (left != null && left!!.value >= value) return false if (right != null && right!!.value <= value) return false return left?.isValid_3(min = min, max = value) ?: true && right?.isValid_3(min = value, max = max) ?: true }
7
Roff
3
5
0f169804fae2984b1a78fc25da2d7157a8c7a7be
3,694
katas
The Unlicense
src/main/kotlin/aoc2019/PlanetOfDiscord.kt
komu
113,825,414
false
{"Kotlin": 395919}
package komu.adventofcode.aoc2019 import komu.adventofcode.utils.nonEmptyLines import kotlin.math.pow fun planetOfDiscord(input: String): Int { var grid = BugGrid(input) val seen = mutableSetOf<BugGrid>() while (true) { grid = grid.step() if (!seen.add(grid)) break } return grid.biodiversityRating() } fun planetOfDiscord2(input: String): Int { var grid = BugGrid(input) repeat(200) { grid = grid.recursiveStep() } return grid.bugs.size } private data class BugCell(val x: Int, val y: Int, val level: Int) { val simpleNeighbors: List<BugCell> get() = listOf( BugCell(x - 1, y, level), BugCell(x + 1, y, level), BugCell(x, y - 1, level), BugCell(x, y + 1, level) ) val recursiveNeighbors: List<BugCell> get() { val result = mutableListOf<BugCell>() when { x == 2 && y == 1 -> { result += copy(x = 1) result += copy(x = 3) result += copy(y = 0) result += (0..4).map { BugCell(x = it, y = 0, level = level + 1) } } x == 1 && y == 2 -> { result += copy(x = 0) result += copy(y = 1) result += copy(y = 3) result += (0..4).map { BugCell(x = 0, y = it, level = level + 1) } } x == 3 && y == 2 -> { result += copy(x = 4) result += copy(y = 1) result += copy(y = 3) result += (0..4).map { BugCell(x = 4, y = it, level = level + 1) } } x == 2 && y == 3 -> { result += copy(x = 1) result += copy(x = 3) result += copy(y = 4) result += (0..4).map { BugCell(x = it, y = 4, level = level + 1) } } else -> { result += if (x == 0) BugCell(x = 1, y = 2, level = level - 1) else copy(x = x - 1) result += if (x == 4) BugCell(x = 3, y = 2, level = level - 1) else copy(x = x + 1) result += if (y == 0) BugCell(x = 2, y = 1, level = level - 1) else copy(y = y - 1) result += if (y == 4) BugCell(x = 2, y = 3, level = level - 1) else copy(y = y + 1) } } return result } } private data class BugGrid(val bugs: Set<BugCell>) { fun biodiversityRating(): Int = (0..24).sumOf { i -> if (BugCell(x = i % 5, y = i / 5, level = 0) in bugs) 2.0.pow(i).toInt() else 0 } fun step(): BugGrid { val newPoints = mutableSetOf<BugCell>() for (y in 0..4) for (x in 0..4) { val p = BugCell(x, y, level = 0) val neighbors = p.simpleNeighbors.count { it in bugs } if (p in bugs) { if (neighbors == 1) newPoints += p } else { if (neighbors in 1..2) newPoints += p } } return BugGrid(newPoints) } fun recursiveStep(): BugGrid { val newPoints = mutableSetOf<BugCell>() val candidates = (bugs + bugs.flatMap { it.recursiveNeighbors }).toSet() for (point in candidates) { val neighbors = point.recursiveNeighbors.count { it in bugs } if (point in bugs) { if (neighbors == 1) newPoints += point } else { if (neighbors in 1..2) newPoints += point } } return BugGrid(newPoints) } companion object { operator fun invoke(input: String): BugGrid { val bugs = mutableSetOf<BugCell>() for ((y, line) in input.nonEmptyLines().withIndex()) for ((x, c) in line.withIndex()) if (c == '#') bugs += BugCell(x, y, level = 0) return BugGrid(bugs) } } }
0
Kotlin
0
0
8e135f80d65d15dbbee5d2749cccbe098a1bc5d8
4,274
advent-of-code
MIT License
year2020/day21/part1/src/main/kotlin/com/curtislb/adventofcode/year2020/day21/part1/Year2020Day21Part1.kt
curtislb
226,797,689
false
{"Kotlin": 2146738}
/* --- Day 21: Allergen Assessment --- You reach the train's last stop and the closest you can get to your vacation island without getting wet. There aren't even any boats here, but nothing can stop you now: you build a raft. You just need a few days' worth of food for your journey. You don't speak the local language, so you can't read any ingredients lists. However, sometimes, allergens are listed in a language you do understand. You should be able to use this information to determine which ingredient contains which allergen and work out which foods are safe to take with you on your trip. You start by compiling a list of foods (your puzzle input), one food per line. Each line includes that food's ingredients list followed by some or all of the allergens the food contains. Each allergen is found in exactly one ingredient. Each ingredient contains zero or one allergen. Allergens aren't always marked; when they're listed (as in (contains nuts, shellfish) after an ingredients list), the ingredient that contains each listed allergen will be somewhere in the corresponding ingredients list. However, even if an allergen isn't listed, the ingredient that contains that allergen could still be present: maybe they forgot to label it, or maybe it was labeled in a language you don't know. For example, consider the following list of foods: mxmxvkd kfcds sqjhc nhms (contains dairy, fish) trh fvjkl sbzzf mxmxvkd (contains dairy) sqjhc fvjkl (contains soy) sqjhc mxmxvkd sbzzf (contains fish) The first food in the list has four ingredients (written in a language you don't understand): mxmxvkd, kfcds, sqjhc, and nhms. While the food might contain other allergens, a few allergens the food definitely contains are listed afterward: dairy and fish. The first step is to determine which ingredients can't possibly contain any of the allergens in any food in your list. In the above example, none of the ingredients kfcds, nhms, sbzzf, or trh can contain an allergen. Counting the number of times any of these ingredients appear in any ingredients list produces 5: they all appear once each except sbzzf, which appears twice. Determine which ingredients cannot possibly contain any of the allergens in your list. How many times do any of those ingredients appear? */ package com.curtislb.adventofcode.year2020.day21.part1 import com.curtislb.adventofcode.year2020.day21.food.FoodList import java.nio.file.Path import java.nio.file.Paths /** * Returns the solution to the puzzle for 2020, day 21, part 1. * * @param inputPath The path to the input file for this puzzle. */ fun solve(inputPath: Path = Paths.get("..", "input", "input.txt")): Int { val file = inputPath.toFile() val foodList = FoodList(file.readText()) return foodList.safeIngredients.sumOf { foodList.countFoodsWith(it) } } fun main() { println(solve()) }
0
Kotlin
1
1
6b64c9eb181fab97bc518ac78e14cd586d64499e
2,859
AdventOfCode
MIT License
2023/day04-25/src/main/kotlin/Day05.kt
CakeOrRiot
317,423,901
false
{"Kotlin": 62169, "Python": 56994, "C#": 20675, "Rust": 10417}
import java.io.File import kotlin.math.min class Day05 { val doubleNewLines = "(\r\n\r\n)|(\n\n)" val newLines = "(\r\n)|(\n)" fun solve1() { val blocks = File("inputs/5.txt").inputStream().bufferedReader().use { it.readText() }.split(doubleNewLines.toRegex()) val seeds = blocks[0].split(' ').drop(1).map { x -> x.toLong() } val maps = mutableListOf<Map>() for (block in blocks.drop(1)) { val lines = block.split(newLines.toRegex()).drop(1) val dsts = mutableListOf<Long>() val srcs = mutableListOf<Long>() val lens = mutableListOf<Long>() for (line in lines.filter { x -> x.isNotEmpty() }) { val split = line.split(' ').map { x -> x.toLong() } dsts.add(split[0]) srcs.add(split[1]) lens.add(split[2]) } maps.add(Map(dsts.toList(), srcs.toList(), lens.toList())) } var mappedSeeds = seeds.toList() for (map in maps) { mappedSeeds = mappedSeeds.map { seed -> map.apply(seed) } } println(mappedSeeds.min()) } fun solve2() { val blocks = File("inputs/5.txt").inputStream().bufferedReader().use { it.readText() } .split(doubleNewLines.toRegex()) val ranges = blocks[0].split(' ').drop(1).map { x -> x.toLong() }.chunked(2).map { (seed, len) -> Range(seed, len) } val maps = mutableListOf<Map>() for (block in blocks.drop(1)) { val lines = block.split(newLines.toRegex()).drop(1) val dsts = mutableListOf<Long>() val srcs = mutableListOf<Long>() val lens = mutableListOf<Long>() for (line in lines.filter { x -> x.isNotEmpty() }) { val split = line.split(' ').map { x -> x.toLong() } dsts.add(split[0]) srcs.add(split[1]) lens.add(split[2]) } maps.add(Map(dsts.toList(), srcs.toList(), lens.toList())) } var mappedRanges = ranges.toList() for (map in maps) { mappedRanges = mappedRanges.flatMap { range -> map.apply(range) } } println(mappedRanges.minBy { x -> x.start }.start) } } data class Range(val start: Long, val len: Long) fun rangeIntersection(range1: Range, range2: Range): Range? { fun isInside(range1: Range, range2: Range): Range? { if (range1.start >= range2.start && range1.start < range2.start + range2.len) { return Range( range1.start, min(range1.len, range2.start + range2.len - range1.start) ) } return null } val inside1 = isInside(range1, range2) if (inside1 != null) return inside1 val inside2 = isInside(range2, range1) if (inside2 != null) return inside2 return null } data class Map(val dstRangeStart: List<Long>, val sourceRangeStart: List<Long>, val len: List<Long>) { fun apply(seed: Long): Long { for ((dst, src, l) in dstRangeStart.zip(sourceRangeStart).zip(len) .map { x -> listOf(x.first.first, x.first.second, x.second) }) if (seed >= src && seed < src + l) { return seed - src + dst } return seed } fun apply(range: Range): List<Range> { var ranges = listOf(range) val resultRanges = mutableListOf<Range>() for ((dst, src, l) in dstRangeStart.zip(sourceRangeStart).zip(len) .map { x -> listOf(x.first.first, x.first.second, x.second) }) { for (range in ranges) { val newRanges = mutableListOf<Range>() val intersection = rangeIntersection(range, Range(src, l)) if (intersection != null) { resultRanges.add(Range(dst + (intersection.start - src), intersection.len)) val left = Range(range.start, intersection.start - range.start) val right = Range( intersection.start + intersection.len, range.start + range.len - (intersection.start + intersection.len) ) if (left.len > 0) newRanges.add(left) if (right.len > 0) newRanges.add(right) } else { newRanges.add(range) } ranges = newRanges.toList() } } resultRanges.addAll(ranges) return resultRanges.toList() } }
0
Kotlin
0
0
8fda713192b6278b69816cd413de062bb2d0e400
4,699
AdventOfCode
MIT License
src/day07/Day07.kt
banshay
572,450,866
false
{"Kotlin": 33644}
package day07 import readInput fun main() { fun part1(input: List<String>): Long { val filesystem = Filesystem() input.map { it.toStatement() } .forEach { it.accept(filesystem) } val threshold: Long = 100_000 return filesystem.root.flatten().filter { it.size() <= threshold }.sumOf { it.size() } } fun part2(input: List<String>): Long { val filesystem = Filesystem() input.map { it.toStatement() } .forEach { it.accept(filesystem) } val freeSpace = 70_000_000L - filesystem.root.size() val requiredSpace = 30_000_000L - freeSpace return filesystem.root.flatten().map { it.size() }.reversed().first { it >= requiredSpace } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day07_test") val input = readInput("Day07") println("test part1: ${part1(testInput)}") println("result part1: ${part1(input)}") println("test part2: ${part2(testInput)}") println("result part2: ${part2(input)}") } fun String.toStatement() = if (startsWith("$")) Input(this) else Output(this) interface Statement { val instruction: String fun accept(visitor: FilesystemVisitor) } class Input(override val instruction: String) : Statement { enum class Command { CD, LS } fun type(): Command { return when { instruction.startsWith("$ cd") -> Command.CD instruction.startsWith("$ ls") -> Command.LS else -> throw IllegalArgumentException("Unknown command in $instruction") } } fun getDir(): String = instruction.substringAfter("$ cd ") override fun accept(visitor: FilesystemVisitor) { visitor.visit(this) } } class Output(override val instruction: String) : Statement { fun toContent(currentDir: Directory): Content { return when { instruction.startsWith("dir ") -> Directory(currentDir, instruction.substringAfter("dir "), mutableListOf()) else -> File(currentDir, instruction.substringAfter(" "), instruction.substringBefore(" ").toLong()) } } override fun accept(visitor: FilesystemVisitor) { visitor.visit(this) } } interface FilesystemVisitor { fun visit(statement: Input) fun visit(statement: Output) } interface Content { val parent: Content? val name: String fun size(): Long } data class Directory(override val parent: Directory?, override val name: String, val contents: MutableList<Content>) : Content { override fun size(): Long { return contents.fold(0) { acc, it -> acc + it.size() } } fun flatten(): List<Directory> { val directories = mutableListOf<Directory>() this.flattenTo(directories) return directories } private fun flattenTo(destination: MutableCollection<Directory>) { destination.add(this) contents.filterIsInstance<Directory>().forEach { it.flattenTo(destination) } } override fun toString(): String { return "$name (${size()})" } } data class File(override val parent: Content?, override val name: String, val size: Long) : Content { override fun size(): Long { return size } override fun toString(): String { return "$name ($size)" } } class Filesystem : FilesystemVisitor { private val _root = Directory(null, "/", mutableListOf()) private var currentDir = _root val root get() = _root override fun visit(statement: Input) { when (statement.type()) { Input.Command.CD -> currentDir = when (statement.getDir()) { "/" -> _root ".." -> currentDir.parent ?: currentDir else -> currentDir.contents.find { it.name == statement.getDir() } as Directory } else -> { } } } override fun visit(statement: Output) { currentDir.contents.add(statement.toContent(currentDir)) } override fun toString(): String { return _root.toString() } }
0
Kotlin
0
0
c3de3641c20c8c2598359e7aae3051d6d7582e7e
4,128
advent-of-code-22
Apache License 2.0
advent-of-code/src/main/kotlin/solution/Day05.kt
kressnick25
573,285,946
false
null
package solution import java.lang.Integer.parseInt import java.util.* import kotlin.collections.ArrayDeque private class Operation ( val move: Int, val from: Int, val to: Int, ) { companion object { fun fromStr(input: String): Operation { val re = """move (?<move>\d+) from (?<from>\d+) to (?<to>\d+)""".toRegex() val matches = re.matchEntire(input)?.groups ?: throw Exception("bad input format: $input") return Operation(move = parseInt(matches["move"]?.value), from = parseInt(matches["from"]?.value), to = parseInt(matches["to"]?.value)) } } } class Day05 : Solution { data class Operation( val move: Int, val from: Int, val to: Int ) private fun getOutput(stacks: Array<ArrayDeque<Char>>): String { var out = "" for (stack in stacks) { if (stack.isNotEmpty()) { out += stack.last() } } return out } private fun parseStacks(lines: List<String>): Pair<Array<ArrayDeque<Char>>, List<solution.Operation>> { val ops: MutableList<solution.Operation> = mutableListOf(); var stacks: Array<ArrayDeque<Char>> = arrayOf() for (line in lines) { if (line.startsWith(" 1")) { stacks = Array(parseInt(line.toCharArray().last().toString())) { ArrayDeque() } break } } for (line in lines) { if (line.startsWith("move")) { ops.add(solution.Operation.fromStr(line)) } if(!line.contains('[')) { continue } else { val chars = line.toCharArray() for (idx in 1..chars.size step 4) { val nextChar = chars[idx] if (nextChar != ' ') { stacks[idx / 4].addFirst(nextChar) } } } } return Pair(stacks, ops) } override fun solvePart1(input: String): String { val parsed = parseStacks(input.lines()) val stacks = parsed.first val ops = parsed.second for (op in ops) { for (unused in 1..op.move) { if (stacks[op.from - 1].isNotEmpty()) { stacks[op.to - 1].addLast(stacks[op.from - 1].removeLast()) } } } return getOutput(stacks) } override fun solvePart2(input: String): String { val parsed = parseStacks(input.lines()) val stacks = parsed.first val ops = parsed.second for (op in ops) { val toMove = ArrayDeque<Char>() for (u in 1..op.move) { if (stacks[op.from - 1].isNotEmpty()) { toMove.addFirst(stacks[op.from - 1].removeLast()) } } stacks[op.to - 1].addAll(toMove) } return getOutput(stacks) } }
0
Rust
0
0
203284a1941e018c7ad3c5d719a6e366013ffb82
3,018
advent-of-code-2022
MIT License
src/main/kotlin/asaad/DayTwo.kt
Asaad27
573,138,684
false
{"Kotlin": 23483}
package asaad import java.io.File class DayTwo(filePath: String) { /* * rock -> Scissors -> paper ->rock... ->win, <-loose */ private val file = File(filePath) private val input = readInput(file) private fun readInput(file: File) = file.readLines() private var part1 = true private val handMapper = mapOf( "A" to HAND.ROCK, "X" to HAND.ROCK, "Y" to HAND.PAPER, "B" to HAND.PAPER, "Z" to HAND.SCISSORS, "C" to HAND.SCISSORS ) private val outcomeMapper = mapOf( "X" to OUTCOME.LOOSE, "Y" to OUTCOME.DRAW, "Z" to OUTCOME.WIN ) private val handSize = HAND.values().size fun result() { println("\tpart 1: ${solve()}") part1 = false println("\tpart 2: ${solve()}") } private fun solve() = input.fold(0) { acc: Int, round: String -> acc + roundScore(round) } private fun roundScore(round: String): Int { var score = 0 val (firstCol, secondCol) = round.split(" ") val opponentHand = handParser(firstCol) val myHand = if (part1) handParser(secondCol) else outcomeToHand(opponentHand, outcomeParser(secondCol)) score += myHand.score + roundOutcome(opponentHand, myHand).score return score } private fun roundOutcome(opponent: HAND, mine: HAND): OUTCOME = when { opponent == mine -> OUTCOME.DRAW (opponent.ordinal + 1).mod(handSize) == mine.ordinal -> OUTCOME.WIN else -> OUTCOME.LOOSE } private fun outcomeToHand(opponent: HAND, outcome: OUTCOME): HAND = when (outcome) { OUTCOME.LOOSE -> HAND.values()[(opponent.ordinal + handSize - 1).mod(handSize)] OUTCOME.WIN -> HAND.values()[(opponent.ordinal + 1).mod(handSize)] else -> opponent } private fun handParser(input: String) = handMapper[input]!! private fun outcomeParser(input: String) = outcomeMapper[input]!! private enum class OUTCOME(val score: Int) { WIN(6), LOOSE(0), DRAW(3); } private enum class HAND(val score: Int) { ROCK(1), PAPER(2), SCISSORS(3); } }
0
Kotlin
0
0
16f018731f39d1233ee22d3325c9933270d9976c
2,222
adventOfCode2022
MIT License
src/main/kotlin/at/mpichler/aoc/solutions/year2021/Day12.kt
mpichler94
656,873,940
false
{"Kotlin": 196457}
package at.mpichler.aoc.solutions.year2021 import at.mpichler.aoc.lib.Day import at.mpichler.aoc.lib.Graph import at.mpichler.aoc.lib.PartSolution open class Part12A : PartSolution() { private lateinit var graph: Graph override fun parseInput(text: String) { graph = Graph() val edges = text.split("\n").map { it.split("-") }.map { Pair(it[0], it[1]) } graph.addEdges(edges) } override fun compute(): Int { return exploreNeighbors("start", 0, mutableListOf()) } private fun exploreNeighbors(node: String, numPaths: Int, visitedSmallCaves: MutableList<String>): Int { var paths = numPaths if (!canVisit(node, visitedSmallCaves)) { return paths } if (node == node.lowercase()) { visitedSmallCaves.add(node) } if (node == "end") { return paths + 1 } for (neighbor in graph.neighbors(node)) { paths = exploreNeighbors(neighbor, paths, visitedSmallCaves.toMutableList()) } return paths } open fun canVisit(node: String, visitedSmallCaves: List<String>): Boolean { return node !in visitedSmallCaves } override fun getExampleAnswer(): Int { return 10 } } class Part12B : Part12A() { override fun canVisit(node: String, visitedSmallCaves: List<String>): Boolean { if (node != node.lowercase()) { return true } val counts = visitedSmallCaves.associateWith { visitedSmallCaves.count { v -> v == it } } if (node == "start" && "start" in counts) { return false } val doubleVisited = counts.values.any { it == 2 } if (doubleVisited) { return node !in counts } return true } override fun getExampleAnswer(): Int { return 36 } } fun main() { Day(2021, 12, Part12A(), Part12B()) }
0
Kotlin
0
0
69a0748ed640cf80301d8d93f25fb23cc367819c
1,934
advent-of-code-kotlin
MIT License
src/main/java/challenges/cracking_coding_interview/trees_graphs/first_common_ancestor/Question.kt
ShabanKamell
342,007,920
false
null
package challenges.cracking_coding_interview.trees_graphs.first_common_ancestor import challenges.util.TreeNode /** * Design an algorithm and write code to find the first common ancestor of two nodes in a binary tree. * Avoid storing additional nodes in a data structure. * NOTE: This is not necessarily a binary search tree. */ object Question { private var TWO_NODES_FOUND = 2 private var ONE_NODE_FOUND = 1 private var NO_NODES_FOUND = 0 // Checks how many 'special' nodes are located under this root private fun covers(root: TreeNode?, p: TreeNode, q: TreeNode): Int { var ret = NO_NODES_FOUND if (root == null) return ret if (root == p || root == q) ret += 1 ret += covers(root.left, p, q) return if (ret == TWO_NODES_FOUND) ret else ret + covers(root.right, p, q) } private fun commonAncestor(root: TreeNode, p: TreeNode, q: TreeNode): TreeNode? { if (q == p && (root.left == q || root.right == q)) return root val nodesFromLeft = covers(root.left, p, q) // Check left side if (nodesFromLeft == TWO_NODES_FOUND) { return if (root.left == p || root.left == q) root.left else commonAncestor(root.left!!, p, q) } else if (nodesFromLeft == ONE_NODE_FOUND) { if (root == p) return p else if (root == q) return q } val nodesFromRight = covers(root.right, p, q) // Check right side if (nodesFromRight == TWO_NODES_FOUND) { return if (root.right == p || root.right == q) root.right else commonAncestor(root.right!!, p, q) } else if (nodesFromRight == ONE_NODE_FOUND) { if (root == p) return p else if (root == q) return q } return if (nodesFromLeft == ONE_NODE_FOUND && nodesFromRight == ONE_NODE_FOUND ) root else null } @JvmStatic fun main(args: Array<String>) { val array = intArrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) val root: TreeNode = TreeNode.createMinimalBST(array) ?: return val n3: TreeNode = root.find(1)!! val n7: TreeNode = root.find(7)!! val ancestor: TreeNode? = commonAncestor(root, n3, n7) println(ancestor?.data) } }
0
Kotlin
0
0
ee06bebe0d3a7cd411d9ec7b7e317b48fe8c6d70
2,221
CodingChallenges
Apache License 2.0
advent-of-code-2020/src/main/kotlin/eu/janvdb/aoc2020/day04/Day04.kt
janvdbergh
318,992,922
false
{"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335}
package eu.janvdb.aoc2020.day04 import eu.janvdb.aocutil.kotlin.readGroupedLines val fieldRegex = Regex("(\\S+):(\\S+)") val yearRegex = Regex("^\\d{4}$") val heightRegex = Regex("^(\\d+)(cm|in)$") val hairColorRegex = Regex("^#[0-9a-f]{6}$") val eyeColorRegex = Regex("^amb|blu|brn|gry|grn|hzl|oth$") val passportIdRegex = Regex("^\\d{9}$") fun main() { val correctPassports = readGroupedLines(2020, "input04.txt").map(::processPassport) .filter { it } .count() println(correctPassports) } fun processPassport(subLines: List<String>): Boolean { val fields = mutableMapOf<String, String>() subLines.flatMap(fieldRegex::findAll) .forEach { fields[it.groupValues[1]] = it.groupValues[2] } /* byr (Birth Year) iyr (Issue Year) eyr (Expiration Year) hgt (Height) hcl (Hair Color) ecl (Eye Color) pid (Passport ID) [ cid (Country ID) ] */ println(fields) val valid = validYear(fields["byr"], 1920, 2002) && validYear(fields["iyr"], 2010, 2020) && validYear(fields["eyr"], 2020, 2030) && validHeight(fields["hgt"]) && validHairColor(fields["hcl"]) && validEyeColor(fields["ecl"]) && validPassportId(fields["pid"]) /*&& fields.containsKey("cid")*/ println(valid) println() return valid } fun validYear(value: String?, min: Int, max: Int): Boolean { if (value == null || !value.matches(yearRegex)) return false val yearValue = value.toInt() return yearValue in min..max } fun validHeight(value: String?): Boolean { if (value == null) return false val matchResult = heightRegex.matchEntire(value) ?: return false val height = matchResult.groupValues[1].toInt() val unit = matchResult.groupValues[2] if (unit == "cm" && height >= 150 && height <= 193) return true if (unit == "in" && height >= 59 && height <= 76) return true return false } fun validHairColor(value: String?): Boolean { return value != null && value.matches(hairColorRegex) } fun validEyeColor(value: String?): Boolean { return value != null && value.matches(eyeColorRegex) } fun validPassportId(value: String?): Boolean { return value != null && value.matches(passportIdRegex) }
0
Java
0
0
78ce266dbc41d1821342edca484768167f261752
2,112
advent-of-code
Apache License 2.0
src/main/kotlin/g0601_0700/s0689_maximum_sum_of_3_non_overlapping_subarrays/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0601_0700.s0689_maximum_sum_of_3_non_overlapping_subarrays // #Hard #Array #Dynamic_Programming #2023_02_20_Time_248_ms_(100.00%)_Space_37.6_MB_(100.00%) class Solution { fun maxSumOfThreeSubarrays(nums: IntArray, k: Int): IntArray { val len = nums.size if (len < 3 * k) { return intArrayOf() } val res = IntArray(3) val left = Array(2) { IntArray(len) } val right = Array(2) { IntArray(len) } var s = 0 for (i in 0 until k) { s += nums[i] } left[0][k - 1] = s run { var i = k while (i + 2 * k <= len) { s = s + nums[i] - nums[i - k] if (s > left[0][i - 1]) { left[0][i] = s left[1][i] = i - k + 1 } else { left[0][i] = left[0][i - 1] left[1][i] = left[1][i - 1] } i++ } } s = 0 for (i in len - 1 downTo len - k) { s += nums[i] } right[0][len - k] = s right[1][len - k] = len - k for (i in len - k - 1 downTo 0) { s = s + nums[i] - nums[i + k] if (s >= right[0][i + 1]) { right[0][i] = s right[1][i] = i } else { right[0][i] = right[0][i + 1] right[1][i] = right[1][i + 1] } } var mid = 0 for (i in k until 2 * k) { mid += nums[i] } var max = 0 var i = k while (i + 2 * k <= len) { val total = left[0][i - 1] + right[0][i + k] + mid if (total > max) { res[0] = left[1][i - 1] res[1] = i res[2] = right[1][i + k] max = total } mid = mid + nums[i + k] - nums[i] i++ } return res } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,996
LeetCode-in-Kotlin
MIT License
2021/src/main/kotlin/Day10.kt
eduellery
433,983,584
false
{"Kotlin": 97092}
class Day10(private val input: List<String>) { private val pairs = setOf("()", "[]", "<>", "{}") private val closing = setOf(')', ']', '}', '>') private val points = mapOf( ')' to 3L, ']' to 57L, '}' to 1197L, '>' to 25137L, '(' to 1L, '[' to 2L, '{' to 3L, '<' to 4L ) private fun String.removePairs(): String = generateSequence(this) { prev -> pairs.fold(prev) { acc, pair -> acc.replace(pair, "") } }.zipWithNext().takeWhile { it.first != it.second }.last().second private fun List<String>.charArrays(): List<CharArray> = this.map { it.removePairs().toCharArray() } private fun List<CharArray>.corruptedScore(): Long = this.mapNotNull { it.firstOrNull { char -> char in closing } }.sumOf { points[it]!! } private fun List<CharArray>.incompleteScore(): Long = this.filterNot { it.any { char -> char in closing } }.map { it.reversed() } .map { remaining -> remaining.fold(0L) { acc, char -> acc * 5 + points[char]!! } }.sorted() .let { it.midpoint() } fun solve1(): Long { return input.charArrays().corruptedScore() } fun solve2(): Long { return input.charArrays().incompleteScore() } }
0
Kotlin
0
1
3e279dd04bbcaa9fd4b3c226d39700ef70b031fc
1,297
adventofcode-2021-2025
MIT License
src/Day10.kt
Totwart123
573,119,178
false
null
fun main() { data class MutablePair<A, B>(var first: A, var second: B) fun part1(input: List<String>): Int { val iterator = input.iterator() var cycles = 0 var register = 1 val signalStrength = mutableMapOf<Int, Int>() var maxCycles = 0 var currentExecution: MutablePair<Int, String>? = null while(cycles <= maxCycles){ if(currentExecution == null && iterator.hasNext()){ currentExecution = MutablePair(0, iterator.next().trim()) if(currentExecution.second.startsWith("noop")){ maxCycles++ } else{ maxCycles += 2 } } cycles++ println("$cycles: ${currentExecution?.second}") if(currentExecution != null){ currentExecution.first++ if(cycles % 40 == 20){ signalStrength[cycles] = cycles*register println("$cycles - ${currentExecution?.first} - ${currentExecution?.second} - ${cycles*register}") } when(currentExecution.second.take(4)){ "noop" -> { if(currentExecution.first == 1){ currentExecution = null } } "addx" -> { if(currentExecution.first == 2){ register += currentExecution.second.split(" ")[1].toInt() currentExecution = null println("register: $register") } } } } } return signalStrength.values.sum() } fun part2(input: List<String>): Int { val iterator = input.iterator() var cycles = 0 var register = 1 val signalStrength = mutableMapOf<Int, Int>() var maxCycles = 0 var currentExecution: MutablePair<Int, String>? = null val rows = MutableList(6) { MutableList(40, ){"."}} while(cycles <= maxCycles){ if(currentExecution == null && iterator.hasNext()){ currentExecution = MutablePair(0, iterator.next().trim()) assert(currentExecution != null) if(currentExecution!!.second.startsWith("noop")){ maxCycles++ } else{ maxCycles += 2 } } cycles++ println("$cycles: ${currentExecution?.second}") if(currentExecution != null){ currentExecution!!.first++ val currentCrtPosition = (cycles - 1) % 40 val currentRow = when(cycles){ in 1..40 -> 0 in 41..80 ->1 in 81..120 -> 2 in 121..160 -> 3 in 161..200 -> 4 else -> 5 } if(currentCrtPosition == register || currentCrtPosition == register + 1 || currentCrtPosition == register - 1){ rows[currentRow][currentCrtPosition] = "#" println(rows[currentRow].joinToString("")) } when(currentExecution!!.second.take(4)){ "noop" -> { if(currentExecution!!.first == 1){ currentExecution = null } } "addx" -> { if(currentExecution!!.first == 2){ register += currentExecution!!.second.split(" ")[1].toInt() currentExecution = null println("register: $register") } } } } } rows.forEach { println(it.joinToString("")) } return 0 } val testInput = readInput("Day10_test") //check(part1(testInput) == 13140) check(part2(testInput) == 0) val input = readInput("Day10") //println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
33e912156d3dd4244c0a3dc9c328c26f1455b6fb
4,290
AoC
Apache License 2.0
src/main/kotlin/pl/jpodeszwik/aoc2023/Day12.kt
jpodeszwik
729,812,099
false
{"Kotlin": 55101}
package pl.jpodeszwik.aoc2023 import java.lang.Integer.parseInt const val DAMAGED = '#' const val UNKNOWN = '?' const val WORKING = '.' data class ComputationKey(val lineIndex: Int, val numberIndex: Int) private fun solve(line: String, numbers: List<Int>): Long { return solve((line + ".").replace("[.]+".toRegex(), "."), 0, numbers, 0, HashMap()) } private fun solve(line: String, lineIndex: Int, numbers: List<Int>, numberIndex: Int, cache: MutableMap<ComputationKey, Long>): Long { // it would be much simpler to iterate over the indices instead of using recursion if (cache.containsKey(ComputationKey(lineIndex, numberIndex))) { return cache[ComputationKey(lineIndex, numberIndex)]!! } if (numberIndex >= numbers.size) { return if (IntRange(lineIndex, line.length - 1).all { line[it] != DAMAGED }) { 1 } else { 0 } } if (lineIndex >= line.length) { return 0 } if (line[lineIndex] == WORKING) { return solve(line, lineIndex + 1, numbers, numberIndex, cache).also { cache[ComputationKey(lineIndex + 1, numberIndex)] = it } } if (line[lineIndex] == UNKNOWN) { val first = numbers[numberIndex] if (line.length < first + lineIndex + 1) { return 0 } val after = line[first + lineIndex] return if (after != DAMAGED && IntRange(0, first - 1).all { line[it + lineIndex] != WORKING }) { solve(line, lineIndex + 1, numbers, numberIndex, cache).also { cache[ComputationKey(lineIndex + 1, numberIndex)] = it } + solve(line, first + lineIndex + 1, numbers, numberIndex + 1, cache).also { cache[ComputationKey(first + lineIndex + 1, numberIndex + 1)] = it } } else { solve(line, lineIndex + 1, numbers, numberIndex, cache).also { cache[ComputationKey(lineIndex + 1, numberIndex)] = it } } } if (line[lineIndex] == DAMAGED) { val first = numbers[numberIndex] if (line.length < first + lineIndex + 1) { return 0 } val after = line[first + lineIndex] return if (after != DAMAGED && IntRange(0, first - 1).all { line[it + lineIndex] != WORKING }) { solve(line, first + lineIndex + 1, numbers, numberIndex + 1, cache).also { cache[ComputationKey(first + lineIndex + 1, numberIndex + 1)] = it } } else { 0 } } return 0 } private fun part1(lines: List<String>) { var sum = 0L lines.forEach { val parts = it.split(" ") val numbers = parts[1].split(",").map { parseInt(it) } val value = solve(parts[0], numbers) sum += value } println(sum) } private fun part2(lines: List<String>) { var sum = 0L lines.forEach { it -> val parts = it.split(" ") val numbers = parts[1].split(",").map { parseInt(it) } val line = parts[0] var newLine = "" val newNumbers = ArrayList<Int>() for (i in 0..<5) { if (i != 0) { newLine += UNKNOWN } newLine += line newNumbers.addAll(numbers) } val value = solve(newLine, newNumbers) sum += value } println(sum) } fun main() { val lines = loadFile("/aoc2023/input12") part1(lines) part2(lines) }
0
Kotlin
0
0
2b90aa48cafa884fc3e85a1baf7eb2bd5b131a63
3,492
advent-of-code
MIT License
src/main/kotlin/com/scavi/brainsqueeze/adventofcode/Day4PassportProcessing.kt
Scavi
68,294,098
false
{"Java": 1449516, "Kotlin": 59149}
package com.scavi.brainsqueeze.adventofcode class Day4PassportProcessing { private val mandatoryFields = setOf("byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid") private val pidRegex = """^\d{9}$""".toRegex() private val hgtRegex = """^(\d+)(cm|in)$""".toRegex() private val hclRegex = """#[a-f0-9]{6}""".toRegex() private val eyeColors = setOf("amb", "blu", "brn", "gry", "grn", "hzl", "oth") fun solve(input: String, isStrict: Boolean): Int { var validPassports = 0 val passports = input.split("\n\n") for (passport in passports) { val details = passport.trim().replace("\n", " ").split(" ").associate { Pair(it.split(":")[0], it.split(":")[1]) } if (details.size >= 7) { var isValid = true for (field in mandatoryFields) { isValid = isValid && details.contains(field) if (isStrict) { val value = details.getOrDefault(field, "") isValid = isValid && value.isNotEmpty() && validate(field, value) } } validPassports += if (isValid) 1 else 0 } } return validPassports } // the when function reduces the original solution where mapped validation functions were used // by 12 lines // Reference: // https://github.com/shaeberling/euler/blob/master/kotlin/src/com/s13g/aoc/aoc2020/Day4.kt#42 private fun validate(field: String, value: String) : Boolean { return when (field) { "byr" -> value.toInt() in 1920..2002 "iyr" -> value.toInt() in 2010..2020 "eyr" -> value.toInt() in 2020..2030 "hgt" -> { val groups = hgtRegex.find(value) if (groups == null) false else { val number = groups.groupValues[1].toInt() when(groups.groupValues[2]) { "cm" -> number in 150..193 "in" -> number in 59..76 else -> false } } } "hcl" -> hclRegex.containsMatchIn(value) "ecl" -> eyeColors.contains(value) "pid" -> pidRegex.containsMatchIn(value) else -> false } } }
0
Java
0
1
79550cb8ce504295f762e9439e806b1acfa057c9
2,393
BrainSqueeze
Apache License 2.0
src/main/kotlin/com/staricka/adventofcode2022/Day24.kt
mathstar
569,952,400
false
{"Kotlin": 77567}
package com.staricka.adventofcode2022 import com.staricka.adventofcode2022.Day24.Zone.Companion.parseZone class Day24 : Day { override val id = 24 enum class Direction(val vec: Pair<Int, Int>) { UP(Pair(-1, 0)), RIGHT(Pair(0, 1)), DOWN(Pair(1,0)), LEFT(Pair(0,-1)); fun step(i: Int, j: Int): Pair<Int, Int> = step(Pair(i,j)) fun step(p: Pair<Int, Int>): Pair<Int, Int> = Pair(vec.first + p.first, vec.second + p.second) } class Zone( val width: Int, val height: Int, val blizzards: Map<Int, Map<Int, List<Direction>>>, val playerPositions: Set<Pair<Int, Int>> = setOf(Pair(0,1)), val goal: Pair<Int, Int> = Pair(height - 1, width - 2) ) { val done = playerPositions.contains(goal) fun step(): Zone { val steppedBlizzards = HashMap<Int, HashMap<Int, ArrayList<Direction>>>() for ((i, m) in blizzards) { for ((j, dl) in m) { for (d in dl) { var (si, sj) = d.step(i, j) if (si == 0) si = height - 2 if (sj == 0) sj = width - 2 if (si == height - 1) si = 1 if (sj == width - 1) sj = 1 steppedBlizzards.computeIfAbsent(si) { HashMap() }.computeIfAbsent(sj) { ArrayList() }.add(d) } } } val steppedPlayer = playerPositions.flatMap { listOf( it, Direction.UP.step(it), Direction.RIGHT.step(it), Direction.DOWN.step(it), Direction.LEFT.step(it) ) }.filter { (i, j) -> (i == 0 && j == 1) || (i == height - 1 && j == width - 2) || i > 0 && i < height - 1 && j > 0 && j < width - 1 && steppedBlizzards[i]?.get(j) == null }.toSet() return Zone(width, height, steppedBlizzards, steppedPlayer, goal) } companion object { fun String.parseZone() : Zone { val width = this.lines().first().length val height = this.lines().size val blizzards = HashMap<Int, HashMap<Int, List<Direction>>>() for ((i, line) in this.lines().withIndex()) { for ((j, c) in line.withIndex()) { val d = when(c) { '^' -> Direction.UP '>' -> Direction.RIGHT 'v' -> Direction.DOWN '<' -> Direction.LEFT else -> null } if (d != null) blizzards.computeIfAbsent(i) {HashMap()}[j] = listOf(d) } } return Zone(width, height, blizzards) } } } override fun part1(input: String): Any { var zone = input.parseZone() var steps = 0 while (!zone.done) { steps++ zone = zone.step() } return steps } override fun part2(input: String): Any { var zone = input.parseZone() var steps = 0 while (!zone.done) { steps++ zone = zone.step() } zone = Zone( zone.width, zone.height, zone.blizzards, setOf(zone.goal), Pair(0, 1) ) while (!zone.done) { steps++ zone = zone.step() } zone = Zone( zone.width, zone.height, zone.blizzards, setOf(zone.goal), Pair(zone.height - 1, zone.width - 2) ) while (!zone.done) { steps++ zone = zone.step() } return steps } }
0
Kotlin
0
0
2fd07f21348a708109d06ea97ae8104eb8ee6a02
3,308
adventOfCode2022
MIT License
ceria/05/src/main/kotlin/Solution.kt
VisionistInc
317,503,410
false
null
import java.io.File; fun main(args : Array<String>) { val input = File(args.first()).readLines() println("Solution 1: ${solution1(input)}") println("Solution 2: ${solution2(input)}") } private fun solution1(input :List<String>) :Int { var seatIDs = mutableListOf<Int>() for (boardingPass in input) { seatIDs.add(getSeatID(boardingPass)) } var sortedSeatIDs = seatIDs.toIntArray() sortedSeatIDs.sort() return sortedSeatIDs.last() } private fun solution2(input :List<String>) :Int { var seatIDs = mutableListOf<Int>() for (boardingPass in input) { seatIDs.add(getSeatID(boardingPass)) } var sortedSeatIDs = seatIDs.toIntArray() sortedSeatIDs.sort() var previousSeat = sortedSeatIDs.first() for (seatID in sortedSeatIDs.drop(1)) { if (seatID - previousSeat == 2) { return seatID - 1 } previousSeat = seatID } return -1 } private fun getSeatID(boardingPass :String) :Int { var seatRow = IntRange(0, 127).toList() var seatCol = IntRange(0, 7).toList() boardingPass.forEach { when (it) { 'F' -> { val middleIndex = if (seatRow.size / 2 % 2 == 1) seatRow.size / 2 - 1 else seatRow.size / 2 seatRow = IntRange(seatRow.first(), seatRow.get(middleIndex)).toList() } 'B' -> { val middleIndex = seatRow.size / 2 seatRow = IntRange(seatRow.get(middleIndex), seatRow.last()).toList() } 'L' -> { val middleIndex = if (seatCol.size % 2 == 1) seatCol.size / 2 + 1 else seatCol.size / 2 - 1 seatCol = IntRange(seatCol.first(), seatCol.get(middleIndex)).toList() } 'R' -> { val middleIndex = if (seatCol.size % 2 == 1) seatCol.size / 2 + 1 else seatCol.size / 2 seatCol = IntRange(seatCol.get(middleIndex), seatCol.last()).toList() } } } return seatRow.get(0) * 8 + seatCol.get(0) }
0
Rust
0
0
002734670384aa02ca122086035f45dfb2ea9949
2,082
advent-of-code-2020
MIT License
src/main/kotlin/ru/timakden/aoc/year2022/Day11.kt
timakden
76,895,831
false
{"Kotlin": 321649}
package ru.timakden.aoc.year2022 import ru.timakden.aoc.util.lcm import ru.timakden.aoc.util.measure import ru.timakden.aoc.util.readInput import ru.timakden.aoc.year2022.Day11.Monkey.Companion.toMonkey /** * [Day 11: Monkey in the Middle](https://adventofcode.com/2022/day/11). */ object Day11 { @JvmStatic fun main(args: Array<String>) { measure { val input = readInput("year2022/Day11") println("Part One: ${part1(input)}") println("Part Two: ${part2(input)}") } } fun part1(input: List<String>): Long { val rounds = 20 val monkeys = input.fold<String, MutableList<MutableList<String>>>(mutableListOf(mutableListOf())) { acc, item -> if (item.isBlank()) acc.add(mutableListOf()) else acc.last().add(item) acc }.map { it.toMonkey() } repeat(rounds) { monkeys.forEach { monkey -> while (monkey.items.isNotEmpty()) { monkey.itemsInspectedCount++ val item = monkey.items.removeFirst() val split = monkey.operation.substringAfter("= ").split(' ') val number1 = if (split[0] == "old") item else split[0].toLong() val number2 = if (split[2] == "old") item else split[2].toLong() val newItem = when (split[1]) { "+" -> number1 + number2 "-" -> number1 - number2 "/" -> number1 / number2 "*" -> number1 * number2 else -> error("Unsupported operand") }.div(3) val newMonkey = if (newItem % monkey.testNumber == 0L) monkeys.find { it.name.substringAfter(' ').toInt() == monkey.trueMonkeyIndex } else monkeys.find { it.name.substringAfter(' ').toInt() == monkey.falseMonkeyIndex } newMonkey?.items?.add(newItem) } } } return monkeys.sortedByDescending { it.itemsInspectedCount } .take(2) .map { it.itemsInspectedCount } .reduce { a, b -> a * b } } fun part2(input: List<String>): Long { val rounds = 10000 val monkeys = input.fold<String, MutableList<MutableList<String>>>(mutableListOf(mutableListOf())) { acc, item -> if (item.isBlank()) acc.add(mutableListOf()) else acc.last().add(item) acc }.map { it.toMonkey() } val lcm = monkeys.map { it.testNumber }.reduce(::lcm) repeat(rounds) { monkeys.forEach { monkey -> while (monkey.items.isNotEmpty()) { monkey.itemsInspectedCount++ val item = monkey.items.removeFirst() val split = monkey.operation.substringAfter("= ").split(' ') val number1 = if (split[0] == "old") item else split[0].toLong() val number2 = if (split[2] == "old") item else split[2].toLong() val newItem = when (split[1]) { "+" -> number1 + number2 "-" -> number1 - number2 "/" -> number1 / number2 "*" -> number1 * number2 else -> throw IllegalArgumentException() } val newMonkey = if (newItem % monkey.testNumber == 0L) monkeys.find { m -> m.name.substringAfter(' ').toInt() == monkey.trueMonkeyIndex } else monkeys.find { m -> m.name.substringAfter(' ').toInt() == monkey.falseMonkeyIndex } newMonkey?.items?.add(newItem % lcm) } } } return monkeys.sortedByDescending { it.itemsInspectedCount } .take(2) .map { it.itemsInspectedCount } .reduce { a, b -> a * b } } private class Monkey( val name: String, val items: MutableList<Long>, val operation: String, val testNumber: Long, val trueMonkeyIndex: Int, val falseMonkeyIndex: Int, var itemsInspectedCount: Long = 0 ) { companion object { fun List<String>.toMonkey(): Monkey { val name = this.first().substringBefore(':') val items = "\\d+".toRegex().findAll(this[1]).map { it.value }.map { it.toLong() }.toMutableList() val operation = this[2].substringAfter(": ") val testNumber = checkNotNull("\\d+".toRegex().find(this[3])?.value?.toLong()) val trueMonkeyIndex = checkNotNull("\\d+".toRegex().find(this[4])?.value?.toInt()) val falseMonkeyIndex = checkNotNull("\\d+".toRegex().find(this[5])?.value?.toInt()) return Monkey(name, items, operation, testNumber, trueMonkeyIndex, falseMonkeyIndex) } } } }
0
Kotlin
0
3
acc4dceb69350c04f6ae42fc50315745f728cce1
5,183
advent-of-code
MIT License
src/main/java/NumberSolver.kt
Koallider
557,760,682
false
{"Kotlin": 8930}
import java.util.* import kotlin.collections.ArrayList import kotlin.collections.HashSet class NumberSolver @JvmOverloads internal constructor( var target: Int, var nums: List<Int>, var findAllSolutions: Boolean = true ) { private val intRegex = """^[+-]*\d*$""".toRegex() var mem: HashMap<String, HashMap<Int, HashSet<String>>> = HashMap() var solutionFound = false fun solve(): Set<String>? { val result = solve(nums.toMutableList()) return result[target] } private fun solve(nums: MutableList<Int>): HashMap<Int, HashSet<String>> { val result = HashMap<Int, HashSet<String>>() if (!findAllSolutions && solutionFound) return result if (nums.size == 1) { val x = nums[0] addResult(result, x, "$x") return result } nums.sort() val numsToString = nums.joinToString(",") if (mem.containsKey(numsToString)) return mem[numsToString]!! for (subset in subsets(nums)) { val comp = subtractList(nums, subset) if (subset.isEmpty() || comp.isEmpty() || subset.size < comp.size) continue val s1 = solve(subset.toMutableList()) val s2 = solve(comp.toMutableList()) for (r1 in s1.keys) { addResults(result, r1, s1[r1]!!) for (r2 in s2.keys) { addResults(result, r2, s2[r2]!!) if(r1 > r2) { addResults(result, r1 + r2, comb(s1[r1]!!, "+", s2[r2]!!)) addResults(result, r1 * r2, comb(s1[r1]!!, "*", s2[r2]!!)) } addResults(result, r1 - r2, comb(s1[r1]!!, "-", s2[r2]!!)) addResults(result, r2 - r1, comb(s2[r2]!!, "-", s1[r1]!!)) if (r1 != 0 && r2 % r1 == 0) { addResults(result, r2 / r1, comb(s2[r2]!!, "/", s1[r1]!!)) } if (r2 != 0 && r1 % r2 == 0) { addResults(result, r1 / r2, comb(s1[r1]!!, "/", s2[r2]!!)) } } } } mem[numsToString] = result if (result.containsKey(target)) { solutionFound = true } return result } private fun subsets(nums: List<Int>): List<List<Int>> { val result: MutableList<List<Int>> = ArrayList() result.add(LinkedList<Int>().apply { add(nums[0]) }) if (nums.size == 1) { return result } val temp = nums.toMutableList() val x = temp.removeAt(0) for (part in subsets(temp)) { result.add(ArrayList(part)) result.add(mutableListOf(x).apply { addAll(part)}) } return result } private fun subtractList(complete: List<Int>, subset: List<Int>): List<Int> { return complete.filter { !subset.contains(it) } } private fun isSingleInt(x: String): Boolean { return x.matches(intRegex) } private fun addResult(map: HashMap<Int, HashSet<String>>, key: Int, solution: String) { val set = map.getOrPut(key){ HashSet() } set.add(solution) } private fun addResults(map: HashMap<Int, HashSet<String>>, key: Int, solutions: HashSet<String>) { val set = map.getOrPut(key){ HashSet() } set.addAll(solutions) } private fun comb(s1: HashSet<String>, op: String, s2: HashSet<String>): HashSet<String> { val result = HashSet<String>() for (a in s1) { for (b in s2) { result.add(operationToString(a, op, b)) } } return result } private fun operationToString(a: String, op: String, b: String): String { if (isSingleInt(a) && isSingleInt(b)) return a + op + b if (isSingleInt(a)) return "$a$op($b)" return if (isSingleInt(b)) "($a)$op$b" else "($a)$op($b)" } companion object { @JvmStatic fun main(args: Array<String>) { val target = 765 val nums = listOf(75, 25, 4, 2, 8 ,6) val solver = NumberSolver(target, nums) val solution = solver.solve() if (solution?.isNotEmpty() == true) { println("It is possible") for (str in solution) { println(str) } } else { println("Its not possible") } } } }
0
Kotlin
0
0
9faa2e3e14d1daba1d6a9e4530f03b22ddeace77
4,502
8OO10CDC
Apache License 2.0
src/main/kotlin/men/zhangfei/leetcode/medium/Problem0003.kt
fitzf
257,562,586
false
{"Kotlin": 9251}
package men.zhangfei.leetcode.medium /** * 3. 无重复字符的最长子串 * https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/ */ class Problem0003 { companion object { /** * 滑动窗口算法 * 1. 使用 HashSet 作为滑动窗口,存储字符 * 2. 设置窗口的左边和右边索引为 0 val l = 0, val r = 0 * 3. 循环判断窗口中是否包含字符串【s】右边索引下的字符,直到窗口滑动到字符串的末尾 * a. 不包含:右边索引右移 r++ 并更新窗口的最大长度 max = max(已存储的最大长度, 当前窗口长度) * b. 包含:左边索引右移 l++ 如果移动后的左边索引到末尾的长度不大于已存在的最大长度的话 跳出循环 */ fun slidingWindow(s: String): Int = when { s.isEmpty() -> 0 s.length == 1 -> 1 else -> { var max = 0 val len = s.length var l = 0 var r = 0 val set: MutableSet<Char> = mutableSetOf() while (r < len) { if (set.contains(s[r])) { set.remove(s[l++]) if (len - l <= max) { break } } else { set.add(s[r++]) max = max.coerceAtLeast(r - l) } } max } } /** * 优化的滑动窗口 * 0. 初始化窗口左边和右边的索引为 0 l = 0, r = 0 * 1. 窗口右边索引递增循环 r++; r < s.length * 2. 如果当前右边索引下的字符已经存在,则判断 当前左边索引 > (该字符上次索引 + 1) l > (map[s[\r]] + 1) * a. 是:则说明 (该字符上次索引 + 1) 至 当前左边索引中有其它重复字符,所以忽略,不改变左边索引 l * b. 否:将左边索引移动到 (该字符上次索引 + 1) 的位置 l = (map[s[\r]] + 1) * 4. 更新最长子串长度 max = max(已存储的最大长度, 当前窗口长度) * 5. 将当前右边索引和字符存入 HashMap<字符,索引>. e.g. {"a": 0, "b": 1} * 6. 转到 1 步 */ fun optimizedSlidingWindow(s: String): Int = when { s.isEmpty() -> 0 s.length == 1 -> 1 else -> { var max = 0 val len = s.length var l = 0 var c: Char val map: HashMap<Char, Int> = hashMapOf() for (r in 0 until len) { c = s[r] map[c]?.let { // 防止左边索引回跳 l = l.coerceAtLeast(it + 1) } max = max.coerceAtLeast(r - l + 1) map[c] = r } max } } } }
1
Kotlin
0
0
a2ea7df7c1e4857808ab054d253dea567049658a
3,082
leetcode
Apache License 2.0
src/main/aoc2020/Day24.kt
nibarius
154,152,607
false
{"Kotlin": 963896}
package aoc2020 import AMap import Pos import toDirection class Day24(input: List<String>) { // Represent the hex grid as a normal 2 dimensional map (there are just some limits on adjacency) val map = AMap().apply { input.forEach { line -> val pos = parse(line) val current = this.getOrDefault(pos, 'W') this[pos] = if (current == 'W') 'B' else 'W' } } private fun Pos.allHexNeighbours(): List<Pos> { // tiles at (-1, -1) and (1, 1) are not adjacent to (0,0), all other are return Pos.allDeltas(true) .subtract(setOf(Pos(-1, -1), Pos(1, 1))) .map { delta -> Pos(x + delta.x, y + delta.y) } } private fun parse(line: String): Pos { val iterator = line.iterator() var pos = Pos(0, 0) while (iterator.hasNext()) { when (val char = iterator.nextChar()) { 'e', 'w' -> pos = pos.move(char.toDirection()) // e, w ==> x +,- 1 's', 'n' -> { pos = pos.move(char.toDirection()) // s, n ==> y +,- 1 val next = iterator.nextChar() if ("$char$next" in listOf("sw", "ne")) { // sw, ne additionally moves x +,- 1 pos = pos.move(next.toDirection()) } } } } return pos } private fun rearrange() { repeat(100) { val copy = map.copy() val black = copy.toMap().filterValues { it == 'B' } val xr = black.minByOrNull { it.key.x }!!.key.x - 1..black.maxByOrNull { it.key.x }!!.key.x + 1 val yr = black.minByOrNull { it.key.y }!!.key.y - 1..black.maxByOrNull { it.key.y }!!.key.y + 1 for (y in yr) { for (x in xr) { val pos = Pos(x, y) val current = copy.getOrDefault(pos, 'W') val blackNeighbours = pos.allHexNeighbours().count { copy[it] == 'B' } when { current == 'W' && blackNeighbours == 2 -> map[pos] = 'B' current == 'B' && (blackNeighbours == 0 || blackNeighbours > 2) -> map[pos] = 'W' } } } } } fun solvePart1(): Int { return map.values.count { it == 'B' } } fun solvePart2(): Int { rearrange() return map.values.count { it == 'B' } } }
0
Kotlin
0
6
f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22
2,489
aoc
MIT License
src/main/kotlin/year_2022/Day10.kt
krllus
572,617,904
false
{"Kotlin": 97314}
package year_2022 import utils.readInput fun main() { fun part1(input: List<String>): Int { val cycleValueMap = mutableMapOf<Int, Int>() cycleValueMap[0] = 1 var cycleCount = 0 input.forEach { if (it.startsWith("noop")) { ++cycleCount cycleValueMap[cycleCount] = cycleValueMap[cycleCount - 1] ?: error("previous value not defined $cycleCount") } if (it.startsWith("addx")) { val value = it.split(" ").last().toInt() ++cycleCount cycleValueMap[cycleCount] = cycleValueMap[cycleCount - 1] ?: error("previous value not defined $cycleCount") ++cycleCount cycleValueMap[cycleCount] = cycleValueMap[cycleCount - 1]?.plus(value) ?: error("previous value not defined $cycleCount") } } var sum = 0 for (a in listOf(20, 60, 100, 140, 180, 220)) { val cal = a * cycleValueMap[a - 1]!! sum += cal } return sum } fun part2(input: List<String>): String { val cycleValueMap = mutableMapOf<Int, Int>() cycleValueMap[0] = 1 var cycleCount = 0 val sprite = Array(241) { '0' } input.forEach { str -> val parsedIndex = (cycleCount % 40) + 1 val drawRange = listOf(parsedIndex - 1, parsedIndex, parsedIndex + 1) var currentValue: Int? if (str.startsWith("noop")) { cycleCount++ cycleValueMap[cycleCount] = cycleValueMap[cycleCount - 1] ?: error("previous value not defined $cycleCount") currentValue = cycleValueMap[cycleCount] if (currentValue in drawRange) { sprite[cycleCount - 1] = '#' } else { sprite[cycleCount - 1] = '.' } } if (str.startsWith("addx")) { val value = str.split(" ").last().toInt() cycleCount++ cycleValueMap[cycleCount] = cycleValueMap[cycleCount - 1] ?: error("previous value not defined $cycleCount") sprite[cycleCount - 1] = '.' currentValue = cycleValueMap[cycleCount] if (currentValue in drawRange) { sprite[cycleCount - 1] = '#' } else { sprite[cycleCount - 1] = '.' } cycleCount++ cycleValueMap[cycleCount] = cycleValueMap[cycleCount - 1]?.plus(value) ?: error("previous value not defined $cycleCount") sprite[cycleCount - 1] = '.' currentValue = cycleValueMap[cycleCount] if (currentValue in drawRange) { sprite[cycleCount - 1] = '#' } else { sprite[cycleCount - 1] = '.' } } } val result = StringBuilder() sprite.forEachIndexed { index, char -> result.append(char) if ((index + 1) % 40 == 0) result.append('\n') } return result.toString() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day10_test") // check(part1(testInput) == 13140) println(part2(testInput)) // CJAPJRE val input = readInput("Day10") // println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
b5280f3592ba3a0fbe04da72d4b77fcc9754597e
3,617
advent-of-code
Apache License 2.0
src/main/kotlin/g0901_1000/s0963_minimum_area_rectangle_ii/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0901_1000.s0963_minimum_area_rectangle_ii // #Medium #Array #Math #Geometry #2023_05_04_Time_183_ms_(100.00%)_Space_38.7_MB_(66.67%) import kotlin.math.abs class Solution { fun minAreaFreeRect(points: Array<IntArray>): Double { val map: MutableMap<Int, MutableSet<Int>> = HashMap() var area: Double for (point in points) { map.putIfAbsent(point[0], HashSet()) map.getValue(point[0]).add(point[1]) } var minArea = Double.MAX_VALUE val n = points.size for (i in 0 until n - 2) { for (j in i + 1 until n - 1) { val dx1 = points[j][0] - points[i][0] val dy1 = points[j][1] - points[i][1] // get the 3rd point for (k in j + 1 until n) { val dx2 = points[k][0] - points[i][0] val dy2 = points[k][1] - points[i][1] if (dx1 * dx2 + dy1 * dy2 != 0) { continue } // find the 4th point val x = dx1 + points[k][0] val y = dy1 + points[k][1] area = calculateArea(points, i, j, k) if (area >= minArea) { continue } // 4th point exists if (map[x] != null && map.getValue(x).contains(y)) { minArea = area } } } } return if (minArea == Double.MAX_VALUE) 0.0 else minArea } private fun calculateArea(points: Array<IntArray>, i: Int, j: Int, k: Int): Double { val first = points[i] val second = points[j] val third = points[k] return abs( first[0] * (second[1] - third[1]) + second[0] * (third[1] - first[1]) + third[0] * (first[1] - second[1]) ).toDouble() } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,956
LeetCode-in-Kotlin
MIT License
Futoshiki Solver/Main.kt
JChoPop
429,859,326
false
{"Kotlin": 20296}
// By HJC 2021-11-21 // 5x5 Futoshiki (Inequality/Unequal Puzzle) // only works when solution exists... for now... // const val puzzle = """ |0-0>0-0-0| |- - - - -| |0-0-0-0-0| |v v ^ - -| |0-0>0-0-0| |- - - ^ -| |4-0-0-0-0| |^ - - - v| |0-0-0-0-0| """ // //fun isEven(num: Int) = num % 2 == 0 val num = mutableListOf<Int>() val sig = mutableMapOf<Int, MutableSet<Int>>() var ind = 0 var dir = 1 var signFlag = false var tries = 0 // fun main() { println(puzzle) stringify(puzzle) println("num: $num") // num: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0] println("sig: $sig\n") // sig: {1=[2], 5=[10], 6=[11], 12=[7], 11=[12], 18=[13], 20=[15], 19=[24]} val sol = num.toMutableList() while (ind < sol.count()) solve(sol, ind, dir) val finalList = sol.toList() printBoard(finalList) } // fun stringify(input: String) { fun setOrAddSign(big: Int, small: Int) { if (sig[big].isNullOrEmpty()) sig[big] = mutableSetOf(small) else sig[big]!!.add(small) } val temp = input.trimMargin().split("|\n") // println("temp: $temp") // [0-0>0-0-0, - - - - -, 0-0-0-0-0, v v ^ - -, 0-0>0-0-0, - - - ^ -, 4-0-0-0-0, ^ - - - v, 0-0-0-0-0] for (i in 0..8) { jloop@ for (j in 0..8) { when (val want = temp[i][j].digitToIntOrNull() ?: temp[i][j]) { ' ', '-' -> continue@jloop is Int -> num.add(want) is Char -> { val (big, small) = when (want) { // key is always greater than value '>' -> Pair(num.lastIndex, num.count()) '<' -> Pair(num.count(), num.lastIndex) 'v' -> Pair(num.count() + j/2 - 5, num.count() + j/2) '^' -> Pair(num.count() + j/2, num.count() + j/2 - 5) else -> throw Exception("Invalid Inequality Symbol (e.g: uppercase V should be lowercase v)") } setOrAddSign(big, small) } } } } } // fun solve(sol: MutableList<Int>, tempind: Int, tempdir: Int) { ind = tempind dir = tempdir while (tryAgain(ind, sol) || dir == -1) { when { sol[ind] != 0 && sol[ind] == num[ind] -> { println("skipping fixed number"); ind += dir } dir == -1 -> if (ind % 5 == 4 || ind >= 20 || sol[ind] == 5) { sol[ind] = 0; ind += dir } else { sol[ind] += 1; dir = 1 println("incremented and U-turn") } dir == 1 -> when { ind % 5 == 4 && sol[ind] == 0 -> { sol[ind] = 15 - sol.slice((ind - 4)..ind).sum() } ind >= 20 && sol[ind] == 0 -> { sol[ind] = 15 - sol.slice((ind % 5)..ind step 5).sum() } sol[ind] == 5 || (ind % 5 == 4 || ind >= 20) -> { sol[ind] = 0; dir = -1 println("reset to 0 and backtracking"); report(sol) break } else -> { sol[ind] += 1; println("incremented") } } } report(sol) } ind += dir println(" next index") // need conditions for completion/no solution } // fun report(sol: MutableList<Int>) { val arrow = if (dir == 1) '→' else '←' println("\nind: $ind, dir: $arrow, sol: $sol") } // // num: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0] // sig: {1=[2], 5=[10], 6=[11], 12=[7], 11=[12], 18=[13], 20=[15], 19=[24]} // fun tryAgain(ind: Int, sol: MutableList<Int>): Boolean { val noDup = sol.slice((0 until ind).filter { it % 5 == ind % 5 || it / 5 == ind / 5 }) println("trying [${sol[ind]}] against $noDup") tries++ // val signPairs = mutableSetOf<Pair<Int, Int>>() if (ind > 4) signPairs.addAll(setOf(Pair(ind, ind - 5), Pair(ind - 5, ind))) if (ind % 5 > 0) signPairs.addAll(setOf(Pair(ind, ind - 1), Pair(ind - 1, ind))) signPairs.reversed().forEach { (k, v) -> if (sig[k]?.contains(v) != true) signPairs -= Pair(k,v) } // signFlag = signPairs.any { (G, s) -> sol[G] < sol[s] }.also { if (it) println(" → inequality disagreement") } return noDup.contains(sol[ind]) || sol[ind] == 0 || signFlag } // fun printBoard(finalList: List<Int>) { println("\n[$tries tries] → Complete!\n") var output = puzzle val outputIter = finalList.listIterator() puzzle.forEachIndexed { charNum, it -> if (it.isDigit()) output = output.replaceRange(charNum, charNum+1, outputIter.next().toString()) } println(output) } // // Solution: // 13254 // 35142 // 24315 // 41523 // 52431 // // Final output: // [2493 tries] → Complete! // // // |1-3>2-5-4| // |- - - - -| // |3-5-1-4-2| // |v v ^ - -| // |2-4>3-1-5| // |- - - ^ -| // |4-1-5-2-3| // |^ - - - v| // |5-2-4-3-1| // // // // //
0
Kotlin
0
0
3fb587f2af747acc29886cdc2a02653196326dbf
5,378
kotlin_projects
MIT License
src/main/kotlin/com/leetcode/P1504.kt
antop-dev
229,558,170
false
{"Kotlin": 695315, "Java": 213000}
package com.leetcode // https://leetcode.com/problems/count-submatrices-with-all-ones/ class P1504 { fun numSubmat(mat: Array<IntArray>): Int { // For each row i, create an array nums where: if mat[i][j] == 0 then nums[j] = 0 else nums[j] = nums[j-1] +1. for (i in mat.indices) { for (j in 1 until mat[i].size) { mat[i][j] = if (mat[i][j] == 1) mat[i][j - 1] + 1 else 0 } } var submatrices = 0; // In the row i, number of rectangles between column j and k(inclusive) and ends in row i, is equal to SUM(min(nums[j, .. idx])) where idx go from j to k. // Expected solution is O(n^3). for (i in mat.lastIndex downTo 0) { for (j in mat[i].indices) { submatrices += mat[i][j] + (0 until i).map { k -> (k..i).map { idx -> mat[idx][j] }.min()!! }.sum() } } return submatrices } }
1
Kotlin
0
0
9a3e762af93b078a2abd0d97543123a06e327164
971
algorithm
MIT License
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2021/2021-07.kt
ferinagy
432,170,488
false
{"Kotlin": 787586}
package com.github.ferinagy.adventOfCode.aoc2021 import com.github.ferinagy.adventOfCode.println import com.github.ferinagy.adventOfCode.readInputText import kotlin.math.abs fun main() { val input = readInputText(2021, "07-input") val test1 = readInputText(2021, "07-test1") println("Part1:") part1(test1).println() part1(input).println() println() println("Part2:") part2(test1).println() part2(input).println() } private fun part1(input: String): Int { return calculateCrabPosition(input, fuelCaclulation = { it }) } private fun part2(input: String): Int { val fuelTable = Array(2000) { 0 } for (i in 1..fuelTable.lastIndex) { fuelTable[i] = fuelTable[i - 1] + i } return calculateCrabPosition(input, fuelCaclulation = { fuelTable[it] }) } private fun calculateCrabPosition(input: String, fuelCaclulation: (Int) -> Int): Int { val list = input.split(",").map { it.toInt() } val min = list.minOrNull()!! val max = list.maxOrNull()!! return (min..max).map { position -> list.sumOf { fuelCaclulation(abs(it - position)) } }.minOrNull()!! }
0
Kotlin
0
1
f4890c25841c78784b308db0c814d88cf2de384b
1,141
advent-of-code
MIT License
src/main/kotlin/Heuristic2D.kt
MatteoMartinelli97
403,882,570
false
{"Kotlin": 39512}
import kotlin.math.abs import kotlin.math.min import kotlin.math.sqrt /** * This object implements some common heuristic functions for a square (or rectangular) grid, where every * square is a node of the graph. * The name are given as [Int] numbers, from left to right, top to bottom as: * * +--------------+ * * | 0 | 1 | 2| 3| 4 | * * | 5 | 6 | 7| 8| 9 | * * |10|11|12|13|14| * * |15|16|17|18|19| * * |20|21|22|23|24| * +--------------+ */ object Heuristic2D { /** * A trivial heuristic that returns always 0. * It is useful as it makes A* become Dijkstra */ fun trivial (width : Int = 10) : (Int, Int) -> Float { return {a, b, -> 0f} } /** * [Manhattan distance](https://en.wikipedia.org/wiki/Taxicab_geometry) * on a squared grid of side = [width] */ fun manhattan(width: Int): (Int, Int) -> Float { return { a, b -> val A = getCoordinates(a, width) val B = getCoordinates(b, width) val dx = abs(A.second - B.second) val dy = abs(A.first - B.first) (dx + dy).toFloat() } } /** * Similar to Manhattan distance, but considering also the possibility of walking * diagonally across the squares, by paying a cost [diagonalCost], which may be different from * [lateralCost], that is the cost of moving along the 4 cardinal directions. * * Default values return [Chebyshev distance](https://en.wikipedia.org/wiki/Chebyshev_distance) */ fun diagonal(width : Int, lateralCost : Float = 1f, diagonalCost : Float = 1f): (Int, Int) -> Float { return { a, b -> val A = getCoordinates(a, width) val B = getCoordinates(b, width) val dx = abs(A.second - B.second) val dy = abs(A.first - B.first) lateralCost * (dx + dy) + (diagonalCost - 2f * lateralCost) * min(dx, dy) } } /** * Wrapper for [diagonal] distance, with the particular values for costs: * - lateralCost = 1 * - diagonalCost = sqrt(2) */ fun octile (width: Int): (Int, Int) -> Float { return diagonal(width, lateralCost = 1f, diagonalCost = sqrt(2f)) } /** * Euclidean distance on a squared grid with side = [width] */ fun euclidean(width: Int): (Int, Int) -> Float { return { a, b -> val A = getCoordinates(a, width) val B = getCoordinates(b, width) val dx = abs(A.second - B.second) val dy = abs(A.first - B.first) sqrt( (dx*dx + dy*dy).toFloat() ) } } private fun getCoordinates(id : Int, width: Int) : Pair<Int, Int> { val row = id / width val col = id % width return Pair(row, col) } }
0
Kotlin
0
0
f14d4ba7058be629b407e06eebe09fae63aa35c1
2,796
Dijkstra-and-AStar
Apache License 2.0
src/Day04.kt
ezeferex
575,216,631
false
{"Kotlin": 6838}
fun String.getSections() = this.split(",") .map { it.split("-").let { section -> Pair(section[0].toInt(), section[1].toInt()) }} .let { pairSection -> Pair(pairSection[0], pairSection[1]) } fun main() { fun part1() = readInput("04").split("\n") .count { val sections = it.getSections() (sections.second.first in sections.first.first..sections.first.second && sections.second.second in sections.first.first..sections.first.second) || (sections.first.first in sections.second.first..sections.second.second && sections.first.second in sections.second.first..sections.second.second) } fun part2() = readInput("04").split("\n") .count { val sections = it.getSections() !(sections.second.first > sections.first.second || sections.first.first > sections.second.second) } println("Part 1: " + part1()) println("Part 2: " + part2()) }
0
Kotlin
0
0
f06f8441ad0d7d4efb9ae449c9f7848a50f3f57c
984
advent-of-code-2022
Apache License 2.0
src/AOC2022/Day01/Day01.kt
kfbower
573,519,224
false
{"Kotlin": 44562}
package AOC2022.Day01 import AOC2022.readInput fun main() { fun makeSummedList(input: List<String>): MutableList<Int> { var calorieList: MutableList<Int> = mutableListOf() var subTotal: Int = 0 input.forEachIndexed { i, s -> if (i < input.size-1) { if (s != "") { subTotal += s.toInt() } else { calorieList.add(subTotal) subTotal = 0 } } else{ subTotal += s.toInt() calorieList.add(subTotal) } } return calorieList } fun part1(input: List<String>): Int { var maxCals: Int = 0 val calorieList = makeSummedList(input) maxCals = calorieList.max() return maxCals } fun part2(input: List<String>): Int { val calorieList = makeSummedList(input) val calListSorted = calorieList.sorted() println(calListSorted) var top1 = calListSorted[calListSorted.size-1] println(top1) var top2 = calListSorted[calListSorted.size-2] println(top2) var top3 = calListSorted[calListSorted.size-3] println(top3) var totalTop3 = top1+top2+top3 return totalTop3 } val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
48a7c563ebee77e44685569d356a05e8695ae36c
1,408
advent-of-code-2022
Apache License 2.0
src/main/kotlin/cz/tomasbublik/Day01.kt
tomasbublik
572,856,220
false
{"Kotlin": 21908}
package cz.tomasbublik fun main() { fun addToGroup( groupedCalories: MutableMap<Int, List<String>>, group: MutableList<String> ) { groupedCalories[group.sumOf { it.toInt() }] = group } fun getGroupedCalories(input: List<String>): MutableMap<Int, List<String>> { val groupedCalories: MutableMap<Int, List<String>> = HashMap() var group: MutableList<String> = ArrayList() for (calories in input) { if (calories.isNotEmpty()) { group.add(calories) } else { addToGroup(groupedCalories, group) group = ArrayList() } } if (group.size > 0) { addToGroup(groupedCalories, group) } return groupedCalories } fun part1(input: List<String>): Int { val groupedCalories: MutableMap<Int, List<String>> = getGroupedCalories(input) return groupedCalories.keys.max() } fun part2(input: List<String>): Int { val groupedCalories: MutableMap<Int, List<String>> = getGroupedCalories(input) val sortedCalories = groupedCalories.keys.sorted().reversed() return sortedCalories.take(3).sum() } // test if implementation meets criteria from the description, like: val testInput = readFileAsLinesUsingUseLines("src/main/resources/day_1_input_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readFileAsLinesUsingUseLines("src/main/resources/day_1_input") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
8c26a93e8f6f7ab0f260c75a287608dd7218d0f0
1,595
advent-of-code-kotlin-2022
Apache License 2.0
kotlin/src/main/kotlin/AoC_Day20.kt
sviams
115,921,582
false
null
import kotlinx.coroutines.experimental.async import kotlinx.coroutines.experimental.runBlocking object AoC_Day20 { fun parseParticleStates(lines: List<String>) : List<ParticleState> = lines.map { line -> val split = line.split(", ") val splits = (0..2).map { split[it].substring(split[it].indexOf('<')+1, split[it].indexOf('>')) } val vecs = splits.map { val items = it.split(",") Vec3D(items[0].trimStart().toInt(), items[1].trimStart().toInt(), items[2].trimStart().toInt()) } ParticleState(vecs[0], vecs[1], vecs[2]) } data class Vec3D(val x: Int, val y: Int, val z: Int) { fun distance() = Math.abs(x) + Math.abs(y) + Math.abs(z) fun plus(other: Vec3D) : Vec3D = Vec3D(x + other.x, y + other.y, z + other.z) } data class ParticleState(val pos: Vec3D, val vel: Vec3D, val acc: Vec3D) { fun increment() : ParticleState { val newVel = vel.plus(acc) return ParticleState(pos.plus(newVel), newVel, acc) } } data class State(val particles: List<ParticleState>, val closest: List<Int>) fun solvePt1(input: List<String>) : Int { val parts = parseParticleStates(input) val minByAccelerationThenVelocity = parts.filter { it.acc.distance() == parts.minBy { it.acc.distance() }!!.acc.distance() }.minBy { it.vel.distance() } return parts.indexOf(minByAccelerationThenVelocity) } fun solvePt2(input: List<String>) : Int = generateSequence(State(parseParticleStates(input), emptyList())) { val newParts = it.particles.map { p -> p.increment() } val filteredParts = newParts.filter { f -> newParts.map { p -> p.pos }.count { x -> x == f.pos } == 1} State(filteredParts,(it.closest + filteredParts.size).takeWhile { x -> x <= it.particles.size }) }.takeWhile { it.closest.size < 10 || it.closest.distinct().size > 1 }.last().closest.last() // Playing around with Kotlin coroutines fun solvePt2Async(input: List<String>) : Int = generateSequence(State(parseParticleStates(input), emptyList())) { val deferred = it.particles.map { p -> async { p.increment() } } // Quite ridiculous since increment() is extremely cheap runBlocking { val newParts = deferred.map { it.await() } val filteredParts = newParts.filter { f -> newParts.map { p -> p.pos }.count { x -> x == f.pos } == 1} State(filteredParts,(it.closest + filteredParts.size).takeWhile { x -> x <= it.particles.size }) } }.takeWhile { it.closest.size < 10 || it.closest.distinct().size > 1 }.last().closest.last() }
0
Kotlin
0
0
19a665bb469279b1e7138032a183937993021e36
2,751
aoc17
MIT License
src/com/leecode/array/Code3.kt
zys0909
305,335,860
false
null
package com.leecode.array /** 输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有奇数位于数组的前半部分,所有偶数位于数组的后半部分。 示例: 输入:nums = [1,2,3,4] 输出:[1,3,2,4] 注:[3,1,2,4] 也是正确的答案之一。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/diao-zheng-shu-zu-shun-xu-shi-qi-shu-wei-yu-ou-shu-qian-mian-lcof */ /** * 申请一个新数组,T(n) ,O(n) */ fun exchange1(nums: IntArray): IntArray { var start = 0 var end = nums.size - 1 val temp = IntArray(nums.size) for (i in nums.indices) { if (nums[i].and(1) == 1) { temp[start++] = nums[i] } else { temp[end--] = nums[i] } } return temp } /** * 双指针法,T(n2),O(1) * start 从前往后找第一个偶数,end从后往前找最后一个奇数,找到后交换位置 */ fun exchange2(nums: IntArray): IntArray { var start = 0 var end = nums.size - 1 var temp: Int while (start < end) { while (start < end && nums[start].and(1) == 1) { start++ } while (start < end && nums[end].and(1) == 0) { end-- } if (start < end) { temp = nums[start] nums[start] = nums[end] nums[end] = temp } } return nums } /** * 快慢指针 */ fun exchange3(nums: IntArray): IntArray { var i = 0 var j = 0 var temp: Int while (i < nums.size) { if (nums[i].and(1) == 1) { if (i != j) { temp = nums[i] nums[i] = nums[j] nums[j] = temp } j++ } i++ } return nums }
0
Kotlin
0
0
869c7c2f6686a773b2ec7d2aaa5bea2de46f1e0b
1,791
CodeLabs
Apache License 2.0
Coding Challenges/Advent of Code/2021/Day 9/part2.kt
Alphabeater
435,048,407
false
{"Kotlin": 69566, "Python": 5974}
import java.io.File import java.util.Scanner var row = 0 var col = 0 var size = 0 val sizeList = mutableListOf<Int>() //list that stores all basin sizes. fun setMapDimensions(file: File) { val scanner = Scanner(file) var bool = false while (scanner.hasNextLine()) { val line = scanner.nextLine() if (!bool) { col = line.length bool = true } row++ } } fun getBasinSize(map: Array<Array<Pair<Int, Boolean>>>, i: Int, j: Int, level: Int) { //checks if indexes are inside the matrix, if it's part of the inner basin(0-8) and if it's not visited already. if (i >= 0 && i <= row - 1 && j >= 0 && j <= col - 1 && !map[i][j].second && map[i][j].first != 9) { map[i][j] = map[i][j].copy(second = true) size++ //when visited, size increases by one. getBasinSize(map, i - 1, j, level + 1) //go to closest 4 neighbors. getBasinSize(map, i + 1, j, level + 1) getBasinSize(map, i, j - 1, level + 1) getBasinSize(map, i, j + 1, level + 1) if (level == 0) sizeList.add(size) //only gets size of the basin when on root. } } fun main() { val file = File("src/input.txt") setMapDimensions(file) val map = Array(row) { Array(col) { Pair(0, false) } } //[value/id, isItVisited?] val scanner = Scanner(file) var i = 0 while (scanner.hasNextLine()) { val line = scanner.nextLine() for ((j, digit) in line.withIndex()) { map[i][j] = map[i][j].copy(first = digit.digitToInt()) } i++ } for (i in 0 until row) { for (j in 0 until col) { size = 0 getBasinSize(map, i, j, 0) } } println(sizeList.sortedDescending().take(3).reduce { acc, i -> acc * i }) }
0
Kotlin
0
0
05c8d4614e025ed2f26fef2e5b1581630201adf0
1,800
Archive
MIT License
src/Day01.kt
risboo6909
572,912,116
false
{"Kotlin": 66075}
fun main() { fun part1(input: List<String>): Int { var maxSoFar: Int = -1 var groupSum = 0 for (line: String in input) { val parsedInt = line.toIntOrNull() if (parsedInt != null) { groupSum += parsedInt } else { // group separator if (groupSum > maxSoFar) { maxSoFar = groupSum } groupSum = 0 } } if (groupSum > maxSoFar) { maxSoFar = groupSum } return maxSoFar } fun part2(input: List<String>): Int { var groupSum = 0 val groupSums = mutableListOf<Int>() for (line: String in input) { val parsedInt = line.toIntOrNull() if (parsedInt != null) { groupSum += parsedInt } else { // group separator groupSums.add(groupSum) groupSum = 0 } } groupSums.add(groupSum) return groupSums.sorted().reversed().take(3).sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
bd6f9b46d109a34978e92ab56287e94cc3e1c945
1,395
aoc2022
Apache License 2.0
src/main/kotlin/com/kishor/kotlin/algo/problems/arrayandstrings/MedianOfTwoSorted.kt
kishorsutar
276,212,164
false
null
package com.kishor.kotlin.algo.problems.arrayandstrings import java.util.* fun main() { val array1 = intArrayOf(1, 2) val array2 = intArrayOf(3, 4) println(findMedianSortedArrays(array1, array2)) } fun findMedianSortedArrays(nums1: IntArray, nums2: IntArray): Double { val pq = PriorityQueue<Int> (2) { a,b -> b.compareTo(a) } var i = 0 var j = 0 var k = 0 val sortedArray = IntArray(nums1.size + nums2.size) { 0 } while (i < nums1.size && j < nums2.size) { if (nums1[i] < nums2[j]) { sortedArray[k] = nums1[i] i++ k++ } else { sortedArray[k] = nums2[j] j++ k++ } } while (i < nums1.size) { sortedArray[k] = nums1[i] i++ k++ } while (j < nums2.size) { sortedArray[k] = nums2[j] j++ k++ } return getMedian(sortedArray) } fun getMedian(sortedArray: IntArray): Double { if (sortedArray.size == 1) return sortedArray[0].toDouble() val mid = (0 + sortedArray.size) / 2 println(mid) if ((0 + sortedArray.size) % 2 != 0) { val result = sortedArray[mid] return result.toDouble() } else { val result = (sortedArray[mid] + sortedArray[mid-1])/2.0 return result } }
0
Kotlin
0
0
6672d7738b035202ece6f148fde05867f6d4d94c
1,338
DS_Algo_Kotlin
MIT License
ceria/13/src/main/kotlin/Solution.kt
VisionistInc
433,099,870
false
{"Kotlin": 91599, "Go": 87605, "Ruby": 65600, "Python": 21104}
import java.io.File; import kotlin.math.abs; val folds = mutableListOf<Pair<String, Int>>() fun main(args : Array<String>) { val input = File(args.first()).readLines() val points = mutableSetOf<Pair<Int, Int>>() var foldingInstruction = false for (line in input) { if (line.isEmpty()) { foldingInstruction = true continue } if (foldingInstruction) { var fold = line.replace("fold along ", "").split("=") folds.add(Pair<String, Int>(fold[0], fold[1].toInt())) } else { var point = line.split(",").map{ it.toInt() } points.add(Pair<Int, Int>(point[0], point[1])) } } println("Solution 1: ${solution1(points)}") println("Solution 2: ") solution2(points) } private fun solution1(p: MutableSet<Pair<Int, Int>>) :Int { var points = p if (folds.first().first.equals("y")) { points = foldUp(points, folds.first().second) } else { points = foldLeft(points, folds.first().second) } return points.size } private fun solution2(p: MutableSet<Pair<Int, Int>>) { var points = p for (f in folds) { if (f.first.equals("y")) { points = foldUp(points, f.second) } else { points = foldLeft(points, f.second) } } var maxRows = points.map{ it.second }.maxOrNull() ?: 0 var maxCols = points.map{ it.first }.maxOrNull() ?: 0 for (row in 0..maxRows) { for (col in 0..maxCols) { if (points.contains(Pair<Int,Int>(col, row))) { print("#") } else { print(".") } } println() } } private fun foldUp(points: MutableSet<Pair<Int, Int>>, y: Int) :MutableSet<Pair<Int, Int>> { val newPoints = mutableSetOf<Pair<Int, Int>>() for (p in points) { if (p.second > y) { newPoints.add(Pair<Int, Int>(p.first, abs((p.second - y) - y))) } else { newPoints.add(p) } } return newPoints } private fun foldLeft(points: MutableSet<Pair<Int, Int>>, x: Int) :MutableSet<Pair<Int, Int>> { val newPoints = mutableSetOf<Pair<Int, Int>>() for (p in points) { if (p.first > x) { newPoints.add(Pair<Int, Int>(abs((p.first - x) - x), p.second)) } else { newPoints.add(p) } } return newPoints }
0
Kotlin
4
1
e22a1d45c38417868f05e0501bacd1cad717a016
2,434
advent-of-code-2021
MIT License
src/main/kotlin/dec10/Main.kt
dladukedev
318,188,745
false
null
package dec10 import java.lang.Exception data class JumpResults( val oneJumps: Int = 0, val threeJumps: Int = 0 ) tailrec fun countJumps(input: List<Int>, currentJolts: Int = 0, accum: JumpResults = JumpResults()): JumpResults { return when { input.contains(currentJolts + 1) -> { countJumps(input, currentJolts + 1, accum.copy(oneJumps = accum.oneJumps + 1)) } input.contains(currentJolts + 3) -> { countJumps(input, currentJolts + 3, accum.copy(threeJumps = accum.threeJumps + 1)) } else -> { accum.copy(threeJumps = accum.threeJumps + 1) } } } fun reduceToChunks(input: List<Int>): List<Int> { val sortedInput = input.sorted() return sortedInput.foldIndexed(listOf(1)) { index, acc, number -> if (index == 0 || number - 1 == sortedInput[index - 1]) { val currentSequenceCount = acc.last() acc.dropLast(1) + listOf(currentSequenceCount + 1) } else { acc + listOf(1) } } } fun countValidPaths(input: List<Int>): Long { return reduceToChunks(input) .map { // map to number of paths based on sequence length when(it) { 1, 2 -> 1L 3 -> 2L 4 -> 4L 5 -> 7L else -> throw Exception("Sequence of unknown length: $it") } } .reduce { acc, number -> acc * number } } fun main() { println("------------ PART 1 ------------") val jumpResults = countJumps(input) val result = jumpResults.oneJumps * jumpResults.threeJumps println("result: $result") println("------------ PART 2 ------------") val result1 = countValidPaths(input) println("result: $result1") }
0
Kotlin
0
0
d4591312ddd1586dec6acecd285ac311db176f45
1,801
advent-of-code-2020
MIT License
src/main/kotlin/tr/emreone/adventofcode/days/Day24.kt
EmRe-One
433,772,813
false
{"Kotlin": 118159}
package tr.emreone.adventofcode.days import tr.emreone.kotlin_utils.automation.Day class Day24 : Day(24, 2021, "Arithmetic Logic Unit") { class Parameters(val a: Int, val b: Int) class QueueItem(val digitIndex: Int, val addend: Int) /* * 0 inp w inp w inp w .... * 1 mul x 0 mul x 0 mul x 0 * 2 add x z add x z add x z * 3 mod x 26 mod x 26 mod x 26 * 4 div z 1 div z 1 div z 1 <-- parameter a * 5 add x 13 add x 12 add x 10 * 6 eql x w eql x w eql x w * 7 eql x 0 eql x 0 eql x 0 * 8 mul y 0 mul y 0 mul y 0 * 9 add y 25 add y 25 add y 25 * 10 mul y x mul y x mul y x * 11 add y 1 add y 1 add y 1 * 12 mul z y mul z y mul z y * 13 mul y 0 mul y 0 mul y 0 * 14 add y w add y w add y w * 15 add y 8 add y 16 add y 4 <-- parameter b * 16 mul y x mul y x mul y x * 17 add z y add z y add z y * * split input to chunked blocks with a size of 18 * only lines with index 5 and 15 are relevant */ class ALU(input: List<String>) { private val parameters: List<Parameters> init { this.parameters = input.chunked(18).map { lines -> val a = lines[5].substringAfterLast(" ").toInt() val b = lines[15].substringAfterLast(" ").toInt() Parameters(a, b) } } fun findModelNumber(largest: Boolean = true): Long { val queue = ArrayDeque<QueueItem>() val digits = Array(14) { 0 } parameters.forEachIndexed { digitIndex, parameters -> if (parameters.a >= 10) { queue.add(QueueItem(digitIndex, parameters.b)) } else { val popped = queue.removeLast() val addend = popped.addend + parameters.a val digit = (if (largest) 9 downTo 1 else 1..9).first { it + addend in 1..9 } digits[popped.digitIndex] = digit digits[digitIndex] = digit + addend } } // convert digits to a number with the horners rule // i.e. ( 1 2 3 ) -> (((0L + 1) * 10 + 2) * 10 + 3) = 123 // ‾ ‾ ‾ return digits.fold(0L) { acc, d -> acc * 10 + d } } } override fun part1(): Long { val alu = ALU(inputAsList) return alu.findModelNumber() } override fun part2(): Long { val alu = ALU(inputAsList) return alu.findModelNumber(largest = false) } }
0
Kotlin
0
0
516718bd31fbf00693752c1eabdfcf3fe2ce903c
3,000
advent-of-code-2021
Apache License 2.0
src/main/kotlin/g1701_1800/s1703_minimum_adjacent_swaps_for_k_consecutive_ones/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1701_1800.s1703_minimum_adjacent_swaps_for_k_consecutive_ones // #Hard #Array #Greedy #Prefix_Sum #Sliding_Window // #2023_06_15_Time_518_ms_(100.00%)_Space_52.2_MB_(100.00%) class Solution { fun minMoves(nums: IntArray, k: Int): Int { val len = nums.size var cnt = 0 var min = Long.MAX_VALUE for (num in nums) { if (num == 1) { cnt++ } } val arr = IntArray(cnt) var idx = 0 val sum = LongArray(cnt + 1) for (i in 0 until len) { if (nums[i] == 1) { arr[idx++] = i sum[idx] = sum[idx - 1] + i } } var i = 0 while (i + k - 1 < cnt) { min = Math.min(min, getSum(arr, i, i + k - 1, sum)) i++ } return min.toInt() } private fun getSum(arr: IntArray, l: Int, h: Int, sum: LongArray): Long { val mid = l + (h - l) / 2 val k = h - l + 1 val radius = mid - l var res = sum[h + 1] - sum[mid + 1] - (sum[mid] - sum[l]) - (1 + radius) * radius if (k % 2 == 0) { res = res - arr[mid] - (radius + 1) } return res } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,231
LeetCode-in-Kotlin
MIT License
src/year2020/day06/Day06.kt
fadi426
433,496,346
false
{"Kotlin": 44622}
package year2020.day06 import util.assertTrue import util.read2020DayInput fun main() { val input = inputToGroupInput(read2020DayInput("Day06")) assertTrue(task01(input) == 6903) assertTrue(task02(input) == 3493) } private fun inputToGroupInput(input: List<String>) = input.joinToString() .split(", ,") .map { it.replace(" ", "") } private fun task01(input: List<String>) = input .map { it.replace(",", "") } .map { it.toList().distinct() } .sumOf { it.size } private fun task02(input: List<String>): Int = input .map { it.split(",") } .map { it.joinToString().split(",") } .map { countGroupYes(it) } .sumOf { it } private fun countGroupYes(list: List<String>) = list.joinToString().toList() .filter { it in 'a'..'z' } .distinct() .map { u -> list.count { it.any { it == u } } == list.size } .count { it == true }
0
Kotlin
0
0
acf8b6db03edd5ff72ee8cbde0372113824833b6
900
advent-of-code-kotlin-template
Apache License 2.0
src/main/kotlin/aoc2022/Day16.kt
j4velin
572,870,735
false
{"Kotlin": 285016, "Python": 1446}
package aoc2022 import readInput import withEachOf import java.util.regex.Pattern import kotlin.math.min data class Valve(val name: String, val flowRate: Int, val tunnels: Set<String>) { companion object { fun fromString(input: String): Valve { // Valve AA has flow rate=0; tunnels lead to valves DD, II, BB val regex = Pattern.compile("Valve ([A-Z]+) has flow rate=(\\d+); tunnels? leads? to valves? ([A-Z, ]*)") val matcher = regex.matcher(input) if (!matcher.matches()) throw IllegalArgumentException("no valid valve description: '$input'") val name = matcher.group(1) val flowRate = matcher.group(2).toInt() val tunnels = matcher.group(3).split(", ").toSet() return Valve(name, flowRate, tunnels) } } } /** * @return all reachable [Valve] from [currentValve] in the order in which they contribute the most in regard to their * potential to release pressure in the remaining time */ private fun getNextValves(currentValve: Valve, caveState: CaveState) = caveState.remainingValves.filter { CaveState.distances.contains(currentValve to it) } .sortedByDescending { it.flowRate * (caveState.remainingTime - 1 - CaveState.distances[currentValve to it]!!) } /** * Visits (= move to & open) the given [valve] * * @param valve the [Valve] to visit * @param caveState the current state of the cave * @param travelTime the time it took to reach [valve] * @return the maximum pressure the cave can release by visiting the [valve] */ private fun visitValve(valve: Valve, caveState: CaveState, travelTime: Int): Int { if (caveState.remainingTime - travelTime <= 1) { // no time to open any other valve return caveState.pressureRelease } val newRemainingTime = caveState.remainingTime - 1 - travelTime // time to get here + time to open valve val newCaveState = caveState.copy( remainingValves = caveState.remainingValves - valve, remainingTime = newRemainingTime, pressureRelease = caveState.pressureRelease + valve.flowRate * newRemainingTime ) val next = getNextValves(valve, newCaveState) return if (next.isEmpty()) { newCaveState.pressureRelease } else { next.maxOf { v -> visitValve(v, newCaveState, CaveState.distances[valve to v]!!) } } } /** * Similar to [visitValve], but can visit 2 [Valve]s in parallel. * * @param valve1 the first [Valve] to visit * @param valve2 the second [Valve] to visit * @param caveState the state of the cave * @param remainingTravelTime1 the remaining time we need to reach [valve1] * @param remainingTravelTime2 the remaining time we need to reach [valve2] * @return the maximum pressure the cave can release by visiting [valve1] and [valve2] */ private fun visitValves( valve1: Valve, valve2: Valve, caveState: CaveState, remainingTravelTime1: Int, remainingTravelTime2: Int ): Int { if (valve1 == valve2) throw IllegalStateException("Can not visit the same valve twice! $valve1") if (caveState.remainingTime - min(remainingTravelTime1, remainingTravelTime2) <= 1) { return caveState.pressureRelease } // arriving at both valves at the same time if (remainingTravelTime1 == remainingTravelTime2) { val newRemainingTime = caveState.remainingTime - 1 - remainingTravelTime1 // time to get here + time to open valve val newCaveState = caveState.copy( remainingValves = caveState.remainingValves - valve1 - valve2, remainingTime = newRemainingTime, pressureRelease = caveState.pressureRelease + valve1.flowRate * newRemainingTime + valve2.flowRate * newRemainingTime ) val next1 = getNextValves(valve1, newCaveState) val next2 = getNextValves(valve2, newCaveState) return if (next1.isEmpty() && next2.isEmpty()) { caveState.pressureRelease } else if (next1.isEmpty()) { next2.maxOf { v -> visitValve(v, newCaveState, CaveState.distances[valve2 to v]!!) } } else if (next2.isEmpty()) { next1.maxOf { v -> visitValve(v, newCaveState, CaveState.distances[valve1 to v]!!) } } else if (next1.size == next2.size) { if (next1.size == 1) { val target = next1.first() visitValve( target, newCaveState, min(CaveState.distances[valve1 to target]!!, CaveState.distances[valve2 to target]!!) ) } else { next1.asSequence().withEachOf(next2.asSequence()).filter { it.first != it.second }.maxOf { pair -> visitValves( pair.first, pair.second, newCaveState, CaveState.distances[valve1 to pair.first]!!, CaveState.distances[valve2 to pair.second]!! ) } } } else { // different size throw UnsupportedOperationException("too complicated for now") } } else if (remainingTravelTime1 < remainingTravelTime2) { // arriving at valve1 first val newRemainingTime = caveState.remainingTime - 1 - remainingTravelTime1 // time to get here + time to open valve val newCaveState = caveState.copy( remainingValves = caveState.remainingValves - valve1 - valve2, // already en route to valve2 remainingTime = newRemainingTime, pressureRelease = caveState.pressureRelease + valve1.flowRate * newRemainingTime ) val next = getNextValves(valve1, newCaveState) return if (next.isEmpty()) { visitValve(valve2, newCaveState, remainingTravelTime2 - remainingTravelTime1 - 1) } else { next.maxOf { v -> visitValves( v, valve2, newCaveState, CaveState.distances[valve1 to v]!!, remainingTravelTime2 - remainingTravelTime1 - 1 ) } } } else { // arriving at valve2 first val newRemainingTime = caveState.remainingTime - 1 - remainingTravelTime2 // time to get here + time to open valve val newCaveState = caveState.copy( remainingValves = caveState.remainingValves - valve1 - valve2, // already en route to valve1 remainingTime = newRemainingTime, pressureRelease = caveState.pressureRelease + valve2.flowRate * newRemainingTime ) val next = getNextValves(valve2, newCaveState) return if (next.isEmpty()) { visitValve(valve1, newCaveState, remainingTravelTime1 - remainingTravelTime2 - 1) } else { next.maxOf { v -> visitValves( valve1, v, newCaveState, remainingTravelTime1 - remainingTravelTime2 - 1, CaveState.distances[valve2 to v]!! ) } } } } private data class CaveState( val remainingValves: Collection<Valve>, val remainingTime: Int, val pressureRelease: Int ) { companion object { lateinit var distances: Map<Pair<Valve, Valve>, Int> private set /** * Sets the [distances] map to the minimum distances between two [Valve]s. * @param valves all [Valve] to consider * @param valveMapping a mapping from the valve name to the actual [Valve] object */ fun calculateShortestDistances(valves: Collection<Valve>, valveMapping: Map<String, Valve>) { val distances = mutableMapOf<Pair<Valve, Valve>, Int>() valves.forEach { start -> valves.filter { it != start }.forEach { end -> distances[start to end] = findMinDistance(start, end, valveMapping, setOf(start)) ?: Int.MAX_VALUE } } CaveState.distances = distances } private fun findMinDistance( from: Valve, to: Valve, valveMapping: Map<String, Valve>, ignore: Collection<Valve> ): Int? { return from.tunnels.mapNotNull { valveMapping[it] }.filter { !ignore.contains(it) }.mapNotNull { next -> if (to == next) { 1 } else { findMinDistance(next, to, valveMapping, ignore + from)?.inc() } }.minByOrNull { it } } } } private fun part1(input: List<String>): Int { val valves = input.map { Valve.fromString(it) } val start = valves.find { it.name == "AA" } ?: throw IllegalArgumentException("No starting valve 'AA' found") CaveState.calculateShortestDistances(valves.filter { it.flowRate > 0 } + start, valves.associateBy { it.name }) val caveState = CaveState(valves.filter { it.flowRate > 0 }, 30, 0) return getNextValves(start, caveState).maxOf { v -> visitValve(v, caveState, CaveState.distances[start to v]!!) } } private fun part2(input: List<String>): Int { val valves = input.map { Valve.fromString(it) } val start = valves.find { it.name == "AA" } ?: throw IllegalArgumentException("No starting valve 'AA' found") CaveState.calculateShortestDistances(valves.filter { it.flowRate > 0 } + start, valves.associateBy { it.name }) val caveState = CaveState(valves.filter { it.flowRate > 0 }, 26, 0) val next = getNextValves(start, caveState) return next.asSequence().withEachOf(next.asSequence()).filter { it.first != it.second } .distinctBy { listOf(it.first.name, it.second.name).sorted() }.map { pair -> visitValves( pair.first, pair.second, caveState, CaveState.distances[start to pair.first]!!, CaveState.distances[start to pair.second]!! ) }.max() } fun main() { val testInput = readInput("Day16_test", 2022) check(part1(testInput) == 1651) check(part2(testInput) == 1707) val input = readInput("Day16", 2022) println(part1(input)) println(part2(input)) // takes really long, but seems to work... }
0
Kotlin
0
0
f67b4d11ef6a02cba5b206aba340df1e9631b42b
10,487
adventOfCode
Apache License 2.0
src/main/kotlin/graph/variation/Reachability3.kt
yx-z
106,589,674
false
null
package graph.variation import graph.core.Edge import graph.core.Graph import graph.core.Vertex import graph.core.whateverFirstSearch import util.Tuple3 import util.tu // given a connected undirected graph G with three tokens at vertex a, b, and c // in each turn you must move ALL three tokens to an adjacent vertex // at the end of each turn, three tokens must lie on three DIFFERENT vertices // your goal is to move them to x, y, z with no restriction on correspondence // your algorithm should return whether such puzzle is solvable fun main(args: Array<String>) { val vertices = (1..9).map { Vertex(it) } val edges = setOf( Edge(vertices[0], vertices[1]), Edge(vertices[1], vertices[2]), Edge(vertices[0], vertices[3]), Edge(vertices[1], vertices[4]), Edge(vertices[3], vertices[4]), Edge(vertices[4], vertices[5]), Edge(vertices[4], vertices[6]), Edge(vertices[4], vertices[7]), Edge(vertices[5], vertices[8])) val G = Graph(vertices, edges) println(G.reachability3( vertices[0], vertices[1], vertices[2], vertices[6], vertices[7], vertices[8])) } fun Graph<Int>.reachability3(a: Vertex<Int>, b: Vertex<Int>, c: Vertex<Int>, x: Vertex<Int>, y: Vertex<Int>, z: Vertex<Int>): Boolean { // our strategy is that transforming G = (V, E) into a new graph G' = (V', E') // V' = { (v1, v2, v3) : v1, v2, v3 in V } // E' = { (v1, v2, v3) -> (u1, u2, u3) : v1 -> u1, v2 -> u2, v3 -> u3 in E // , v1 != v2 != v3 and u1 != u2 != u3 } // then run G'.whateverFirstSearch(a, b, c) and check if (x, y, z) is in the // spanning tree of G' starting @ (a, b, c) val newVertices = HashSet<Vertex<Tuple3<Vertex<Int>, Vertex<Int>, Vertex<Int>>>>() vertices.forEach { v1 -> vertices.forEach { v2 -> vertices.forEach { v3 -> newVertices.add(Vertex(v1 tu v2 tu v3)) } } } val newEdges = HashSet<Edge<Tuple3<Vertex<Int>, Vertex<Int>, Vertex<Int>>>>() newVertices.forEach { val (v1, v2, v3) = it.data if (v1 !== v2 && v2 !== v3 && v1 !== v3) { getEdgesOf(v1).forEach { (s1, e1) -> val u1 = if (s1 === v1) e1 else s1 getEdgesOf(v2).forEach { (s2, e2) -> val u2 = if (s2 === v2) e2 else s2 getEdgesOf(v3).forEach { (s3, e3) -> val u3 = if (s3 === v3) e3 else s3 if (u1 !== u2 && u2 !== u3 && u1 !== u3) { newEdges.add(Edge(Vertex(v1 tu v2 tu v3), Vertex(u1 tu u2 tu u3))) } } } } } } val newGraph = Graph(newVertices, newEdges) val spanningTree = newGraph.whateverFirstSearch(Vertex(a tu b tu c)) return spanningTree.contains(Vertex(x tu y tu z)) }
0
Kotlin
0
1
15494d3dba5e5aa825ffa760107d60c297fb5206
2,728
AlgoKt
MIT License
src/main/kotlin/com/jaspervanmerle/aoc2020/day/Day17.kt
jmerle
317,518,472
false
null
package com.jaspervanmerle.aoc2020.day class Day17 : Day("346", "1632") { private data class Point(val coordinates: List<Int>) private abstract class Dimension(val dimensions: Int, input: String) { private val cubes = mutableSetOf<Point>() private val adjacentDirections = getPoints(-1..1) .filter { point -> point.coordinates.any { it != 0 } } init { input.lines().forEachIndexed { y, line -> line.toCharArray().forEachIndexed { x, ch -> if (ch == '#') { addActiveCube(parseInitialLocation(x, y)) } } } } protected abstract fun parseInitialLocation(x: Int, y: Int): Point fun addActiveCube(location: Point) { cubes.add(location) } fun countActiveCubes(): Int { return cubes.size } fun isActive(location: Point): Boolean { return location in cubes } fun countActiveNeighbors(location: Point): Int { return adjacentDirections .map { direction -> Point(location.coordinates.mapIndexed { index, i -> i + direction.coordinates[index] }) } .count { isActive(it) } } fun getPoints(range: IntRange): List<Point> { val columns = (0 until dimensions).map { range.toList() } val cartesianProduct = columns.fold(listOf(listOf<Int>())) { acc, value -> acc.flatMap { list -> value.map { element -> list + element } } } return cartesianProduct.map { Point(it) } } fun getMinCoordinate(): Int { return cubes.flatMap { it.coordinates }.minOrNull()!! } fun getMaxCoordinate(): Int { return cubes.flatMap { it.coordinates }.maxOrNull()!! } } private class Dimension3d(input: String = "") : Dimension(3, input) { override fun parseInitialLocation(x: Int, y: Int): Point { return Point(listOf(x, y, 0)) } } private class Dimension4d(input: String = "") : Dimension(4, input) { override fun parseInitialLocation(x: Int, y: Int): Point { return Point(listOf(x, y, 0, 0)) } } override fun solvePartOne(): Any { return getActiveCubesAfterBoot(Dimension3d(getInput())) { Dimension3d() } } override fun solvePartTwo(): Any { return getActiveCubesAfterBoot(Dimension4d(getInput())) { Dimension4d() } } private fun getActiveCubesAfterBoot(initialDimension: Dimension, dimensionCreator: () -> Dimension): Int { var currentDimension = initialDimension for (i in 1..6) { val newDimension = dimensionCreator() val minCoord = currentDimension.getMinCoordinate() - 1 val maxCoord = currentDimension.getMaxCoordinate() + 1 val pointsToCheck = currentDimension.getPoints(minCoord..maxCoord) for (point in pointsToCheck) { if (currentDimension.isActive(point)) { if (currentDimension.countActiveNeighbors(point) in 2..3) { newDimension.addActiveCube(point) } } else { if (currentDimension.countActiveNeighbors(point) == 3) { newDimension.addActiveCube(point) } } } currentDimension = newDimension } return currentDimension.countActiveCubes() } }
0
Kotlin
0
0
81765a46df89533842162f3bfc90f25511b4913e
3,673
advent-of-code-2020
MIT License
exercises/practice/yacht/.meta/src/reference/kotlin/Yacht.kt
exercism
47,675,865
false
{"Kotlin": 382097, "Shell": 14600}
import YachtCategory.* object Yacht { fun solve(category: YachtCategory, vararg dices: Int): Int = when (category) { YACHT -> if (dices.distinct().size == 1) 50 else 0 ONES -> dices.filter { it == 1 }.sum() TWOS -> dices.filter { it == 2 }.sum() THREES -> dices.filter { it == 3 }.sum() FOURS -> dices.filter { it == 4 }.sum() FIVES -> dices.filter { it == 5 }.sum() SIXES -> dices.filter { it == 6 }.sum() FULL_HOUSE -> { val counts = dices.groupBy { it }.map { it.key to it.value.count() }.sortedByDescending { it.second } if (counts.size >= 2 && counts[0].second >= 3 && counts[1].second >= 2) { counts[0].first * counts[0].second + counts[1].first * counts[1].second } else 0 } FOUR_OF_A_KIND -> dices.groupBy { it }.filter { it.value.size >= 4 }.keys.sumOf { it * 4 } LITTLE_STRAIGHT -> if ((1..5).all { dices.contains(it) }) 30 else 0 BIG_STRAIGHT -> if ((2..6).all { dices.contains(it) }) 30 else 0 CHOICE -> dices.sum() } }
51
Kotlin
190
199
7f1c7a11cfe84499cfef4ea2ecbc6c6bf34a6ab9
1,098
kotlin
MIT License
src/main/kotlin/ru/amai/study/hackerrank/practice/interviewPreparationKit/search/swap/SwapNodes.kt
slobanov
200,526,003
false
null
package ru.amai.study.hackerrank.practice.interviewPreparationKit.search.swap import java.util.* fun swapNodes(indexes: Array<Array<Int>>, queries: Array<Int>): List<List<Int>> { val root = buildTree(indexes) return queries.map { swapMultiplier -> val queryResult = mutableListOf<Int>() traverseInOrderWithSwaps(root, swapMultiplier) { node -> queryResult += node.index } queryResult } } private fun traverseInOrderWithSwaps( node: Node, swapMultiplier: Int, level: Int = 1, observer: (Node) -> Unit ) { if (level % swapMultiplier == 0) node.swapSubTrees() val (_, left, right) = node left?.let { traverseInOrderWithSwaps(left, swapMultiplier, level + 1, observer) } observer(node) right?.let { traverseInOrderWithSwaps(right, swapMultiplier, level + 1, observer) } } private fun buildTree(indexes: Array<Array<Int>>): Node { val nodeMap = mutableMapOf<Int, Node>() indexes.forEachIndexed { i, (l, r) -> val p = i + 1 listOf(p, l, r) .filter { it != -1 } .forEach { nodeMap.putIfAbsent(it, Node(it)) } if (l != -1) nodeMap.getValue(p).left = nodeMap.getValue(l) if (r != -1) nodeMap.getValue(p).right = nodeMap.getValue(r) } return nodeMap.getValue(1) } private data class Node( val index: Int, var left: Node? = null, var right: Node? = null ) private fun Node.swapSubTrees() { val tmp = left left = right right = tmp } fun main() { val scan = Scanner(System.`in`) val n = scan.nextLine().trim().toInt() val indexes = Array(n) { Array(2) { 0 } } for (indexesRowItr in 0 until n) { indexes[indexesRowItr] = scan.nextLine().split(" ").map { it.trim().toInt() }.toTypedArray() } val queriesCount = scan.nextLine().trim().toInt() val queries = Array(queriesCount) { 0 } for (queriesItr in 0 until queriesCount) { val queriesItem = scan.nextLine().trim().toInt() queries[queriesItr] = queriesItem } val result = swapNodes(indexes, queries) println(result.joinToString("\n") { it.joinToString(" ") }) }
0
Kotlin
0
0
2cfdf851e1a635b811af82d599681b316b5bde7c
2,171
kotlin-hackerrank
MIT License
src/main/kotlin/days/Day18.kt
andilau
573,139,461
false
{"Kotlin": 65955}
package days import java.util.ArrayDeque @AdventOfCodePuzzle( name = "Boiling Boulders", url = "https://adventofcode.com/2022/day/18", date = Date(day = 18, year = 2022) ) class Day18(input: List<String>) : Puzzle { private val droplets = input.map(Point3D::from).toSet() override fun partOne() = droplets.sumOf { (it.neighbors() subtract droplets).count() } override fun partTwo(): Int { var outsideFacing = 0 val rangeX = droplets.minOf { it.x } - 1..droplets.maxOf { it.x } + 1 val rangeY = droplets.minOf { it.y } - 1..droplets.maxOf { it.y } + 1 val rangeZ = droplets.minOf { it.z } - 1..droplets.maxOf { it.z } + 1 val inspect = ArrayDeque<Point3D>().apply { add(Point3D(rangeX.first, rangeY.first, rangeZ.first)) } val seen = mutableSetOf<Point3D>() while (inspect.isNotEmpty()) { val pop = inspect.pop() if (pop in seen) continue seen += pop pop.neighbors().filter { it.x in rangeX && it.y in rangeY && it.z in rangeZ } .forEach { side -> if (side in droplets) outsideFacing++ else inspect.add(side) } } return outsideFacing } data class Point3D(val x: Int, val y: Int, val z: Int) { fun neighbors() = setOf( copy(x = x - 1), copy(x = x + 1), copy(y = y - 1), copy(y = y + 1), copy(z = z - 1), copy(z = z + 1) ) companion object { fun from(line: String) = line.split(",").map(String::toInt).let { (x, y, z) -> Point3D(x, y, z) } } } }
0
Kotlin
0
0
da824f8c562d72387940844aff306b22f605db40
1,621
advent-of-code-2022
Creative Commons Zero v1.0 Universal
src/twentytwo/Day08.kt
Monkey-Matt
572,710,626
false
{"Kotlin": 73188}
package twentytwo fun main() { // test if implementation meets criteria from the description, like: val testInput = readInputLines("Day08_test") println(part1(testInput)) check(part1(testInput) == 21) println(part2(testInput)) check(part2(testInput) == 8) println("---") val input = readInputLines("Day08_input") println(part1(input)) println(part2(input)) } private data class Position(val x: Int, val y: Int) private val List<String>.lastYIndex get() = this.lastIndex private val List<String>.lastXIndex get() = this[0].lastIndex private fun part1(forest: List<String>): Int { val width = forest[0].length val height = forest.size var visibleTreesCount = 0 for (y in 0 until height) { for (x in 0 until width) { val treePosition = Position(x, y) if (forest.treeIsVisible(treePosition)) visibleTreesCount++ } } return visibleTreesCount } private fun List<String>.treeIsVisible(position: Position): Boolean { val forest = this // edge is always visible if (position.y == 0 || position.x == 0) return true if (position.y == forest.lastYIndex || position.x == forest.lastXIndex) return true val currentTree = forest[position.y][position.x] var blocked = false for (i in position.y-1 downTo 0) { // up if (forest[i][position.x] >= currentTree) { blocked = true break } } if (!blocked) return true blocked = false for (i in position.y+1 .. forest.lastYIndex) { // down if (forest[i][position.x] >= currentTree) { blocked = true break } } if (!blocked) return true blocked = false for (j in position.x-1 downTo 0) { // left if (forest[position.y][j] >= currentTree) { blocked = true break } } if (!blocked) return true blocked = false for (j in position.x+1 .. forest.lastXIndex) { // right if (forest[position.y][j] >= currentTree) { blocked = true break } } if (!blocked) return true return false } private fun part2(forest: List<String>): Int { val width = forest[0].length val height = forest.size val treeScores = mutableListOf<Int>() for (y in 0 until height) { for (x in 0 until width) { val treePosition = Position(x, y) treeScores.add(forest.treeScore(treePosition)) } } return treeScores.max() } private fun List<String>.treeScore(position: Position): Int { val forest = this val currentTree = forest[position.y][position.x] var score1 = 0 // up for (i in position.y-1 downTo 0) { score1++ if (forest[i][position.x] >= currentTree) { break } } var score2 = 0 // down for (i in position.y+1 .. forest.lastIndex) { score2++ if (forest[i][position.x] >= currentTree) { break } } var score3 = 0 // left for (j in position.x-1 downTo 0) { score3++ if (forest[position.y][j] >= currentTree) { break } } var score4 = 0 // right for (j in position.x+1 .. forest[0].lastIndex) { score4++ if (forest[position.y][j] >= currentTree) { break } } return score1 * score2 * score3 * score4 }
1
Kotlin
0
0
600237b66b8cd3145f103b5fab1978e407b19e4c
3,438
advent-of-code-solutions
Apache License 2.0
src/main/kotlin/de/bitfroest/aoc2020/Day01.kt
Lazalatin
317,801,508
false
null
package de.bitfroest.aoc2020 object Day01 { private fun Pair<Int, Int>.sum() = first + second private fun Pair<Int, Int>.product() = first * second private fun List<Int>.toPairs(): Sequence<Pair<Int, Int>> { return this.asSequence().flatMapIndexed { i, first -> this.drop(i).map { second -> Pair(first, second) } } } fun solve(inputs: List<String>): Int { val numericInputs = inputs.map(String::toInt) return numericInputs.toPairs() .filter { it.sum() == 2020 } .first().product() } // --- Second Task private fun Triple<Int, Int, Int>.sum() = first + second + third private fun Triple<Int, Int, Int>.product() = first * second * third private fun List<Int>.toTriples(): Sequence<Triple<Int, Int, Int>> { return this.asSequence().flatMapIndexed() { i, first -> this.drop(i).flatMapIndexed { j, second -> this.drop(j).map { third -> Triple(first, second, third) } } } } fun solve2(inputs: List<String>): Int { val numericInputs = inputs.map(String::toInt) return numericInputs.toTriples() .filter { it.sum() == 2020 } .first().product() } }
0
Kotlin
0
0
816e0e010137f97918ff5e631b3e3155b49b842a
1,263
advent-of-code-2020
Creative Commons Zero v1.0 Universal
src/Day20.kt
Oktosha
573,139,677
false
{"Kotlin": 110908}
import kotlin.math.abs import kotlin.math.sign typealias Message = MutableList<NumberWithMeta> fun Message.valueAt(index: Int): Long { return this[index % this.size].value } data class NumberWithMeta(val value: Long, val originalPosition: Int) fun main() { fun readInputDay20(filename: String): Message { return readInput(filename).mapIndexed { index, s -> NumberWithMeta(s.toLong(), index) }.toMutableList() } fun readInputDay20pt2(filename: String): Message { return readInput(filename).mapIndexed { index, s -> NumberWithMeta(s.toLong() * 811589153L, index) } .toMutableList() } fun swap(input: Message, position: Int, direction: Int): Int { val nextPosition = (position + input.size + direction) % input.size val temp = input[nextPosition] input[nextPosition] = input[position] input[position] = temp return nextPosition } fun mix(input: Message): Message { for (index in 0 until input.size) { var position = input.indexOfFirst { x -> x.originalPosition == index } val numberOfSteps = (abs(input[position].value) % (input.size - 1).toLong()).toInt() val direction = input[position].value.sign repeat(numberOfSteps) { position = swap(input, position, direction) } // print("step: $index") // for (x in input) { // print(" ${x.value}") // } // println() } return input } fun getGrooveCoordinatesSum(input: Message): Long { val start = input.indexOfFirst { x -> x.value == 0L } return input.valueAt(start + 1000) + input.valueAt(start + 2000) + input.valueAt(start + 3000) } fun part1(input: Message): Long { return getGrooveCoordinatesSum(mix(input)) } fun part2(input: Message): Long { repeat(10) { mix(input) } return getGrooveCoordinatesSum(input) } val testInput = readInputDay20("Day20-test") val input = readInputDay20("Day20") val testInput2 = readInputDay20pt2("Day20-test") val input2 = readInputDay20pt2("Day20") println("Day 20") println("part 1 test: ${part1(testInput)}") println("part 1 real: ${part1(input)}") println("part 2 test: ${part2(testInput2)}") println("part 2 real: ${part2(input2)}") }
0
Kotlin
0
0
e53eea61440f7de4f2284eb811d355f2f4a25f8c
2,409
aoc-2022
Apache License 2.0
src/nativeMain/kotlin/com.qiaoyuang.algorithm/special/Questions51.kt
qiaoyuang
100,944,213
false
{"Kotlin": 338134}
package com.qiaoyuang.algorithm.special import com.qiaoyuang.algorithm.round0.BinaryTreeNode import kotlin.math.max fun test51() { printlnResult(testCase()) } /** * Questions 51: Find the maximum sum of paths */ private fun BinaryTreeNode<Int>.maxSum(): Int { val max = intArrayOf(Int.MIN_VALUE) maxSum(max) return max.first() } private infix fun BinaryTreeNode<Int>.maxSum(maxSum: IntArray): Int { val maxSumLeft = intArrayOf(Int.MIN_VALUE) val leftValue = left?.let { max(0, it.maxSum(maxSumLeft)) } ?: 0 val maxSumRight = intArrayOf(Int.MIN_VALUE) val rightValue = right?.let { max(0, it.maxSum(maxSumRight)) } ?: 0 maxSum[0] = max(maxSumLeft.first(), maxSumRight.first()) maxSum[0] = max(maxSum.first(), value + leftValue + rightValue) return value + max(leftValue, rightValue) } private fun printlnResult(root: BinaryTreeNode<Int>) = println("The maximum sum of paths in binary tree ${root.preOrderList()}(preorder) is ${root.maxSum()}") private fun testCase() = BinaryTreeNode( value = -9, left = BinaryTreeNode( value = 4, ), right = BinaryTreeNode( value = 20, left = BinaryTreeNode( value = 15, left = BinaryTreeNode(value = -3) ), right = BinaryTreeNode( value = 7, ) ) )
0
Kotlin
3
6
66d94b4a8fa307020d515d4d5d54a77c0bab6c4f
1,431
Algorithm
Apache License 2.0
src/main/kotlin/com/github/michaelbull/advent2021/day19/BeaconMap.kt
michaelbull
433,565,311
false
{"Kotlin": 162839}
package com.github.michaelbull.advent2021.day19 import com.github.michaelbull.advent2021.math.Vector3 fun Sequence<String>.toBeaconMap(): BeaconMap { val it = iterator() val scanners = generateSequence(it::readScanner).toList() return BeaconMap(scanners) } data class BeaconMap( val scanners: List<Scanner> ) { fun count(): Int { return scan().beacons.size } fun maxDistance(): Int { val translations = scan().translations return translations.maxOf { a -> translations.maxOf { b -> a manhattanDistanceTo b } } } fun scan(): ScanResult { val beacons = scanners.take(1).flatMap(Scanner::beacons).toMutableSet() val remaining = scanners.drop(1).toMutableList() val translations = mutableSetOf<Vector3>() while (remaining.isNotEmpty()) { for (i in remaining.indices.reversed()) { val (translation, translatedBeacons) = scan(beacons, remaining[i]) ?: continue remaining[i] = remaining.last() remaining.removeLast() beacons += translatedBeacons translations += translation } } return ScanResult(beacons, translations) } private fun scan(knownBeacons: Set<Vector3>, scanner: Scanner): Pair<Vector3, List<Vector3>>? { for (rotation in ROTATION_RANGE) { val rotatedBeacons = scanner.beacons.map { it.rotateBy(rotation) } val translations = knownBeacons .product(rotatedBeacons) .map { (a, b) -> a - b } for (translation in translations) { val translatedBeacons = rotatedBeacons.map { it + translation } val overlaps = translatedBeacons.count(knownBeacons::contains) if (overlaps >= 12) { return translation to translatedBeacons } } } return null } private fun <T, R> Iterable<T>.product(other: Iterable<R>): List<Pair<T, R>> { return flatMap { left -> other.map { right -> left to right } } } private infix fun Vector3.manhattanDistanceTo(other: Vector3): Int { val (deltaX, deltaY, deltaZ) = (other - this).abs() return deltaX + deltaY + deltaZ } private fun Vector3.rotateBy(rotation: Int): Vector3 { return when (rotation) { 0 -> Vector3(x, y, z) 1 -> Vector3(x, z, -y) 2 -> Vector3(x, -y, -z) 3 -> Vector3(x, -z, y) 4 -> Vector3(y, x, -z) 5 -> Vector3(y, z, x) 6 -> Vector3(y, -x, z) 7 -> Vector3(y, -z, -x) 8 -> Vector3(z, x, y) 9 -> Vector3(z, y, -x) 10 -> Vector3(z, -x, -y) 11 -> Vector3(z, -y, x) 12 -> Vector3(-x, y, -z) 13 -> Vector3(-x, z, y) 14 -> Vector3(-x, -y, z) 15 -> Vector3(-x, -z, -y) 16 -> Vector3(-y, x, z) 17 -> Vector3(-y, z, -x) 18 -> Vector3(-y, -x, -z) 19 -> Vector3(-y, -z, x) 20 -> Vector3(-z, x, -y) 21 -> Vector3(-z, y, x) 22 -> Vector3(-z, -x, y) 23 -> Vector3(-z, -y, -x) else -> throw IllegalArgumentException("rotation must be in [$ROTATION_RANGE], but was: $rotation") } } private companion object { private val ROTATION_RANGE = 0..23 } }
0
Kotlin
0
4
7cec2ac03705da007f227306ceb0e87f302e2e54
3,519
advent-2021
ISC License