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
004.median-of-two-sorted-arrays/solution.kt
JC6
45,993,346
false
{"Kotlin": 5788, "Java": 3827, "Python": 2717}
import kotlin.math.max import kotlin.math.min fun findMedianSortedArrays(nums1: IntArray, nums2: IntArray): Double { val size = nums1.size + nums2.size return if (size % 2 == 0) { (findK(nums1, nums2, size / 2) + findK(nums1, nums2, size / 2 + 1)) / 2.0 } else { findK(nums1, nums2, size / 2 + 1).toDouble() } } fun findK(nums1: IntArray, nums2: IntArray, k: Int): Int { var i = max(0, k - nums2.size) var j = min(k, nums1.size) while (i < j) { val m = (i + j) / 2 if (nums1[m] < nums2[k - m - 1]) { i = m + 1 } else { j = m } } return when (i) { 0 -> nums2[k - i - 1] k -> nums1[i - 1] else -> max(nums1[i - 1], nums2[k - i - 1]) } }
0
Kotlin
0
0
493dbe86cb1b59d4f3a770a8653ec3be1ff25b6d
773
LeetCode
MIT License
src/main/kotlin/com/nibado/projects/advent/y2018/Day20.kt
nielsutrecht
47,550,570
false
null
package com.nibado.projects.advent.y2018 import com.nibado.projects.advent.Day import com.nibado.projects.advent.Direction import com.nibado.projects.advent.Point import com.nibado.projects.advent.resourceString object Day20 : Day { private val input = resourceString(2018, 21).let { it.substring(1, it.length - 1) } private val directions = Direction.values().map { it.toString()[0] to it }.toMap() data class Tree(val steps: CharSequence, val branches: List<Tree>) { override fun toString() = StringBuilder().let { toString(it); it.toString() } private fun toString(builder: StringBuilder, depth: Int = 0) { val pre = " ".repeat(depth) builder.append(pre).append(if (steps.isBlank()) "*" else steps).append('\n') branches.forEach { it.toString(builder, depth + 1) } } fun walk(p: Point = Point(0, 0), set: MutableSet<Pair<Point, Point>>): Set<Pair<Point, Point>> { var cur = p for(s in steps) { val new = cur + directions[s]!! if(set.contains(new to cur)) { set += cur to new } } return set } } fun buildTree(s: CharSequence): Tree { val splits = findSplits(s).map { s.subSequence(it.first, it.second) } if (splits.size == 1) { return Tree(splits.first(), listOf()) } else { return Tree("", splits.map { buildTree(it) }) } } private fun findSplits(s: CharSequence): List<Pair<Int, Int>> { val splits = mutableListOf(0) var depth = 0 for (i in s.indices) { if (s[i] == ')') { depth-- if (depth == 0) { splits += i splits += i + 1 } } else if (s[i] == '(') { if (depth == 0) { splits += i splits += i + 1 } depth++ } else if (s[i] == '|' && depth == 0) { splits += i splits += i + 1 } } splits += s.length return splits.windowed(2, 2).map { (a, b) -> a to b } } override fun part1(): Int { /* * ENNWSWW NEWS * SSSEEN WNSE * EE SWEN * NNN */ val list = listOf("ENWWW(NEEE|SSE(EE|N))", "ENNWSWW(NEWS|)SSSEEN(WNSE|)EE(SWEN|)NNN") val inp = list[1] println(inp) val tree = buildTree(inp) println(tree) return 0 } override fun part2(): Int { return 0 } } fun main(args: Array<String>) { println(Day20.part1()) }
1
Kotlin
0
15
b4221cdd75e07b2860abf6cdc27c165b979aa1c7
2,858
adventofcode
MIT License
src/shmp/lang/language/lexis/Connotation.kt
ShMPMat
240,860,070
false
null
package shmp.lang.language.lexis import shmp.lang.language.LanguageException data class Connotation(var name: String, val strength: Double, var isGlobal: Boolean = false) { fun getCompatibility(that: Connotation) = (if (name == that.name) 1.0 else connotationsCompatibility[name]?.get(that.name))?.times(strength) operator fun plus(that: Connotation): Connotation { if (name != that.name) throw LanguageException("Cannot sum connotations $name and ${that.name}") return Connotation(name, strength + that.strength, isGlobal || that.isGlobal) } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Connotation) return false if (name != other.name) return false return true } override fun hashCode(): Int { return name.hashCode() } override fun toString() = "$name:$strength" } data class Connotations(val values: Set<Connotation> = setOf()) { constructor(values: List<Connotation>): this(values.toSet()) operator fun plus(that: Connotations): Connotations { val values = values.toMutableSet() for (value in that.values) { if (value in values) { val newConnotation = value + values.first { it == value } values.remove(value) values += newConnotation } else values += value } return Connotations(values) } override fun toString() = if (values.isNotEmpty()) values.joinToString() else "no connotations" } infix fun Connotations.distance(that: Connotations): Double { val mutualConnotations = values.mapNotNull { c -> val other = that.values.firstOrNull { c == it } ?: return@mapNotNull null c to other } val otherElementsAmount = values.size + that.values.size - 2 * mutualConnotations.size if (values.isEmpty() || that.values.isEmpty()) return 0.0 return mutualConnotations .map { (c1, c2) -> c1.strength * c2.strength } .toMutableList() .apply { addAll(List(otherElementsAmount) { 0.0 }) } .average() } infix fun List<Connotation>.distance(that: List<Connotation>) = Connotations(this) distance Connotations(that) infix fun Connotations.localDistance(that: Connotations): Double { val globalConnotations = values .filter { it.isGlobal && that.values.firstOrNull { c -> c == it }?.isGlobal ?: true } + that.values.filter { it.isGlobal && values.firstOrNull { c -> c == it }?.isGlobal ?: true } return values.filter { it !in globalConnotations } distance that.values.filter { it !in globalConnotations } } val connotationsCompatibility = mapOf<String, Map<String, Double>>( "small" to mapOf("big" to 0.0), "big" to mapOf("small" to 0.0), "young" to mapOf("old" to 0.0), "old" to mapOf("young" to 0.0), "comfort" to mapOf("not_comfort" to 0.0), "not_comfort" to mapOf("comfort" to 0.0), "defence" to mapOf("danger" to 0.0), "danger" to mapOf("defence" to 0.0), "light" to mapOf("darkness" to 0.0), "darkness" to mapOf("light" to 0.0), "understand" to mapOf("not_understand" to 0.0), "not_understand" to mapOf("understand" to 0.0) )
0
Kotlin
0
1
4d26b0d50a1c3c6318eede8dd9678d3765902d4b
3,307
LanguageGenerator
MIT License
src/Day07.kt
stephenkao
572,205,897
false
{"Kotlin": 14623}
enum class NodeType { FILE, DIRECTORY } class Node(nodeType: NodeType, filename: String, filesize: Int = 0, parentDirectory: Node? = null) { val nodeType = nodeType val filename = filename val filesize = filesize // only for files var parentDirectory = parentDirectory // only for directories var nodes = mutableListOf<Node>() fun getTotalSize(): Int { return nodes.fold(0) { acc, node -> when (node.nodeType) { NodeType.FILE -> acc + node.filesize NodeType.DIRECTORY -> acc + node.getTotalSize() } } } fun getFiles(): List<Node> { return nodes.filter { it.nodeType == NodeType.FILE } } fun getDirectories(): List<Node> { return nodes.filter { it.nodeType == NodeType.DIRECTORY } } fun isFile() = nodeType == NodeType.FILE fun isDirectory() = nodeType == NodeType.DIRECTORY } fun printTree(node: Node, depth: Int = 0) { val indentation = " ".repeat(depth) if (depth == 0) { println("$indentation ${node.filename} (${node.filesize})") } node.getFiles().forEach { node -> println("$indentation | ${node.filename} ${node.filesize}") } node.getDirectories().forEach { node -> println("$indentation | ${node.filename} (${node.filesize})") printTree(node, depth + 1) } } fun main() { val day = "07" val cdRegex = Regex("^\\$\\scd\\s(.*)$") val dirRegex = Regex("^dir\\s(.*)$") val fileRegex = Regex("^(\\d*)\\s(.*)$") fun generateFileSystem(input: List<String>): Node { val rootDirectory = Node(NodeType.DIRECTORY, "/") var currentDirectory = rootDirectory for (line in input) { if (cdRegex.matches(line)) { val (filename) = cdRegex.find(line)!!.destructured if (filename == "..") { currentDirectory = currentDirectory.parentDirectory!! // println("CHANGING TO .. (${currentDirectory.filename})") } else if (filename != "/") { currentDirectory = currentDirectory.getDirectories().find { it.filename == filename }!! // println("CHANGING TO $filename") } } else if (dirRegex.matches(line)) { val (filename) = dirRegex.find(line)!!.destructured currentDirectory.nodes.add(Node(NodeType.DIRECTORY, filename, parentDirectory = currentDirectory)) // println("ADD DIRECTORY $filename to ${currentDirectory.filename}") } else if (fileRegex.matches(line)) { val (filesize, filename) = fileRegex.find(line)!!.destructured currentDirectory.nodes.add(Node(NodeType.FILE, filename, filesize.toInt())) // println("ADD FILE $filename to ${currentDirectory.filename}") } } return rootDirectory } fun part1(input: List<String>): Int { val maxSize = 100000 val rootDirectory = generateFileSystem(input) fun getDeletionCandidateSum(node: Node, sum: Int = 0): Int { if (node.isFile() || node.nodes.size == 0) { return sum } val totalSize = node.getTotalSize() var baseVal = if (totalSize <= maxSize) sum + totalSize else sum return node.nodes.fold(baseVal) { acc, node -> getDeletionCandidateSum(node, acc) } } return getDeletionCandidateSum(rootDirectory) } fun part2(input: List<String>): Int { val rootDirectory = generateFileSystem(input) val unusedSpace = 70000000 - rootDirectory.getTotalSize() val requiredSpace = 30000000 - unusedSpace fun getDeletionCandidateSize(node: Node, size: Int): Int { val totalSize = node.getTotalSize() var smallestSize = size if (totalSize in requiredSpace..smallestSize) { smallestSize = totalSize } node.getDirectories().forEach { node -> smallestSize = getDeletionCandidateSize(node, smallestSize) } return smallestSize } return getDeletionCandidateSize(rootDirectory, rootDirectory.getTotalSize()) } val testInput = readInput("Day${day}_test") check(part1(testInput) == 95437) check(part2(testInput) == 24933642) val input = readInput("Day${day}") println("Part 1: ${part1(input)}") println("Part 2: ${part2(input)}") }
0
Kotlin
0
0
7a1156f10c1fef475320ca985badb4167f4116f1
4,545
advent-of-code-kotlin-2022
Apache License 2.0
src/nativeMain/kotlin/Day12.kt
rubengees
576,436,006
false
{"Kotlin": 67428}
class Day12 : Day { private companion object { private const val START = 'S' private const val END = 'E' } private data class Point(val x: Int, val y: Int) private class Matrix(private val data: List<List<Char>>) { private val points get() = data.indices.flatMap { y -> data[y].indices.map { x -> Point(x, y) } } val start = points.filter { get(it) == START } val end = points.find { get(it) == END } ?: error("Missing end") operator fun get(point: Point) = data[point.y][point.x] fun height(point: Point): Int { return when (val char = get(point)) { START -> 0 END -> 25 else -> char.code - 'a'.code } } fun neighbours(point: Point): List<Point> { val (x, y) = point return listOf(Point(x, y - 1), Point(x, y + 1), Point(x - 1, y), Point(x + 1, y)) .filter { data.getOrNull(it.y)?.getOrNull(it.x) != null } .filter { height(point) >= height(it) - 1 } } fun withAAsStart(): Matrix { return Matrix(data.map { lines -> lines.map { char -> if (char == 'a') START else char } }) } } private class PriorityQueue<T>(private val comparator: Comparator<T>, data: Iterable<T> = emptyList()) { private val data = data.sortedWith(comparator).toMutableList() fun enqueue(item: T) { var index = data.binarySearch(item, comparator) if (index < 0) index = -index - 1 data.add(index, item) } fun dequeue(): T? { return data.removeFirst() } fun isNotEmpty() = data.isNotEmpty() } private fun parse(input: String): Matrix { val data = input.lines().map { line -> line.toCharArray().toList() } return Matrix(data) } private fun aStar(matrix: Matrix, h: (a: Point, b: Point) -> Int): List<Point>? { val cameFrom = mutableMapOf<Point, Point>() val gScore = matrix.start.associateWith { 0 }.toMutableMap() val openSet = PriorityQueue(compareBy { gScore.getValue(it) + h(it, matrix.end) }, matrix.start) fun reconstructPath(): List<Point> { val result = mutableListOf(matrix.end) var current = matrix.end while (current in cameFrom) { current = cameFrom.getValue(current) result.add(current) } return result } while (openSet.isNotEmpty()) { val current = openSet.dequeue() ?: error("openSet is empty") if (current == matrix.end) { return reconstructPath() } for (neighbour in matrix.neighbours(current)) { val score = gScore.getValue(current) + 1 if (score < gScore.getOrElse(neighbour) { Int.MAX_VALUE }) { cameFrom[neighbour] = current gScore[neighbour] = score openSet.enqueue(neighbour) } } } return null } override suspend fun part1(input: String): String { val matrix = parse(input) val heuristic = { _: Point, _: Point -> 0 } val shortestPath = aStar(matrix, heuristic) ?: error("No path found") return (shortestPath.count() - 1).toString() } override suspend fun part2(input: String): String { val matrix = parse(input) val heuristic = { _: Point, _: Point -> 0 } val shortestPath = aStar(matrix.withAAsStart(), heuristic) ?: error("No path found") return (shortestPath.count() - 1).toString() } }
0
Kotlin
0
0
21f03a1c70d4273739d001dd5434f68e2cc2e6e6
3,743
advent-of-code-2022
MIT License
src/Day03.kt
Pixselve
572,907,486
false
{"Kotlin": 7404}
fun main() { fun characterPriority(char: Char) = if (char.code >= 97) char.code - 96 else char.code - 65 + 27 fun part1(input: List<String>): Int { return input.fold(0) { acc, line -> val firstPart = line.slice(0 until line.length / 2) val secondPart = line.slice(line.length / 2 until line.length) val intersection = firstPart.toSet().intersect(secondPart.toSet()) acc + intersection.fold(0) { acc2, char -> acc2 + (characterPriority(char)) } } } fun part2(input: List<String>): Int { // group 3 lines together return input.chunked(3).sumOf { val common = it[0].toSet().intersect(it[1].toSet()).intersect(it[2].toSet()) characterPriority(common.first()) } } val testInput = readInput("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
10e14393b8b6ee3f98dfd4c37e32ad81f9952533
999
advent-of-code-2022-kotlin
Apache License 2.0
app/src/main/kotlin/com/resurtm/aoc2023/day13/Solution.kt
resurtm
726,078,755
false
{"Kotlin": 119665}
package com.resurtm.aoc2023.day13 fun launchDay13(testCase: String) { val input = readInput(testCase) println("Day 13, part 1: ${calcPart1(input)}") println("Day 13, part 2: ${calcPart2(input)}") } private fun calcPart2(input: Input): Int { var result = 0 input.forEach { pattern -> val res = smudge(pattern) result += if (res.first.first) (res.first.second + 1) * 100 else 0 result += if (res.second.first) res.second.second + 1 else 0 } return result } private fun smudge(pattern: Pattern): Pair<Pair<Boolean, Int>, Pair<Boolean, Int>> { val h = checkPatternHorizontal(pattern) val v = checkPatternVertical(pattern) for (row in pattern.indices) { for (col in pattern[row].indices) { val smudged = pattern.map { it.toMutableList() } smudged[row][col] = if (smudged[row][col] == '.') '#' else '.' val hor = checkPatternHorizontal(smudged) hor.forEach { if (h.isNotEmpty() && h.first().first && h.first().second != it.second) return Pair(it, Pair(false, -1)) else if (v.isNotEmpty() && v.first().first) return Pair(it, Pair(false, -1)) } val ver = checkPatternVertical(smudged) ver.forEach { if (v.isNotEmpty() && v.first().first && v.first().second != it.second) return Pair(Pair(false, -1), it) else if (h.isNotEmpty() && h.first().first) return Pair(Pair(false, -1), it) } } } return Pair(Pair(false, -1), Pair(false, -1)) } private fun calcPart1(input: Input): Int { var result = 0 input.forEach { pattern -> val hor = checkPatternHorizontal(pattern) val ver = checkPatternVertical(pattern) result += if (hor.isNotEmpty() && hor.first().first) (hor.first().second + 1) * 100 else 0 result += if (ver.isNotEmpty() && ver.first().first) ver.first().second + 1 else 0 } return result } private fun checkPatternHorizontal(pattern: Pattern): List<Pair<Boolean, Int>> { val result = mutableListOf<Pair<Boolean, Int>>() for (row0 in 0..<pattern.size - 1) { var row1 = row0 var row2 = row0 + 1 var size = 0 var allMatch = true loop@ while (row1 >= 0 && row2 < pattern.size) { for (col in pattern[0].indices) if (pattern[row1][col] != pattern[row2][col]) { allMatch = false break@loop } row1-- row2++ size++ } if (allMatch && (row1 == -1 || row2 == pattern.size)) result.add(Pair(true, row0)) } return result } private fun checkPatternVertical(pattern: Pattern): List<Pair<Boolean, Int>> { val result = mutableListOf<Pair<Boolean, Int>>() for (col0 in 0..<pattern[0].size - 1) { var col1 = col0 var col2 = col0 + 1 var size = 0 var allMatch = true loop@ while (col1 >= 0 && col2 < pattern[0].size) { for (row in pattern.indices) if (pattern[row][col1] != pattern[row][col2]) { allMatch = false break@loop } col1-- col2++ size++ } if (allMatch && (col1 == -1 || col2 == pattern[0].size)) result.add(Pair(true, col0)) } return result } private fun readInput(testCase: String): Input { val reader = object {}.javaClass.getResourceAsStream(testCase)?.bufferedReader() ?: throw Exception("Invalid state, cannot read the input") val input: MutableList<List<MutableList<Char>>> = mutableListOf() var pattern: MutableList<MutableList<Char>> = mutableListOf() var curr = 0 while (true) { val rawLine = (reader.readLine() ?: break).trim() if (rawLine.isEmpty()) { input.add(pattern) pattern = mutableListOf() curr++ } else pattern.add(rawLine.toMutableList()) } input.add(pattern) return input } private typealias Input = List<Pattern> private typealias Pattern = List<MutableList<Char>>
0
Kotlin
0
0
fb8da6c246b0e2ffadb046401502f945a82cfed9
4,214
advent-of-code-2023
MIT License
bot/src/main/kotlin/util/DamerauLevenshtein.kt
NyCodeGHG
511,133,398
false
{"Kotlin": 54668, "Dockerfile": 334}
package dev.nycode.regenbogenice.util import kotlin.math.min /** * Calculates the string distance between source and target strings using * the Damerau-Levenshtein algorithm. The distance is case-sensitive. * * @param source The source String. * @param target The target String. * @return The distance between source and target strings. */ fun calculateDistance(source: CharSequence, target: CharSequence): Int { val sourceLength = source.length val targetLength = target.length if (sourceLength == 0) return targetLength if (targetLength == 0) return sourceLength val dist = Array(sourceLength + 1) { IntArray(targetLength + 1) } for (i in 0 until sourceLength + 1) { dist[i][0] = i } for (j in 0 until targetLength + 1) { dist[0][j] = j } for (i in 1 until sourceLength + 1) { for (j in 1 until targetLength + 1) { val cost = if (source[i - 1] == target[j - 1]) 0 else 1 dist[i][j] = min( min(dist[i - 1][j] + 1, dist[i][j - 1] + 1), dist[i - 1][j - 1] + cost ) if (i > 1 && j > 1 && source[i - 1] == target[j - 2] && source[i - 2] == target[j - 1]) { dist[i][j] = min(dist[i][j], dist[i - 2][j - 2] + cost) } } } return dist[sourceLength][targetLength] } inline fun <T> Collection<T>.minByDistanceOrNull( text: CharSequence, toString: (T) -> CharSequence = { it.toString() } ) = minByOrNull { calculateDistance(text, toString(it)) }
8
Kotlin
0
6
65738ee9202382834d3accbe27a24c8fa3d7d63f
1,546
regenbogen-ice
MIT License
kotlin/src/main/kotlin/com/github/jntakpe/aoc2022/days/Day8.kt
jntakpe
572,853,785
false
{"Kotlin": 72329, "Rust": 15876}
package com.github.jntakpe.aoc2022.days import com.github.jntakpe.aoc2022.shared.Day import com.github.jntakpe.aoc2022.shared.readInputLines import kotlin.math.abs object Day8 : Day { override val input = readInputLines(8).map { c -> c.map { it.digitToInt() }.toTypedArray() }.toTypedArray() override fun part1(): Int { return input .flatMapIndexed { y, a -> a.mapIndexed { x, v -> isVisible(x, y, v, input) } } .count { it } } override fun part2(): Int { return input .flatMapIndexed { y, a -> a.mapIndexed { x, v -> scenicScore(x, y, v, input) } } .max() } private fun isVisible(x: Int, y: Int, size: Int, positions: Array<Array<Int>>): Boolean { val edge = positions.lastIndex val column = (0..edge).map { positions[it][x] }.toTypedArray() return listOf(x, y).any { it in listOf(0, edge) } || hasTree(0 until x, positions[y], size) || hasTree(x + 1..edge, positions[y], size) || hasTree(0 until y, column, size) || hasTree(y + 1..edge, column, size) } private fun scenicScore(x: Int, y: Int, size: Int, positions: Array<Array<Int>>): Int { val edge = positions.lastIndex if (listOf(x, y).any { it in listOf(0, edge) }) return 0 var score = view(x - 1 downTo 0, positions[y], size) score *= view(x + 1..edge, positions[y], size) val column = (0..edge).map { positions[it][x] }.toTypedArray() score *= view(y - 1 downTo 0, column, size) score *= view(y + 1..edge, column, size) return score } private fun hasTree(range: IntRange, line: Array<Int>, size: Int) = !range.any { line[it] >= size } private fun view(range: IntProgression, line: Array<Int>, size: Int): Int { return (range.indexOfFirst { line[it] >= size }.takeIf { it >= 0 } ?: abs(range.first - range.last)) + 1 } }
1
Kotlin
0
0
63f48d4790f17104311b3873f321368934060e06
1,958
aoc2022
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/UniquePaths2.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2021 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode /** * Unique Paths II * @see <a href="https://leetcode.com/problems/unique-paths-ii/">Source</a> */ fun interface UniquePaths2 { /** * Calculates the number of unique paths from the top-left corner to the bottom-right corner * of a grid, considering obstacles. * * @param obstacleGrid A 2D array representing the grid with obstacles (0 for open cell, 1 for obstacle). * @return The number of unique paths from top-left to bottom-right. */ operator fun invoke(obstacleGrid: Array<IntArray>): Int } /** * Approach 1: Dynamic Programming * Time Complexity: O(M times N). * Space Complexity: O(1). */ class UniquePaths2DP : UniquePaths2 { override operator fun invoke(obstacleGrid: Array<IntArray>): Int { val r: Int = obstacleGrid.size val c: Int = obstacleGrid[0].size // If the starting cell has an obstacle, then simply return as there would be // no paths to the destination. if (obstacleGrid[0][0] == 1) { return 0 } // Number of ways of reaching the starting cell = 1. obstacleGrid[0][0] = 1 // Filling the values for the first column for (i in 1 until r) { obstacleGrid[i][0] = if (obstacleGrid[i][0] == 0 && obstacleGrid[i - 1][0] == 1) 1 else 0 } // Filling the values for the first row for (i in 1 until c) { obstacleGrid[0][i] = if (obstacleGrid[0][i] == 0 && obstacleGrid[0][i - 1] == 1) 1 else 0 } // Starting from cell(1,1) fill up the values // No. of ways of reaching cell[i][j] = cell[i - 1][j] + cell[i][j - 1] // i.e. From above and left. for (i in 1 until r) { for (j in 1 until c) { if (obstacleGrid[i][j] == 0) { obstacleGrid[i][j] = obstacleGrid[i - 1][j] + obstacleGrid[i][j - 1] } else { obstacleGrid[i][j] = 0 } } } // Return value stored in rightmost bottommost cell. That is the destination. return obstacleGrid[r - 1][c - 1] } } /** * A more concise approach using Kotlin features. */ class UniquePaths2Short : UniquePaths2 { override operator fun invoke(obstacleGrid: Array<IntArray>): Int { val width = obstacleGrid[0].size val dp = IntArray(width) { 0 } dp[0] = 1 obstacleGrid.forEach { row -> for (j in 0 until width) { dp[j] = if (row[j] == 1) 0 else dp.getOrElse(j - 1) { 0 } + dp[j] } } return dp.last() } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,258
kotlab
Apache License 2.0
src/year2023/day04/Solution.kt
TheSunshinator
572,121,335
false
{"Kotlin": 144661}
package year2023.day04 import arrow.core.nonEmptyListOf import kotlin.math.pow import utils.ProblemPart import utils.readInputs import utils.runAlgorithm fun main() { val (realInput, testInputs) = readInputs(2023, 4, transform = ::parse) runAlgorithm( realInput = realInput, testInputs = testInputs, part1 = ProblemPart( expectedResultsForTests = nonEmptyListOf(13), algorithm = ::part1, ), part2 = ProblemPart( expectedResultsForTests = nonEmptyListOf(30), algorithm = ::part2, ), ) } private fun parse(input: List<String>): List<Int> = input.map { line -> winningNumberRegex.findAll(line).count() } private val winningNumberRegex = "(?<= )(\\d+)(?= .*\\|.* \\1(?!\\d))".toRegex() private fun part1(input: List<Int>): Long { return input.sumOf { if (it == 0) 0L else 2.0.pow(it - 1).toLong() } } private fun part2(input: List<Int>): Long { val counts = MutableList(input.size) { 1L } input.forEachIndexed { index, winningNumberCount -> (1..winningNumberCount).asSequence() .map { it + index } .forEach { indexToAddCopies -> counts[indexToAddCopies] += counts[index] } } return counts.reduce(Long::plus) }
0
Kotlin
0
0
d050e86fa5591447f4dd38816877b475fba512d0
1,307
Advent-of-Code
Apache License 2.0
src/day22/Code.kt
fcolasuonno
572,734,674
false
{"Kotlin": 63451, "Dockerfile": 1340}
package day22 import Coord import day06.main import readInput fun main() { abstract class Tile { abstract val nextStep: MutableList<Coord> abstract val nextDir: MutableList<Int> } data class Step( override val nextStep: MutableList<Coord> = mutableListOf(), override val nextDir: MutableList<Int> = mutableListOf() ) : Tile() data class Wall( override val nextStep: MutableList<Coord> = mutableListOf(), override val nextDir: MutableList<Int> = mutableListOf() ) : Tile() data class Position(val coord: Coord, val dir: Int = 0) { fun password() = 4 * (coord.first + 1) + 1000 * (coord.second + 1) + dir } fun parseMap(input: List<String>) = input.flatMapIndexed { y, s -> s.mapIndexedNotNull { x, type -> when (type) { '.' -> Coord(x, y) to Step() '#' -> Coord(x, y) to Wall() else -> null } } }.toMap() fun parseInstructions(instructions: String) = instructions.run { split("""\d+""".toRegex()).zip(split("""\D+""".toRegex())) { dir, amount -> when (dir) { "R" -> 1 "L" -> -1 else -> 0 } to amount.toInt() } } fun parse(input: List<String>) = parseMap(input.takeWhile { it.isNotEmpty() }) to parseInstructions(input.last()) fun Map<Coord, Tile>.wrapPart1() { forEach { (c, tile) -> val next = c.copy(first = c.first + 1) tile.nextStep.add(when (this[next]) { is Step -> next is Wall -> c else -> keys.filter { it.second == c.second }.minBy { it.first }.takeIf { this[it]!! is Step } ?: c }) tile.nextDir.add(0) } forEach { (c, tile) -> val next = c.copy(second = c.second + 1) tile.nextStep.add(when (this[next]) { is Step -> next is Wall -> c else -> keys.filter { it.first == c.first }.minBy { it.second }.takeIf { this[it]!! is Step } ?: c }) tile.nextDir.add(0) } forEach { (c, tile) -> val next = c.copy(first = c.first - 1) tile.nextStep.add(when (this[next]) { is Step -> next is Wall -> c else -> keys.filter { it.second == c.second }.maxBy { it.first }.takeIf { this[it]!! is Step } ?: c }) tile.nextDir.add(0) } forEach { (c, tile) -> val next = c.copy(second = c.second - 1) tile.nextStep.add(when (this[next]) { is Step -> next is Wall -> c else -> keys.filter { it.first == c.first }.maxBy { it.second }.takeIf { this[it]!! is Step } ?: c }) tile.nextDir.add(0) } } fun part1(input: List<String>) = parse(input).let { (map, instructions) -> map.apply { wrapPart1() } instructions.fold(Position(map.keys.minWith(compareBy(Coord::second, Coord::first)))) { position, instr -> val (turn, walk) = instr val newDir = (position.dir + turn + 4) % 4 var newCoord = position.coord repeat(walk) { newCoord = map[newCoord]!!.nextStep[newDir] } position.copy(coord = newCoord, dir = newDir) }.password() } fun Map<Coord, Tile>.wrapPart2( right: (Coord) -> Coord, left: (Coord) -> Coord, up: (Coord) -> Coord, down: (Coord) -> Coord, rightDir: (Coord) -> Int, leftDir: (Coord) -> Int, upDir: (Coord) -> Int, downDir: (Coord) -> Int, ) { forEach { (c, tile) -> val next = c.copy(first = c.first + 1) tile.nextStep.add(when (this[next]) { is Step -> next is Wall -> c else -> right(c).takeIf { this[it]!! is Step } ?: c }) tile.nextDir.add( if (this[next] == null && this[right(c)]!! is Step) rightDir(c) else 0 ) } forEach { (c, tile) -> val next = c.copy(second = c.second + 1) tile.nextStep.add(when (this[next]) { is Step -> next is Wall -> c else -> down(c).takeIf { this[it]!! is Step } ?: c }) tile.nextDir.add( if (this[next] == null && this[down(c)]!! is Step) downDir(c) else 1 ) } forEach { (c, tile) -> val next = c.copy(first = c.first - 1) tile.nextStep.add(when (this[next]) { is Step -> next is Wall -> c else -> left(c).takeIf { this[it]!! is Step } ?: c }) tile.nextDir.add( if (this[next] == null && this[left(c)]!! is Step) leftDir(c) else 2 ) } forEach { (c, tile) -> val next = c.copy(second = c.second - 1) tile.nextStep.add(when (this[next]) { is Step -> next is Wall -> c else -> up(c).takeIf { this[it]!! is Step } ?: c }) tile.nextDir.add( if (this[next] == null && this[up(c)]!! is Step) upDir(c) else 3 ) } } val SIZE = 50 fun part2(input: List<String>) = parse(input).let { (map, instructions) -> map.apply { wrapPart2(right = { when (it.second) { in (0 * SIZE) until (1 * SIZE) -> Coord(2 * SIZE - 1, 3 * SIZE - it.second - 1) in (1 * SIZE) until (2 * SIZE) -> Coord(1 * SIZE + it.second, 1 * SIZE - 1) in (2 * SIZE) until (3 * SIZE) -> Coord(3 * SIZE - 1, 3 * SIZE - it.second - 1) else -> Coord(1 * SIZE + (it.second - 3 * SIZE), 3 * SIZE - 1) } }, left = { when (it.second) { in (0 * SIZE) until (1 * SIZE) -> Coord(0, 3 * SIZE - it.second - 1) in (1 * SIZE) until (2 * SIZE) -> Coord(it.second - 1 * SIZE, 2 * SIZE) in (2 * SIZE) until (3 * SIZE) -> Coord(1 * SIZE, 3 * SIZE - 1 - it.second) else -> Coord(it.second - 2 * SIZE, 0) } }, up = { when (it.first) { in (0 * SIZE) until (1 * SIZE) -> Coord(1 * SIZE, 1 * SIZE + it.first) in (1 * SIZE) until (2 * SIZE) -> Coord(0, 2 * SIZE + it.first) else -> Coord(it.first - 2 * SIZE, 4 * SIZE - 1) } }, down = { when (it.first) { in (0 * SIZE) until (1 * SIZE) -> Coord(2 * SIZE + it.first, 0) in (1 * SIZE) until (2 * SIZE) -> Coord(1 * SIZE - 1, 2 * SIZE + it.first) else -> Coord(2 * SIZE - 1, it.first - 1 * SIZE) } }, rightDir = { when (it.second) { in (0 * SIZE) until (1 * SIZE) -> 2 in (1 * SIZE) until (2 * SIZE) -> 3 in (2 * SIZE) until (3 * SIZE) -> 2 else -> 3 } }, leftDir = { when (it.second) { in (0 * SIZE) until (1 * SIZE) -> 0 in (1 * SIZE) until (2 * SIZE) -> 1 in (2 * SIZE) until (3 * SIZE) -> 0 else -> 1 } }, upDir = { when (it.first) { in (0 * SIZE) until (1 * SIZE) -> 0 in (1 * SIZE) until (2 * SIZE) -> 0 else -> 3 } }, downDir = { when (it.first) { in (0 * SIZE) until (1 * SIZE) -> 1 in (1 * SIZE) until (2 * SIZE) -> 2 else -> 2 } }) } instructions.fold(Position(map.keys.minWith(compareBy(Coord::second, Coord::first)))) { position, instr -> val (turn, walk) = instr var newDir = (position.dir + turn + 4) % 4 var newCoord = position.coord repeat(walk) { val tmp = map[newCoord]!!.nextStep[newDir] newDir = map[newCoord]!!.nextDir[newDir] newCoord = tmp } Position(coord = newCoord, dir = newDir) }.password() } val input = readInput(::main.javaClass.packageName, false) println("Part1=\n" + part1(input)) println("Part2=\n" + part2(input)) }
0
Kotlin
0
0
9cb653bd6a5abb214a9310f7cac3d0a5a478a71a
8,973
AOC2022
Apache License 2.0
kotlin/structures/WaveletTree.kt
polydisc
281,633,906
true
{"Java": 540473, "Kotlin": 515759, "C++": 265630, "CMake": 571}
package structures import java.util.Arrays object WaveletTree { fun createTree(a: IntArray): Node { val lo: Int = Arrays.stream(a).min().orElse(Integer.MAX_VALUE) val hi: Int = Arrays.stream(a).max().orElse(Integer.MIN_VALUE) return build(a, 0, a.size, lo, hi) } fun build(a: IntArray, from: Int, to: Int, lo: Int, hi: Int): Node { val node = Node() node.lo = lo node.hi = hi if (lo < hi && from < to) { val mid = lo + hi ushr 1 val p: Predicate<Integer?> = Predicate<Integer> { x -> x <= mid } node.b = IntArray(to - from + 1) var i = 0 while (i + 1 < node.b.size) { node.b[i + 1] = node.b[i] + if (p.test(a[i + from])) 1 else 0 i++ } val pivot = stablePartition(a, from, to, p) node.left = build(a, from, pivot, lo, mid) node.right = build(a, pivot, to, mid + 1, hi) } return node } fun stablePartition(a: IntArray, from: Int, to: Int, p: Predicate<Integer?>): Int { val b1 = IntArray(to - from + 1) val b2 = IntArray(to - from + 1) var cnt1 = 0 var cnt2 = 0 for (i in from until to) { if (p.test(a[i])) { b1[cnt1++] = a[i] } else { b2[cnt2++] = a[i] } } System.arraycopy(b1, 0, a, from, cnt1) System.arraycopy(b2, 0, a, from + cnt1, cnt2) return cnt1 } // Usage example fun main(args: Array<String?>?) { val a = intArrayOf(5, 1, 2, 1, 1) val t = createTree(a) System.out.println(t.countEq(1, 5, 1)) } class Node { var lo = 0 var hi = 0 var left: Node? = null var right: Node? = null var b: IntArray // kth smallest element in [from, to] fun kth(from: Int, to: Int, k: Int): Int { if (from > to) return 0 if (lo == hi) return lo val inLeft = b[to] - b[from - 1] val lb = b[from - 1] // amt of nos in first (from-1) nos that go in left val rb = b[to] // amt of nos in first (to) nos that go in left return if (k <= inLeft) left!!.kth(lb + 1, rb, k) else right!!.kth(from - lb, to - rb, k - inLeft) } // number of elements in [from, to] less than or equal to k fun countLessOrEq(from: Int, to: Int, k: Int): Int { if (from > to || k < lo) return 0 if (hi <= k) return to - from + 1 val lb = b[from - 1] val rb = b[to] return left!!.countLessOrEq(lb + 1, rb, k) + right!!.countLessOrEq(from - lb, to - rb, k) } // number of elements in [from, to] equal to k fun countEq(from: Int, to: Int, k: Int): Int { if (from > to || k < lo || k > hi) return 0 if (lo == hi) return to - from + 1 val lb = b[from - 1] val rb = b[to] val mid = lo + hi ushr 1 return if (k <= mid) left!!.countEq(lb + 1, rb, k) else right!!.countEq(from - lb, to - rb, k) } } }
1
Java
0
0
4566f3145be72827d72cb93abca8bfd93f1c58df
3,190
codelibrary
The Unlicense
core/src/org/flightofstairs/redesignedPotato/model/Encounter.kt
FlightOfStairs
95,606,091
false
null
package org.flightofstairs.redesignedPotato.model import org.flightofstairs.redesignedPotato.model.EncounterDifficulty.* data class Thresholds(val easy: Int, val medium: Int, val hard: Int, val deadly: Int) { operator fun plus(other: Thresholds) = Thresholds(easy + other.easy, medium + other.medium, hard + other.hard, deadly + other.deadly) } enum class EncounterDifficulty { Easy, Medium, Hard, Deadly, } // See DMG p82-83 data class Encounter(val players: List<PlayerCharacter>, val monsters: List<MonsterInfo>) { val partyThresholds = players.map { levelXpThresholds[it.level] ?: throw IllegalArgumentException("Not a valid level: ${it.level}") }.reduce { left, right -> left + right } val monsterXp = monsters.sumBy { it.xp } val encounterMultiplier = encounterMultiplier(players.size, monsters.size) val adjustedXp = (monsterXp * encounterMultiplier).toInt() val encounterDifficulty = when { adjustedXp >= partyThresholds.deadly -> Deadly adjustedXp >= partyThresholds.hard -> Hard adjustedXp >= partyThresholds.deadly -> Medium else -> Easy } companion object { private fun encounterMultiplier(players: Int, monsters: Int): Double { val multipliers = listOf(0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 4.0, 5.0) val position = when (monsters) { 1 -> 1 2 -> 2 3, 4, 5, 6 -> 3 7, 8, 9, 10 -> 4 11, 12, 13, 14 -> 5 else -> 6 } + when { players < 3 -> 1 players > 5 -> -1 else -> 0 } return multipliers[minOf(position, multipliers.size - 1)] } } } internal val levelXpThresholds = mapOf( 1 to Thresholds(25, 50, 75, 100), 2 to Thresholds(50, 100, 150, 200), 3 to Thresholds(75, 150, 225, 400), 4 to Thresholds(125, 250, 375, 500), 5 to Thresholds(250, 500, 750, 1100), 6 to Thresholds(300, 600, 900, 1400), 7 to Thresholds(350, 750, 1100, 1700), 8 to Thresholds(450, 900, 1400, 2100), 9 to Thresholds(550, 1100, 1600, 2400), 10 to Thresholds(600, 1200, 1900, 2800), 11 to Thresholds(800, 1600, 2400, 3600), 12 to Thresholds(1000, 2000, 3000, 4500), 13 to Thresholds(1100, 2200, 3400, 5100), 14 to Thresholds(1250, 2500, 3800, 5700), 15 to Thresholds(1400, 2800, 4300, 6400), 16 to Thresholds(1600, 3200, 4800, 7200), 17 to Thresholds(2000, 3900, 5900, 8800), 18 to Thresholds(2100, 4200, 6300, 9500), 19 to Thresholds(2400, 4900, 7300, 10900), 20 to Thresholds(2800, 5700, 8500, 12700))
0
Kotlin
0
0
530a011e884ddfa8c6b39529c1d187441e36478a
2,736
redesigned-potato
MIT License
src/Day09.kt
Aldas25
572,846,570
false
{"Kotlin": 106964}
import kotlin.math.abs fun main() { val dirs = mapOf( 'U' to Pair(0, 1), 'D' to Pair(0, -1), 'R' to Pair(1, 0), 'L' to Pair(-1, 0) ) fun moveTail (head: Pair<Int, Int>, tail: Pair<Int, Int>): Pair<Int, Int> { var dx = head.first - tail.first var dy = head.second - tail.second if (maxOf(abs(dx), abs(dy)) <= 1) return tail dx = minOf(1, maxOf(-1, dx)) dy = minOf(1, maxOf(-1, dy)) return Pair(tail.first + dx, tail.second + dy) } fun part1(input: List<String>): Int { var head = Pair(0, 0) var tail = Pair(0, 0) val positions = mutableSetOf(tail) for (s in input) { val move = s[0] val count = s.substring(2).toInt() repeat(count) { head = Pair( head.first + dirs[move]!!.first, head.second + dirs[move]!!.second ) tail = moveTail(head, tail) // println(" head: $head, tail: $tail") positions.add(tail) } } return positions.size } fun part2(input: List<String>): Int { val rope = Array(10) { Pair(0, 0) } val positions = mutableSetOf(rope[9]) for (s in input) { val move = s[0] val count = s.substring(2).toInt() repeat(count) { rope[0] = Pair( rope[0].first + dirs[move]!!.first, rope[0].second + dirs[move]!!.second ) for (i in 1..9) { rope[i] = moveTail(rope[i-1], rope[i]) } // println(" head: $head, tail: $tail") positions.add(rope[9]) } } return positions.size } val filename = // "inputs/day09_sample" // "inputs/day09_sample2" "inputs/day09" val input = readInput(filename) println("Part 1: ${part1(input)}") println("Part 2: ${part2(input)}") }
0
Kotlin
0
0
80785e323369b204c1057f49f5162b8017adb55a
2,092
Advent-of-Code-2022
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/BusRoutes.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.awt.Point import java.util.LinkedList import java.util.Queue /** * 815. Bus Routes * @see <a href="https://leetcode.com/problems/bus-routes/">Source</a> */ fun interface BusRoutes { fun numBusesToDestination(routes: Array<IntArray>, source: Int, target: Int): Int } /** * Approach #1: Breadth First Search */ class BusRoutesBFS : BusRoutes { override fun numBusesToDestination(routes: Array<IntArray>, source: Int, target: Int): Int { if (source == target) return 0 val n: Int = routes.size val graph: MutableList<MutableList<Int>> = ArrayList() for (i in 0 until n) { routes[i].sort() graph.add(ArrayList()) } val seen: MutableSet<Int> = HashSet() val targets: MutableSet<Int> = HashSet() val queue: Queue<Point> = LinkedList() // Build the graph. Two buses are connected if // they share at least one bus stop. for (i in 0 until n) for (j in i + 1 until n) if (intersect(routes[i], routes[j])) { graph[i].add(j) graph[j].add(i) } // Initialize seen, queue, targets. // seen represents whether a node has ever been enqueued to queue. // queue handles our breadth first search. // targets is the set of goal states we have. for (i in 0 until n) { if (routes[i].binarySearch(source) >= 0) { seen.add(i) queue.offer(Point(i, 0)) } if (routes[i].binarySearch(target) >= 0) { targets.add(i) } } while (queue.isNotEmpty()) { val info: Point = queue.poll() val node: Int = info.x val depth: Int = info.y if (targets.contains(node)) return depth + 1 for (nei in graph[node]) { if (!seen.contains(nei)) { seen.add(nei) queue.offer(Point(nei, depth + 1)) } } } return -1 } private fun intersect(a: IntArray, b: IntArray): Boolean { var i = 0 var j = 0 while (i < a.size && j < b.size) { if (a[i] == b[j]) return true if (a[i] < b[j]) i++ else j++ } return false } } class BusRoutesBFS2 : BusRoutes { override fun numBusesToDestination(routes: Array<IntArray>, source: Int, target: Int): Int { val n: Int = routes.size val toRoutes = HashMap<Int, HashSet<Int>>() for (i in routes.indices) { for (j in routes[i]) { if (!toRoutes.containsKey(j)) toRoutes[j] = HashSet() toRoutes[j]?.add(i) } } val bfs: Queue<IntArray> = LinkedList() bfs.offer(intArrayOf(source, 0)) val seen = HashSet<Int>() seen.add(source) val seenRoutes = BooleanArray(n) while (bfs.isNotEmpty()) { val stop = bfs.peek()[0] val bus = bfs.peek()[1] bfs.poll() if (stop == target) return bus for (i in toRoutes.getOrDefault(stop, HashSet())) { if (seenRoutes[i]) continue for (j in routes[i]) { if (!seen.contains(j)) { seen.add(j) bfs.offer(intArrayOf(j, bus + 1)) } } seenRoutes[i] = true } } return -1 } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
4,158
kotlab
Apache License 2.0
src/aoc2018/kot/Day10.kt
Tandrial
47,354,790
false
null
package aoc2018.kot import getNumbers import java.io.File object Day10 { data class Particle(var x: Int, var y: Int, val xSpeed: Int, val ySpeed: Int) { fun tick() { x += xSpeed y += ySpeed } } fun solve(input: List<String>): Pair<String, Int> { val particles = parse(input) var s = 0 while (true) { val (lminX, lminY) = Pair(particles.minBy { it.x }!!.x, particles.minBy { it.y }!!.y) val (lmaxX, lmaxY) = Pair(particles.maxBy { it.x }!!.x, particles.maxBy { it.y }!!.y) particles.forEach(Particle::tick) val (minX, minY) = Pair(particles.minBy { it.x }!!.x, particles.minBy { it.y }!!.y) val (maxX, maxY) = Pair(particles.maxBy { it.x }!!.x, particles.maxBy { it.y }!!.y) s++ if (lmaxY - lminY < maxY - minY && lmaxX - lminX < maxX - minX) { val sb = StringBuilder() (lminY..lmaxY).forEach { y -> val row = particles.filter { it.y - it.ySpeed == y }.map { it.x - it.xSpeed } (lminX..lmaxX).forEach { if (it in row) sb.append('#') else sb.append(' ') } sb.append('\n') } return Pair(sb.toString(), (s - 1)) // val image = BufferedImage(lmaxX - lminX + 1, lmaxY - lminY + 1, TYPE_INT_RGB) // for (star in particles) { // image.setRGB(star.x - star.xSpeed - lminX, star.y - star.ySpeed - lminY, Color.WHITE.rgb) // } // ImageIO.write(image, "png", File("Day10.png")) } } } private fun parse(input: List<String>): List<Particle> = input.map { val (x, y, xSpeed, ySpeed) = it.getNumbers() Particle(x, y, xSpeed, ySpeed) } } fun main(args: Array<String>) { val input = File("./input/2018/Day10_input.txt").readLines() val (partOne, partTwo) = Day10.solve(input) println("Part One = $partOne") println("Part Two = $partTwo") }
0
Kotlin
1
1
9294b2cbbb13944d586449f6a20d49f03391991e
1,838
Advent_of_Code
MIT License
src/main/kotlin/de/pgebert/aoc/days/Day16.kt
pgebert
724,032,034
false
{"Kotlin": 65831}
package de.pgebert.aoc.days import de.pgebert.aoc.Day class Day16(input: String? = null) : Day(16, "The Floor Will Be Lava", input) { private val obstacles = parseObstacles() override fun partOne() = Beam(position = Point(0, -1), direction = Point(0, 1)).getNumberOfEnergizedTiles() override fun partTwo() = getStartingBeams().maxOf { beam -> beam.getNumberOfEnergizedTiles() } private fun getStartingBeams(): List<Beam> { val startingBeams = buildList<Beam> { for (x in inputList.indices) { add(Beam(position = Point(x, -1), direction = Point(0, 1))) add(Beam(position = Point(x, inputList[x].length), direction = Point(0, -1))) } for (y in inputList.first().indices) { add(Beam(position = Point(-1, y), direction = Point(1, 0))) add(Beam(position = Point(inputList.size, y), direction = Point(-1, 0))) } } return startingBeams } private fun Beam.getNumberOfEnergizedTiles(): Int { val visited = mutableSetOf<Beam>() val queue = ArrayDeque<Beam>() queue += this while (queue.isNotEmpty()) { val beam = queue.removeFirst() val newPosition = beam.position.plus(beam.direction) if (newPosition.x !in inputList.indices || newPosition.y !in inputList.first().indices) continue val newDirections: List<Point> = obstacles .firstOrNull { obstacle -> obstacle.position == newPosition } ?.let { (_, character) -> buildList { when (character) { '/' -> add(Point(-beam.direction.y, -beam.direction.x)) '\\' -> add(Point(beam.direction.y, beam.direction.x)) '|' -> { add(Point(-beam.direction.y, 0)) // split 1 add(Point(beam.direction.y, 0)) // split 2 add(Point(beam.direction.x, 0)) // former direction } '-' -> { add(Point(0, -beam.direction.x)) // split 1 add(Point(0, beam.direction.x)) // split 2 add(Point(0, beam.direction.y)) // former direction } } } } ?.filterNot { it == Point(0, 0) } ?: listOf(beam.direction) // former direction newDirections.forEach { newDirection -> Beam(position = newPosition, direction = newDirection) .takeUnless { it in visited } ?.also { queue.add(it) visited.add(it) } } } return visited.map { it.position }.toSet().size } private fun parseObstacles() = buildList { for (x in inputList.indices) { for (y in inputList[x].indices) { val char = inputList[x][y] if (char != '.') { add(Obstacle(position = Point(x, y), character = char)) } } } } data class Point(val x: Int, val y: Int) { fun plus(other: Point) = Point(x + other.x, y + other.y) } data class Beam(val position: Point, val direction: Point) data class Obstacle(val position: Point, val character: Char) }
0
Kotlin
1
0
a30d3987f1976889b8d143f0843bbf95ff51bad2
3,641
advent-of-code-2023
MIT License
day3/day3/src/main/kotlin/Day8.kt
teemu-rossi
437,894,529
false
{"Kotlin": 28815, "Rust": 4678}
val digits = mapOf( 0 to "abcefg", // 6 1 to "cf", // 2 2 to "acdeg", // 5 3 to "acdfg", // 5 4 to "bcdf", // 4 5 to "abdfg", // 5 6 to "abdefg", // 6 7 to "acf", // 3 8 to "abcdefg", // 7 9 to "abcdfg" // 6 ) fun main() { val values = generateSequence(::readLine) .mapNotNull { line -> line.trim().takeUnless { trimmed -> trimmed.isBlank() } } .toList() var uniqCount = 0 var totalSum = 0 for (line in values) { val split = line.split(" ") val possibleSignals = split.take(10) val valueShown = split.takeLast(4) uniqCount += valueShown.count { it.length == 2 || it.length == 7 || it.length == 3 || it.length == 4 } val mapping = mutableMapOf( "a" to mutableListOf("a", "b", "c", "d", "e", "f", "g"), "b" to mutableListOf("a", "b", "c", "d", "e", "f", "g"), "c" to mutableListOf("a", "b", "c", "d", "e", "f", "g"), "d" to mutableListOf("a", "b", "c", "d", "e", "f", "g"), "e" to mutableListOf("a", "b", "c", "d", "e", "f", "g"), "f" to mutableListOf("a", "b", "c", "d", "e", "f", "g"), "g" to mutableListOf("a", "b", "c", "d", "e", "f", "g") ) val digitMapping = mutableMapOf<String, Int>() fun mustBeDigit(sig: String, digit: Int) { for (c in sig) { mapping[c.toString()]!!.removeIf { it !in digits[digit]!! } } digitMapping[sig] = digit } for (sig in possibleSignals) { when (sig.length) { 2 -> mustBeDigit(sig, 1) 4 -> mustBeDigit(sig, 4) 3 -> mustBeDigit(sig, 7) 7 -> mustBeDigit(sig, 8) } } val seven = possibleSignals.first { it.length == 3 }.toList().map { it.toString() } val four = possibleSignals.first { it.length == 4 }.toList().map { it.toString() } val one = possibleSignals.first { it.length == 2 }.toList().map { it.toString() } // seven has 'aaaa' in addition to one // mapping["a"] = (seven - one).toMutableList() // four has 'bb' and 'dddd' in addition to one // val bOrD = four - one // mapping["b"]!!.removeIf { it !in bOrD } fun mustBeSegment(input: String, real: String) { mapping[input]!!.removeAll { it != real } mapping.keys.forEach { key -> if (key != input) { mapping[key]!!.removeAll { it == real } } } } // count instances in digits for (segment in "abcdefg".toList().map { it.toString() }) { val count = possibleSignals.count { segment in it } when (count) { 6 -> mustBeSegment(segment, "b") // 8 -> mustBeSegment(segment, "c") // 7 -> "d" tai "g" 4 -> mustBeSegment(segment, "e") 9 -> mustBeSegment(segment, "f") } } repeat(10) { for ((k, v) in mapping.toMap()) { if (v.size == 1) { for ((k2, v2) in mapping.toMap()) { if (k2 != k) { mapping[k2]!!.removeAll { it == v.first() } } } } } } val mappedDigits = buildString { for (v in valueShown) { val mapped = v.toList().mapNotNull { mapping[it.toString()]?.first() }.sorted().joinToString("") val digit = digits.filter { (k, v) -> v == mapped }.keys.first() append(digit) } } totalSum += mappedDigits.toInt() println("$line --> $mappedDigits") for ((k, v) in mapping) { println("$k ${v.joinToString("")}") } } println("uniqCount = $uniqCount, totalSum=$totalSum") } // 0: 1: 2: 3: 4: // aaaa .... aaaa aaaa .... // b c . c . c . c b c // b c . c . c . c b c // .... .... dddd dddd dddd // e f . f e . . f . f // e f . f e . . f . f // gggg .... gggg gggg .... // // 5: 6: 7: 8: 9: // aaaa aaaa aaaa aaaa aaaa // b . b . . c b c b c // b . b . . c b c b c // dddd dddd .... dddd dddd // . f e f . f e f . f // . f e f . f e f . f // gggg gggg .... gggg gggg // //println("a 8: ${digits.values.count { it.contains("a") }}") //println("b 6: ${digits.values.count { it.contains("b") }}") //println("c 8: ${digits.values.count { it.contains("c") }}") //println("d 7: ${digits.values.count { it.contains("d") }}") //println("e 4: ${digits.values.count { it.contains("e") }}") //println("f 9: ${digits.values.count { it.contains("f") }}") //println("g 7: ${digits.values.count { it.contains("g") }}") //
0
Kotlin
0
0
16fe605f26632ac2e134ad4bcf42f4ed13b9cf03
5,103
AdventOfCode
MIT License
knapsack/src/main/kotlin/com/nickperov/stud/algorithms/knapsack/KnapSackProblem.kt
nickperov
327,780,009
false
null
package com.nickperov.stud.algorithms.knapsack import kotlin.random.Random data class KnapSack(val weightLimit: Int) data class Item(val weight: Int, val price: Int) data class ProblemParameters(val knapSackSize: Int, val itemListSize: Int, val itemWeightLimit: Int, val itemPriceLimit: Int) data class Problem(val knapSack: KnapSack, val items: List<Item>) // Default values const val knapsackDefaultSize = 100 const val itemListDefaultSize = 50 const val itemWeightDefaultLimit = 10 const val itemPriceDefaultLimit = 20 fun main(args: Array<String>) { val problem = initProblemFromArgs(args) printItems(problem.items) } private fun initProblemFromArgs(args: Array<String>): Problem { println("Init from command line arguments") val (knapsackSize, itemListSize, itemWeightLimit, itemPriceLimit) = initParameters(args) println("Knapsack size: $knapsackSize; product list size: $itemListSize; product limits: (weight: $itemWeightLimit, price: $itemPriceLimit)") val knapSack = KnapSack(knapsackSize) val items = initItems(itemListSize, itemWeightLimit, itemPriceLimit) return Problem(knapSack, items) } private fun initParameters(args: Array<String>): ProblemParameters { return if (args.isNotEmpty()) { if (args.size != 4) throw RuntimeException("Wrong number of arguments") ProblemParameters(args[0].toInt(), args[1].toInt(), args[2].toInt(), args[3].toInt()) } else { println("Command line arguments are empty, use default values") ProblemParameters(knapsackDefaultSize, itemListDefaultSize, itemWeightDefaultLimit, itemPriceDefaultLimit) } } private fun printItems(items: List<Item>) { val itemPrintFormat = "%5s %10s %10s" println("Items list") println("----------------------------------------------") print("|") println(itemPrintFormat.format("Number", "Weight", "Price")) println("----------------------------------------------") items.forEachIndexed { index, item -> print("|"); println(itemPrintFormat.format(index, item.weight, item.price)) } } private fun initItems(number: Int, weightLimit: Int, priceLimit: Int): List<Item> { return generateSequence(0) { i -> i + 1 }.take(number).map { initItem(weightLimit, priceLimit) }.toList() } private fun initItem(weightLimit: Int, priceLimit: Int) = Item(Random.nextInt(weightLimit) + 1, Random.nextInt(priceLimit) + 1)
0
Kotlin
0
0
6696f5d8bd73ce3a8dfd4200f902e2efe726cc5a
2,413
Algorithms
MIT License
y2019/src/main/kotlin/adventofcode/y2019/Day16.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2019 import adventofcode.io.AdventSolution import kotlin.math.absoluteValue fun main() = Day16.solve() object Day16 : AdventSolution(2019, 16, "Flawed Frequency Transmission") { override fun solvePartOne(input: String) = generateSequence(input.map(Character::getNumericValue), this::fft) .drop(100) .first() .take(8) .joinToString("") private fun fft(digits: List<Int>) = List(digits.size) { index -> val period = 4 * (index + 1) fun sum(start: Int) = (start..digits.lastIndex step period).sumOf { blockStart -> val blockEnd = (blockStart + index).coerceAtMost(digits.lastIndex) (blockStart..blockEnd).sumOf { digits[it] } } (sum(index) - sum(3 * index + 2)).absoluteValue % 10 } override fun solvePartTwo(input: String): String { val offset = input.take(7).toInt() val reverseOffset = 10000 * input.length - offset - 8 val relevantInput = input.repeat(10000 - offset / input.length).reversed().map { it - '0' } val transformed = generateSequence(relevantInput) { it.scan(0) { a, b -> (a + b) % 10 } }.drop(100).first() return transformed.drop(reverseOffset).take(8).joinToString("").reversed() } }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
1,359
advent-of-code
MIT License
src/main/kotlin/be/inniger/euler/problems01to10/Problem07.kt
bram-inniger
135,620,989
false
{"Kotlin": 20003}
package be.inniger.euler.problems01to10 import be.inniger.euler.util.EratosthenesSieve import kotlin.math.ln import kotlin.math.roundToInt // -1 as the problem specification is 1-indexed but Kotlin's collections are 0-indexed private const val PRIME_INDEX = 10_001 - 1 /** * 10001st prime * * By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. * What is the 10 001st prime number? */ fun solve07() = EratosthenesSieve(sieveSize).getPrimes()[PRIME_INDEX] /** * Calculate a reasonable upper bound to use as sieve size, in a way that the sieve will contain the 10_001th prime. * The code below very roughly calculates the inverse of a Prime-counting function. * Details here: https://en.wikipedia.org/wiki/Prime-counting_function * * The approximate function to count primes "pi(N) = N / ln(N)" is reversed by trying exponentially larger N values, * until "pi(N)" evaluates to something larger than 10_001. * This way we know that calculating the sieve up until N should contain the 10_001th prime. * * When running the program for the 10_001th prime we find the following values: * * Prime nr. 10_001 = 104743 * * Upper sieve size = 125278 * Showing that indeed the upper bound is reasonably guessed! */ private val sieveSize = generateSequence(10.0) { it * 1.1 } .first { it / ln(it) > PRIME_INDEX } .roundToInt()
0
Kotlin
0
0
8fea594f1b5081a824d829d795ae53ef5531088c
1,393
euler-kotlin
MIT License
src/Day05.kt
Yasenia
575,276,480
false
{"Kotlin": 15232}
import java.util.Stack fun main() { val stackLinePattern = "^(\\[[A-Z]]| {3})( \\[[A-Z]]| {4})*$".toRegex() val commandLinePattern = "^move (\\d+) from (\\d+) to (\\d+)$".toRegex() fun part1(input: List<String>): String { val stacks = mutableListOf<Stack<Char>>() for (line in input) { if (line.matches(stackLinePattern)) { for (i in 0..line.length / 4) { while (stacks.size <= i) stacks.add(Stack()) val crate = line[i * 4 + 1] if (crate != ' ') stacks[i].add(0, line[i * 4 + 1]) } } else { val groupValues = commandLinePattern.find(line)?.groupValues ?: continue val count = groupValues[1].toInt() val fromStack = stacks[groupValues[2].toInt() - 1] val toStack = stacks[groupValues[3].toInt() - 1] repeat(count) { toStack.push(fromStack.pop()) } } } return stacks.map { it.peek() }.joinToString("") } fun part2(input: List<String>): String { val stacks = mutableListOf<Stack<Char>>() val bufferStack = Stack<Char>() for (line in input) { if (line.matches(stackLinePattern)) { for (i in 0..line.length / 4) { while (stacks.size <= i) stacks.add(Stack()) val crate = line[i * 4 + 1] if (crate != ' ') stacks[i].add(0, line[i * 4 + 1]) } } else { val groupValues = commandLinePattern.find(line)?.groupValues ?: continue val count = groupValues[1].toInt() val fromStack = stacks[groupValues[2].toInt() - 1] val toStack = stacks[groupValues[3].toInt() - 1] repeat(count) { bufferStack.push(fromStack.pop()) } repeat(count) { toStack.push(bufferStack.pop()) } } } return stacks.map { it.peek() }.joinToString("") } val testInput = readInput("Day05_test") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readInput("Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
9300236fa8697530a3c234e9cb39acfb81f913ba
2,252
advent-of-code-kotlin-2022
Apache License 2.0
2022/main/day_20/Main.kt
Bluesy1
572,214,020
false
{"Rust": 280861, "Kotlin": 94178, "Shell": 996}
package day_20_2022 import java.io.File data class Mover(var uuid: Int, var value: Long) fun solve(part1: Boolean, input: List<Long>): String { val movers: MutableList<Mover> = ArrayList() for ((counter, num) in input.withIndex()) { val value: Long = num movers.add(Mover(counter, if (part1) value else value * 811589153)) } for (k in 0 until if (part1) 1 else 10) { for (i in movers.indices) { lateinit var mover: Mover var loc = 0 for (j in movers.indices) { if (movers[j].uuid == i + 10000 * k) { mover = movers[j] loc = j } } movers.removeAt(loc) val rotate = (mover.value % movers.size).toInt() movers.add(((loc + rotate) % movers.size + movers.size) % movers.size, mover) } for (i in movers.indices) movers[i].uuid = movers[i].uuid + 10000 } var offset = 0 for (j in movers.indices) { if (movers[j].value == 0L) offset = j } return "" + (movers[(offset + 1000) % movers.size].value + movers[(offset + 2000) % movers.size].value + movers[(offset + 3000) % movers.size].value) } fun part1(input: List<Long>) { print("The sum of the numbers in the 1000th, 2000th, and 3000th positions after 0 is ${solve(true, input)}") } fun part2(input: List<Long>) { print("The sum of the three real numbers in the 1000th, 2000th, and 3000th positions after 0 is ${solve(false, input)}") } fun main(){ val inputFile = File("2022/inputs/Day_20.txt") val input = inputFile.readLines().map(String::toLong) print("\n----- Part 1 -----\n") part1(input) print("\n----- Part 2 -----\n") part2(input) }
0
Rust
0
0
537497bdb2fc0c75f7281186abe52985b600cbfb
1,761
AdventofCode
MIT License
src/main/kotlin/com/dmc/advent2022/Day04.kt
dorienmc
576,916,728
false
{"Kotlin": 86239}
// --- Day 4: Camp Cleanup --- package com.dmc.advent2022 class Day04 : Day<Int> { override val index = 4 override fun part1(input: List<String>): Int { return input.map{ it.asRanges() }.count { (left, right) -> left fullyOverlaps right } } override fun part2(input: List<String>): Int { return input.map{ it.asRanges()}.count { (left, right) -> left overlaps right } } } fun String.toRangeSet() : Set<Int> { return (this.substringBefore('-').toInt()..this.substringAfter('-').toInt()).toMutableSet() } fun String.asRanges() : Pair<Set<Int>,Set<Int>> = this.substringBefore(",").toRangeSet() to this.substringAfter(",").toRangeSet() infix fun Set<Int>.fullyOverlaps(other: Set<Int>) : Boolean { val interSet = this.intersect(other) return (interSet.size == this.size || interSet.size == other.size) } infix fun Set<Int>.overlaps(other: Set<Int>) : Boolean= this.intersect(other).isNotEmpty() fun main() { val day = Day04() // test if implementation meets criteria from the description, like: val testInput = readInput(day.index, true) check(day.part1(testInput) == 2) val input = readInput(day.index) day.part1(input).println() day.part2(input).println() }
0
Kotlin
0
0
207c47b47e743ec7849aea38ac6aab6c4a7d4e79
1,249
aoc-2022-kotlin
Apache License 2.0
src/nativeMain/kotlin/com.qiaoyuang.algorithm/round1/Questions57.kt
qiaoyuang
100,944,213
false
{"Kotlin": 338134}
package com.qiaoyuang.algorithm.round1 fun test57() { printlnResult1(intArrayOf(1, 2, 4, 7, 11, 15), 15) printlnResult1(intArrayOf(0, 1, 2, 4, 7, 11, 15), 15) printlnResult2(15) printlnResult2(1) printlnResult2(6) printlnResult2(9) printlnResult2(10) printlnResult2(12) } /** * Questions 57-1: Find the two numbers in an increment IntArray that their sum is s */ private infix fun IntArray.findTwoNumbers(s: Int): Pair<Int, Int> { var pointer1 = 0 var pointer2 = lastIndex while (pointer1 != pointer2) when { this[pointer1] + this[pointer2] > s -> pointer2-- this[pointer1] + this[pointer2] < s -> pointer1++ else -> return this[pointer1] to this[pointer2] } throw IllegalArgumentException("This IntArray doesn't have two numbers that sum is $s") } private fun printlnResult1(array: IntArray, s: Int) = println("The two numbers are ${array.findTwoNumbers(s)} in IntArray: ${array.toList()} that their sum is $s") /** * Questions 57-2: Input an integer, find the all continuous positive integer sequence that each sum equals this integer */ private fun Int.findSequences(): List<IntRange> { require(this > 0) { "The integer must greater than 0" } var small = 1 var big = 2 val max = (1 + this) shr 1 return buildList { while (big <= max && big != small) { val range = small..big val sum = range.sum() when { sum < this@findSequences -> big++ sum > this@findSequences -> small++ else -> { add(range) big++ } } } } } private fun printlnResult2(num: Int) { println("The all continuous positive integer sequences that sum equals $num is:") num.findSequences().forEach { println(it.toList()) } }
0
Kotlin
3
6
66d94b4a8fa307020d515d4d5d54a77c0bab6c4f
1,914
Algorithm
Apache License 2.0
src/Day07.kt
Oktosha
573,139,677
false
{"Kotlin": 110908}
class FileTree(val root: Directory, private val position: MutableList<Directory>) { var answerPart1 = 0 var answerPart2 = 70000000 companion object Factory { fun create(input: List<String>): FileTree { val root = Directory("/") val fileTree = FileTree(root, mutableListOf(root)) var cmd = mutableListOf<String>() for (line in input) { if (line[0] == '$' && cmd.isNotEmpty()) { fileTree.execute(cmd) cmd = mutableListOf() } cmd.add(line) } fileTree.execute(cmd) return fileTree } } class File(@Suppress("unused") val name: String, val size: Int) class Directory( val name: String, val files: MutableList<File> = mutableListOf(), val dirs: MutableList<Directory> = mutableListOf() ) private fun execute(cmd: List<String>) { if (cmd[0][2] == 'l') { create(cmd.drop(1)) } else { cd(cmd[0].split(" ")[2]) } } private fun cd(direction: String) { when (direction) { "/" -> { while (position.size > 1) { position.removeLast() } } ".." -> { assert(position.size > 1) position.removeLast() } else -> { position.add(position.last().dirs.find { x -> x.name == direction }!!) } } } private fun create(lsData: List<String>) { val cur = position.last() assert(cur.dirs.isEmpty() && cur.files.isEmpty()) for (entry in lsData) { val (meta, name) = entry.split(" ") if (meta == "dir") { cur.dirs.add(Directory(name)) } else { cur.files.add(File(name, meta.toInt())) } } } fun calculateSizes(dir: Directory, updateAnswer: (Int, FileTree) -> Unit): Int { var size = 0 for (child in dir.dirs) { size += calculateSizes(child, updateAnswer) } size += dir.files.sumOf { f -> f.size } updateAnswer(size, this) return size } } fun updateAnswerPart1(size: Int, fileTree: FileTree) { if (size <= 100000) { fileTree.answerPart1 += size } } fun main() { println("Day 07") val input = readInput("Day07") val fileTree = FileTree.create(input) val occupiedSpace = fileTree.calculateSizes(fileTree.root, ::updateAnswerPart1) println(fileTree.answerPart1) val diskSpace = 70000000 val requiredSpace = 30000000 val freeSpace = diskSpace - occupiedSpace val spaceToClean = requiredSpace - freeSpace fileTree.calculateSizes(fileTree.root) { size, tree -> if (size >= spaceToClean && size < tree.answerPart2) tree.answerPart2 = size } println(fileTree.answerPart2) }
0
Kotlin
0
0
e53eea61440f7de4f2284eb811d355f2f4a25f8c
2,989
aoc-2022
Apache License 2.0
src/main/kotlin/day18/Day18.kt
cyril265
433,772,262
false
{"Kotlin": 39445, "Java": 4273}
package day18 import popUntil import readToList import java.util.* val input = readToList("day18.txt") fun main() { var current = createPairExpression(input.first()) input.drop(1).forEach { line -> val parsed = createPairExpression(line) current += parsed } println("magnitude " + current.magnitude()) var currentMax = 0L for (line1 in input) { for (line2 in input) { if (line1 === line2) continue val pairSum = createPairExpression(line1) + createPairExpression(line2) val magnitude = pairSum.magnitude() if (magnitude > currentMax) currentMax = magnitude } } println("max $currentMax") } fun createPairExpression(input: String): CoolPair { val pair = parsePair(input) pair.reduce() return pair } fun parsePair(input: String): CoolPair { val stack = Stack<Token>() for (char in input) { when (char) { '[' -> { stack.push(OpenBracket) } ']' -> { val pair = createNextPair(stack) stack.push(pair) } ',' -> { stack.push(Comma) } else -> { stack.push(Digit.ofChar(char)) } } } return stack.pop() as CoolPair } fun createNextPair(stack: Stack<Token>): CoolPair { val (left, right) = stack.popUntil { it is OpenBracket } .reversed() .filterIsInstance<PairComponent>() return CoolPair(left, right) } sealed interface Token object OpenBracket : Token object Comma : Token interface PairComponent : Token data class Digit(var number: Int) : PairComponent { companion object { fun ofChar(char: Char) = Digit(Character.getNumericValue(char)) } override fun toString(): String { return number.toString() } }
0
Kotlin
0
0
1ceda91b8ef57b45ce4ac61541f7bc9d2eb17f7b
1,901
aoc2021
Apache License 2.0
2022/src/main/kotlin/Day15.kt
dlew
498,498,097
false
{"Kotlin": 331659, "TypeScript": 60083, "JavaScript": 262}
import kotlin.math.abs object Day15 { fun part1(input: String, y: Int): Int { val sensors = parseInput(input) val startX = sensors.first().closestBeacon.x var left = startX - 1 while (sensors.any { it.rulesOut(left, y) }) { left-- } var right = startX + 1 while (sensors.any { it.rulesOut(right, y) }) { right++ } return right - left - 2 } fun part2(input: String, max: Int): Long { val sensors = parseInput(input) (0..max).forEach { y -> var x = 0 while (x <= max) { val maxSize = sensors.maxOf { it.distanceToBeacon - manhattanDistance(it.location, x, y) } if (maxSize == -1) { return tuningFrequency(x, y) } x += maxSize + 1 } } throw IllegalStateException("Could not find beacon!") } private fun manhattanDistance(p1: Point, p2: Point) = manhattanDistance(p1, p2.x, p2.y) private fun manhattanDistance(p: Point, x: Int, y: Int) = abs(p.x - x) + abs(p.y - y) private fun tuningFrequency(x: Int, y: Int) = x * 4_000_000L + y private data class Point(val x: Int, val y: Int) private data class Sensor(val location: Point, val closestBeacon: Point) { val distanceToBeacon = manhattanDistance(location, closestBeacon) inline fun rulesOut(x: Int, y: Int) = manhattanDistance(location, x, y) <= distanceToBeacon } private val INPUT_REGEX = Regex("Sensor at x=(-?\\d+), y=(-?\\d+): closest beacon is at x=(-?\\d+), y=(-?\\d+)") private fun parseInput(input: String): List<Sensor> { return input .splitNewlines() .map { val (sensorX, sensorY, beaconX, beaconY) = INPUT_REGEX.matchEntire(it)!!.destructured Sensor( location = Point(sensorX.toInt(), sensorY.toInt()), closestBeacon = Point(beaconX.toInt(), beaconY.toInt()) ) } } }
0
Kotlin
0
0
6972f6e3addae03ec1090b64fa1dcecac3bc275c
1,866
advent-of-code
MIT License
src/main/kotlin/g1301_1400/s1373_maximum_sum_bst_in_binary_tree/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1301_1400.s1373_maximum_sum_bst_in_binary_tree // #Hard #Dynamic_Programming #Depth_First_Search #Tree #Binary_Tree #Binary_Search_Tree // #2023_06_06_Time_451_ms_(100.00%)_Space_54.3_MB_(100.00%) import com_github_leetcode.TreeNode /* * Example: * var ti = TreeNode(5) * var v = ti.`val` * Definition for a binary tree node. * class TreeNode(var `val`: Int) { * var left: TreeNode? = null * var right: TreeNode? = null * } */ class Solution { fun maxSumBST(root: TreeNode?): Int { val temp = checkBST(root) return Math.max(temp.maxSum, 0) } private class IsBST { var max = Int.MIN_VALUE var min = Int.MAX_VALUE var isBst = true var sum = 0 var maxSum = Int.MIN_VALUE } private fun checkBST(root: TreeNode?): IsBST { if (root == null) { return IsBST() } val lp = checkBST(root.left) val rp = checkBST(root.right) val mp = IsBST() mp.max = Math.max(root.`val`, Math.max(lp.max, rp.max)) mp.min = Math.min(root.`val`, Math.min(lp.min, rp.min)) mp.sum = lp.sum + rp.sum + root.`val` val check = root.`val` > lp.max && root.`val` < rp.min if (lp.isBst && rp.isBst && check) { mp.isBst = true val tempMax = Math.max(mp.sum, Math.max(lp.sum, rp.sum)) mp.maxSum = Math.max(tempMax, Math.max(lp.maxSum, rp.maxSum)) } else { mp.isBst = false mp.maxSum = Math.max(lp.maxSum, rp.maxSum) } return mp } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,579
LeetCode-in-Kotlin
MIT License
src/main/aoc2015/Day9.kt
nibarius
154,152,607
false
{"Kotlin": 963896}
package aoc2015 import java.util.* import kotlin.math.max class Day9(input: List<String>) { val parsedInput = parseInput(input) private fun initMapIfNeeded(key: String, map: MutableMap<String, MutableMap<String, Int>>) { if (!map.containsKey(key)) { map[key] = mutableMapOf() } } fun parseInput(input: List<String>): Map<String, Map<String, Int>> { val ret = mutableMapOf<String, MutableMap<String, Int>>() input.forEach { line -> val parts = line.split(" ") val a = parts[0] val b = parts[2] val distance = parts.last().toInt() initMapIfNeeded(a, ret) initMapIfNeeded(b, ret) ret[a]!![b] = distance ret[b]!![a] = distance } return ret } data class State(val visited: List<String>) { var distance = 0 } private fun findDistance(shortest: Boolean): Int { val toCheck = PriorityQueue<State>(compareBy { state -> state.distance }) parsedInput.keys.forEach { toCheck.add(State(listOf(it))) } var longest = -1 while (toCheck.isNotEmpty()) { val current = toCheck.remove() if (current.visited.size == parsedInput.size) { if (shortest) return current.distance longest = max(current.distance, longest) continue } parsedInput.filterKeys { !current.visited.contains(it) } .forEach { (nextCity, distances) -> val dist = current.distance + distances.getValue(current.visited.last()) val visited = current.visited.toMutableList().apply { add(nextCity) } toCheck.add(State(visited).apply { distance = dist }) } } return longest } fun solvePart1(): Int { return findDistance(true) } fun solvePart2(): Int { return findDistance(false) } }
0
Kotlin
0
6
f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22
2,019
aoc
MIT License
src/Day06.kt
frungl
573,598,286
false
{"Kotlin": 86423}
fun main() { fun part1(input: List<String>): Int { val str = input.first() val tmp = str.mapIndexed { index, _ -> when(str.length - index >= 4) { true -> str.substring(index, index + 4) else -> "" } }.dropLast(3) return 4 + tmp.indexOfFirst { it.toCharArray().distinct().size == 4 } } fun part2(input: List<String>): Int { val str = input.first() val tmp = str.mapIndexed { index, _ -> when(str.length - index >= 14) { true -> str.substring(index, index + 14) else -> "" } }.dropLast(13) return 14 + tmp.indexOfFirst { it.toCharArray().distinct().size == 14 } } fun beautiful(input: List<String>, size: Int): Int = input.first().windowed(size).indexOfFirst { it.toSet().size == size } + size val testInput = readInput("Day06_test") check(part1(testInput) == 7) check(part2(testInput) == 19) val input = readInput("Day06") println(part1(input)) println(part2(input)) println(beautiful(input, 4)) println(beautiful(input, 14)) }
0
Kotlin
0
0
d4cecfd5ee13de95f143407735e00c02baac7d5c
1,206
aoc2022
Apache License 2.0
src/aoc2022/Day08.kt
FluxCapacitor2
573,641,929
false
{"Kotlin": 56956}
package aoc2022 import Day import column object Day08 : Day(2022, 8) { override fun part1() { var totalVisible = 0 val input = lines.filter { it.isNotEmpty() } for ((row, line) in input.withIndex()) { for ((column, char) in line.withIndex()) { if (row == 0 || column == 0 || row == input.size - 1 || column == input[column].length - 1) { // This tree is on the edge; it is visible totalVisible++ } else { // If not, we have to check if there are any taller trees that block view from the edge val columnString = input.column(column) val isVisible = listOf( line.substring(0, column), // Left line.substring(column + 1), // Right columnString.substring(0, row), // Above columnString.substring(row + 1), // Below ).any { !isObstructed(char, it) } if (isVisible) totalVisible++ } } } println("Part 1 result: $totalVisible") } private fun isObstructed(tree: Char, line: String): Boolean { for (char in line) { if (char.digitToInt() >= tree.digitToInt()) return true } return false } override fun part2() { var maxScenicScore = 0 val input = lines.filter { it.isNotEmpty() } for ((row, line) in input.withIndex()) { for ((column, char) in line.withIndex()) { if (row == 0 || column == 0 || row == input.size - 1 || column == line.length - 1) { // This tree is on the edge; one of the scenic scores must be zero, so nothing needs to be computed continue } val columnString = input.column(column) // Compute the scenic score for each character val scores = listOf( getVisibleTrees(columnString.substring(0, row).reversed(), char), // Above getVisibleTrees(columnString.substring(row + 1), char), // Below getVisibleTrees(line.substring(0, column).reversed(), char), // Left getVisibleTrees(line.substring(column + 1), char) // Right ) val total = scores.reduce { acc, i -> acc * i } maxScenicScore = total.coerceAtLeast(maxScenicScore) } } println("Part 2 result: $maxScenicScore") } private fun getVisibleTrees(list: String, char: Char): Int { if (list.isEmpty()) return 0 for ((index, c) in list.withIndex()) { if (c.digitToInt() >= char.digitToInt()) { return index + 1 } } return list.length } }
0
Kotlin
0
0
a48d13763db7684ee9f9129ee84cb2f2f02a6ce4
2,905
advent-of-code-2022
Apache License 2.0
src/main/kotlin/day20/Code.kt
fcolasuonno
317,324,330
false
null
package day20 import isDebug import java.io.File import kotlin.math.sqrt fun main() { val name = if (isDebug()) "test.txt" else "input.txt" System.err.println(name) val dir = ::main::class.java.`package`.name val input = File("src/main/kotlin/$dir/$name").readLines() val parsed = parse(input) part1(parsed) part2(parsed) } private val List<List<Boolean>>.borders: List<List<Boolean>> get() = listOf( first(), map { it.last() }, last(), map { it.first() } ) private val lineStructure = """Tile (\d+):""".toRegex() fun parse(input: List<String>) = input.joinToString(separator = "\n").split("\n\n").map { it.split("\n").let { tileInfo -> requireNotNull(lineStructure.matchEntire(tileInfo.first())?.destructured?.let { val (tileNum) = it.toList() tileNum.toLong() to tileInfo.drop(1).map { it.map { it == '#' } } }) } }.toMap() fun part1(input: Map<Long, List<List<Boolean>>>) { val res = input.mapValues { it.value.borders }.let { val borders = it.values.flatten() it.filterValues { it.count { border -> borders.count { it == border || it == border.reversed() } == 1 } == 2 }.keys.reduce { acc, i -> acc * i } } println("Part 1 = $res") } data class Tile(val tile: Long, val data: List<List<Boolean>>, val neightbours: List<Long?>) { val top = neightbours[0] val right = neightbours[1] val bottom = neightbours[2] val left = neightbours[3] fun oriented(rTop: Long?, rLeft: Long?) = when { rTop == this.top && rLeft == this.left -> this rTop == this.top && rLeft == this.right -> flipH() rTop == this.bottom && rLeft == this.left -> flipV() rTop == this.right && rLeft == this.bottom -> rotCW().flipV() rTop == this.left && rLeft == this.top -> rotCW().flipH() rTop == this.left && rLeft != this.top -> rotCW() rTop != this.left && rLeft == this.top -> rotCW().rotCW().rotCW() rTop != this.left && rLeft != this.top -> rotCW().rotCW() else -> TODO("Not yet implemented TOP:$top , LEFT:$left -> RTOP:$rTop, RLEFT:$rLeft") } private fun flipH() = copy(data = data.flipH(), neightbours = neightbours.flipH()) private fun flipV() = copy(data = data.flipV(), neightbours = neightbours.flipV()) private fun rotCW() = copy(data = data.rotateCW(), neightbours = neightbours.rotateCW()) // override fun toString() = data.joinToString("\n") { it.joinToString("") { if (it) "#" else "." } } override fun toString() = "$tile: T=$top, R=$right, B=$bottom, L=$left" private fun List<Long?>.rotateCW() = mapIndexed { index, _ -> get((index + size - 1) % size) } private fun List<Long?>.flipH() = listOf(get(0), get(3), get(2), get(1)) private fun List<Long?>.flipV() = listOf(get(2), get(1), get(0), get(3)) } fun part2(input: Map<Long, List<List<Boolean>>>) { val tiles = input.mapValues { Tile(it.key, it.value, it.value.borders.map { border -> input.filter { other -> other.key != it.key && other.value.borders.let { border in it || border.reversed() in it } }.keys.singleOrNull() }) } val size = sqrt(input.size.toDouble()).toInt() val arranged = MutableList(size) { MutableList<Tile?>(size) { null } } var current = tiles.entries.first { it.value.neightbours.count { it == null } == 2 }.key var top: Long? = null var left: Long? = null for (i in 0 until size) { for (j in 0 until size) { val oriented = tiles.getValue(current).oriented(top, left) arranged[i][j] = oriented if (oriented.right != null) { left = current top = arranged.getOrNull(i - 1)?.getOrNull(j + 1)?.tile current = oriented.right } else { left = null top = arranged[i][0]?.tile current = arranged[i][0]?.bottom ?: 0L } } } val grid = List(size * 8) { y -> List(size * 8) { x -> arranged[y / 8][x / 8]!!.data[y % 8 + 1][x % 8 + 1] } } val monster = listOf( " # ", "# ## ## ###", " # # # # # # " ).flatMapIndexed { y, s -> s.indices.filter { s[it] == '#' }.map { x -> x to y } } val res = listOf( grid, grid.rotateCW(), grid.rotateCW().rotateCW(), grid.rotateCW().rotateCW().rotateCW(), grid.flipH(), grid.flipV(), grid.rotateCW().flipV(), grid.rotateCW().flipH(), ).map { possibleGrid -> (0..(grid.size - 20)).sumBy { x -> (0..(grid.size - 3)).count { y -> monster.all { possibleGrid[it.second + y][it.first + x] } } } }.maxOrNull()?.let { grid.sumBy { it.count { it } } - it * monster.count() } println("Part 2 = $res") } fun List<List<Boolean>>.rotateCW() = indices.map { index -> reversed().map { it[index] } } fun List<List<Boolean>>.flipH() = map { it.reversed() } fun List<List<Boolean>>.flipV() = reversed()
0
Kotlin
0
0
e7408e9d513315ea3b48dbcd31209d3dc068462d
5,292
AOC2020
MIT License
src/day3/Day03_A.kt
HGilman
572,891,570
false
{"Kotlin": 109639, "C++": 5375, "Python": 400}
package day3 import readInput fun main() { fun part1(input: List<String>): Int { return input.sumOf { rucksack -> val compartmentSize = rucksack.length / 2 val firstCompartment = rucksack.substring(0, compartmentSize) val secondCompartment = rucksack.substring(compartmentSize) // actually there is no need to make full intersection, // it is enough to find first symbol, that is contained in both parts val commonSymbols = firstCompartment.toSet() intersect secondCompartment.toSet() commonSymbols.first().priority() } } fun part2(input: List<String>): Int { val elfGroups: List<List<String>> = input.chunked(3) return elfGroups.sumOf { group: List<String> -> val firstElf = group[0].toSet() val secondElf = group[1].toSet() val thirdElf = group[2].toSet() val intersection = firstElf intersect secondElf intersect thirdElf intersection.first().priority() } } val testInput = readInput("day3/Day03_test") check(part1(testInput) == 157) val input = readInput("day3/Day03") println(part1(input)) println(part2(input)) } fun Char.priority(): Int { return if (isLowerCase()) { this - 'a' + 1 } else { this - 'A' + 27 } }
0
Kotlin
0
1
d05a53f84cb74bbb6136f9baf3711af16004ed12
1,380
advent-of-code-2022
Apache License 2.0
src/Lesson1Iterations/BinaryGap.kt
slobodanantonijevic
557,942,075
false
{"Kotlin": 50634}
/** * 100/100 * @param N * @return */ fun solution(N: Int): Int { val binary: String = java.lang.Integer.toBinaryString(N) var longestGap = 0 var currentGap = 0 var firstLeadingOne = false for (i in 0 until binary.length) { val digit = binary[i] if (firstLeadingOne) { if (digit == '1') { if (currentGap > longestGap) longestGap = currentGap currentGap = 0 } else { currentGap++ } } else { if (digit == '1') { firstLeadingOne = true } } } return longestGap } /** * A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N. * * For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3. The number 20 has binary representation 10100 and contains one binary gap of length 1. The number 15 has binary representation 1111 and has no binary gaps. The number 32 has binary representation 100000 and has no binary gaps. * * Write a function: * * int solution(int N); * * that, given a positive integer N, returns the length of its longest binary gap. The function should return 0 if N doesn't contain a binary gap. * * For example, given N = 1041 the function should return 5, because N has binary representation 10000010001 and so its longest binary gap is of length 5. Given N = 32 the function should return 0, because N has binary representation '100000' and thus no binary gaps. * * Write an efficient algorithm for the following assumptions: * * N is an integer within the range [1..2,147,483,647]. */
0
Kotlin
0
0
155cf983b1f06550e99c8e13c5e6015a7e7ffb0f
1,859
Codility-Kotlin
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/MaxNumber.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import kotlin.math.max /** * Create Maximum Number */ fun maxNumber(nums1: IntArray, nums2: IntArray, k: Int): IntArray { val n: Int = nums1.size val m: Int = nums2.size var ans = IntArray(k) var i = max(0, k - m) while (i <= k && i <= n) { val candidate = merge(maxArray(nums1, i), maxArray(nums2, k - i), k) if (greater(candidate, 0, ans, 0)) ans = candidate ++i } return ans } private fun merge(nums1: IntArray, nums2: IntArray, k: Int): IntArray { val ans = IntArray(k) var i = 0 var j = 0 var r = 0 while (r < k) { ans[r] = if (greater(nums1, i, nums2, j)) nums1[i++] else nums2[j++] ++r } return ans } private fun greater(nums1: IntArray, i: Int, nums2: IntArray, j: Int): Boolean { var i1 = i var j2 = j while (i1 < nums1.size && j2 < nums2.size && nums1[i1] == nums2[j2]) { i1++ j2++ } return j2 == nums2.size || i1 < nums1.size && nums1[i1] > nums2[j2] } private fun maxArray(nums: IntArray, startIndex: Int): IntArray { val n = nums.size val ans = IntArray(startIndex) var i = 0 var j = 0 while (i < n) { while (n - i + j > startIndex && j > 0 && ans[j - 1] < nums[i]) j-- if (j < startIndex) ans[j++] = nums[i] ++i } return ans }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,973
kotlab
Apache License 2.0
src/Day08.kt
Reivax47
572,984,467
false
{"Kotlin": 32685}
import kotlin.math.ceil fun main() { fun part1(input: List<String>): Int { val hauteur = input.size val largeur = input[0].length val mesArbres = mutableListOf<trees>() for (indexY in 0 until hauteur) { for (indexX in 0 until largeur) { val visible = (indexX == 0 || indexY == 0 || indexX == largeur - 1 || indexY == hauteur - 1) val value = input[indexY].substring(indexX, indexX + 1).toInt() mesArbres.add(trees(indexX, indexY, value, visible)) } } for (indexY in 0 until hauteur) { var max = mesArbres.find { it.y == indexY && it.x == 0 }?.hauteur for (indexX in 1..largeur - 1) { val arbre = mesArbres.find { it.y == indexY && it.x == indexX } if (arbre?.hauteur!! > max!!) { arbre?.visible = true max = arbre?.hauteur } } max = mesArbres.find { it.y == indexY && it.x == (largeur - 1) }?.hauteur for (indexX in (largeur - 2) downTo 0) { val arbre = mesArbres.find { it.y == indexY && it.x == indexX } if (arbre?.hauteur!! > max!!) { arbre?.visible = true max = arbre?.hauteur } } } for (indexX in 0 until largeur) { var max = mesArbres.find { it.y == 0 && it.x == indexX }?.hauteur for (indexY in 1..hauteur -1) { val arbre = mesArbres.find { it.y == indexY && it.x == indexX } if (arbre?.hauteur!! > max!!) { arbre?.visible = true max = arbre?.hauteur } } max = mesArbres.find { it.y == hauteur-1 && it.x == indexX }?.hauteur for (indexY in (hauteur - 2) downTo 0) { val arbre = mesArbres.find { it.y == indexY && it.x == indexX } if (arbre?.hauteur!! > max!!) { arbre?.visible = true max = arbre?.hauteur } } } val listeVisible = mesArbres.filter { it.visible } val reponse = listeVisible.size return reponse } fun docalcul(unArbre : trees, sensX : Int, sensY: Int, largeur: Int, laforet: List<trees>): Int { var rep = 1 var x = unArbre.x var y= unArbre.y var onsrt = false while (x + sensX >= 1 && x + sensX < largeur -1 && y + sensY >= 1 && y + sensY < largeur -1 && !onsrt ) { val candidat = laforet.find { it.x == x + sensX && it.y == y + sensY } if (candidat != null && candidat.hauteur >= unArbre.hauteur) { onsrt = true } else { rep ++ x += sensX y += sensY } } return rep } fun part2(input: List<String>): Int { val hauteur = input.size val largeur = input[0].length val mesArbres = mutableListOf<trees>() for (indexY in 0 until hauteur) { for (indexX in 0 until largeur) { val visible = (indexX == 0 || indexY == 0 || indexX == largeur - 1 || indexY == hauteur - 1) val value = input[indexY].substring(indexX, indexX + 1).toInt() mesArbres.add(trees(indexX, indexY, value, visible)) } } val liste =mesArbres.filter { it.hauteur >= 5 && it.x > 0 && it.y > 0 && it.x < (largeur -1) && it.y < (hauteur -1) } var reponse = 0 liste.forEach { unArbre -> var up = docalcul(unArbre,0,-1, largeur, liste) var right = docalcul(unArbre,1,0, largeur, liste) var down = docalcul(unArbre,0,1, largeur, liste) var left = docalcul(unArbre,-1,0, largeur, liste) val total = left*right*up*down reponse = if(total > reponse) total else reponse } return reponse } // test if implementation meets criteria from the description, like: val testInput = readInput("Day08_test") check(part1(testInput) == 21) check(part2(testInput) == 8) val input = readInput("Day08") println(part1(input)) println(part2(input)) } data class trees(val x: Int, val y: Int, val hauteur: Int, var visible: Boolean)
0
Kotlin
0
0
0affd02997046d72f15d493a148f99f58f3b2fb9
4,448
AD2022-01
Apache License 2.0
src/main/kotlin/g2201_2300/s2213_longest_substring_of_one_repeating_character/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2201_2300.s2213_longest_substring_of_one_repeating_character // #Hard #Array #String #Ordered_Set #Segment_Tree // #2023_06_27_Time_879_ms_(100.00%)_Space_64.8_MB_(100.00%) class Solution { internal class TreeNode(var start: Int, var end: Int) { var leftChar = 0.toChar() var leftCharLen = 0 var rightChar = 0.toChar() var rightCharLen = 0 var max = 0 var left: TreeNode? = null var right: TreeNode? = null } fun longestRepeating(s: String, queryCharacters: String, queryIndices: IntArray): IntArray { val sChar = s.toCharArray() val qChar = queryCharacters.toCharArray() val root = buildTree(sChar, 0, sChar.size - 1) val result = IntArray(qChar.size) for (i in qChar.indices) { updateTree(root, queryIndices[i], qChar[i]) if (root != null) { result[i] = root.max } } return result } private fun buildTree(s: CharArray, from: Int, to: Int): TreeNode? { if (from > to) { return null } val root = TreeNode(from, to) if (from == to) { root.max = 1 root.leftChar = s[from] root.rightChar = root.leftChar root.rightCharLen = 1 root.leftCharLen = root.rightCharLen return root } val middle = from + (to - from) / 2 root.left = buildTree(s, from, middle) root.right = buildTree(s, middle + 1, to) updateNode(root) return root } private fun updateTree(root: TreeNode?, index: Int, c: Char) { if (root == null || root.start > index || root.end < index) { return } if (root.start == index && root.end == index) { root.rightChar = c root.leftChar = root.rightChar return } updateTree(root.left, index, c) updateTree(root.right, index, c) updateNode(root) } private fun updateNode(root: TreeNode?) { if (root == null) { return } root.leftChar = root.left!!.leftChar root.leftCharLen = root.left!!.leftCharLen root.rightChar = root.right!!.rightChar root.rightCharLen = root.right!!.rightCharLen root.max = Math.max(root.left!!.max, root.right!!.max) if (root.left!!.rightChar == root.right!!.leftChar) { val len = root.left!!.rightCharLen + root.right!!.leftCharLen if (root.left!!.leftChar == root.left!!.rightChar && root.left!!.leftCharLen == root.left!!.end - root.left!!.start + 1 ) { root.leftCharLen = len } if (root.right!!.leftChar == root.right!!.rightChar && root.right!!.leftCharLen == root.right!!.end - root.right!!.start + 1 ) { root.rightCharLen = len } root.max = Math.max(root.max, len) } } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
3,031
LeetCode-in-Kotlin
MIT License
src/main/kotlin/aoc2021/day10/SyntaxScorer.kt
arnab
75,525,311
false
null
package aoc2021.day10 object SyntaxScorer { fun parse(data: String) = data.split("\n") private val openingTokens = listOf('(', '[', '{', '<') private val closingTokens = listOf(')', ']', '}', '>') fun calculateErrorScore(data: List<String>): Int { val errors = mutableMapOf<Char, Int>() data.forEach next@{ line -> val inProgress = ArrayDeque<Char>() line.forEach { token -> if (token in openingTokens) inProgress.addLast(token) else if (closingTokens.indexOf(token) == openingTokens.indexOf(inProgress.last())) inProgress.removeLast() else { errors.merge(token, 1, Int::plus) return@next } } } return errors.map { (token, count) -> when (token) { ')' -> 3 * count ']' -> 57 * count '}' -> 1197 * count '>' -> 25137 * count else -> throw IllegalArgumentException("Woah! Unknown token: $token") } }.sumBy { it } } fun autoCompleteAndScore(data: List<String>): Long { val autocompleteScores = mutableListOf<Long>() data.map next@{ line -> val incomplete = ArrayDeque<Char>() line.forEach { token -> if (token in openingTokens) incomplete.addLast(token) else if (closingTokens.indexOf(token) == openingTokens.indexOf(incomplete.last())) incomplete.removeLast() else { return@next } } autocompleteScores.add( incomplete.reversed() .map { token -> closingTokens[openingTokens.indexOf(token)] } .map { autoCompleteScore(it) } .fold(0) { total, points -> total * 5 + points } ) } return autocompleteScores.sorted()[autocompleteScores.size/2] } private fun autoCompleteScore(token: Char) = when (token) { ')' -> 1 ']' -> 2 '}' -> 3 '>' -> 4 else -> throw IllegalArgumentException("Woah! Unknown token: $token") } }
0
Kotlin
0
0
1d9f6bc569f361e37ccb461bd564efa3e1fccdbd
2,312
adventofcode
MIT License
src/Day04.kt
colmmurphyxyz
572,533,739
false
{"Kotlin": 19871}
fun main() { fun part1(input: List<String>): Int { var answer = 0 for (line in input) { val pair = line.split(",") val r1 = pair[0].split("-").map { it -> it.toInt() } val r2 = pair[1].split("-").map { it -> it.toInt() } val set1 = (r1[0]..r1[1]).toSet() val set2 = (r2[0]..r2[1]).toSet() if (set1.containsAll(set2) || set2.containsAll(set1)) { answer += 1 } } return answer } fun part2(input: List<String>): Int { var answer = 0 for (line in input) { val pair = line.split(",") val r1 = pair[0].split("-").map { it -> it.toInt() } val r2 = pair[1].split("-").map { it -> it.toInt() } val set1 = (r1[0]..r1[1]).toSet() val set2 = (r2[0]..r2[1]).toSet() if ((set1 intersect set2).isNotEmpty()) { answer += 1 } } return answer } val input = readInput("Day04") println("Part 1 answer: ${part1(input)}") println("Part 2 answer: ${part2(input)}") }
0
Kotlin
0
0
c5653691ca7e64a0ee7f8e90ab1b450bcdea3dea
1,137
aoc-2022
Apache License 2.0
src/Day02.kt
emanguy
573,113,840
false
{"Kotlin": 17921}
import java.lang.IllegalArgumentException enum class RPSResult(val resultPoints: Int) { WIN(6) { override fun whatToPlayAgainst(move: RPSMove) = when (move) { RPSMove.ROCK -> RPSMove.PAPER RPSMove.PAPER -> RPSMove.SCISSORS RPSMove.SCISSORS -> RPSMove.ROCK } }, TIE(3) { override fun whatToPlayAgainst(move: RPSMove) = move }, LOSS(0) { override fun whatToPlayAgainst(move: RPSMove) = when (move) { RPSMove.ROCK -> RPSMove.SCISSORS RPSMove.PAPER -> RPSMove.ROCK RPSMove.SCISSORS -> RPSMove.PAPER } }; abstract fun whatToPlayAgainst(move: RPSMove): RPSMove companion object { fun fromString(string: String): RPSResult = when (string.lowercase()) { "x" -> LOSS "y" -> TIE "z" -> WIN else -> throw IllegalArgumentException("Not a result: $string") } } } enum class RPSMove(val movePoints: Int) { ROCK(1) { override fun resultVersus(other: RPSMove) = when (other) { PAPER -> RPSResult.LOSS SCISSORS -> RPSResult.WIN ROCK -> RPSResult.TIE } }, PAPER(2) { override fun resultVersus(other: RPSMove) = when (other) { SCISSORS -> RPSResult.LOSS ROCK -> RPSResult.WIN PAPER -> RPSResult.TIE } }, SCISSORS(3) { override fun resultVersus(other: RPSMove) = when (other) { ROCK -> RPSResult.LOSS PAPER -> RPSResult.WIN SCISSORS -> RPSResult.TIE } }; abstract fun resultVersus(other: RPSMove): RPSResult companion object { fun fromString(string: String): RPSMove = when (string.lowercase()) { "a", "x" -> ROCK "b", "y" -> PAPER "c", "z" -> SCISSORS else -> throw IllegalArgumentException("Not a valid move: $string") } } } fun main() { fun part1(inputs: List<String>): Int { var totalScore = 0 for (rpsRound in inputs) { val (theirMove, myMove) = rpsRound.split(" ").map(RPSMove::fromString) totalScore += myMove.movePoints + myMove.resultVersus(theirMove).resultPoints } return totalScore } fun part2(inputs: List<String>): Int { var totalScore = 0 for (rpsRound in inputs) { val (theirMoveStr, myResultStr) = rpsRound.split(" ") val theirMove = RPSMove.fromString(theirMoveStr) val myResult = RPSResult.fromString(myResultStr) val myMove = myResult.whatToPlayAgainst(theirMove) totalScore += myMove.movePoints + myResult.resultPoints } return totalScore } // Verify the sample input works val inputs = readInput("Day02_test") check(part1(inputs) == 15) check(part2(inputs) == 12) val finalInputs = readInput("Day02") println(part1(finalInputs)) println(part2(finalInputs)) }
0
Kotlin
0
1
211e213ec306acc0978f5490524e8abafbd739f3
3,037
advent-of-code-2022
Apache License 2.0
src/year2020/day02/Day02.kt
fadi426
433,496,346
false
{"Kotlin": 44622}
package year2020.day02 import util.assertTrue import util.read2020DayInput fun main() { val input = read2020DayInput("Day02") assertTrue(task01(input) == 460) assertTrue(task02(input) == 251) } private data class Policy(val min: Int, val max: Int, val letter: Char) { fun oldIsValid(value: String): Boolean = value.filter { it == letter }.length in min..max fun newIsValid(value: String): Boolean = listOf(value[min - 1], value[max - 1]).count { it == letter } == 1 } private data class Password(val policy: Policy, val value: String) { fun oldIsValid() = policy.oldIsValid(value) fun newIsValid() = policy.newIsValid(value) } private fun convertInputToPasswords(input: List<String>) = input.map { it.split(" ") } .map { Password( Policy( it[0].substringBefore("-").toInt(), it[0].substringAfter("-").toInt(), it[1].first() ), it[2] ) } private fun task01(input: List<String>) = convertInputToPasswords(input).count { it.oldIsValid() } private fun task02(input: List<String>) = convertInputToPasswords(input).count { it.newIsValid() }
0
Kotlin
0
0
acf8b6db03edd5ff72ee8cbde0372113824833b6
1,181
advent-of-code-kotlin-template
Apache License 2.0
src/main/kotlin/net/hiddevb/advent/advent2019/day03/main.kt
hidde-vb
224,606,393
false
null
package net.hiddevb.advent.advent2019.day03 import net.hiddevb.advent.common.initialize import kotlin.math.abs /** * --- Day 3: Crossed Wires --- */ fun main() { val fileStrings = initialize("Day 3: Crossed Wires", arrayOf("day3.txt")) println("Part 1: Basic") val solution1 = solveBasic(fileStrings[0]) println("Solved!\nSolution: $solution1\n") println("Part 2: Advanced") val solution2 = solveAdvanced(fileStrings[0]) println("Solved!\nSolution: $solution2\n") } // Part 1 fun solveBasic(input: String): Int? { val wireStrings = input.split("\n") val piecesOne = generatePieceSet(wireStrings[0].split(",")) val piecesTwo = generatePieceSet(wireStrings[1].split(",")) val crossings: MutableList<Int> = ArrayList() for(pieceI in piecesTwo) { for(pieceJ in piecesOne) { val point: Point? = pieceI.getCrossingPoint(pieceJ) if(point != null && point != Point(0,0, 0)) { crossings.add(abs(point.x) + abs(point.y)) } } } return crossings.min() } // Part 2 fun solveAdvanced(input: String): Int? { val wireStrings = input.split("\n") val piecesOne = generatePieceSet(wireStrings[0].split(",")) val piecesTwo = generatePieceSet(wireStrings[1].split(",")) val crossings: MutableList<Int> = ArrayList() for(pieceI in piecesTwo) { for(pieceJ in piecesOne) { val point: Point? = pieceI.getCrossingPoint(pieceJ) if(point != null && point != Point(0,0, 0)) { crossings.add(point.dist) } } } println(crossings) return crossings.min() } fun generatePieceSet(wire: List<String>): MutableList<Piece> { val toReturn: MutableList<Piece> = ArrayList() var x = 0 var y = 0 var dist = 0 for (instruction in wire) { val direction = instruction[0] val amount = instruction.substring(1).toInt() when (direction) { 'R' -> { toReturn.add(Piece(Point(x, y, dist), Point(x + amount, y, dist))) x += amount } 'L' -> { toReturn.add(Piece(Point(x - amount, y, dist), Point(x, y, dist))) x -= amount } 'U' -> { toReturn.add(Piece(Point(x, y, dist), Point(x, y + amount,dist))) y += amount } 'D' -> { toReturn.add(Piece(Point(x, y - amount,dist), Point(x, y,dist))) y -= amount } } dist += amount } return toReturn }
0
Kotlin
0
0
d2005b1bc8c536fe6800f0cbd05ac53c178db9d8
2,617
advent-of-code-2019
MIT License
src/Day03.kt
mythicaleinhorn
572,689,424
false
{"Kotlin": 11494}
fun main() { fun part1(input: List<String>): Int { var result = 0 for (rucksack in input) { val first = rucksack.substring(0 until rucksack.length / 2) val second = rucksack.substring(rucksack.length / 2) val sameItems = first.filter { c -> second.contains(c) } val sameChar = sameItems[0] val sameCharCode = if (sameChar.category == CharCategory.LOWERCASE_LETTER) { sameChar.code - 96 } else { sameChar.code - 38 } result += sameCharCode } return result } fun part2(input: List<String>): Int { var result = 0 for (i in input.indices step 3) { val first = input[i] val second = input[i + 1] val third = input[i + 2] val sameItems = first.filter { c -> second.contains(c) && third.contains(c) } val sameChar = sameItems[0] val sameCharCode = if (sameChar.category == CharCategory.LOWERCASE_LETTER) { sameChar.code - 96 } else { sameChar.code - 38 } result += sameCharCode } return result } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
959dc9f82c14f59d8e3f182043c59aa35e059381
1,527
advent-of-code-2022
Apache License 2.0
kotlin/Graph.kt
NeonMika
433,743,141
false
{"Kotlin": 68645}
data class Graph<D>(val edges: List<Edge<D>>) { val nodes: Map<D, Node<D>> = edges.flatMap { listOf(Node(it.fromData), Node(it.toData)) }.distinct().associateBy { it.data } init { edges.forEach { edge -> edge.resolve(this) } } fun dijkstra(cur: Node<D>): DijkstraData<D> { val visited = mutableSetOf<Node<D>>() val distances = nodes.values.associateWith { Integer.MAX_VALUE }.toMutableMap().also { it[cur] = 0 } val paths = nodes.values.associateWith { mutableListOf<Edge<D>>() }.toMutableMap() dijkstra( mutableSetOf(cur), visited, distances, paths ) return DijkstraData(visited, distances, paths) } fun dijkstra( seenButNotVisited: MutableSet<Node<D>>, visited: MutableSet<Node<D>>, distances: MutableMap<Node<D>, Int>, paths: MutableMap<Node<D>, MutableList<Edge<D>>> ) { do { val cur = seenButNotVisited.minByOrNull { distances[it]!! }!! for (e in cur.outEdges) { val neighbor = e.to if (neighbor !in visited) { seenButNotVisited += neighbor val possibleNewMinDist: Int = distances[cur]!! + e.weight if (possibleNewMinDist < distances[neighbor]!!) { distances[neighbor] = possibleNewMinDist paths[neighbor]!!.clear() paths[neighbor]!! += paths[cur]!! paths[neighbor]!! += e } } } visited += cur seenButNotVisited -= cur distances -= cur } while (visited.size < nodes.size) } override fun toString(): String = buildString { for (e in edges) { appendLine(e) } } } data class Node<D>(val data: D) { var outEdges: List<Edge<D>> = mutableListOf() var inEdges: List<Edge<D>> = mutableListOf() val undirNeighbors: List<Node<D>> get() = outEdges.map { it.to } + inEdges.map { it.from } override fun toString(): String = data.toString() } data class Edge<D>(val fromData: D, val toData: D, val weight: Int = 1) { lateinit var from: Node<D> lateinit var to: Node<D> fun opposite(node: Node<D>) = if (from == node) to else if (to == node) from else null fun resolve(graph: Graph<D>) { from = graph.nodes[fromData]!! to = graph.nodes[toData]!! from.outEdges += this to.inEdges += this } override fun toString(): String { return "$from -> $to [$weight]" } } data class DijkstraData<D>( val visited: MutableSet<Node<D>>, val distances: MutableMap<Node<D>, Int>, val paths: MutableMap<Node<D>, MutableList<Edge<D>>> )
0
Kotlin
0
0
c625d684147395fc2b347f5bc82476668da98b31
2,890
advent-of-code-2021
MIT License
src/main/kotlin/day9/Day09.kt
Avataw
572,709,044
false
{"Kotlin": 99761}
package day9 //35:30min fun solveA(input: List<String>): Int { val tail = Knot("T", tail = null) val head = Knot("H", tail = tail) input.forEach { movement -> val (direction, amountString) = movement.split(" ") val amount = amountString.toInt() repeat(amount) { head.move(direction) } } return tail.visited.toSet().count() } // 63:21min fun solveB(input: List<String>): Int { val finalTail = Knot("9", tail = null) val head = (8 downTo 0).fold(finalTail) { prevKnot, next: Int -> Knot(next.toString(), tail = prevKnot) } input.forEach { movement -> val (direction, amountString) = movement.split(" ") val amount = amountString.toInt() repeat(amount) { head.move(direction) } } return finalTail.visited.toSet().count() } data class Position(val x: Int, val y: Int) { fun up() = Position(x, y + 1) fun down() = Position(x, y - 1) fun left() = Position(x - 1, y) fun right() = Position(x + 1, y) fun downRight() = down().right() fun downLeft() = down().left() fun upRight() = up().right() fun upLeft() = up().left() fun isAdjacent(other: Position) = other.x in x - 1..x + 1 && other.y in y - 1..y + 1 fun isRightFrom(other: Position) = x > other.x fun isLeftFrom(other: Position) = x < other.x fun isUpFrom(other: Position) = y > other.y fun isDownFrom(other: Position) = y < other.y fun isSameRowAs(other: Position) = y == other.y fun isSameColumnAs(other: Position) = x == other.x } data class Knot(val name: String, var position: Position = Position(0, 0), val tail: Knot?) { val visited = mutableListOf(position) fun move(direction: String) { val newPosition: Position = when (direction) { "U" -> position.up() "D" -> position.down() "R" -> position.right() "L" -> position.left() else -> throw Exception("Position could not be parsed") } visited.add(newPosition).also { position = newPosition tail?.trailBehind(position) } } private fun trailBehind(other: Position) { if (position.isAdjacent(other)) return val newPosition = when { position.isDownFrom(other) && position.isSameColumnAs(other) -> position.up() position.isUpFrom(other) && position.isSameColumnAs(other) -> position.down() position.isLeftFrom(other) && position.isSameRowAs(other) -> position.right() position.isRightFrom(other) && position.isSameRowAs(other) -> position.left() position.isDownFrom(other) && position.isLeftFrom(other) -> position.upRight() position.isDownFrom(other) && position.isRightFrom(other) -> position.upLeft() position.isUpFrom(other) && position.isLeftFrom(other) -> position.downRight() position.isUpFrom(other) && position.isRightFrom(other) -> position.downLeft() else -> throw Exception("Next position could not be calculated ") } visited.add(newPosition).also { position = newPosition tail?.trailBehind(position) } } } // party B //package day9 // ////35:30 //fun solveA(input: List<String>): Int { // val tail = Knot("T", tail = null) // val head = Knot("H", tail = tail) // // for (movement in input) { // val (direction, amountString) = movement.split(" ") // println("$direction $amountString") // val amount = amountString.toInt() // // for (step in 0 until amount) { // head.move(direction) // } // } // // return head.tail!!.visited.toSet().count() //} // //// 63:21min //fun solveB(input: List<String>): Int { // val nine = Knot("9", tail = null) // val eight = Knot("8", tail = nine) // val seven = Knot("7", tail = eight) // val six = Knot("6", tail = seven) // val five = Knot("5", tail = six) // val four = Knot("4", tail = five) // val three = Knot("3", tail = four) // val two = Knot("2", tail = three) // val one = Knot("1", tail = two) // val head = Knot("H", tail = one) // // // for (movement in input) { // val (direction, amountString) = movement.split(" ") // println("$direction $amountString") // val amount = amountString.toInt() // // for (step in 0 until amount) { // head.move(direction) // } // println("-> <-") // println(nine) // } // // return nine.visited.toSet().count() //} // // //// same row same column, just // //data class Position(val x: Int, val y: Int) // // //data class Knot(val name: String, var position: Position = Position(0, 0), val tail: Knot?) { // // val visited = mutableListOf(position) // // private fun isTouching(other: Knot) = position.x in other.position.x - 1..other.position.x + 1 && // position.y in other.position.y - 1..other.position.y + 1 // // fun move(direction: String) { // // var newPosition: Position = when (direction) { // "U" -> Position(position.x, position.y + 1) // "D" -> Position(position.x, position.y - 1) // "R" -> Position(position.x + 1, position.y) // "L" -> Position(position.x - 1, position.y) // else -> throw Exception("Position could not be parsed") // } // visited.add(newPosition) // // println("Move $name from $position to $newPosition") // position = newPosition // trailBehind() // } // // private fun trailBehind() { // if (tail == null) return // if (isTouching(tail)) return // // var newPosition: Position? = null // // if (position.x > tail.position.x && position.y == tail.position.y) { // newPosition = Position(tail.position.x + 1, tail.position.y) // } else if (position.x < tail.position.x && position.y == tail.position.y) { // newPosition = Position(tail.position.x - 1, tail.position.y) // } else if (position.x == tail.position.x && position.y > tail.position.y) { // newPosition = Position(tail.position.x, tail.position.y + 1) // } else if (position.x == tail.position.x && position.y < tail.position.y) { // newPosition = Position(tail.position.x, tail.position.y - 1) // } else if (position.x > tail.position.x && position.y > tail.position.y) { // newPosition = Position(tail.position.x + 1, tail.position.y + 1) // } else if (position.x > tail.position.x && position.y < tail.position.y) { // newPosition = Position(tail.position.x + 1, tail.position.y - 1) // } else if (position.x < tail.position.x && position.y > tail.position.y) { // newPosition = Position(tail.position.x - 1, tail.position.y + 1) // } else if (position.x < tail.position.x && position.y < tail.position.y) { // newPosition = Position(tail.position.x - 1, tail.position.y - 1) // } // // if (newPosition == null) throw Exception("something went wrong") // // tail.visited.add(newPosition) // tail.position = newPosition // tail.trailBehind() // } //} //package day9 Part A // ////35:30 //fun solveA(input: List<String>): Int { // val head = Knot("H", Position(0, 0)) // val tail = Knot("T", Position(0, 0)) // // for (movement in input) { // val (direction, amountString) = movement.split(" ") // println("$direction $amountString") // val amount = amountString.toInt() // // for (step in 0 until amount) { // head.move(direction) // if (head.isTouching(tail)) continue // // if (head.position.x == tail.position.x || head.position.y == tail.position.y) { // tail.move(direction) // } else { // if (direction == "R" || direction == "L") { // if (head.position.y > tail.position.y) tail.move("U$direction") // else tail.move("D$direction") // } else { // if (head.position.x > tail.position.x) tail.move(direction + "R") // else tail.move(direction + "L") // } // } // } // } // // return tail.visited.toSet().count() //} // //fun solveB(input: List<String>): Long { // TODO() //} // // //// same row same column, just // //data class Position(val x: Int, val y: Int) // //data class Knot(val name: String, var position: Position) { // // val visited = mutableListOf(position) // // fun isTouching(other: Knot) = position.x in other.position.x - 1..other.position.x + 1 && // position.y in other.position.y - 1..other.position.y + 1 // // fun move(direction: String) { // var newPosition: Position? // // when (direction) { // "U" -> newPosition = Position(position.x, position.y + 1) // "D" -> newPosition = Position(position.x, position.y - 1) // "R" -> newPosition = Position(position.x + 1, position.y) // "L" -> newPosition = Position(position.x - 1, position.y) // "UR" -> newPosition = Position(position.x + 1, position.y + 1) // "UL" -> newPosition = Position(position.x - 1, position.y + 1) // "DR" -> newPosition = Position(position.x + 1, position.y - 1) // "DL" -> newPosition = Position(position.x - 1, position.y - 1) // else -> throw Exception("Position could not be parsed") // } // visited.add(newPosition) // // println("Move $name from $position to $newPosition") // position = newPosition // } // //} // //
0
Kotlin
2
0
769c4bf06ee5b9ad3220e92067d617f07519d2b7
9,700
advent-of-code-2022
Apache License 2.0
src/Day04.kt
daniyarmukhanov
572,847,967
false
{"Kotlin": 9474}
//use this file as template fun main() { fun part1(input: List<String>): Int { var counter = 0 input.forEach { val first = it.split(",").first().split("-").map { i -> i.toInt() }.zipWithNext().first() val last = it.split(",").last().split("-").map { i -> i.toInt() }.zipWithNext().first() if ((first.first <= last.first && first.second >= last.second) || (last.first <= first.first && last.second >= first.second) ) { counter++ } } return counter } fun part2(input: List<String>): Int { var counter = 0 input.forEach { val a = it.split(",").first().split("-").map { i -> i.toInt() }.zipWithNext().first() val b = it.split(",").last().split("-").map { i -> i.toInt() }.zipWithNext().first() if ( (a.first <= b.first && a.second >= b.first) || (a.first >= b.first && b.second >= a.first) ) { counter++ } } return counter } val testInput = readInput("Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
ebad16b2809ef0e3c7034d5eed75e6a8ea34c854
1,307
aoc22
Apache License 2.0
puzzles/src/main/kotlin/com/kotlinground/puzzles/graph/numberofprovinces/numberOfProvinces.kt
BrianLusina
113,182,832
false
{"Kotlin": 483489, "Shell": 7283, "Python": 1725}
package com.kotlinground.puzzles.graph.numberofprovinces /** * Finds the number of connected components(graphs) in a given adjacency list is_connected. Uses DFS traversal algorithm * to find the connected components or the number of graphs from the provided 2D array. * * Complexity: * - Time Complexity: O(n^2). * Initializing the visited array takes O(n) time. * The dfs function visits each node once, which takes O(n) time because there are n nodes in total. * From each node, we iterate over all possible edges using graph[node] which takes O(n) time for each visited node. * As a result, it takes a total of O(n^2) time to visit all the nodes and iterate over its edges. * * - Space Complexity: O(n) * visited array takes O(n) space * Recursion call stack used by dfs can have no more than n elements in the worst case. It would take up to O(n) * space in that case. * * @param isConnected [Array]: 2D Array denoting an adjacency list where the index is a city and the values at that index * denote interconnectivity with 1 showing a direct connection and 0 showing no connection * * @return [Int]: Number of connected components or number of graphs from the list */ fun numberOfProvinces(isConnected: Array<IntArray>): Int { // number of cities is the length of the rows from the grid val cities = isConnected.size // keep track of number of provinces var provinces = 0 // keep track of visited cities val visited = BooleanArray(cities) for (city in 0 until cities) { // if city has not been visited if (!visited[city]) { // increment number of provinces provinces++ // perform a dfs from the city to other cities dfs(city, isConnected, visited) } } return provinces } fun dfs(node: Int, grid: Array<IntArray>, visit: BooleanArray) { // mark this node as visited/or mark this city as visited visit[node] = true for (i in grid.indices) { // get the city's neighbour to check if it can be reached, in this case if the value is 1, we can reach // city's neighbour, i.e, they are connected val neighbour = grid[node][i] // Checks if the neighbour has already been visited val neighbourVisited = visit[i] if (neighbour == 1 && !neighbourVisited) { dfs(i, grid, visit) } } }
1
Kotlin
1
0
5e3e45b84176ea2d9eb36f4f625de89d8685e000
2,429
KotlinGround
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/MaxValue2.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.util.Arrays import kotlin.math.max /** * 1751. Maximum Number of Events That Can Be Attended II * @see <a href="https://leetcode.com/problems/maximum-number-of-events-that-can-be-attended-ii/">Source</a> */ fun interface MaxValue2 { operator fun invoke(events: Array<IntArray>, k: Int): Int } /** * Approach 1: Top-down Dynamic Programming + Binary Search */ class MaxValue2TopDown : MaxValue2 { private lateinit var dp: Array<IntArray> override operator fun invoke(events: Array<IntArray>, k: Int): Int { events.sortWith { a: IntArray, b: IntArray -> a[0] - b[0] } val n = events.size dp = Array(k + 1) { IntArray(n) } for (row in dp) { Arrays.fill(row, -1) } return dfs(0, k, events) } private fun dfs(curIndex: Int, count: Int, events: Array<IntArray>): Int { if (count == 0 || curIndex == events.size) { return 0 } if (dp[count][curIndex] != -1) { return dp[count][curIndex] } val nextIndex = bisectRight(events, events[curIndex][1]) dp[count][curIndex] = max( dfs( curIndex + 1, count, events, ), events[curIndex][2] + dfs(nextIndex, count - 1, events), ) return dp[count][curIndex] } } /** * Approach 2: Bottom-up Dynamic Programming + Binary Search */ class MaxValue2BottomUp : MaxValue2 { override operator fun invoke(events: Array<IntArray>, k: Int): Int { val n: Int = events.size val dp = Array(k + 1) { IntArray(n + 1) } events.sortWith { a: IntArray, b: IntArray -> a[0] - b[0] } for (curIndex in n - 1 downTo 0) { for (count in 1..k) { val nextIndex = bisectRight(events, events[curIndex][1]) dp[count][curIndex] = max(dp[count][curIndex + 1], events[curIndex][2] + dp[count - 1][nextIndex]) } } return dp[k][0] } } /** * Approach 3: Top-down Dynamic Programming + Cached Binary Search */ class MaxValue2TopDownBS : MaxValue2 { private lateinit var dp: Array<IntArray> private lateinit var nextIndices: IntArray override operator fun invoke(events: Array<IntArray>, k: Int): Int { events.sortWith { a: IntArray, b: IntArray -> a[0] - b[0] } val n = events.size nextIndices = IntArray(n) for (curIndex in 0 until n) { nextIndices[curIndex] = bisectRight(events, events[curIndex][1]) } dp = Array(k + 1) { IntArray(n) } for (row in dp) { Arrays.fill(row, -1) } return dfs(0, k, events) } private fun dfs(curIndex: Int, count: Int, events: Array<IntArray>): Int { if (count == 0 || curIndex == events.size) { return 0 } if (dp[count][curIndex] != -1) { return dp[count][curIndex] } val nextIndex = nextIndices[curIndex] dp[count][curIndex] = max( dfs(curIndex + 1, count, events), events[curIndex][2] + dfs(nextIndex, count - 1, events), ) return dp[count][curIndex] } } /** * Approach 5: Top-down Dynamic Programming Without Binary Search */ class MaxValue2SimpleTopDown : MaxValue2 { lateinit var dp: Array<IntArray> override operator fun invoke(events: Array<IntArray>, k: Int): Int { Arrays.sort( events, ) { a: IntArray, b: IntArray -> a[0] - b[0] } val n = events.size dp = Array(k + 1) { IntArray(n) } for (row in dp) { Arrays.fill(row, -1) } return dfs(0, 0, -1, events, k) } private fun dfs(curIndex: Int, count: Int, prevEndingTime: Int, events: Array<IntArray>, k: Int): Int { if (curIndex == events.size || count == k) { return 0 } if (prevEndingTime >= events[curIndex][0]) { return dfs(curIndex + 1, count, prevEndingTime, events, k) } if (dp[count][curIndex] != -1) { return dp[count][curIndex] } val ans = max( dfs(curIndex + 1, count, prevEndingTime, events, k), dfs(curIndex + 1, count + 1, events[curIndex][1], events, k) + events[curIndex][2], ) dp[count][curIndex] = ans return ans } } fun bisectRight(events: Array<IntArray>, target: Int): Int { var left = 0 var right = events.size while (left < right) { val mid = (left + right) / 2 if (events[mid][0] <= target) { left = mid + 1 } else { right = mid } } return left }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
5,349
kotlab
Apache License 2.0
y2018/src/main/kotlin/adventofcode/y2018/Day20.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2018 import adventofcode.io.AdventSolution import java.util.* object Day20 : AdventSolution(2018, 20, "A Regular Map") { override fun solvePartOne(input: String) = findDistances(input).values.maxOrNull() override fun solvePartTwo(input: String) = findDistances(input).count { it.value >= 1000 } private fun findDistances(input: String): Map<Point, Int> { val distanceTo = mutableMapOf(Point(0, 0) to 0) var currentPositions = setOf(Point(0, 0)) val positionsWhenEnteringIntersection = Stack<Set<Point>>() val endPositionsOfBranches = Stack<Set<Point>>() for (ch in input) { when (ch) { in "NESW" -> { currentPositions = currentPositions.map { oldPosition -> oldPosition.step(ch).apply { distanceTo.merge(this, distanceTo.getValue(oldPosition) + 1, ::minOf) } }.toSet() } '(' -> { endPositionsOfBranches.push(emptySet()) positionsWhenEnteringIntersection.push(currentPositions) } '|' -> { endPositionsOfBranches.push(endPositionsOfBranches.pop() + currentPositions) currentPositions = positionsWhenEnteringIntersection.peek() } ')' -> { currentPositions = endPositionsOfBranches.pop() + currentPositions positionsWhenEnteringIntersection.pop() } } } return distanceTo } private data class Point(val x: Int, val y: Int) { fun step(ch: Char) = when (ch) { 'N' -> Point(x, y - 1) 'E' -> Point(x + 1, y) 'S' -> Point(x, y + 1) 'W' -> Point(x - 1, y) else -> throw IllegalStateException() } } }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
2,001
advent-of-code
MIT License
src/Day14.kt
astrofyz
572,802,282
false
{"Kotlin": 124466}
import java.io.File fun main() { fun createWall(input: List<String>, xMax: Int, xMin: Int, yMax: Int, yMin: Int): MutableList<MutableList<Int>> { var wall = MutableList(yMax-yMin+1, { MutableList(xMax-xMin+1, {0}) }) fun MutableList<MutableList<Int>>.paintRock(crd: Pair<String, String>): MutableList<MutableList<Int>> { val startPoint = crd.first.split(',').map { it.toInt() }.toMutableList() val endPoint = crd.second.split(',').map { it.toInt() } val dx = listOf<Int>((endPoint[0]-startPoint[0]).coerceIn(-1 .. 1), (endPoint[1]-startPoint[1]).coerceIn(-1 .. 1)) while (startPoint != endPoint){ this[startPoint[1]-yMin][startPoint[0]-xMin] = 1 startPoint[0] += dx[0] startPoint[1] += dx[1] } this[endPoint[1]-yMin][endPoint[0]-xMin] = 1 return this } for (rock in input){ var vertices = rock.split(" -> ") vertices.zipWithNext().forEach { wall = wall.paintRock(it) } } return wall } fun part1(testInput: String): Int { val regex = "[0-9]+".toRegex() val matches = regex.findAll(testInput) val coords = matches.map { it.value }.toList() val xCoords = coords.filterIndexed { index, _ -> index % 2 == 0 }.toList() val yCoords = coords.filterIndexed { index, _ -> index % 2 == 1 }.toList() val xMax = maxOf(xCoords.maxOf { it.toInt() }, 500) val xMin = xCoords.minOf { it.toInt() } val yMax = yCoords.maxOf { it.toInt() } val yMin = minOf(yCoords.minOf { it.toInt() }, 0) var startX = 500 - xMin val wall = createWall(testInput.split("\n"), xMax, xMin, yMax, yMin) var countSand = 0 var startPoint = Pair(startX, wall.map { it[startX] }.toList().indexOfFirst{it != 0} - 1) var point = startPoint println(startPoint) var flag = "fall" // fall, rest, abyss fun Pair<Int, Int>.makeStep(): Pair<Pair<Int, Int>, String>{ val down = wall.getOrNull(this.second+1)?.getOrNull(this.first) when (down) { 0 -> return Pair(Pair(this.first, this.second + 1), "fall") null -> return Pair(Pair(this.first, this.second), "abyss") 1, 2 -> { val left = wall.getOrNull(this.second + 1)?.getOrNull(this.first - 1) val right = wall.getOrNull(this.second + 1)?.getOrNull(this.first + 1) when (left) { 1, 2 -> { when (right) { 1, 2 -> return Pair(this, "rest") null -> return Pair(this, "abyss") 0 -> return Pair(Pair(this.first + 1, this.second + 1), "fall") } } null -> return Pair(this, "abyss") 0 -> return Pair(Pair(this.first - 1, this.second + 1), "fall") } } } return Pair(Pair(this.first, this.second), "fall") } while (flag != "abyss") { var (newPoint, flag) = point.makeStep() when (flag){ "fall" -> {point = newPoint} "rest" -> {wall[point.second][point.first] = 2; startPoint = Pair(startX, wall.map { it[startX] }.toList().indexOfFirst{it != 0} - 1) point = startPoint countSand++ } "abyss" -> break } } for (row in wall){ println(row.joinToString("") .replace('1', '#') .replace('2', 'o') .replace('0', '.')) } println(countSand) return 0 } fun part2(input: List<String>): Int { var blockedPoints = mutableSetOf<Pair<Int, Int>>() fun MutableSet<Pair<Int, Int>>.paintRock(crd: Pair<String, String>): MutableSet<Pair<Int, Int>> { var startPoint = crd.first.split(',').map { it.toInt() }.toMutableList() var endPoint = crd.second.split(',').map { it.toInt() } var dx = listOf((endPoint[0]-startPoint[0]).coerceIn(-1 .. 1), (endPoint[1]-startPoint[1]).coerceIn(-1 .. 1)) while (startPoint != endPoint){ this.add(Pair(startPoint[0], startPoint[1])) startPoint[0] += dx[0] startPoint[1] += dx[1] } this.add(Pair(endPoint[0], endPoint[1])) return this } for (rock in input){ var vertices = rock.split(" -> ") vertices.zipWithNext().forEach { blockedPoints = blockedPoints.paintRock(it) } } var yFloor = blockedPoints.sortedBy { it.second }.takeLast(1)[0].second + 2 var startPoint = Pair(500, blockedPoints.filter{it.first == 500}.sortedBy { it.second }.take(1)[0].second-1) var point = startPoint var flag = "fall" // fall, rest fun Pair<Int, Int>.makeStep(): Pair<Pair<Int, Int>, String>{ val down = Pair(this.first, this.second+1) val right = Pair(this.first+1, this.second+1) val left = Pair(this.first-1, this.second+1) for (direction in listOf(down, right, left)){ when (direction) { !in blockedPoints -> { if (direction.second == yFloor) return Pair(this, "rest") else return Pair(direction, "fall") } in blockedPoints -> continue } } return Pair(Pair(this.first, this.second), "rest") } var countSand = 0 while (true) { var (newPoint, flag) = point.makeStep() when (flag){ "fall" -> {point = newPoint} "rest" -> { blockedPoints.add(newPoint) startPoint = Pair(500, blockedPoints.filter{it.first == 500}.sortedBy { it.second }.take(1)[0].second-1) point = startPoint countSand++ if (newPoint == Pair(500, 0)) break } } } println(countSand) println(blockedPoints.maxOf { it.first }) println(blockedPoints.minOf { it.first }) println(blockedPoints.maxOf { it.second }) println(blockedPoints.minOf { it.second }) return 0 } // test if implementation meets criteria from the description, like: val testInput = File("src", "Day14_test.txt").readText() part1(testInput) part2(testInput.split("\n")) val input = File("src", "Day14.txt").readText() part1(input) part2(input.split("\n")) }
0
Kotlin
0
0
a0bc190b391585ce3bb6fe2ba092fa1f437491a6
6,963
aoc22
Apache License 2.0
src/Utils.kt
frango9000
573,098,370
false
{"Kotlin": 73317}
import java.io.File import java.math.BigInteger import java.security.MessageDigest import java.util.function.Predicate import kotlin.math.absoluteValue import kotlin.system.measureNanoTime /** * Reads lines from the given input txt file. */ fun readInput(name: String) = File("src", "$name.txt").readLines() /** * Reads lines from the given input txt file. */ fun readTestInput(name: String) = File("test/kotlin", "$name.txt").readLines() /** * Converts string to md5 hash. */ fun String.md5() = BigInteger(1, MessageDigest.getInstance("MD5").digest(toByteArray())).toString(16).padStart(32, '0') /** * partitions the given list by a given predicate is true */ fun <E> List<E>.partitionWhen(partitionWhen: Predicate<E>): List<List<E>> { return this.fold(arrayListOf(arrayListOf<E>())) { acc: ArrayList<ArrayList<E>>, curr: E -> if (partitionWhen.test(curr)) { acc.add(arrayListOf()) } else if (acc.lastIndex >= 0) { acc[acc.lastIndex].add(curr) } acc } } /** * partitions the given list by the provided value */ fun <E> List<E>.partitionOnElement(by: E): List<List<E>> { return this.partitionWhen { by?.equals(it) == true } } data class Coordinate(var x: Int = 0, var y: Int = 0) fun printTime(pre: String = "\n[", post: String = "]\n\n", function: () -> Unit) { print("$pre${measureNanoTime { function() }.toFloat() / 1000000}ms$post") } fun Iterable<Int>.product() = this.reduce { acc, i -> acc * i } fun Iterable<Long>.product() = this.reduce { acc, i -> acc * i } infix fun Int.isDivisibleBy(divisor: Int) = this % divisor == 0 infix fun Long.isDivisibleBy(divisor: Long) = this % divisor == 0L /** * Euclid's algorithm for finding the greatest common divisor of a and b. */ fun gcd(a: Long, b: Long): Long = if (b == 0L) a.absoluteValue else gcd(b, a % b) /** * Find the least common multiple of a and b using the gcd of a and b. */ fun lcm(a: Long, b: Long) = (a * b) / gcd(a, b) fun Iterable<Long>.lcm(): Long = reduce(::lcm) fun <R, T> List<List<T>>.mapMatrix(mapper: (T) -> R): List<List<R>> { return this.map { it.map { mapper(it) } } } fun <R, T> List<List<T>>.mapMatrixIndexed(mapper: (Int, Int, T) -> R): List<List<R>> { return this.mapIndexed { i, row -> row.mapIndexed { j, item -> mapper(i, j, item) } } } fun <R, T> List<List<T>>.matrixForEach(mapper: (T) -> R): Unit { return this.forEach { it.forEach { mapper(it) } } } fun <R, T> List<List<T>>.matrixForEachIndexed(mapper: (Int, Int, T) -> R): Unit { return this.forEachIndexed { i, row -> row.forEachIndexed { j, item -> mapper(i, j, item) } } } infix fun Int.towards(to: Int): IntProgression { val step = if (this > to) -1 else 1 return IntProgression.fromClosedRange(this, to, step) } fun Iterable<IntRange>.merge(): List<IntRange> { val sorted = this.filter { !it.isEmpty() }.sortedBy { it.first } sorted.isNotEmpty() || return emptyList() val stack = ArrayDeque<IntRange>() stack.add(sorted.first()) sorted.drop(1).forEach { current -> if (current.last <= stack.last().last) { // } else if (current.first > stack.last().last + 1) { stack.add(current) } else { stack.add(stack.removeLast().first..current.last) } } return stack } val IntRange.size get() = (last - first + 1).coerceAtLeast(0) fun IntRange.subtract(others: Iterable<IntRange>): List<IntRange> { val relevant = others.merge().filter { it overlaps this } if (relevant.isEmpty()) return listOf(this) return buildList { var includeFrom = first relevant.forEach { minus -> if (minus.first > includeFrom) add(includeFrom until minus.first.coerceAtMost(last)) includeFrom = minus.last + 1 } if (includeFrom <= last) add(includeFrom..last) } } infix fun <T : Comparable<T>> ClosedRange<T>.overlaps(other: ClosedRange<T>): Boolean { if (isEmpty() || other.isEmpty()) return false return !(this.endInclusive < other.start || this.start > other.endInclusive) }
0
Kotlin
0
0
62e91dd429554853564484d93575b607a2d137a3
4,133
advent-of-code-22
Apache License 2.0
src/Day18.kt
Aldas25
572,846,570
false
{"Kotlin": 106964}
fun main() { class Cube(val x: Int, val y: Int, val z: Int) val dirs = listOf( Cube(-1, 0, 0), Cube(1, 0, 0), Cube(0, -1, 0), Cube(0, 1, 0), Cube(0, 0, -1), Cube(0, 0, 1) ) fun part1(cubes: List<Cube>): Int { var ans = 0 val grid = Array(50) { Array(50) { Array(50) { false } } } for (cube in cubes) { if (grid[cube.x][cube.y][cube.z]) println("repeating cubes: ${cube.x}, ${cube.y}, ${cube.z}") grid[cube.x][cube.y][cube.z] = true } for (cube in cubes) { for (dir in dirs) { val x = cube.x + dir.x val y = cube.y + dir.y val z = cube.z + dir.z if (x < 0 || y < 0 || z < 0 || !grid[x][y][z]) ans++ } } return ans } fun part2(cubes: List<Cube>): Int { val grid = Array(50) { Array(50) { Array(50) { false } } } for (cube in cubes) grid[cube.x][cube.y][cube.z] = true val group = Array(50) { Array(50) { Array(50) { -1 } } } fun bfs(start: Cube, groupId: Int, isGrid: Boolean) { val q = mutableListOf(start) while (q.isNotEmpty()) { val cube = q.removeFirst() val x = cube.x val y = cube.y val z = cube.z if (x < 0 || y < 0 || z < 0) continue if (x >= 50 || y >= 50 || z >= 50) continue if (group[x][y][z] != -1) continue if (grid[x][y][z] != isGrid) continue group[x][y][z] = groupId for (dir in dirs) { val nX = x + dir.x val nY = y + dir.y val nZ = z + dir.z q.add(Cube(nX, nY, nZ)) } } } var groupCnt = 0 for (x in grid.indices) for (y in grid[0].indices) for (z in grid[0][0].indices) if (group[x][y][z] == -1) bfs(Cube(x, y, z), groupCnt++, grid[x][y][z]) var ans = 0 for (cube in cubes) { for (dir in dirs) { val x = cube.x + dir.x val y = cube.y + dir.y val z = cube.z + dir.z if (x < 0 || y < 0 || z < 0) { ans++ } else if (!grid[x][y][z] && group[x][y][z] == group[0][0][0]) ans++ } } return ans } fun parseInput(input: List<String>): List<Cube> { fun parseCube(line: String): Cube { val parts = line.split(",") return Cube(parts[0].toInt(), parts[1].toInt(), parts[2].toInt()) } val list: MutableList<Cube> = mutableListOf() for (line in input) list.add(parseCube(line)) return list } val filename = // "inputs/day18_sample" "inputs/day18" val input = readInput(filename) val cubes1 = parseInput(input) val cubes2 = parseInput(input) println("Part 1: ${part1(cubes1)}") println("Part 2: ${part2(cubes2)}") }
0
Kotlin
0
0
80785e323369b204c1057f49f5162b8017adb55a
3,250
Advent-of-Code-2022
Apache License 2.0
src/main/kotlin/com/ginsberg/advent2017/Day14.kt
tginsberg
112,672,087
false
null
/* * Copyright (c) 2017 by <NAME> */ package com.ginsberg.advent2017 import com.ginsberg.advent2017.hash.KnotHash import java.math.BigInteger /** * AoC 2017, Day 14 * * Problem Description: http://adventofcode.com/2017/day/14 * Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2017/day14/ */ class Day14(input: String) { private val binaryStrings = parseInput(input) private val grid by lazy { stringsToGrid() } fun solvePart1(): Int = binaryStrings.sumBy { it.count { it == '1' } } fun solvePart2(): Int { var groups = 0 grid.forEachIndexed { x, row -> row.forEachIndexed { y, spot -> if (spot == 1) { groups += 1 markNeighbors(x, y) } } } return groups } private fun markNeighbors(x: Int, y: Int) { if (grid[x][y] == 1) { grid[x][y] = 0 neighborsOf(x, y).forEach { markNeighbors(it.first, it.second) } } } private fun neighborsOf(x: Int, y: Int): List<Pair<Int, Int>> = listOf(Pair(x - 1, y), Pair(x + 1, y), Pair(x, y - 1), Pair(x, y + 1)) .filter { it.first in 0..127 } .filter { it.second in 0..127 } private fun stringsToGrid(): List<IntArray> = binaryStrings .map { s -> s.map { it.asDigit() } } .map { it.toIntArray() } private fun parseInput(input: String): List<String> = (0..127) .map { KnotHash.hash("$input-$it") } .map { BigInteger(it, 16).toString(2).padStart(128, '0') } }
0
Kotlin
0
15
a57219e75ff9412292319b71827b35023f709036
1,672
advent-2017-kotlin
MIT License
src/aoc2022/day14/AoC14.kt
Saxintosh
576,065,000
false
{"Kotlin": 30013}
package aoc2022.day14 import myRange import readLines private data class P(val x: Int, val y: Int) { fun up() = P(x, y - 1) fun down() = P(x, y + 1) fun left() = P(x - 1, y) fun right() = P(x + 1, y) override fun toString() = "($x,$y)" } private class Regolith { private val map = HashMap<P, Char>() private var rocks = 0 private var deepestRock = 0 private var floor = 0 private var fallingForeverDetected = false private var isFull = false fun parse(lines: List<String>) { lines.forEach { it.split(" -> ").windowed(2) { (a, b) -> val s1 = a.split(",").map(String::toInt) val s2 = b.split(",").map(String::toInt) val p1 = P(s1[0], s1[1]) val p2 = P(s2[0], s2[1]) when (p1.x == p2.x) { true -> for (y in myRange(p1.y, p2.y)) { map[P(p1.x, y)] = '#' } false -> for (x in myRange(p1.x, p2.x)) { map[P(x, p1.y)] = '#' } } } } deepestRock = map.keys.maxBy { it.y }.y floor = deepestRock + 1 rocks = map.size } val size get() = map.size - rocks fun P.next(): P? { val p1 = down() if (map[p1] == null) return p1 val p2 = p1.left() if (map[p2] == null) return p2 val p3 = p1.right() if (map[p3] == null) return p3 return null } fun dropSand() { var p = P(500, 0) var next = p.next() while (next != null && next.y < deepestRock) { p = next next = p.next() } if (next == null) map[p] = 'o' else fallingForeverDetected = true } fun dropSand2() { var p = P(500, 0) var next = p.next() while (next != null && next.y < floor) { p = next next = p.next() } if (next == null) { map[p] = 'o' if (p.y == 0) isFull = true } else { map[next] = 'o' } } fun process() { while (!fallingForeverDetected) dropSand() } fun process2() { while (!isFull) dropSand2() } } fun main() { fun part1(lines: List<String>): Int { val r = Regolith() r.parse(lines) r.process() return r.size } fun part2(lines: List<String>): Int { val r = Regolith() r.parse(lines) r.process2() return r.size } readLines(24, 93, ::part1, ::part2) }
0
Kotlin
0
0
877d58367018372502f03dcc97a26a6f831fc8d8
2,111
aoc2022
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/MatrixRankTransform.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.util.TreeMap import kotlin.math.max /** * 1632. Rank Transform of a Matrix * @see <a href="https://leetcode.com/problems/rank-transform-of-a-matrix/">Source</a> */ fun interface MatrixRankTransform { operator fun invoke(matrix: Array<IntArray>): Array<IntArray> } class MatrixRankTransformMap : MatrixRankTransform { override operator fun invoke(matrix: Array<IntArray>): Array<IntArray> { val m: Int = matrix.size val n: Int = matrix[0].size val map = TreeMap<Int, MutableList<IntArray>>() for (i in 0 until m) { for (j in 0 until n) { map.putIfAbsent(matrix[i][j], ArrayList()) map[matrix[i][j]]?.add(intArrayOf(i, j)) } } val rank = IntArray(m + n) for ((_, value1) in map) { val parentMap = HashMap<Int, Int>() for (pair in value1) { union(parentMap, pair[0], pair[1] + m) } val groups = HashMap<Int, MutableList<Int>>() for (value in parentMap.keys) { val parent = find(parentMap, value) groups.putIfAbsent(parent, ArrayList()) groups[parent]?.add(value) } for ((_, v) in groups) { var maxRank = 0 for (value in v) { maxRank = max(maxRank, rank[value]) } for (value in v) { rank[value] = maxRank + 1 } } for (pair in value1) { matrix[pair[0]][pair[1]] = rank[pair[0]] } } return matrix } private fun find(parentMap: HashMap<Int, Int>, value: Int): Int { if (parentMap[value] == value) { return value } parentMap[value] = find(parentMap, parentMap.getOrDefault(value, 0)) return parentMap.getOrDefault(value, 0) } private fun union(parentMap: HashMap<Int, Int>, u: Int, v: Int) { if (!parentMap.containsKey(u)) { parentMap[u] = u } if (!parentMap.containsKey(v)) { parentMap[v] = v } val pu = find(parentMap, u) val pv = find(parentMap, v) if (pu != pv) { parentMap[pu] = pv } } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,968
kotlab
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/FindKthLargest.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.util.PriorityQueue import java.util.Random import kotlin.math.max import kotlin.math.min /** * 215. Kth Largest Element in an Array * @see <a href="https://leetcode.com/problems/kth-largest-element-in-an-array/">Source</a> */ fun interface FindKthLargest { operator fun invoke(nums: IntArray, k: Int): Int } /** * Approach 1: Sort */ class FindKthLargestSort : FindKthLargest { override operator fun invoke(nums: IntArray, k: Int) = nums.sorted()[nums.size - k] } /** * Approach 2: Min-Heap */ class FindKthLargestMinHeap : FindKthLargest { override operator fun invoke(nums: IntArray, k: Int): Int { val heap: PriorityQueue<Int> = PriorityQueue() for (num in nums) { heap.add(num) if (heap.size > k) { heap.remove() } } return heap.peek() } } /** * Approach 3: Quickselect */ class FindKthLargestQuickSelect : FindKthLargest { override operator fun invoke(nums: IntArray, k: Int): Int { val list: MutableList<Int> = ArrayList() for (num in nums) { list.add(num) } return quickSelect(list, k) } private fun quickSelect(nums: List<Int>, k: Int): Int { val pivotIndex: Int = Random().nextInt(nums.size) val pivot = nums[pivotIndex] val left: MutableList<Int> = ArrayList() val mid: MutableList<Int> = ArrayList() val right: MutableList<Int> = ArrayList() for (num in nums) { if (num > pivot) { left.add(num) } else if (num < pivot) { right.add(num) } else { mid.add(num) } } if (k <= left.size) { return quickSelect(left, k) } return if (left.size + mid.size < k) { quickSelect(right, k - left.size - mid.size) } else { pivot } } } /** * Approach 4: Counting Sort */ class FindKthLargestCountingSort : FindKthLargest { override operator fun invoke(nums: IntArray, k: Int): Int { var minValue = Int.MAX_VALUE var maxValue = Int.MIN_VALUE for (num in nums) { minValue = min(minValue.toDouble(), num.toDouble()).toInt() maxValue = max(maxValue.toDouble(), num.toDouble()).toInt() } val count = IntArray(maxValue - minValue + 1) for (num in nums) { count[num - minValue]++ } var remain = k for (num in count.indices.reversed()) { remain -= count[num] if (remain <= 0) { return num + minValue } } return -1 } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,351
kotlab
Apache License 2.0
src/Day04.kt
jalex19100
574,686,993
false
{"Kotlin": 19795}
fun main() { fun part1(input: List<String>): Int { var count = 0 input.forEach { line -> val pairs = line.split(',', '-') val pair1 = (pairs[0].toInt()..pairs[1].toInt()).toSet() val pair2 = (pairs[2].toInt()..pairs[3].toInt()).toSet() if (pair1.isNotEmpty() && pair2.isNotEmpty() && pair1.containsAll(pair2) || pair2.containsAll(pair1)) count++ } return count } fun part2(input: List<String>): Int { var count = 0 input.forEach { line -> val pairs = line.split(',', '-') val pair1 = (pairs[0].toInt()..pairs[1].toInt()).toSet() val pair2 = (pairs[2].toInt()..pairs[3].toInt()).toSet() if (pair1.isNotEmpty() && pair2.isNotEmpty() && pair1.intersect(pair2).isNotEmpty()) count++ } return count } // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
a50639447a2ef3f6fc9548f0d89cc643266c1b74
1,146
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/File02.kt
andrewrlee
319,095,151
false
null
import java.io.File import java.nio.charset.StandardCharsets.UTF_8 private class Challenge02 { data class Policy(val low: Int, val high: Int, val v: Char) val pattern = "(\\d+)-(\\d+) (\\w): (\\w+)".toRegex() fun readPoliciesAndPasswords() = File("src/main/resources/02-input.txt").readLines(UTF_8) .map { pattern.find(it)!!.groupValues } .map { Pair(Policy(it[1].toInt(), it[2].toInt(), it[3].toCharArray()[0]), it[4]) } fun isValidV1(policy: Policy, password: String): Boolean { val (low, high, v) = policy val occurrences = password.groupingBy { it }.eachCount()[v] ?: 0 return occurrences in low..high } fun isValidV2(policy: Policy, password: String): Boolean { val (low, high, v) = policy val lowCharMatch = password.length < low || password[low - 1] == v val highCharMatch = password.length < high || password[high - 1] == v return (lowCharMatch || highCharMatch) && !(lowCharMatch && highCharMatch) } private fun findAnswer1v1() = readPoliciesAndPasswords().count { (policy, password) -> isValidV1(policy, password) } private fun findAnswer2v1() = readPoliciesAndPasswords().count { (policy, password) -> isValidV2(policy, password) } fun solve() { println(findAnswer1v1()) println(findAnswer2v1()) } } fun main() = Challenge02().solve()
0
Kotlin
0
0
a9c21a6563f42af7fada3dd2e93bf75a6d7d714c
1,387
adventOfCode2020
MIT License
src/Day16.kt
abeltay
572,984,420
false
{"Kotlin": 91982, "Shell": 191}
import java.util.* fun main() { data class Valve( val name: String, val flowRate: Int, val vertex: MutableList<Int> = mutableListOf() ) data class State( val openedValves: Set<Int>, val location: Int, val pressure: Int, val timeLeft: Int ) val stateComparator = Comparator<State> { a, b -> if (a.timeLeft != b.timeLeft) b.timeLeft - a.timeLeft else b.pressure - a.pressure } fun parseInput(input: List<String>): List<Valve> { val inputLineRegex = """Valve ([A-Z]+) has flow rate=(\d+)""".toRegex() val valves = mutableListOf<Valve>() for (it in input) { val part = it.substringBefore(';') val (valve, flowString) = inputLineRegex .matchEntire(part) ?.destructured ?: throw IllegalArgumentException("Incorrect input line $it") valves.add(Valve(name = valve, flowRate = flowString.toInt())) } for ((idx, value) in input.withIndex()) { val part = if (value.contains("valves")) { value.substringAfter("; tunnels lead to valves ") } else { value.substringAfter("; tunnel leads to valve ") } val linkedValves = part.split(", ") for (it in linkedValves) { val valve = valves.indexOfFirst { valve -> valve.name == it } if (valve == -1) { throw IllegalArgumentException("Incorrect input $valve") } valves[idx].vertex.add(valve) } } return valves } fun updateMatrix(map: MutableList<MutableList<Int>>, from: Int, to: Int) { val cost = map[from][to] for (i in map[to].indices) { val newCost = cost + map[from][i] if (newCost < map[to][i]) { map[to][i] = newCost map[i][to] = newCost } } } fun createAdjacencyMatrix(valves: List<Valve>): MutableList<MutableList<Int>> { val limit = 9 val adjacencyMatrix = MutableList(valves.size) { MutableList(valves.size) { limit } } for (i in valves.indices) { for (j in valves[i].vertex) { adjacencyMatrix[i][j] = 1 adjacencyMatrix[j][i] = 1 } } for (i in valves.indices) { adjacencyMatrix[i][i] = 0 } for (i in adjacencyMatrix.indices) { for (j in adjacencyMatrix[i].indices) { updateMatrix(adjacencyMatrix, i, j) } } return adjacencyMatrix } fun getFlow(valves: List<Valve>, openedValves: Set<Int>): Int { var flow = 0 for (it in openedValves) { flow += valves[it].flowRate } return flow } fun explore( valves: List<Valve>, adjacencyMatrix: List<List<Int>>, priorityQueue: PriorityQueue<State>, optimisedMap: HashMap<Set<Int>, Int> ) { val state = priorityQueue.poll() val flowRate = getFlow(valves, state.openedValves) if (!state.openedValves.contains(state.location) && valves[state.location].flowRate > 0) { val newValves = state.openedValves.toMutableSet() newValves.add(state.location) priorityQueue.add( State( openedValves = newValves, location = state.location, pressure = state.pressure + flowRate, timeLeft = state.timeLeft - 1 ) ) val newEndPressure = state.pressure + flowRate + ((flowRate + valves[state.location].flowRate) * (state.timeLeft - 1)) val sorted = newValves.sorted().toSet() val existingPressure = optimisedMap[sorted] if (existingPressure == null || existingPressure < newEndPressure) { optimisedMap[sorted] = newEndPressure } return } for (i in adjacencyMatrix[state.location].indices) { if (i == state.location || valves[i].flowRate == 0 || state.openedValves.contains(i)) continue val timeAfterMoving = state.timeLeft - adjacencyMatrix[state.location][i] if (timeAfterMoving > 0) { priorityQueue.add( State( openedValves = state.openedValves, location = i, pressure = state.pressure + flowRate * adjacencyMatrix[state.location][i], timeLeft = state.timeLeft - adjacencyMatrix[state.location][i] ) ) } } } fun part1(input: List<String>): Int { val valves = parseInput(input) val adjacencyMatrix = createAdjacencyMatrix(valves) val priorityQueue = PriorityQueue(stateComparator) priorityQueue.add( State( openedValves = setOf(), location = valves.indexOfFirst { it.name == "AA" }, pressure = 0, timeLeft = 30 ) ) val optimisedMap = HashMap<Set<Int>, Int>() while (priorityQueue.isNotEmpty()) { explore(valves, adjacencyMatrix, priorityQueue, optimisedMap) } return optimisedMap.maxOf { it.value } } fun part2(input: List<String>): Int { val valves = parseInput(input) val adjacencyMatrix = createAdjacencyMatrix(valves) val priorityQueue = PriorityQueue(stateComparator) priorityQueue.add( State( openedValves = setOf(), location = valves.indexOfFirst { it.name == "AA" }, pressure = 0, timeLeft = 26 ) ) val optimisedMap = HashMap<Set<Int>, Int>() while (priorityQueue.isNotEmpty()) { explore(valves, adjacencyMatrix, priorityQueue, optimisedMap) } val usableValves = mutableListOf<Int>() for ((idx, valve) in valves.withIndex()) { if (valve.flowRate > 0) usableValves.add(idx) } var answer = 0 for ((idx, value) in optimisedMap) { for ((idx2, value2) in optimisedMap) { if (idx.intersect(idx2).isEmpty()) { val pressure = value + value2 if (pressure > answer) answer = pressure } } } return answer } val testInput = readInput("Day16_test") check(part1(testInput) == 1651) check(part2(testInput) == 1707) val input = readInput("Day16") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
a51bda36eaef85a8faa305a0441efaa745f6f399
6,867
advent-of-code-2022
Apache License 2.0
year2023/src/main/kotlin/net/olegg/aoc/year2023/day8/Day8.kt
0legg
110,665,187
false
{"Kotlin": 511989}
package net.olegg.aoc.year2023.day8 import net.olegg.aoc.someday.SomeDay import net.olegg.aoc.year2023.DayOf2023 /** * See [Year 2023, Day 8](https://adventofcode.com/2023/day/8) */ object Day8 : DayOf2023(8) { private val PATTERN = "(\\w+) = \\((\\w+), (\\w+)\\)".toRegex() override fun first(): Any? { val (instruction, nodeStrings) = data.split("\n\n") val nodes = nodeStrings.lineSequence() .mapNotNull { PATTERN.find(it) } .associate { it.groupValues[1] to mapOf('L' to it.groupValues[2], 'R' to it.groupValues[3]) } return generateSequence(0) { it + 1 } .runningFold("AAA" to 0) { (curr, steps), index -> val char = instruction[index % instruction.length] nodes.getValue(curr).getValue(char) to steps + 1 } .first { it.first == "ZZZ" } .second } override fun second(): Any? { val (instruction, nodeStrings) = data.split("\n\n") val nodes = nodeStrings.lineSequence() .mapNotNull { PATTERN.find(it) } .associate { it.groupValues[1] to mapOf('L' to it.groupValues[2], 'R' to it.groupValues[3]) } val aNodes = nodes.keys.filter { it.endsWith("A") } val loops = aNodes.map { node -> generateSequence(0L) { it + 1 } .runningFold(node to 0L) { (curr, steps), index -> val char = instruction[(index % instruction.length).toInt()] nodes.getValue(curr).getValue(char) to steps + 1 } .first { it.first.endsWith("Z") } .second } return loops.map { it / instruction.length } .fold(instruction.length.toLong(), Long::times) } } fun main() = SomeDay.mainify(Day8)
0
Kotlin
1
7
e4a356079eb3a7f616f4c710fe1dfe781fc78b1a
1,671
adventofcode
MIT License
src/main/kotlin/aoc2022/Day05.kt
w8mr
572,700,604
false
{"Kotlin": 140954}
package aoc2022 import aoc.* import aoc.parser.* class Day05() { sealed interface Crate { val id: Char } object Empty : Crate { override val id: Char = '#' } data class Filled(override val id: Char): Crate data class Move(val count: Int, val from: Int, val to: Int) val filled = "[" followedBy regex("[A-Z]") followedBy "]" map { c -> Filled(c[0]) } val empty = " " asValue Empty val crate = filled or empty val crateLine = crate sepBy " " followedBy "\n" val crates = zeroOrMore(crateLine) val crateNumbers = regex("(?:[ ]*\\d*[ ]*)*") followedBy "\n\n" val move = "move " followedBy number() val from = " from " followedBy number() val to = " to " followedBy number() val instructions = zeroOrMore(seq(move, from, to followedBy "\n", ::Move)) val parser = seq(crates, crateNumbers, instructions) { c, _, i -> Pair(c, i) } fun solve(input: String, reorder: (List<List<Crate>>, Move) -> List<List<Crate>>): String { val (crates, moves) = parser.parse(input) val trans = crates.transpose().map { it.filter { it != Empty } } val end = moves.fold(trans, reorder) val result = end.map(List<Crate>::first).map(Crate::id) return result.joinToString(separator = "") } fun <T> move1(list: List<List<T>>, m: Move): List<List<T>> = move(list, m) { it.reversed() } fun <T> move2(list: List<List<T>>, m: Move): List<List<T>> = move(list, m) { it } fun <T> move(list: List<List<T>>, move: Move, f: (List<T>) -> List<T>): List<List<T>> { val movedCrates = f(list[move.from-1].take(move.count)) return list.mapIndexed { idx, inner -> when (idx+1) { move.from -> inner.drop(move.count) move.to -> movedCrates + inner else -> inner } } } fun part1(input: String): String { return solve(input, ::move1) } fun part2(input: String): String { return solve(input, ::move2) } }
0
Kotlin
0
0
e9bd07770ccf8949f718a02db8d09daf5804273d
2,063
aoc-kotlin
Apache License 2.0
src/leetcode_problems/medium/LongestCommonPref.kt
MhmoudAlim
451,633,139
false
{"Kotlin": 31257, "Java": 586}
package leetcode_problems.medium//https://leetcode.com/problems/longest-common-prefix/ //best fun longestCommonPrefix(strs: Array<String>?): String { if (strs == null || strs.isEmpty()) return "" for (i in 0 until strs[0].length) { val c = strs[0][i] for (j in 1 until strs.size) { if (i == strs[j].length || strs[j][i] != c) return strs[0].substring(0, i) } } return strs[0] } fun longestCommonPrefix1(strs: Array<String>): String { println(strs.contentToString()) if (strs.isEmpty()) return "" if (strs.size == 1) return strs[0] val firstItem = strs[0] for (i in firstItem.indices) { strs.forEach { if (firstItem[i] != it[i]) return firstItem.substring(0, i) } } return "" } fun longestCommonPrefix2(strs: Array<String>): String { println(strs.contentToString()) return if (strs.isNotEmpty()) strs.reduce { accumulator, string -> accumulator.commonPrefixWith(string) } else "" } fun main() { val strs = arrayOf("flower", "fla", "flight", "fl") val strs2 = arrayOf("flower", "fla", "asd", "fl") val strs3 = arrayOf("a", "ab") println(longestCommonPrefix(strs)) }
0
Kotlin
0
0
31f0b84ebb6e3947e971285c8c641173c2a60b68
1,230
Coding-challanges
MIT License
src/com/leecode/array/Code7.kt
zys0909
305,335,860
false
null
package com.leecode.array /** 给定一个排序数组,你需要在 原地 删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。 不要使用额外的数组空间,你必须在 原地 修改输入数组 并在使用 O(1) 额外空间的条件下完成。 示例 1: 给定数组 nums = [1,1,2], 函数应该返回新的长度 2, 并且原数组 nums 的前两个元素被修改为 1, 2。 你不需要考虑数组中超出新长度后面的元素。 示例 2: 给定 nums = [0,0,1,1,1,2,2,3,3,4], 函数应该返回新的长度 5, 并且原数组 nums 的前五个元素被修改为 0, 1, 2, 3, 4。 你不需要考虑数组中超出新长度后面的元素。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array */ fun main() { val nums = intArrayOf(0, 0, 1, 1, 1, 2, 2, 3, 3, 4) val i = removeDuplicates(nums) System.arraycopy(nums, 0, nums, 0, i) println(nums.joinToString()) } fun removeDuplicates(nums: IntArray): Int { var i = 0 var j = 1 while (j < nums.size) { if (nums[i] != nums[j]) { i++ nums[i] = nums[j] } j++ } return i + 1 }
0
Kotlin
0
0
869c7c2f6686a773b2ec7d2aaa5bea2de46f1e0b
1,235
CodeLabs
Apache License 2.0
src/main/kotlin/kt/kotlinalgs/app/graph/TransitiveClosure.ws.kts
sjaindl
384,471,324
false
null
package kt.kotlinalgs.app.graph println("Test") /* relax all intermediate nodes O(V^3) 1. create adj matrix directed weighted graph 2. for each intermediate in 0 until V for each start in 0 until V for each end in 0 until V relax if matrix[i][k] + matrix[k][j] < matrix[i][j] */ data class DirectedWeightedGraphWithAdjMatrix(val matrix: Array<IntArray>) class TransitiveClosure() { fun reachabilityMatrix(graph: DirectedWeightedGraphWithAdjMatrix): Array<BooleanArray> { val size = graph.matrix.size val matrix = Array<BooleanArray>(size) { BooleanArray(size) } for (row in graph.matrix.indices) { for (col in graph.matrix[0].indices) { matrix[row][col] = if (graph.matrix[row][col] != Int.MAX_VALUE) true else false } } for (start in 0 until size) { for (intermediate in 0 until size) { for (end in 0 until size) { if (matrix[start][intermediate] && matrix[intermediate][end]) { matrix[start][end] = true } } } } return matrix } fun reachabilityMatrixDFS(graph: DirectedWeightedGraphWithAdjMatrix): Array<BooleanArray> { val size = graph.matrix.size val transitiveClosureMatrix = Array<BooleanArray>(size) { BooleanArray(size) } // 1. call DFS for each vertice not in tc matrix (not marked itself) // 2. rec DFS func: // mark node pair as reachable // check neighbours, if not already marked for (vertice in graph.matrix.indices) { reachabilityMatrixDFS(graph, vertice, vertice, transitiveClosureMatrix) } return transitiveClosureMatrix } private fun reachabilityMatrixDFS( graph: DirectedWeightedGraphWithAdjMatrix, start: Int, current: Int, tc: Array<BooleanArray> ) { tc[start][current] = true for (nb in graph.matrix.indices) { if (graph.matrix[current][nb] != Int.MAX_VALUE && !tc[start][nb]) { reachabilityMatrixDFS(graph, start, nb, tc) } } } fun printShortestPaths(matrix: Array<BooleanArray>) { for (from in matrix.indices) { for (to in matrix.indices) { println("$from -> $to: Dist ${matrix[from][to]}") } } } } val INF = Int.MAX_VALUE val graph = DirectedWeightedGraphWithAdjMatrix( arrayOf( intArrayOf(0, 5, INF, 10), intArrayOf(INF, 0, 3, INF), intArrayOf(INF, INF, 0, 1), intArrayOf(INF, INF, INF, 0) ) ) // https://www.geeksforgeeks.org/transitive-closure-of-a-graph/ // with graph from: https://www.geeksforgeeks.org/floyd-warshall-algorithm-dp-16/ // O(V^3) runtime val transitive = TransitiveClosure() val outputMatrix = transitive.reachabilityMatrix(graph) transitive.printShortestPaths(outputMatrix) // https://www.geeksforgeeks.org/transitive-closure-of-a-graph-using-dfs/ // O(V * (E+V)) val tcMatrix = transitive.reachabilityMatrixDFS(graph) transitive.printShortestPaths(tcMatrix)
0
Java
0
0
e7ae2fcd1ce8dffabecfedb893cb04ccd9bf8ba0
3,219
KotlinAlgs
MIT License
implementation/common/src/main/kotlin/io/github/tomplum/aoc/extensions/CollectionExtensions.kt
TomPlum
317,142,882
false
null
package io.github.tomplum.aoc.extensions import kotlin.math.pow /** * Returns the product of all of the integers in the given list. */ fun List<Int>.product(): Int = if (isNotEmpty()) reduce { product, next -> product * next } else 0 fun List<Long>.product(): Long = if (isNotEmpty()) reduce { product, next -> product * next } else 0 /** * Converts the [IntArray] into its decimal equivalent. * This assumes the array contains only 1s and 0s. * @return The decimal representation. */ fun IntArray.toDecimal(): Long = reversed() .mapIndexed { i, bit -> if (bit == 1) 2.0.pow(i) else 0 } .map { integer -> integer.toLong() } .sum() /** * For two sets A and B, the Cartesian product of A and B is denoted by A×B and defined as: * A×B = { (a,b) | aϵA and bϵB } * * Put simply, the Cartesian Product is the multiplication of two sets to form the set of all ordered pairs. * This function returns the cartesian product of itself and the given set, meaning A and B are [this] and [other]. * * @see cartesianProductQuadratic for a variant that returns the product of itself. */ fun <S, T> List<S>.cartesianProduct(other: List<T>): List<Pair<S, T>> = this.flatMap { value -> List(other.size){ i -> Pair(value, other[i]) } } /** * For two sets A and B, the Cartesian product of A and B is denoted by A×B and defined as: * A×B = { (a,b) | aϵA and bϵB } * * Put simply, the Cartesian Product is the multiplication of two sets to form the set of all ordered pairs. * This function returns the cartesian product of itself, meaning both A and B are simply [this]. * * @see cartesianProductCubic for a variant that accepts another set. */ fun <T> List<T>.cartesianProductQuadratic(): List<Pair<T, T>> = this.flatMap { value -> List(this.size){ i -> Pair(value, this[i]) } } /** * For three sets A, B and C, the Cartesian product of A, B and C is denoted by A×B×C and defined as: * A×B×C = { (p, q, r) | pϵA and qϵB and rϵC } * * Put simply, the Cartesian Product is the multiplication of three sets to form the set of all ordered pairs. * This function returns the cartesian product of itself and the given sets, meaning that A, B & C are all [this]. * * @see cartesianProductQuadratic for a variation that simply finds the product of itself. */ fun <T> List<T>.cartesianProductCubic(): List<Triple<T, T, T>> = cartesianProduct(this, this, this).map { set -> Triple(set[0], set[1], set[2]) } /** * For three sets A, B and C, the Cartesian product of A, B and C is denoted by A×B×C and defined as: * A×B×C = { (p, q, r) | pϵA and qϵB and rϵC } * * Put simply, the Cartesian Product is the multiplication of three sets to form the set of all ordered pairs. * This function returns the cartesian product of itself and the given sets, meaning both A, B and C are [this], * [second] and [third] respectively. */ fun <T> List<T>.cartesianProductCubic(second: List<T>, third: List<T>): List<Triple<T, T, T>> = cartesianProduct(this, second, third).map { set -> Triple(set[0], set[1], set[2]) } /** * Finds the Cartesian Product of any number of given [sets]. */ private fun <T> cartesianProduct(vararg sets: List<T>): List<List<T>> = sets.fold(listOf(listOf())) { acc, set -> acc.flatMap { list -> set.map { element -> list + element } } }
1
Kotlin
0
0
73b3eacb7cb8a7382f8891d3866eda983b6ea7a9
3,322
advent-of-code-2020
Apache License 2.0
src/main/kotlin/nl/kelpin/fleur/advent2018/Day18.kt
fdlk
159,925,533
false
null
package nl.kelpin.fleur.advent2018 class Day18(val input: List<String>) { private fun insideGrid(point: Point, state: List<String>): Boolean = with(point) { (0 until state.size).contains(y) && (0 until state[0].length).contains(x) } private fun charAt(point: Point, state: List<String>): Char = with(point) { state[y][x] } private fun neighbors(point: Point, state: List<String>): List<Char> = listOf( point.move(Up).move(Left), point.move(Up), point.move(Up).move(Right), point.move(Right), point.move(Right).move(Down), point.move(Down), point.move(Down).move(Left), point.move(Left)) .filter { insideGrid(it, state) } .map { charAt(it, state) } private fun nextChar(char: Char, point: Point, state: List<String>): Char { val neighborChars = neighbors(point, state).groupingBy { it }.eachCount() return when (char) { '.' -> when { neighborChars.getOrDefault('|', 0) >= 3 -> '|' else -> '.' } '|' -> when { neighborChars.getOrDefault('#', 0) >= 3 -> '#' else -> '|' } '#' -> when { neighborChars.contains('#') && neighborChars.contains('|') -> '#' else -> '.' } else -> throw IllegalStateException() } } private fun states() = sequence { var state = input while (true) { yield(state) state = state.mapIndexed { y, line -> line.toList().mapIndexed { x, char -> nextChar(char, Point(x, y), state) }.joinToString("") } } } fun value(state: List<String>): Int { val characters = state.map { it.toList() }.flatten().groupingBy { it }.eachCount() return characters['#']!! * characters['|']!! } fun part1(n: Int = 10): Int = value(states().drop(n).first()) fun part2(n: Int = 1000000000): Int { val seen = mutableSetOf<List<String>>() val firstRepeater = states().find { !seen.add(it) } val firstSeen = states().indexOfFirst { it == firstRepeater } val period = states().drop(firstSeen + 1).indexOfFirst { it == firstRepeater } val leftover = (n - firstSeen) % (period + 1) return value(states().drop(firstSeen + leftover).first()) } }
0
Kotlin
0
3
a089dbae93ee520bf7a8861c9f90731eabd6eba3
2,499
advent-2018
MIT License
src/main/kotlin/dev/shtanko/algorithms/mocks/interview/PairsOfPrefixOrSuffix.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.mocks.interview /** * Given a list of words, find all the pair of words for which one of them is a prefix or suffix of the other. */ fun findPrefixOrSuffixPairs(words: List<String>): List<Pair<String, String>> { val trie = Trie() val reverseTrie = Trie() for (word in words) { trie.insert(word, true) reverseTrie.insert(word, false) } val wordPairs = mutableListOf<Pair<String, String>>() getNextWords(trie.root, wordPairs) getNextWords(reverseTrie.root, wordPairs) return wordPairs } private fun getNextWords(node: TrieNode, wordPairs: MutableList<Pair<String, String>>): List<String> { val nextWords = mutableListOf<String>() val nextNonDelimiterChildren = node.children.filterKeys { it != DELIMITER } for ((_, child) in nextNonDelimiterChildren) { nextWords.addAll(getNextWords(child, wordPairs)) } if (DELIMITER in node.children) { val wordEndingHere = node.children[DELIMITER]!!.word!! for (nextWord in nextWords) { wordPairs.add(wordEndingHere to nextWord) } nextWords.add(wordEndingHere) } return nextWords } const val DELIMITER = '*' private class TrieNode { val children = mutableMapOf<Char, TrieNode>() var word: String? = null } private class Trie { val root = TrieNode() fun insert(word: String, leftToRight: Boolean) { var currentNode = root val range = if (leftToRight) word.indices else word.indices.reversed() for (idx in range) { val ch = word[idx] if (ch !in currentNode.children) { currentNode.children[ch] = TrieNode() } currentNode = currentNode.children[ch]!! } currentNode.children[DELIMITER] = TrieNode().also { it.word = word } } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,481
kotlab
Apache License 2.0
src/Day04.kt
Frendzel
573,198,577
false
{"Kotlin": 5336}
fun main() { fun part1(input: List<String>) = input .map { it.split(",") } .map { val first = it[0].split("-") val firstRange = IntRange(first[0].toInt(), first[1].toInt()) val second = it[1].split("-") val secondRange = IntRange(second[0].toInt(), second[1].toInt()) (firstRange.contains(secondRange.first) && firstRange.contains(secondRange.last)) || (secondRange.contains(firstRange.first) && secondRange.contains(firstRange.last)) }.count { it } fun part2(input: List<String>): Int = input .map { it.split(",") } .map { val first = it[0].split("-") val firstRange = IntRange(first[0].toInt(), first[1].toInt()) val second = it[1].split("-") val secondRange = IntRange(second[0].toInt(), second[1].toInt()) (firstRange.contains(secondRange.first) || firstRange.contains(secondRange.last)) || (secondRange.contains(firstRange.first) || secondRange.contains(firstRange.last)) }.count { it } val testInput = readInput("Day04_test") val part1 = part1(testInput) println(part1) check(part1 == 490) val part2 = part2(testInput) println(part2) check(part2 == 921) }
0
Kotlin
0
0
a8320504be93dfba1f634413a50e7240d16ba6d9
1,381
advent-of-code-kotlin
Apache License 2.0
src/main/kotlin/dev/bogwalk/batch3/Problem34.kt
bog-walk
381,459,475
false
null
package dev.bogwalk.batch3 import dev.bogwalk.util.maths.factorial /** * Problem 34: Digit Factorials * * https://projecteuler.net/problem=34 * * Goal: Find the sum of all numbers less than N that divide the sum of the factorial of their * digits (& therefore have minimum 2 digits). * * Constraints: 10 <= N <= 1e5 * * Factorion: A natural number that equals the sum of the factorials of its digits. * The only non-single-digit factorions are: 145 and 40585. * * e.g.: N = 20 * qualifying numbers = {19} * as 1! + 9! = 362_881, which % 19 = 0 * e.g. 18 does not work as 1! + 8! = 40321, which % 18 > 0 * sum = 19 */ class DigitFactorials { // pre-calculation of all digit factorials to increase performance private val factorials = List(10) { it.factorial().intValueExact() } /** * HackerRank specific implementation that finds the sum of all numbers < [n] that are divisors * of the sum of the factorials of their digits. * * Increase this solution's efficiency by creating an array of upper constraint * size (plus 1) & looping once through all numbers then caching the result plus the * previously calculated sum, if it matches the necessary requirements. */ fun sumOfDigitFactorialsHR(n: Int): Int { var sum = 0 for (num in 10 until n) { val numSum = num.toString().sumOf { ch -> factorials[ch.digitToInt()] } if (numSum % num == 0) { sum += num } } return sum } /** * Project Euler specific implementation that finds the sum of all numbers that are factorions. * * The numbers cannot have more than 7 digits, as 9! * 8 returns only a 7-digit number. * * 9! * 7 returns 2_540_160, so the 1st digit of the 7-digit number cannot be greater than 2. */ fun sumOfDigitFactorialsPE(): Int { var sum = 0 for (num in 10 until 2_000_000) { val digits = num.toString().map { it.digitToInt() } var numSum = 0 for (digit in digits) { numSum += factorials[digit] // prevents further unnecessary calculation if (numSum > num) break } if (numSum == num) sum += numSum } return sum } }
0
Kotlin
0
0
62b33367e3d1e15f7ea872d151c3512f8c606ce7
2,342
project-euler-kotlin
MIT License
src/day18/Day18B.kt
HGilman
572,891,570
false
{"Kotlin": 109639, "C++": 5375, "Python": 400}
package day18 import day18.Cube.Companion.normals import readInput import java.util.Stack fun main() { val day = 18 val testInput = readInput("day$day/testInput") // check(part1B(testInput) == 64) // check(part2B(testInput) == 58) val input = readInput("day$day/input") // println(part1B(input)) println(part2B(input)) } fun part1B(input: List<String>): Int { val cubesOrigins = input.map { val (x, y, z) = it.split(',').map { it.toInt() } Point3D(x, y, z) }.toSet() var counter = 0 cubesOrigins.forEach { origin -> normals.forEach { n -> val checkPoint = origin + n if (!cubesOrigins.contains(checkPoint)) { counter++ } } } return counter } fun part2B(input: List<String>): Int { val cubesOrigins = input.map { val (x, y, z) = it.split(',').map { it.toInt() } Point3D(x + 2, y + 2, z + 2) }.toSet() val delta = 2 val maxX = cubesOrigins.maxOf { it.x } + delta val maxY = cubesOrigins.maxOf { it.y } + delta val maxZ = cubesOrigins.maxOf { it.z } + delta val field: MutableList<MutableList<MutableList<Int>>> = MutableList(maxZ) { z -> MutableList(maxY) { y -> MutableList(maxX) { x -> 0 } } } // fill map with 1, where are cubes stay cubesOrigins.forEach { o -> field[o.z][o.y][o.x] = 1 } val cubes = mutableListOf<Cube>() cubesOrigins.forEach { origin -> val cube = Cube(origin) normals.forEach { n -> val checkPoint = origin + n val isFreeFace = !cubesOrigins.contains(checkPoint) cube.faces[n] = isFreeFace } cubes.add(cube) } fun isPointOutOfBoundaries(p: Point3D): Boolean { return (p.x !in (0 until maxX)) || (p.y !in (0 until maxY)) || (p.z !in (0 until maxZ)) } fun isFreePoint(p: Point3D): Boolean { return field[p.z][p.y][p.x] == 0 } // point - for this point we check if there is the path in field from this point to outside of field (out of field's boundaries) fun dfsStackbased(point: Point3D, num: Int) { val stack = Stack<Point3D>() stack.add(point) var stackMaxDepth = stack.size while (!stack.isEmpty()) { val p = stack.pop() if (isPointOutOfBoundaries(p)) { continue } if (!isFreePoint(p)) { continue } // mark as visited field[p.z][p.y][p.x] = num normals.forEach { n -> stack.add(p + n) } if (stackMaxDepth < stack.size) { stackMaxDepth = stack.size } } } val checked = 2 // 1, 1, 1 - definitely is not part of cubes array, // so now all space except closed area should be filled with 2 dfsStackbased(Point3D(1, 1, 1), checked) // not only closed area points (air points) will be 0 var counter = 0 cubes.forEach { c -> normals.forEach { normal -> val checkPoint = c.origin + normal if (field[checkPoint.z][checkPoint.y][checkPoint.x] == checked) { counter++ } } } return counter }
0
Kotlin
0
1
d05a53f84cb74bbb6136f9baf3711af16004ed12
3,359
advent-of-code-2022
Apache License 2.0
src/Day02.kt
konclave
573,548,763
false
{"Kotlin": 21601}
fun main() { fun solve1(input: List<String>): Int { return input.fold(0) { acc, pair -> val (he, me) = pair.split(" ") val heInt = he.first().code val meInt = me.first().code val bonus = meInt - 87 acc + bonus + when (heInt - meInt) { -23 -> 3 -21, -24 -> 6 else -> 0 } } } fun solve2(input: List<String>): Int { return input.fold(0) { acc, pair -> val (he, me) = pair.split(" ") val heInt = he.first().code val meInt = me.first().code val bonus = (meInt - 88) * 3 acc + bonus + when (heInt - 64) { 1 -> { when (meInt - 87) { 1 -> 3 2 -> 1 else -> 2 } } 2 -> { when (meInt - 87) { 1 -> 1 2 -> 2 else -> 3 } } else -> { when (meInt - 87) { 1 -> 2 2 -> 3 else -> 1 } } } } } val input = readInput("Day02") println(solve1(input)) println(solve2(input)) }
0
Kotlin
0
0
337f8d60ed00007d3ace046eaed407df828dfc22
1,425
advent-of-code-2022
Apache License 2.0
src/day14/Day14.kt
daniilsjb
726,047,752
false
{"Kotlin": 66638, "Python": 1161}
package day14 import java.io.File fun main() { val data = parse("src/day14/Day14.txt") println("🎄 Day 14 🎄") println() println("[Part 1]") println("Answer: ${part1(data)}") println() println("[Part 2]") println("Answer: ${part2(data)}") } private fun parse(path: String): List<List<Char>> = File(path) .readLines() .map(String::toList) private fun part1(data: List<List<Char>>): Int { val h = data.size val w = data[0].size var counter = 0 for (col in 0..<w) { var top = 0 for (row in 0..<h) { when (data[row][col]) { 'O' -> counter += h - top++ '#' -> top = row + 1 } } } return counter } private fun part2(data: List<List<Char>>): Int { val h = data.size val w = data[0].size val cycles = mutableMapOf<String, Int>() val loads = mutableListOf<Int>() val grid = data.map { it.toMutableList() } for (i in 1..1_000_000_000) { // North for (col in 0..<w) { var dst = 0 for (row in 0..<h) { when (grid[row][col]) { '#' -> dst = row + 1 'O' -> { grid[row][col] = '.' grid[dst][col] = 'O' dst += 1 } } } } // West for (row in 0..<h) { var dst = 0 for (col in 0..<w) { when (grid[row][col]) { '#' -> dst = col + 1 'O' -> { grid[row][col] = '.' grid[row][dst] = 'O' dst += 1 } } } } // South for (col in w - 1 downTo 0) { var dst = h - 1 for (row in h - 1 downTo 0) { when (grid[row][col]) { '#' -> dst = row - 1 'O' -> { grid[row][col] = '.' grid[dst][col] = 'O' dst -= 1 } } } } // East for (row in h - 1 downTo 0) { var dst = w - 1 for (col in w - 1 downTo 0) { when (grid[row][col]) { '#' -> dst = col - 1 'O' -> { grid[row][col] = '.' grid[row][dst] = 'O' dst -= 1 } } } } val cycle = grid.flatten().toString() cycles[cycle]?.let { start -> val remainder = (1_000_000_000 - start) % (i - start) val loop = cycles.values.filter { it >= start } return loads[loop[remainder] - 1] } cycles[cycle] = i loads += grid.withIndex().sumOf { (y, row) -> row.count { it == 'O' } * (h - y) } } error("Could not detect a cycle.") }
0
Kotlin
0
0
46a837603e739b8646a1f2e7966543e552eb0e20
3,249
advent-of-code-2023
MIT License
src/Day09.kt
diego09310
576,378,549
false
{"Kotlin": 28768}
import kotlin.math.abs fun main() { data class Coordinates (var x: Int, var y: Int) { override fun toString(): String { return "$x $y" } } fun getDirection(or: Coordinates, dest: Coordinates): Coordinates? { val xDiff = dest.x - or.x val yDiff = dest.y - or.y return if (abs(xDiff) >= 2 || abs(yDiff) >= 2) { val x = if (xDiff >= 1) 1 else if (xDiff <= -1) -1 else 0 val y = if (yDiff >= 1) 1 else if (yDiff <= -1) -1 else 0 Coordinates(x, y) } else { null } } fun part1(input: List<String>): Int { val visited = HashSet<Coordinates>() val hPos = Coordinates(0, 0) val tPos = Coordinates(0, 0) for (l in input) { val s = l.split(' ')[1].toInt() for (i in 0 until s) { if (l[0] == 'U') { hPos.y++ } if (l[0] == 'R') { hPos.x++ } if (l[0] == 'D') { hPos.y-- } if (l[0] == 'L') { hPos.x-- } val dir = getDirection(tPos, hPos) if (dir != null) { tPos.x += dir.x tPos.y += dir.y } visited.add(tPos.copy()) } } return visited.size } fun part2(input: List<String>): Int { val visited = HashSet<Coordinates>() val hPos = Coordinates(0, 0) val tPos = Array(9) { Coordinates(0, 0) } for (l in input) { val s = l.split(' ')[1].toInt() for (i in 0 until s) { if (l[0] == 'U') { hPos.y++ } if (l[0] == 'R') { hPos.x++ } if (l[0] == 'D') { hPos.y-- } if (l[0] == 'L') { hPos.x-- } var prev = hPos for (t in tPos) { val dir = getDirection(t, prev) if (dir != null) { t.x += dir.x t.y += dir.y } prev = t } visited.add(tPos[8].copy()) } } return visited.size } // test if implementation meets criteria from the description, like: val testInput = readInput("../../9linput") check(part1(testInput) == 13) val input = readInput("../../9input") println(part1(input)) check(part2(testInput) == 1) val testInput2 = readInput("../../92linput") check(part2(testInput2) == 36) println(part2(input)) }
0
Kotlin
0
0
644fee9237c01754fc1a04fef949a76b057a03fc
2,849
aoc-2022-kotlin
Apache License 2.0
2020/11/week1/minhyungPark/algorithm/Leetcode1631.kt
Road-of-CODEr
270,008,701
false
{"Java": 199573, "C++": 42297, "JavaScript": 29489, "Kotlin": 28801, "Python": 20313, "HTML": 7981, "Shell": 7160}
/** * Leetcode 1631. Path With Minimum Effort * https://leetcode.com/contest/weekly-contest-212/problems/path-with-minimum-effort/ */ import kotlin.math.abs import kotlin.math.max class Leetcode1631 { companion object { val dx = intArrayOf(-1, 1, 0, 0) val dy = intArrayOf(0, 0, -1, 1) } fun minimumEffortPath(heights: Array<IntArray>): Int { val n = heights.size val m = heights[0].size val visit = Array(n) { IntArray(m) { Int.MAX_VALUE } } val pq = PriorityQueue<Triple<Int, Int, Int>>(compareBy { it.first }) pq.offer(Triple(0,0,0)) while (pq.isNotEmpty()) { val (height, x, y) = pq.poll() if (x == n-1 && y == m-1) { return height } for (i in dx.indices) { val nx = x + dx[i] val ny = y + dy[i] if (nx < 0 || ny < 0 || nx >= n || ny >= m) { continue } val newHeight = max(height, abs(heights[nx][ny] - heights[x][y])) if (newHeight >= visit[nx][ny]) { continue } visit[nx][ny] = newHeight pq.offer(Triple(newHeight, nx, ny)) } } return 0 } }
3
Java
11
36
1c603bc40359aeb674da9956129887e6f7c8c30a
1,310
stupid-week-2020
MIT License
src/medium/_1508RangeSumOfSortedSubarraySums.kt
ilinqh
390,190,883
false
{"Kotlin": 382147, "Java": 32712}
package medium class _1508RangeSumOfSortedSubarraySums { class Solution { private val MODULO = 1000000007 fun rangeSum(nums: IntArray, n: Int, left: Int, right: Int): Int { val prefixSums = IntArray(n + 1) { 0 } for (i in 0 until n) { prefixSums[i + 1] = prefixSums[i] + nums[i] } val prefixPrefixSums = IntArray(n + 1) for (i in 0 until n) { prefixPrefixSums[i + 1] = prefixPrefixSums[i] + prefixSums[i + 1] } return (getSum(prefixSums, prefixPrefixSums, n, right) - getSum(prefixSums, prefixPrefixSums, n, left - 1) ) % MODULO } private fun getSum(prefixSums: IntArray, prefixPrefixSums: IntArray, n: Int, k: Int): Int { val num = getKth(prefixSums, n, k) var sum = 0 var count = 0 for (i in 0 until n) { var j = 1 while (j <= n && prefixSums[j] - prefixSums[i] < num) { j += 1 } j -= 1 sum = (sum + prefixPrefixSums[j] - prefixPrefixSums[i] - prefixSums[i] * (j - i)) % MODULO count += j - i } sum = (sum + num * (k - count)) % MODULO return sum } private fun getKth(prefixSums: IntArray, n: Int, k: Int): Int { var low = 0 var high = prefixSums[n] while (low < high) { val middle = ((high - low) shr 1) + low val count = getCount(prefixSums, n, middle) if (count < k) { low = middle + 1 } else { high = middle } } return low } private fun getCount(prefixSums: IntArray, n: Int, x: Int): Int { var count = 0 var j = 1 for (i in 0 until n) { while (j <= n && prefixSums[j] - prefixSums[i] <= x) { j += 1 } j -= 1 count += j - i } return count } } }
0
Kotlin
0
0
8d2060888123915d2ef2ade293e5b12c66fb3a3f
2,214
AlgorithmsProject
Apache License 2.0
kotlin/src/main/kotlin/AoC_Day21.kt
sviams
115,921,582
false
null
import kotlinx.coroutines.experimental.async import kotlinx.coroutines.experimental.runBlocking object AoC_Day21 { val startState = Matrix(listOf( listOf(0,1,0), listOf(0,0,1), listOf(1,1,1) )) data class Matrix(val data: List<List<Int>>) { val size : Int by lazy { data.size } fun rotate() = Matrix((0 until data.size).map { row -> (0 until data.size).map { col -> data[col][row] } }.reversed()) fun flip() = Matrix((0 until data.size).map { row -> data[row].reversed() }) val countActive : Int by lazy { data.fold(0) {acc, row -> acc + row.sum() } } fun matches(other: List<Matrix>) = this.countActive == other.first().countActive && other.contains(this) fun divideToChunksAndTransform(rules: List<Rule>) : List<List<Matrix>> { val chunkSize = if (size % 2 == 0) 2 else 3 val noChunks = size / chunkSize val deferred = (0 until noChunks).map { chunkRow -> val rowOffset = chunkRow * chunkSize async { (0 until noChunks).map { chunkCol -> val colOffset = chunkCol * chunkSize val before = Matrix(data.subList(rowOffset, rowOffset + chunkSize).map { it.subList(colOffset, colOffset + chunkSize) }) rules.single { rule -> before.matches(rule.input) }.output } } } return runBlocking { deferred.map { it.await() } } } fun generatePossible() : List<Matrix> { val rotOne = rotate() val rotTwo = rotOne.rotate() val rotThree = rotTwo.rotate() return listOf(this, this.flip(), rotOne, rotOne.flip(), rotTwo, rotTwo.flip(), rotThree, rotThree.flip()).distinct() } fun transform(rules: List<Rule>) : Matrix = joinChunks(this.divideToChunksAndTransform(rules)) } data class Rule(val input: List<Matrix>, val output: Matrix) fun stringToMatrix(input: String) : Matrix { val inputSplit = input.split("/") val mat : List<List<Int>> = inputSplit.map { row -> row.toCharArray().map { c -> if (c == '#') 1 else 0 } } return Matrix(mat) } fun parseRules(input: List<String>) : List<Rule> = input.map { line -> val lineSplit = line.split(" => ") Rule(stringToMatrix(lineSplit[0]).generatePossible(), stringToMatrix(lineSplit[1])) } fun joinARowFromChunks(chunks: List<Matrix>, rowIndex: Int) : List<Int> = chunks.map { it.data[rowIndex] }.fold(emptyList()) { acc, piece -> acc + piece} fun joinChunksInARow(chunks: List<Matrix>) : List<List<Int>> = (0 until chunks.first().size).map { index -> joinARowFromChunks(chunks, index) } fun joinChunks(chunks: List<List<Matrix>>) : Matrix = Matrix(chunks.fold(emptyList()) { rowAcc, rowChunks -> rowAcc + joinChunksInARow(rowChunks) }) fun solve(input: List<String>, iterations: Int) : Int { val rules = parseRules(input) return generateSequence(startState) { it.transform(rules) }.take(iterations + 1).last().countActive } }
0
Kotlin
0
0
19a665bb469279b1e7138032a183937993021e36
3,258
aoc17
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/RemoveStones.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode /** * 947. Most Stones Removed with Same Row or Column * @see <a href="https://leetcode.com/problems/most-stones-removed-with-same-row-or-column/">Source</a> */ fun interface RemoveStones { operator fun invoke(stones: Array<IntArray>): Int } class RemoveStonesMap : RemoveStones { private val f: MutableMap<Int, Int> = HashMap() private var islands = 0 override operator fun invoke(stones: Array<IntArray>): Int { for (i in stones.indices) union(stones[i][0], stones[i][1].inv()) return stones.size - islands } fun find(x: Int): Int { if (f.putIfAbsent(x, x) == null) { islands++ } if (x != f[x]) { f[x]?.let { f[x] = find(it) } } return f.getOrDefault(x, 0) } private fun union(x: Int, y: Int) { var x0 = x var y0 = y x0 = find(x0) y0 = find(y0) if (x0 != y0) { f[x0] = y0 islands-- } } } class RemoveStonesDFS : RemoveStones { override operator fun invoke(stones: Array<IntArray>): Int { val graph: MutableMap<Int, MutableList<Int>> = HashMap() for (stone in stones) { graph.computeIfAbsent(stone[0]) { ArrayList() }.add(stone[1].inv()) graph.computeIfAbsent(stone[1].inv()) { ArrayList() }.add(stone.first()) } var numOfComponent = 0 val visited: MutableSet<Int> = HashSet() for (stone in stones) { for (i in 0..1) { val s = if (i == 0) stone[0] else stone[1].inv() if (!visited.contains(s)) { numOfComponent++ dfs(s, graph, visited) } } } return stones.size - numOfComponent } private fun dfs(stone: Int, graph: Map<Int, List<Int>>, visited: MutableSet<Int>) { if (visited.add(stone)) { for (next in graph.getOrDefault(stone, emptyList())) { dfs(next, graph, visited) } } } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,720
kotlab
Apache License 2.0
kotlin/0934-shortest-bridge.kt
neetcode-gh
331,360,188
false
{"JavaScript": 473974, "Kotlin": 418778, "Java": 372274, "C++": 353616, "C": 254169, "Python": 207536, "C#": 188620, "Rust": 155910, "TypeScript": 144641, "Go": 131749, "Swift": 111061, "Ruby": 44099, "Scala": 26287, "Dart": 9750}
class Solution { fun shortestBridge(grid: Array<IntArray>): Int { // q = [ (row,column,level) ] val queue: Queue<Triple<Int, Int, Int>> = LinkedList() val rowColumnDirections = arrayOf( intArrayOf(0, 1), intArrayOf(0, -1), intArrayOf(1, 0), intArrayOf(-1, 0) ) fun dfs(startRow: Int, startColumn: Int) { if ( startRow !in grid.indices || startColumn !in grid[startRow].indices || grid[startRow][startColumn] == 0 || grid[startRow][startColumn] == VISITED_CELL ) return grid[startRow][startColumn] = VISITED_CELL queue.add(Triple(startRow, startColumn, 0)) for ((rowDir, columDir) in rowColumnDirections) { dfs(startRow + rowDir, startColumn + columDir) } } // find one island and mark the cells with -1 outer@ for (row in grid.indices) { inner@ for (column in grid[row].indices) { if (grid[row][column] != 1) continue dfs(row, column) break@outer } } while (queue.isNotEmpty()) { val (row, column, level) = queue.remove() for ((rowDir, colDir) in rowColumnDirections) { if (row + rowDir !in grid.indices) continue if (column + colDir !in grid[row + rowDir].indices) continue if (grid[row + rowDir][column + colDir] == VISITED_CELL) continue if (grid[row + rowDir][column + colDir] == 1) return level queue.add(Triple(row + rowDir, column + colDir, level + 1)) grid[row + rowDir][column + colDir] = VISITED_CELL } } throw IllegalStateException("Two islands where expected to be in the grid.") } companion object { private const val VISITED_CELL = -1 } }
337
JavaScript
2,004
4,367
0cf38f0d05cd76f9e96f08da22e063353af86224
1,981
leetcode
MIT License
src/Day20.kt
uekemp
575,483,293
false
{"Kotlin": 69253}
import kotlin.system.measureTimeMillis typealias EncryptedList = ArrayDeque<ListItem> // Using ArrayList instead of ArrayDeque consumes about the same time //typealias EncryptedList = ArrayList<ListItem> // Using LinkedList instead of ArrayDeque is roughly 4 times slower for part2! // typealias EncryptedList = LinkedList<ListItem> data class ListItem(val value: Long, val position: Int) { override fun toString(): String { return value.toString() } } fun EncryptedList.moveItemAt(index: Int) { val item = this[index] if (item.value != 0L) { val insertAt = index + item.value removeAt(index) if (insertAt > 0) { add((insertAt % size).toInt(), item) } else if (insertAt < 0) { add((size + (insertAt % size)).toInt(), item) } else { add(size, item) } } } fun EncryptedList.computeResult(): Long { val indexOfZero = indexOfFirst { item -> item.value == 0L } val i1 = (indexOfZero + 1000) % size val i2 = (indexOfZero + 2000) % size val i3 = (indexOfZero + 3000) % size val sum = this[i1].value + this[i2].value + this[i3].value println("${this[i1]} + ${this[i2]} + ${this[i3]} = $sum") return sum } fun parseEncryptedData(input: List<String>, decryptionKey: Int = 1): EncryptedList { return EncryptedList(input.mapIndexed { index, line -> ListItem(line.toLong() * decryptionKey, index) }.toList()) } fun main() { fun part1(input: List<String>): Long { val list = parseEncryptedData(input) for (index in 0 until list.size) { list.moveItemAt(list.indexOfFirst { item -> item.position == index }) } return list.computeResult() } fun part2(input: List<String>): Long { val list = parseEncryptedData(input, 811589153) repeat(10) { for (index in 0 until list.size) { list.moveItemAt(list.indexOfFirst { item -> item.position == index }) } } return list.computeResult() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day20_test") check(part1(testInput) == 3L) val input = readInput("Day20") check(part1(input) == 9945L) val d = measureTimeMillis { check(part2(input) == 3338877775442L) } println("\nDuration for part2=${d}ms") }
0
Kotlin
0
0
bc32522d49516f561fb8484c8958107c50819f49
2,405
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/dp/DreamDollars.kt
yx-z
106,589,674
false
null
package dp // given a util.set of bills with the following values val bills = intArrayOf(365, 91, 52, 28, 13, 7, 4, 1) // a greedy algorithm to make up target money is always taking the largest bill that does not exceed // the remaining amound. ex. $122 = $91 + $28 + $1 + $1 + $1 -> 5 fun billsGreedy(k: Int): Int { var rem = k var count = 0 bills.forEach { while (rem >= it) { rem -= it count++ } } return count } // 1. describe a recursive algorithm that computes the minimum number of bills needed to make up $k fun billsRec(k: Int): Int { if (k == 0) { return 0 } return bills.filter { k >= it }.map { billsRec(k - it) }.min()!! + 1 } // 2. a DP algorithm of the above fun billsDP(k: Int): Int { // dp[i] = minimum number of bills to make up i // dp[i] = 0, if i == 0 // dp[i] = util.min(dp[i - bill]) + 1 for bill : i - bill >= 0 val dp = IntArray(k + 1) for (i in 1..k) { dp[i] = bills.filter { i - it >= 0 }.map { dp[i - it] }.min()!! + 1 } return dp[k] } fun main(args: Array<String>) { // prettyPrintln(billsGreedy(122)) // prettyPrintln(billsRec(21)) // prettyPrintln(billsDP(122)) // 3. give an example that such algorithm fails to be the option with least number of bills used var amount = 1 while (billsGreedy(amount) == billsDP(amount)) { amount++ } println(amount) }
0
Kotlin
0
1
15494d3dba5e5aa825ffa760107d60c297fb5206
1,325
AlgoKt
MIT License
src/Day08.kt
max-zhilin
573,066,300
false
{"Kotlin": 114003}
import java.util.* fun List<String>.isVisible(row: Int, col: Int): Boolean { val rowSize = size val colSize = this[0].length if (row == 0 || row == rowSize - 1 || col == 0 || col == colSize - 1) return true val tree = this[row][col] var visible = false var lineVisible = true for (i in 0 until row) if (this[i][col] >= tree) lineVisible = false visible = visible || lineVisible lineVisible = true for (i in row + 1 until rowSize) if (this[i][col] >= tree) lineVisible = false visible = visible || lineVisible lineVisible = true for (i in 0 until col) if (this[row][i] >= tree) lineVisible = false visible = visible || lineVisible lineVisible = true for (i in col + 1 until colSize) if (this[row][i] >= tree) lineVisible = false visible = visible || lineVisible // if (visible) println("$row $col") return visible } fun List<String>.countVisible(row: Int, col: Int): Int { val maxRow = size - 1 val maxCol = this[0].length - 1 if (row == 0 || row == maxRow || col == 0 || col == maxCol) return 0 val tree = this[row][col] var res = 1 var i = row - 1 while (true) { if (this[i][col] >= tree || i == 0) break i-- } res *= row - i i = row + 1 while (true) { if (this[i][col] >= tree || i == maxRow) break i++ } res *= row - i i = col - 1 while (true) { if (this[row][i] >= tree || i == 0) break i-- } res *= col - i i = col + 1 while (true) { if (this[row][i] >= tree || i == maxCol) break i++ } res *= col - i return res } fun main() { fun part1(input: List<String>): Int { var sum = 0 for (row in input.indices) { for (col in 0 until input[0].length) { if (input.isVisible(row, col)) sum++ } } return sum } fun part2(input: List<String>): Int { var max = 0 for (row in input.indices) { for (col in 0 until input[0].length) { max = maxOf(max, input.countVisible(row, col)) } } return max } // test if implementation meets criteria from the description, like: val testInput = readInput("Day08_test") // println(part1(testInput)) check(part1(testInput) == 21) // println(part2(testInput)) check(part2(testInput) == 8) val input = readInput("Day08") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d9dd7a33b404dc0d43576dfddbc9d066036f7326
2,522
AoC-2022
Apache License 2.0
src/interview_question/_1714SmallestKLCCI.kt
ilinqh
390,190,883
false
{"Kotlin": 382147, "Java": 32712}
package interview_question import java.util.* class _1714SmallestKLCCI { class Solution { fun smallestK(arr: IntArray, k: Int): IntArray { if (k == 0) { return IntArray(0) } val maxHeap = PriorityQueue<Int>(k) { a, b -> b - a } for (i in arr.indices) { if (maxHeap.size == k) { val max = maxHeap.peek() if (arr[i] < max) { maxHeap.poll() maxHeap.add(arr[i]) } } else { maxHeap.add(arr[i]) } } return maxHeap.toIntArray() } } class BestSolution { fun smallestK(arr: IntArray, k: Int): IntArray { randomizedSelected(arr, 0, arr.size - 1, k) val vec = IntArray(k) for (i in 0 until k) { vec[i] = arr[i] } return vec } private fun randomizedSelected(arr: IntArray, left: Int, right: Int, k: Int) { if (left > right) { return } val position = randomizedPartition(arr, left, right) val num = position - left + 1 if (k == num) { return } else if (k < num) { randomizedSelected(arr, left, position - 1, k) } else { randomizedSelected(arr, position + 1, right, k - num) } } private fun randomizedPartition(nums: IntArray, left: Int, right: Int): Int { val i = Random().nextInt(right - left + 1) + left swap(nums, right, i) return partition(nums, left, right) } private fun partition(nums: IntArray, left: Int, right: Int): Int { val pivot = nums[right] var i = left - 1 var j = left while (j <= right - 1) { if (nums[j] <= pivot) { i += 1 swap(nums, i, j) } j++ } swap(nums, i + 1, right) return i + 1 } private fun swap(nums: IntArray, i: Int, j: Int) { val temp = nums[i] nums[i] = nums[j] nums[j] = temp } } }
0
Kotlin
0
0
8d2060888123915d2ef2ade293e5b12c66fb3a3f
2,366
AlgorithmsProject
Apache License 2.0
src/main/kotlin/day13.kt
tianyu
574,561,581
false
{"Kotlin": 49942}
import Packet.Mono import Packet.Multi import assertk.assertThat import assertk.assertions.isEqualTo import assertk.assertions.isGreaterThan import assertk.assertions.isLessThan private fun main() { tests { "Parse a packet" { assertThat(Packet("[1,1,3,1,1]")).isEqualTo( Multi(Mono(1), Mono(1), Mono(3), Mono(1), Mono(1)) ) assertThat(Packet("[[1],[2,3,4]]")).isEqualTo( Multi( Multi(Mono(1)), Multi(Mono(2), Mono(3), Mono(4)) ) ) assertThat(Packet("[[],1000]")).isEqualTo( Multi( Multi(), Mono(1000) ) ) } "Comparing packets" { assertThat(Packet("[1,1,3,1,1]")).isLessThan(Packet("[1,1,5,1,1]")) assertThat(Packet("[[1],[2,3,4]]")).isLessThan(Packet("[[1],4]")) assertThat(Packet("[9]")).isGreaterThan(Packet("[[8,7,6]]")) assertThat(Packet("[[4,4],4,4]")).isLessThan(Packet("[[4,4],4,4,4]")) assertThat(Packet("[[[]]]")).isGreaterThan(Packet("[[]]")) assertThat(Packet("[1,[2,[3,[4,[5,6,7]]]],8,9]")).isGreaterThan(Packet("[1,[2,[3,[4,[5,6,0]]]],8,9]")) } } part1("The sum of the indicies of all the valid packet pairs is:") { packets().chunked(2).mapIndexedNotNull { index, (left, right) -> if (left <= right) index + 1 else null }.sum() } part2("The decoder key for the distress signal is:") { val dividers = listOf(Packet("[[2]]"), Packet("[[6]]")) val packets = buildList { addAll(dividers) addAll(packets()) sort() } dividers.map { packets.indexOf(it) + 1 }.fold(1, Int::times) } } private fun Packet(text: String) = text.reader().cursor().readPacket() private sealed interface Packet: Comparable<Packet> { data class Mono(val value: Int): Packet { override fun compareTo(other: Packet): Int = when (other) { is Mono -> value.compareTo(other.value) is Multi -> Multi(this).compareTo(other) } } data class Multi(val values: List<Packet>): Packet { constructor(vararg values: Packet): this(values.toList()) override fun compareTo(other: Packet): Int = when (other) { is Mono -> compareTo(Multi(other)) is Multi -> { repeat(minOf(values.size, other.values.size)) { val result = values[it].compareTo(other.values[it]) if (result != 0) return result } values.size.compareTo(other.values.size) } } } } private fun packets() = sequence { readInput("day13.txt").use { do { yield(it.cursor().readPacket()) yield(it.cursor().readPacket()) } while (it.read() == '\n'.code) } } private fun Cursor.readPacket(): Packet = when (codepoint) { in '0'.code..'9'.code -> readMonoPacket() '['.code -> readMultiPacket() else -> throw AssertionError("Unexpected start of packet: ${codepoint.toChar()}") } private fun Cursor.readMonoPacket(): Mono { val value = buildString { while (codepoint in '0'.code .. '9'.code) { appendCodePoint(codepoint) advance() } } return Mono(value.toInt()) } private fun Cursor.readMultiPacket(): Multi { val values = buildList { while (codepoint != ']'.code && advance() != ']'.code) { add(readPacket()) } } advance() return Multi(values) }
0
Kotlin
0
0
6144cc0ccf1a51ba2e28c9f38ae4e6dd4c0dc1ea
3,277
AdventOfCode2022
MIT License
src/main/kotlin/complexity/Complexity.kt
waploaj
520,509,366
false
{"Kotlin": 10629}
package complexity // ------------------------------ Time complexity ---------------------------------- //Big O notation for the different level of scalability in two dimension //-- Execution time //-- Memory Usage //Time complexity - is the time it take for algorithm to run compare with data size. //Constant Time - is the same running time regardless of an input size. fun checkFirst(name: List<String>){ if(name.firstOrNull()!=null){ println(name.first()) }else println("No name") } //Liner time complexity - As the input increase the time to execute also increase fun printName(names:List<String>){ for (element in names){ println(element) } } //Quadratic Time Complexity - refer to algorithm that takes time proportional to the square input size. //Big O notation for quadratic time is = O(n^2) fun multiplicationBoard(n:Int){ for (number in 1 ..n){ print("|") for (otherNumber in 1..n){ println("$number * $otherNumber = ${number * otherNumber}|") } } } //Logarithmic Time Complexity - fun linearContains(value:Int, numbers:List<Int>):Boolean { for(element in numbers) { return value == element } return false } //This is not efficient lets sort the values of number and divide in half //As input increase the time takes to execute the algorithm increase at slowly rate. //Big O notation for logarithm time complexity is Q(log n) fun pseudoBinaryContains(value: Int, numbers: List<Int>):Boolean { if (numbers.isEmpty()) return false numbers.sorted() val middleIndex = numbers.size/2 if (value <= numbers[middleIndex]){ for (element in 0 .. middleIndex){ return (numbers[element] == value) } }else{ for (elements in middleIndex until numbers.size){ return numbers[elements] == value } } return false } //Quasilinear Time Complexity - perform worse than liner time but dramatically better than quadratic time. //Other complexity time (polynomial , exponential and factorial time). //NOTE: for small data sets, time complexity may not be an accurate measure of speed. //Comparing Time complexity. //suppose you find sums of numbers from 1 to n fun sumFromOne(n:Int):Int{ var result = 0 for (i in 1..n){ result += i } return result } //This sum can be rewritten also with reduce function //The time complexity of reduce function it also Q(n) fun sumFromOnes(n:Int):Int{ return (1..n).reduce { element, sum -> sum + element } } //We can use the famous mathematician <NAME> //That use the time complexity constant Q(1) fun sumFrom1(n:Int):Int{ return n * (n + 1)/2 } //--------------------------------------- Space complexity --------------------------------- //space complexity - is measure of the resources for algorithm required to manipulate input data. //Let's create the copy of sorted list and print it. //The space complexity is Q(n) fun printedSorted(number: List<Int>){ val sorted = number.sorted() for (element in sorted){ println(element) } } /* NOTE: key Point -Big O notation it used to represent the general form of space and time complexity. -Time and space are high-level measures of scalability, they don't measure the actual speed of algorithm itself -For small dataset time complexity is usually irrelevant, a quasilinear algorithm can be slower than liner algo * */
0
Kotlin
0
1
6a44d6089233d316461be07b504a9c17a1de3220
3,451
Masomo
Apache License 2.0
src/problems/day5/part1/part1.kt
klnusbaum
733,782,662
false
{"Kotlin": 43060}
package problems.day5.part1 import java.io.File import java.util.* //private const val testFile = "input/day5/test.txt" private const val inputFile = "input/day5/input.txt" fun main() { val lowestLocationNum = File(inputFile).bufferedReader().useLines { lowestLocationNumber(it) } println("Lowest Location Num: $lowestLocationNum") } private fun lowestLocationNumber(lines: Sequence<String>): Long { val almanac = lines.fold(AlmanacBuilder()) { builder, line -> builder.nextLine(line) }.build() return almanac.seeds.mapNotNull { almanac.seedLocation(it) }.min() } private class Almanac(val seeds: List<Long>, val maps: Map<String, OverrideMap>) { fun seedLocation(seed: Long): Long? { val soil = maps["seed-to-soil"]?.get(seed) ?: return null val fertilizer = maps["soil-to-fertilizer"]?.get(soil) ?: return null val water = maps["fertilizer-to-water"]?.get(fertilizer) ?: return null val light = maps["water-to-light"]?.get(water) ?: return null val temperature = maps["light-to-temperature"]?.get(light) ?: return null val humidity = maps["temperature-to-humidity"]?.get(temperature) ?: return null val location = maps["humidity-to-location"]?.get(humidity) ?: return null return location } } private class AlmanacBuilder { private var state = State.SEEDS private var currentMapName = "" private var currentMap = TreeMap<Long, Override>() private val maps = mutableMapOf<String, OverrideMap>() private val seeds = mutableListOf<Long>() fun nextLine(line: String): AlmanacBuilder { when (state) { State.SEEDS -> { seeds.addAll(line.toSeeds()) state = State.SEEDS_BLANK } State.SEEDS_BLANK -> state = State.HEADER State.HEADER -> { currentMapName = line.substringBefore(" ") currentMap = TreeMap<Long, Override>() state = State.MAP } State.MAP -> { if (line != "") { addOverride(line) } else { recordMap() state = State.HEADER } } } return this } fun addOverride(line: String) { val overrides = line.split(" ").map { it.toLong() } val srcStart = overrides[1] val srcEnd = overrides[1] + overrides[2] - 1 val dstStart = overrides[0] currentMap[srcStart] = Override(srcStart, srcEnd, dstStart) } fun recordMap() { maps[currentMapName] = OverrideMap(currentMap) } fun build(): Almanac { if (state == State.MAP) { recordMap() } return Almanac(seeds, maps) } private enum class State { SEEDS, SEEDS_BLANK, HEADER, MAP, } } private fun String.toSeeds() = this.substringAfter(":").trim().split(" ").map { it.toLong() } private class OverrideMap(val overrides: TreeMap<Long, Override>) { operator fun get(key: Long): Long { val possibleOverride = overrides.headMap(key, true).lastEntry()?.value ?: return key if (key <= possibleOverride.srcEnd) { return possibleOverride.dstStart + (key - possibleOverride.srcStart) } return key } } private data class Override(val srcStart: Long, val srcEnd: Long, val dstStart: Long)
0
Kotlin
0
0
d30db2441acfc5b12b52b4d56f6dee9247a6f3ed
3,439
aoc2023
MIT License
src/org/aoc2021/Day24.kt
jsgroth
439,763,933
false
{"Kotlin": 86732}
package org.aoc2021 import java.nio.file.Files import java.nio.file.Path private fun <K, V> Map<K, V>.replaceKeyValue(k: K, v: V): Map<K, V> { return this.entries.associate { (thisKey, thisValue) -> if (thisKey == k) (k to v) else (thisKey to thisValue) } } object Day24 { data class Instruction(val operator: String, val a: String, val b: String? = null) private fun solve(lines: List<String>, findMax: Boolean): String { val program = parseProgram(lines) val expressions = generateExpressions(program) expressions.find { (_, variables) -> variables["z"] == LiteralValue(0) }?.let { (conditions, _) -> if (conditions.any { !it.value }) { throw IllegalStateException("unexpected condition: $conditions") } val result = Array(14) { 0 } conditions.forEach { condition -> val compare = if (condition.compare.a is Input) { Compare(Add(condition.compare.a, LiteralValue(0)), condition.compare.b) } else { condition.compare } if (compare.a !is Add || compare.a.a !is Input || compare.a.b !is LiteralValue || compare.b !is Input) { throw IllegalStateException("unexpected compare: $compare") } if (compare.a.b.value < 0) { result[compare.a.a.index] = if (findMax) 9 else (1 - compare.a.b.value) result[compare.b.index] = result[compare.a.a.index] + compare.a.b.value } else { result[compare.b.index] = if (findMax) 9 else (1 + compare.a.b.value) result[compare.a.a.index] = result[compare.b.index] - compare.a.b.value } } return result.map(Int::digitToChar).joinToString(separator = "") } throw IllegalArgumentException("no solution found") } sealed interface Expression { fun simplify(): Expression } data class Input(val index: Int) : Expression { override fun simplify() = this override fun toString() = "input$index" } data class LiteralValue(val value: Int) : Expression { override fun simplify() = this override fun toString() = value.toString() } data class Add(val a: Expression, val b: Expression) : Expression { override fun simplify(): Expression { return if (a is LiteralValue && b is LiteralValue) { LiteralValue(a.value + b.value) } else if (a == LiteralValue(0)) { b } else if (b == LiteralValue(0)) { a } else if (a is Add && a.b is LiteralValue && b is LiteralValue) { Add(a.a, LiteralValue(a.b.value + b.value)).simplify() } else { this } } override fun toString() = "($a + $b)" } data class Multiply(val a: Expression, val b: Expression) : Expression { override fun simplify(): Expression { return if (a is LiteralValue && b is LiteralValue) { LiteralValue(a.value * b.value) } else if (a == LiteralValue(0) || b == LiteralValue(0)) { LiteralValue(0) } else if (a == LiteralValue(1)) { b } else if (b == LiteralValue(1)) { a } else if (a is Multiply && a.b is LiteralValue && b is LiteralValue) { Multiply(a.a, LiteralValue(a.b.value * b.value)).simplify() } else { this } } override fun toString() = "($a * $b)" } data class Divide(val a: Expression, val b: Expression) : Expression { override fun simplify(): Expression { return if (a is LiteralValue && b is LiteralValue) { LiteralValue(a.value / b.value) } else if (a == LiteralValue(0)) { LiteralValue(0) } else if (b == LiteralValue(1)) { a } else if (a is Multiply && a.b is LiteralValue && b is LiteralValue && (a.b.value % b.value == 0)) { Multiply(a.a, LiteralValue(a.b.value / b.value)).simplify() } else if (a is Add && a.a is Input && a.b is LiteralValue && b is LiteralValue && a.b.value < b.value - 9) { LiteralValue(0) } else if (a is Add && a.b is Add && a.b.a is Input && a.b.b is LiteralValue && b is LiteralValue && a.b.b.value >= 0 && a.b.b.value < b.value - 9) { Divide(a.a, b).simplify() } else { this } } override fun toString() = "($a / $b)" } data class Modulo(val a: Expression, val b: Expression): Expression { override fun simplify(): Expression { return if (a is LiteralValue && b is LiteralValue) { LiteralValue(a.value % b.value) } else if (a == LiteralValue(0)) { LiteralValue(0) } else if (a is Add && b is LiteralValue) { Add(Modulo(a.a, b).simplify(), Modulo(a.b, b).simplify()).simplify() } else if (a is Multiply && a.b is LiteralValue && b is LiteralValue && (a.b.value % b.value == 0)) { LiteralValue(0) } else if (a is Input && b is LiteralValue && b.value > 9) { a } else { this } } override fun toString() = "($a % $b)" } data class Compare(val a: Expression, val b: Expression, val invert: Boolean = false): Expression { override fun simplify(): Expression { return if (a is LiteralValue && b is LiteralValue) { if (invert) { LiteralValue(if (a.value == b.value) 0 else 1) } else { LiteralValue(if (a.value == b.value) 1 else 0) } } else if (a is Compare && b == LiteralValue(0)) { Compare(a.a, a.b, invert = true).simplify() } else if (isConditionImpossible(a, b)) { LiteralValue(if (invert) 1 else 0) } else { this } } override fun toString() = if (!invert) { "($a == $b ? 1 : 0)" } else { "($a == $b ? 0 : 1)" } } private fun isConditionImpossible(a: Expression, b: Expression): Boolean { if (b !is Input) { return false } if (a is LiteralValue && (a.value < 1 || a.value > 9)) { return true } if (a is Add && a.a is Input && a.b is LiteralValue && a.b.value >= 9) { return true } if (a is Add && a.a is Modulo && a.b is LiteralValue && a.b.value > 9) { return true } return false } data class Condition(val compare: Compare, val value: Boolean) private fun generateExpressions( program: List<Instruction>, initialState: Map<String, Expression> = listOf("w", "x", "y", "z").associateWith { LiteralValue(0) }, i: Int = 0, initialInputIndex: Int = 0, conditions: List<Condition> = listOf(), ): List<Pair<List<Condition>, Map<String, Expression>>> { val variables = initialState.toMutableMap() var inputIndex = initialInputIndex for (j in i until program.size) { val instruction = program[j] when (instruction.operator) { "inp" -> { variables[instruction.a] = Input(inputIndex) inputIndex++ } "add" -> { val aValue = variables[instruction.a]!! val bValue = getExpressionValueOf(instruction.b!!, variables) variables[instruction.a] = Add(aValue, bValue).simplify() } "mul" -> { val aValue = variables[instruction.a]!! val bValue = getExpressionValueOf(instruction.b!!, variables) variables[instruction.a] = Multiply(aValue, bValue).simplify() } "div" -> { val aValue = variables[instruction.a]!! val bValue = getExpressionValueOf(instruction.b!!, variables) variables[instruction.a] = Divide(aValue, bValue).simplify() } "mod" -> { val aValue = variables[instruction.a]!! val bValue = getExpressionValueOf(instruction.b!!, variables) variables[instruction.a] = Modulo(aValue, bValue).simplify() } "eql" -> { val aValue = variables[instruction.a]!! val bValue = getExpressionValueOf(instruction.b!!, variables) val compare = Compare(aValue, bValue).simplify() if (compare is Compare) { val oneBranch = variables.replaceKeyValue(instruction.a, LiteralValue(1)) val zeroBranch = variables.replaceKeyValue(instruction.a, LiteralValue(0)) return generateExpressions(program, oneBranch.toMap(), j + 1, inputIndex, conditions.plus(Condition(compare, true))) .plus(generateExpressions(program, zeroBranch.toMap(), j + 1, inputIndex, conditions.plus(Condition(compare, false)))) } variables[instruction.a] = compare } } } return listOf(conditions to variables.toMap()) } private fun getExpressionValueOf(value: String, variables: Map<String, Expression>): Expression { return variables[value] ?: LiteralValue(value.toInt()) } private fun parseProgram(lines: List<String>): List<Instruction> { return lines.map { line -> val split = line.split(" ") if (split[0] == "inp") { Instruction(split[0], split[1]) } else { Instruction(split[0], split[1], split[2]) } } } @JvmStatic fun main(args: Array<String>) { val lines = Files.readAllLines(Path.of("input24.txt"), Charsets.UTF_8) val solution1 = solve(lines, true) println(solution1) val solution2 = solve(lines, false) println(solution2) } }
0
Kotlin
0
0
ba81fadf2a8106fae3e16ed825cc25bbb7a95409
10,550
advent-of-code-2021
The Unlicense
src/Day05.kt
mpythonite
572,671,910
false
{"Kotlin": 29542}
fun main() { fun part1(input: List<String>): String { var stacks = mutableListOf<ArrayDeque<Char>>() val pattern = "^[^0-9]+([0-9]+)[^0-9]+([0-9]+)[^0-9]+([0-9]+)\$".toRegex() input.forEach{ var index = 0 if (it.isNotBlank() && it.indexOf('[') >= 0) { while(index * 4 < it.length) { val current = it[index * 4 + 1] if (current != ' ') { while (stacks.size <= index) stacks.add(ArrayDeque()) stacks[index].addLast(current) } index++ } } else if (it.startsWith("move")) { val match = pattern.find(it)!! val (amountStr, from, to) = match.destructured val amount = amountStr.toInt()-1 for(i in 0..amount) { stacks[to.toInt()-1].addFirst(stacks[from.toInt()-1].removeFirst()) } } } return stacks.fold("") { result, element -> result + element.first()} } fun part2(input: List<String>): String { var stacks = mutableListOf<ArrayDeque<Char>>() val pattern = "^[^0-9]+([0-9]+)[^0-9]+([0-9]+)[^0-9]+([0-9]+)\$".toRegex() input.forEach{ var index = 0 if (it.isNotBlank() && it.indexOf('[') >= 0) { while(index * 4 < it.length) { val current = it[index * 4 + 1] if (current != ' ') { while (stacks.size <= index) stacks.add(ArrayDeque()) stacks[index].addLast(current) } index++ } } else if (it.startsWith("move")) { val match = pattern.find(it)!! val (amountStr, from, to) = match.destructured val amount = amountStr.toInt()-1 val craneStack = ArrayDeque<Char>() for(i in 0..amount) { craneStack.addFirst(stacks[from.toInt()-1].removeFirst()) } for (i in 0..amount) stacks[to.toInt()-1].addFirst(craneStack.removeFirst()) } } return stacks.fold("") { result, element -> result + element.first()} } // test if implementation meets criteria from the description, like: val testInput = readInput("Day05_test") check(part1(testInput) == "CMZ") // check(part2(testInput) == 1) val input = readInput("Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
cac94823f41f3db4b71deb1413239f6c8878c6e4
2,656
advent-of-code-2022
Apache License 2.0
src/day01/Day01.kt
emartynov
572,129,354
false
{"Kotlin": 11347}
package day01 import readInput fun main() { fun part1(input: List<String>): Int { return input.split { string -> string.isEmpty() } .map { list -> list.sumOf { string -> string.toInt() } }.max() } fun part2(input: List<String>): Int { return input.split { string -> string.isEmpty() } .map { list -> list.sumOf { string -> string.toInt() } }.sortedDescending() .take(3) .sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("day01/Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput("day01/Day01") println(part1(input)) println(part2(input)) } fun <T : Any> List<T>.split(isMarker: (T) -> Boolean): List<List<T>> { val result = mutableListOf<List<T>>() var previousIndex = 0 forEachIndexed { index, value -> if (isMarker(value)) { result.add(subList(previousIndex, index)) previousIndex = index + 1 } else if (index == size -1) { result.add(subList(previousIndex, size)) } } return result }
0
Kotlin
0
1
8f3598cf29948fbf55feda585f613591c1ea4b42
1,240
advent-of-code-2022
Apache License 2.0
src/main/kotlin/Day07.kt
nmx
572,850,616
false
{"Kotlin": 18806}
fun main(args: Array<String>) { val TOTAL_DISK_SPACE = 70000000 val UNUSED_SPACE_NEEDED = 30000000 abstract class Node(val name: String, var size: Int) { abstract fun calcSize(): Int abstract fun sumMatchingSizes(): Int } class File(name: String, size: Int): Node(name, size) { override fun calcSize(): Int { return size } override fun sumMatchingSizes(): Int { return 0 } } class Dir(name: String, val parent: Dir?): Node(name, 0) { val children = mutableMapOf<String, Node>() override fun calcSize(): Int { size = children.values.sumOf { it.calcSize() } return size } override fun sumMatchingSizes(): Int { return (if (size <= 100000) size else 0) + children.values.sumOf { it.sumMatchingSizes() } } fun findSmallestDirWithMinSize(minSize: Int): Dir? { val me = if (size >= minSize) this else null val descendantCandidates = children.values.mapNotNull { if (it !is Dir) null else it.findSmallestDirWithMinSize(minSize) } return (listOfNotNull(me) + descendantCandidates).minWithOrNull(compareBy { it.size }) } } fun executeLine(cwd: Dir, lines: List<String>, startLineNum: Int): Pair<Dir, Int> { var lineNum = startLineNum val tokens = lines[lineNum++].split(" ") if (tokens[0] != "$") { throw Exception("Expected prompt, got ${tokens[0]}") } when (tokens[1]) { "cd" -> { val targetDir = tokens[2] when (targetDir) { "/" -> { if (cwd.parent != null) { throw Exception("unexpected cd to root after start") } // else ignore } ".." -> { return Pair(cwd.parent!!, lineNum) } else -> { // assume "cd X" never precedes the ls output for its parent return Pair(cwd.children.getValue(targetDir) as Dir, lineNum) } } } "ls" -> { if (cwd.children.isNotEmpty()) { throw Exception("already listed ${cwd.name}") } else { while (lineNum < lines.size && lines[lineNum].isNotEmpty() && !lines[lineNum].startsWith("$") ) { val (dirOrSize, name) = lines[lineNum++].split(" ") val child = if (dirOrSize == "dir") { Dir(name, cwd) } else { File(name, dirOrSize.toInt()) } if (cwd.children.containsKey(name)) throw Exception("$name already exists") cwd.children[name] = child } } return Pair(cwd, lineNum) } else -> { throw Exception("bad token ${tokens[1]}") } } return Pair(cwd, lineNum) } fun loadFileSystem(input: String): Dir { val lines = input.split("\n") val root = Dir("/", null) var cwd = root var lineNum = 0 while (lineNum < lines.size && lines[lineNum].isNotEmpty()) { val res = executeLine(cwd, lines, lineNum) cwd = res.first lineNum = res.second } root.calcSize() return root } fun part1(root: Dir) { println("Part 1 sum of matching sizes: " + root.sumMatchingSizes()) } fun part2(root: Dir) { val freeSpace = TOTAL_DISK_SPACE - root.size val spaceNeeded = UNUSED_SPACE_NEEDED - freeSpace if (spaceNeeded <= 0) { throw Exception("There's already enough free space") } println("Needed space: $spaceNeeded") val toDelete = root.findSmallestDirWithMinSize(spaceNeeded) println("Dir to delete: ${toDelete!!.name} ${toDelete!!.size}") } val input = object {}.javaClass.getResource("Day07.txt").readText() val root = loadFileSystem(input) part1(root) part2(root) }
0
Kotlin
0
0
33da2136649d08c32728fa7583ecb82cb1a39049
4,470
aoc2022
MIT License
src/twentytwo/Day14.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("Day14_test") val part1 = part1(testInput) println(part1) check(part1 == 24) val part2 = part2(testInput) println(part2) check(part2 == 93) println("---") val input = readInputLines("Day14_input") println(part1(input)) println(part2(input)) } private fun part1(input: List<String>): Int { val map = createSandMap(input) MapPrinter(map).printInterestingRange() while (true) { val stayedOnMap = map.dropSandEndless() if (!stayedOnMap) break } return map.sandCount } private fun part2(input: List<String>): Int { val map = createSandMap(input) // MapPrinter(map).printInterestingRange() while (true) { val sourceBlocked = map.dropSandWithBottom() if (sourceBlocked) break } return map.sandCount } private fun createSandMap(input: List<String>): SandMap { val map = SandMap() val pointLists = input.map { line -> line .split(" -> ") .map { point -> val (x, y) = point.split(",").map { it.toInt() } Point(x, y) } } pointLists.forEach { points -> points.windowed(2).forEach { (a, b) -> map.addLine(a, b) } } return map } private class SandMap { private val map: MutableList<MutableList<Thing>> = MutableList(800) { MutableList(400) { Thing.EMPTY } } val sandCount: Int get() { var count = 0 map.forEach { line -> count += line.count { it == Thing.SAND } } return count } fun getAt(x: Int, y: Int): Thing { return map[x][y] } fun addLine(point1: Point, point2: Point) { for (x in point1.x toward point2.x) { for (y in point1.y toward point2.y) { map[x][y] = Thing.ROCK } } } /** * drops one piece of sand into the map, a map where sand can fall off * return true if the sand stayed within the map */ fun dropSandEndless(): Boolean { val bottomHeight = getInterestingRange().second.y val startPosition = Point(500, 0) var sandPosition = startPosition while (true) { val belowPosition = Point(sandPosition.x, sandPosition.y + 1) val belowThing = getAt(belowPosition.x, belowPosition.y) val leftPosition = Point(sandPosition.x - 1, sandPosition.y + 1) val leftThing = getAt(leftPosition.x, leftPosition.y) val rightPosition = Point(sandPosition.x + 1, sandPosition.y + 1) val rightThing = getAt(rightPosition.x, rightPosition.y) if (belowThing == Thing.EMPTY) { sandPosition = belowPosition } else if (leftThing == Thing.EMPTY) { sandPosition = leftPosition } else if (rightThing == Thing.EMPTY) { sandPosition = rightPosition } else { map[sandPosition.x][sandPosition.y] = Thing.SAND return true } if (sandPosition.y >= bottomHeight + 1) { return false } } } /** * drops one piece of sand into the map, a map which has a bottom line that sits below all * other lines * return true if the sand blocked the start position */ fun dropSandWithBottom(): Boolean { val bottomHeight = getInterestingRange().second.y val startPosition = Point(500, 0) var sandPosition = startPosition while (true) { val belowPosition = Point(sandPosition.x, sandPosition.y + 1) val belowThing = getAt(belowPosition.x, belowPosition.y) val leftPosition = Point(sandPosition.x - 1, sandPosition.y + 1) val leftThing = getAt(leftPosition.x, leftPosition.y) val rightPosition = Point(sandPosition.x + 1, sandPosition.y + 1) val rightThing = getAt(rightPosition.x, rightPosition.y) if (belowThing == Thing.EMPTY) { sandPosition = belowPosition } else if (leftThing == Thing.EMPTY) { sandPosition = leftPosition } else if (rightThing == Thing.EMPTY) { sandPosition = rightPosition } else { map[sandPosition.x][sandPosition.y] = Thing.SAND return sandPosition == Point(500, 0) } if (sandPosition.y >= bottomHeight + 1) { map[sandPosition.x][sandPosition.y] = Thing.SAND return false } } } /** * The range that contains rocks * Returns pair of start/lowest to end/highest position of things */ fun getInterestingRange(): Pair<Point, Point> { val smallestX = map.indexOfFirst { it.contains(Thing.ROCK) } val largestX = map.indexOfLast { it.contains(Thing.ROCK) } var largestY = 0 map.forEach { list -> val last = list.indexOfLast { it == Thing.ROCK } if (last > largestY) largestY = last } return Pair(Point(smallestX, 0), Point(largestX, largestY)) } } private data class Point(val x: Int, val y: Int) private enum class Thing { SAND, ROCK, EMPTY } private infix fun Int.toward(to: Int): IntProgression { val step = if (this > to) -1 else 1 return IntProgression.fromClosedRange(this, to, step) } private class MapPrinter(val map: SandMap) { private val interestingPoints = map.getInterestingRange() private val smallestPoint = interestingPoints.first private val largestPoint = interestingPoints.second fun printInterestingRange() { printXNumbers() for (i in smallestPoint.y .. largestPoint.y) { printLine(i) } } private fun printXNumbers() { print(" ") for (i in smallestPoint.x .. largestPoint.x) { print(i.toString()[0]) } print("\n") print(" ") for (i in smallestPoint.x .. largestPoint.x) { print(i.toString()[1]) } print("\n") print(" ") for (i in smallestPoint.x .. largestPoint.x) { print(i.toString()[2]) } print("\n") } private fun printLine(y: Int) { print(y) val ySize = y.toString().count() repeat(4 - ySize) { print(" ") } for (i in smallestPoint.x .. largestPoint.x) { if (y == 0 && i == 500) { print("+") continue } print(map.getAt(i, y).symbol) } print("\n") } private val Thing.symbol: String get() = when (this) { Thing.SAND -> "O" Thing.ROCK -> "#" Thing.EMPTY -> "." } }
1
Kotlin
0
0
600237b66b8cd3145f103b5fab1978e407b19e4c
6,995
advent-of-code-solutions
Apache License 2.0
facebook/y2020/round2/a.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package facebook.y2020.round2 private fun solve(): Long { val (n, k) = readInts() val (s, x, y) = List(3) { val array = readInts().toIntArray() + IntArray(n - k) { 0 } val (a, b, c, d) = readInts() for (i in k until n) { array[i] = ((a.toLong() * array[i - 2] + b.toLong() * array[i - 1] + c) % d).toInt() } array } var up = 0L var down = 0L var canUp = 0L var canDown = 0L for (i in s.indices) { if (s[i] < x[i]) up += x[i] - s[i] canUp += maxOf(0, x[i] + y[i] - s[i]) if (s[i] > x[i] + y[i]) down += s[i] - x[i] - y[i] canDown += maxOf(0, s[i] - x[i]) } if (up > canDown || down > canUp) return -1L return maxOf(up, down) } fun main() = repeat(readInt()) { println("Case #${it + 1}: ${solve()}") } private fun readLn() = readLine()!! private fun readInt() = readLn().toInt() private fun readStrings() = readLn().split(" ") private fun readInts() = readStrings().map { it.toInt() }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
918
competitions
The Unlicense
src/aoc2023/Day03.kt
anitakar
576,901,981
false
{"Kotlin": 124382}
package aoc2023 import readInput fun main() { fun createArray(input: List<String>): Array<Array<Char>> { val result = Array(input.size) { Array(input[0].length) { '.' } } for ((index, line) in input.withIndex()) { result[index] = line.toCharArray().toTypedArray() } return result } fun validIndex(row: Int, col: Int, array: Array<Array<Char>>): Boolean { return row >= 0 && row < array.size && col >= 0 && col < array[0].size } fun isSymbol(char: Char): Boolean { return char != '.' } fun adjacentToSymbol(row: Int, startCol: Int, endCol: Int, array: Array<Array<Char>>): Boolean { fun inNumber(i: Int, j: Int): Boolean { return i == row && j >= startCol && j <= endCol } var adjacentToSymbol = false for (i in row - 1..row + 1) { for (j in startCol - 1..endCol + 1) { if (validIndex(i, j, array) && isSymbol(array[i][j]) && !inNumber(i, j)) { adjacentToSymbol = true } } } return adjacentToSymbol } fun part1(input: List<String>): Int { var sum = 0 val array = createArray(input) for (i in array.indices) { var withinNumber = false var start = -1 var end = -1 var number = 0 for (j in 0 until array[0].size) { if (array[i][j].isDigit()) { if (!withinNumber) { withinNumber = true start = j end = j number = array[i][j].digitToInt() } else { number = (number * 10) + array[i][j].digitToInt() end = j } } else { if (withinNumber) { withinNumber = false if (adjacentToSymbol(i, start, end, array)) { sum += number } start = -1 end = -1 number = 0 } } } if (withinNumber) { if (adjacentToSymbol(i, start, end, array)) { sum += number } } } return sum } fun readNumberRight(row: Int, col: Int, array: Array<Array<Char>>): Int { var k = 1 var number = 0 do { number = number * 10 + array[row][col + k].digitToInt() k += 1 } while (validIndex(row, col + k, array) && array[row][col + k].isDigit()) return number } val exponentToPower = mapOf(0 to 1, 1 to 10, 2 to 100, 3 to 1000, 4 to 10000, 5 to 100000) fun readNumberLeft(row: Int, col: Int, array: Array<Array<Char>>): Int { var k = 1 var number = 0 if (!validIndex(row, col - k, array) || !array[row][col - k].isDigit()) { return number } do { number += array[row][col - k].digitToInt() * exponentToPower[k - 1]!! k += 1 } while (validIndex(row, col - k, array) && array[row][col - k].isDigit()) return number } fun processRow(row: Int, j: Int, array: Array<Array<Char>>): Pair<Int, Int> { var ratio = 1 var numberOfAdjacent = 0 if (validIndex(row, j - 1, array) && array[row][j - 1].isDigit() && validIndex(row, j + 1, array) && array[row][j + 1].isDigit() && !array[row][j].isDigit() ) { numberOfAdjacent += 2 //println(readNumberRight(row, j, array)) //println(readNumberLeft(row, j, array)) ratio *= readNumberRight(row, j, array) ratio *= readNumberLeft(row, j, array) } else { if (validIndex(row, j - 1, array) && array[row][j - 1].isDigit()) { numberOfAdjacent += 1 var k = j - 1 while (validIndex(row, k, array) && array[row][k].isDigit()) { k -= 1 } val right = readNumberRight(row, k, array) val number = right //println(number) ratio *= number } else if (validIndex(row, j, array) && array[row][j].isDigit()) { numberOfAdjacent += 1 //println(readNumberRight(row, j - 1, array)) ratio *= readNumberRight(row, j - 1, array) } else if (validIndex(row, j + 1, array) && array[row][j + 1].isDigit()) { numberOfAdjacent += 1 //println(readNumberRight(row, j, array)) ratio *= readNumberRight(row, j, array) } } return Pair(numberOfAdjacent, ratio) } fun part2(input: List<String>): Long { var pairs = 0 var sum = 0L val array = createArray(input) for (i in array.indices) { for (j in array[i].indices) { if (array[i][j] == '*') { var numberOfAdjacent = 0 var ratio = 1 if (validIndex(i, j - 1, array) && array[i][j - 1].isDigit()) { numberOfAdjacent += 1 val numLeft = readNumberLeft(i, j, array) //println(numLeft) ratio *= numLeft } if (validIndex(i, j + 1, array) && array[i][j + 1].isDigit()) { numberOfAdjacent += 1 val numRight = readNumberRight(i, j, array) //println(numRight) ratio *= numRight } val (adjcUp, numUp) = processRow(i - 1, j, array) numberOfAdjacent += adjcUp ratio *= numUp val (adjcDown, numDown) = processRow(i + 1, j, array) numberOfAdjacent += adjcDown ratio *= numDown if (numberOfAdjacent == 2) { sum += ratio pairs += 1 //println(ratio) } //println("------") } } } //println(pairs) return sum } println(part1(readInput("aoc2023/Day03_test"))) println(part1(readInput("aoc2023/Day03"))) println(part2(readInput("aoc2023/Day03_test"))) // println(part2(readInput("aoc2023/Day03_test1"))) // println(part2(readInput("aoc2023/Day03_test2"))) // println(part2(readInput("aoc2023/Day03_test3"))) // println(part2(readInput("aoc2023/Day03_test4"))) // println(part2(readInput("aoc2023/Day03_test5"))) // println(part2(readInput("aoc2023/Day03_test6"))) println(part2(readInput("aoc2023/Day03"))) }
0
Kotlin
0
1
50998a75d9582d4f5a77b829a9e5d4b88f4f2fcf
7,013
advent-of-code-kotlin
Apache License 2.0
app/src/y2021/day03/Day03BinaryDiagnostic.kt
henningBunk
432,858,990
false
{"Kotlin": 124495}
package y2021.day03 import common.Answers import common.AocSolution import common.annotations.AoCPuzzle import transpose fun main(args: Array<String>) { Day03BinaryDiagnostic().solveThem() } @AoCPuzzle(2021, 3) class Day03BinaryDiagnostic : AocSolution { override val answers = Answers(samplePart1 = 198, samplePart2 = 230, part1 = 3687446, part2 = 4406844) override fun solvePart1(input: List<String>): Any { val gamma = input .map { it.toList().map(Character::getNumericValue) } .transpose() .map { it.findMostCommon() } val epsilon = gamma.map { it xor 1 } return gamma.toDecimal() * epsilon.toDecimal() } override fun solvePart2(input: List<String>): Any { val inputAsIntList = input.map { it.toList().map(Character::getNumericValue) } val oxygenGeneratorRating = findRecursive( input = inputAsIntList, index = 0, criteria = ::oxygenGeneratorRatingBitCriteria ).toDecimal() val co2ScrubberRating = findRecursive( input = inputAsIntList, index = 0, criteria = ::co2ScrubberRatingBitCriteria ).toDecimal() println("Oxygen Generator Rating: $oxygenGeneratorRating") println("CO2 Scrubber Rating: $co2ScrubberRating") return oxygenGeneratorRating * co2ScrubberRating } private fun List<Int>.findMostCommon(): Int = if (count { it == 1 } >= count { it == 0 }) 1 else 0 private fun List<Int>.findLeastCommon(): Int = if (count { it == 1 } >= count { it == 0 }) 0 else 1 private fun oxygenGeneratorRatingBitCriteria( bit: List<Int>, transposedDiagnosticReport: List<List<Int>>, index: Int ): Boolean { val mostCommonForIndex = transposedDiagnosticReport .map { it.findMostCommon() } .get(index) return bit[index] == mostCommonForIndex } private fun co2ScrubberRatingBitCriteria(bit: List<Int>, transposedDiagnosticReport: List<List<Int>>, index: Int): Boolean { val leastCommonForIndex = transposedDiagnosticReport .map { it.findLeastCommon() } .get(index) return bit[index] == leastCommonForIndex } private fun findRecursive( input: List<List<Int>>, index: Int, criteria: (List<Int>, List<List<Int>>, Int) -> Boolean, ): List<Int> { val transposedInput = input.transpose() val filteredInput = input.filter { criteria(it, transposedInput, index) } return when (filteredInput.size) { 1 -> filteredInput.first() else -> findRecursive(filteredInput, index + 1, criteria) } } private fun List<Int>.toDecimal() = joinToString(separator = "").toInt(2) }
0
Kotlin
0
0
94235f97c436f434561a09272642911c5588560d
2,823
advent-of-code-2021
Apache License 2.0
src/main/kotlin/2021/Day3.kt
mstar95
317,305,289
false
null
package `2021` import days.Day class Day3 : Day(3) { override fun partOne(): Any { val pairs = inputList.map { it.split("").drop(1).dropLast(1).map { it.toInt() } } val accumulator = pairs.first().map { 0 }.toMutableList() pairs.forEach { row -> row.forEachIndexed { index, i -> accumulator[index] += i } } val half = pairs.size / 2 val gamma = accumulator.map { if (it > half) 1 else 0 }.joinToString(separator = "") { it.toString() }.toInt(2) val epsilon = accumulator.map { if (it > half) 0 else 1 }.joinToString(separator = "") { it.toString() }.toInt(2) return gamma * epsilon } override fun partTwo(): Any { val pairs: List<List<Int>> = inputList.map { it.split("").drop(1).dropLast(1).map { it.toInt() } } val a = iterate(pairs, 0, 1).joinToString(separator = "") { it.toString() }.toInt(2) val b = iterate(pairs,0 ,0).joinToString(separator = "") { it.toString() }.toInt(2) return a*b } fun iterate(l: List<List<Int>>, i: Int, bit: Int): List<Int> { println(l.size) if (l.size == 1) { return l.first() } val score = l.fold(0) { acc, it -> if(it[i] == bit) acc + 1 else acc } val other = l.size - score if(bit == 1 ) { return if (score >= other) { val rest = l.filter { it[i] == bit } iterate(rest, i + 1, bit) } else { val rest = l.filter { it[i] != bit } iterate(rest, i + 1, bit) } } else { return if (score <= other) { val rest = l.filter { it[i] == bit } iterate(rest, i + 1, bit) } else { val rest = l.filter { it[i] != bit } iterate(rest, i + 1, bit) } } } }
0
Kotlin
0
0
ca0bdd7f3c5aba282a7aa55a4f6cc76078253c81
1,900
aoc-2020
Creative Commons Zero v1.0 Universal
src/main/kotlin/dev/shtanko/algorithms/leetcode/SmallestSufficientTeam.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode /** * 1125. Smallest Sufficient Team * @see <a href="https://leetcode.com/problems/smallest-sufficient-team/">Source</a> */ fun interface SmallestSufficientTeam { operator fun invoke(reqSkills: Array<String>, people: List<List<String>>): IntArray } class SmallestSufficientTeamDFS : SmallestSufficientTeam { private var sol: MutableList<Int> = ArrayList() override operator fun invoke(reqSkills: Array<String>, people: List<List<String>>): IntArray { val idx: MutableMap<String, Int> = HashMap() var n = 0 for (s in reqSkills) idx[s] = n++ // skills are represented by 0, 1, 2.... val pe = IntArray(people.size) for (i in pe.indices) { for (p in people[i]) { val skill = idx[p]!! pe[i] += 1 shl skill } } // each person is transferred to a number, of which the bits of 1 means the guy has the skill search(0, pe, ArrayList(), n) val ans = IntArray(sol.size) for (i in sol.indices) ans[i] = sol[i] return ans } fun search(cur: Int, pe: IntArray, onesol: MutableList<Int>, n: Int) { // when all bits are 1, all skills are covered if (cur == (1 shl n) - 1) { if (sol.isEmpty() || onesol.size < sol.size) { sol = ArrayList(onesol) } return } if (sol.isNotEmpty() && onesol.size >= sol.size) { return } var zeroBit = 0 while (cur shr zeroBit and 1 == 1) zeroBit++ for (i in pe.indices) { val per = pe[i] if (per shr zeroBit and 1 == 1) { onesol.add(i) // when a person can cover a zero bit in the current number, we can add him search(cur or per, pe, onesol, n) onesol.removeAt(onesol.size - 1) // search in a backtracking way } } } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,560
kotlab
Apache License 2.0
src/Day12.kt
nikolakasev
572,681,478
false
{"Kotlin": 35834}
fun main() { fun bothParts(input: Array<Array<Int>>, begin: Pair<Int, Int>): Int { val dist = mutableMapOf<Pair<Int, Int>, Int>() val q = ArrayDeque<Pair<Int, Int>>() for (y in 0..input.size - 1) { for (x in 0..input[y].size - 1) { val pair = Pair(x, y) dist[pair] = Int.MAX_VALUE q.add(pair) } } dist[begin] = 0 val destination = Pair(88, 20) while (q.isNotEmpty()) { val v = q.minBy { pair -> dist[pair]!! } q.remove(v) getNeighbours(input, v.first, v.second).forEach { if (it in q) { dist[it] = dist[v]!! + 1 if (it == destination) println("got one from " + begin + " at distance " + (dist[v]!! + 1)) } } } return dist[destination]!! } fun part2(input: Array<Array<Int>>): Int { val aas = mutableListOf<Pair<Int, Int>>() for (y in 0..input.size - 1) { for (x in 0..input[y].size - 1) { if (input[y][x] == 97) aas.add(Pair(x, y)) } } return aas.minOf { bothParts(input, it) } // return 0 } fun part1(input: Array<Array<Int>>): Int { return bothParts(input, Pair(0, 20)) } // val testInput = readText("Day12_test").replace('S', 'a').replace('E', 'z') val input = readText("Day12").replace('S', 'a').replace('E', 'z') println(part1(inputTo2DArray(input) { s -> s.code })) println(part2(inputTo2DArray(input) { s -> s.code })) } fun getNeighbours(input: Array<Array<Int>>, x: Int, y: Int): List<Pair<Int, Int>> { val value = if (input[y][x] == 83) 97 else if (input[y][x] == 69) 122 else input[y][x] val predicate = { a: Int, b: Int -> (b <= a || (b - a) == 1) } val top = try { input[y - 1][x] } catch (e: Exception) { null } val bottom = try { input[y + 1][x] } catch (e: Exception) { null } val left = try { input[y][x - 1] } catch (e: Exception) { null } val right = try { input[y][x + 1] } catch (e: Exception) { null } return sequence { top?.let { if (predicate(value, it)) yield(Pair(x, y - 1)) } bottom?.let { if (predicate(value, it)) yield(Pair(x, y + 1)) } left?.let { if (predicate(value, it)) yield(Pair(x - 1, y)) } right?.let { if (predicate(value, it)) yield(Pair(x + 1, y)) } }.toList() }
0
Kotlin
0
1
5620296f1e7f2714c09cdb18c5aa6c59f06b73e6
2,676
advent-of-code-kotlin-2022
Apache License 2.0
aoc-2022/src/commonMain/kotlin/fr/outadoc/aoc/twentytwentytwo/Day05.kt
outadoc
317,517,472
false
{"Kotlin": 183714}
package fr.outadoc.aoc.twentytwentytwo import fr.outadoc.aoc.scaffold.Day import fr.outadoc.aoc.scaffold.readDayInput class Day05 : Day<String> { private val initialState: State = readDayInput() .splitToSequence("\n\n") .first() .lines() .parseState() private val instructions: Sequence<Instruction> = readDayInput() .splitToSequence("\n\n") .last() .lineSequence() .map { line -> line.parseInstruction() } private data class State(val stacks: List<List<Char>>) private data class Instruction(val count: Int, val from: Int, val to: Int) private fun List<String>.parseState(): State { val lines = dropLast(1).map { line -> line.chunked(size = 4) { it.replace(Regex("\\W"), "") .trim() .toCharArray() .toList() .ifEmpty { listOf(' ') } .first() } } val stackCount = lines.first().size val stacks: List<MutableList<Char>> = List(stackCount) { mutableListOf() } lines.forEach { chars -> chars.forEachIndexed { index, c -> if (c != ' ') { stacks[index].add(c) } } } return State(stacks = stacks.map { stack -> stack.reversed() }) } private val instructionRegex = Regex("^move ([0-9]+) from ([0-9]+) to ([0-9]+)$") private fun String.parseInstruction(): Instruction { val values = instructionRegex.find(this)!!.groupValues return Instruction( count = values[1].toInt(), from = values[2].toInt(), to = values[3].toInt() ) } private fun State.reduce(instruction: Instruction): State { val tail = stacks[instruction.from - 1].takeLast(instruction.count) return copy( stacks = stacks.mapIndexed { index, chars -> when (index + 1) { instruction.from -> chars.dropLast(instruction.count) instruction.to -> chars + tail else -> chars } } ) } private fun State.print() { stacks.forEachIndexed { index, chars -> println("$index ${chars.joinToString(separator = " ") { "[$it]" }}") } println() } override fun step1(): String { val unfoldedInstructions = instructions.flatMap { instruction -> List(instruction.count) { instruction.copy(count = 1) } } val finalState: State = unfoldedInstructions.fold(initialState) { acc, instruction -> acc.reduce(instruction) } return finalState.stacks .map { stack -> stack.last() } .joinToString(separator = "") } override val expectedStep1 = "HNSNMTLHQ" override fun step2(): String { val finalState: State = instructions.fold(initialState) { acc, instruction -> acc.reduce(instruction) } return finalState.stacks .map { stack -> stack.last() } .joinToString(separator = "") } override val expectedStep2 = "RNLFDJMCT" }
0
Kotlin
0
0
54410a19b36056a976d48dc3392a4f099def5544
3,401
adventofcode
Apache License 2.0
src/Day25.kt
palex65
572,937,600
false
{"Kotlin": 68582}
@file:Suppress("PackageDirectoryMismatch") package day25 import readInput import kotlin.math.abs data class NumberSNAFU(val digits: String) { override fun toString() = digits } val DigitsSNAFU = mapOf('2' to 2, '1' to 1, '0' to 0, '-' to -1, '=' to -2) val SymbolsSNAFU = DigitsSNAFU.keys.toList() fun NumberSNAFU.toLong(): Long { var power = 1L var n = 0L digits.reversed().forEach { digit -> n += checkNotNull(DigitsSNAFU[digit]) * power power *= 5 } return n } fun <T> List<T>.firstIndexed( predicate: (Int)->Boolean ): T { for (idx in indices) if (predicate(idx)) return get(idx) error("not found") } fun Long.toNumberSNAFU(): NumberSNAFU { if (this==0L) return NumberSNAFU("0") var power = 1L var max = power *2 while (max < abs(this)) { power *= 5; max += power*2 } var n = this val digits = StringBuilder() while(power > 0) { val dig = SymbolsSNAFU.firstIndexed { n > max-power*(it+1) } digits.append(dig) n -= DigitsSNAFU[dig]!! * power max -= power *2 power /= 5 } return NumberSNAFU( digits.toString() ) } fun part1(lines: List<String>): String { val sum = lines.sumOf { NumberSNAFU(it).toLong() } return sum.toNumberSNAFU().digits } fun main() { val testInput = readInput("Day25_test") check(part1(testInput) == "2=-1=0") val input = readInput("Day25") println(part1(input)) // 2=2-1-010==-0-1-=--2 }
0
Kotlin
0
2
35771fa36a8be9862f050496dba9ae89bea427c5
1,478
aoc2022
Apache License 2.0