path
stringlengths
5
169
owner
stringlengths
2
34
repo_id
int64
1.49M
755M
is_fork
bool
2 classes
languages_distribution
stringlengths
16
1.68k
content
stringlengths
446
72k
issues
float64
0
1.84k
main_language
stringclasses
37 values
forks
int64
0
5.77k
stars
int64
0
46.8k
commit_sha
stringlengths
40
40
size
int64
446
72.6k
name
stringlengths
2
64
license
stringclasses
15 values
src/main/kotlin/day2/solver.kt
derekaspaulding
317,756,568
false
null
package day2 import java.io.File fun parse(passwordSpec: String): Triple<Pair<Int, Int>, Char, String> { val (bounds, characterSpec, password) = passwordSpec.split(" ") val (min, max) = bounds.split("-").map { bound -> bound.toInt() } val character = characterSpec[0] return Triple(Pair(min, max), character, password) } fun checkProblemOne(passwords:List<String>): Int = passwords.count { val (bounds, character, password) = parse(it) val (min, max) = bounds val charCount = password.count{ char -> char == character} charCount in min..max } fun checkProblemTwo(passwords: List<String>): Int = passwords.count { val (indices, character, password) = parse(it) val (firstChar, secondChar) = indices.toList().map { i -> password[i - 1] } // indices in input are 1 based firstChar != secondChar && (firstChar == character || secondChar == character) } fun main() { val passwords = File("src/main/resources/day2/input.txt") .useLines { it.toList() } println("First criteria matches: ${checkProblemOne(passwords)} of ${passwords.size}") println("Second criteria matches: ${checkProblemTwo(passwords)} of ${passwords.size}") }
0
Kotlin
0
0
0e26fdbb3415fac413ea833bc7579c09561b49e5
1,194
advent-of-code-2020
MIT License
src/main/kotlin/com/ginsberg/advent2021/Day14.kt
tginsberg
432,766,033
false
{"Kotlin": 92813}
/* * Copyright (c) 2021 by <NAME> */ /** * Advent of Code 2021, Day 14 - Extended Polymerization * Problem Description: http://adventofcode.com/2021/day/14 * Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2021/day14/ */ package com.ginsberg.advent2021 class Day14(input: List<String>) { private val lastChar = input.first().last() private val template: Map<String, Long> = parseTemplate(input.first()) private val rules: Map<String, Char> = parseRules(input) fun solvePart1(): Long = solve(10) fun solvePart2(): Long = solve(40) private fun solve(iterations: Int): Long = (0 until iterations) .fold(template) { polymer, _ -> polymer.react() } .byCharFrequency() .values .sorted() .let { it.last() - it.first() } private fun Map<String, Long>.react(): Map<String, Long> = buildMap { this@react.forEach { (pair, count) -> val inserted = rules.getValue(pair) plus("${pair.first()}$inserted", count) plus("$inserted${pair.last()}", count) } } private fun Map<String, Long>.byCharFrequency(): Map<Char, Long> = this .map { it.key.first() to it.value } .groupBy({ it.first }, { it.second }) .mapValues { it.value.sum() + if (it.key == lastChar) 1 else 0 } private fun <T> MutableMap<T, Long>.plus(key: T, amount: Long) { this[key] = this.getOrDefault(key, 0L) + amount } private fun parseTemplate(input: String): Map<String, Long> = input .windowed(2) .groupingBy { it } .eachCount().mapValues { it.value.toLong() } private fun parseRules(input: List<String>): Map<String, Char> = input.drop(2).associate { it.substring(0..1) to it[6] } }
0
Kotlin
2
34
8e57e75c4d64005c18ecab96cc54a3b397c89723
1,905
advent-2021-kotlin
Apache License 2.0
src/main/kotlin/com/github/shmvanhouten/adventofcode/day22gridcomputing/EmptyNodeRoutePlanner.kt
SHMvanHouten
109,886,692
false
{"Kotlin": 616528}
package com.github.shmvanhouten.adventofcode.day22gridcomputing class EmptyNodeRoutePlanner { fun getRouteToCoordinate(targetCoordinate: Coordinate, sourceCoordinate: Coordinate, storageCluster: StorageCluster): NodeRoute { //Todo: consolidate with week 13 routeFinder var visitedNodes = setOf<NodeRoute>() var unvisitedNodes = setOf(NodeRoute(sourceCoordinate)) while (unvisitedNodes.isNotEmpty()) { val currentNode = getLowestDistanceNode(unvisitedNodes) unvisitedNodes -= currentNode val adjacentNodes = buildAdjacentNodes(currentNode, storageCluster) adjacentNodes.forEach { adjacentNode -> val possibleVisitedNode = visitedNodes.find { it == adjacentNode } if (possibleVisitedNode != null) { if (possibleVisitedNode.shortestPath.size > adjacentNode.shortestPath.size) { visitedNodes -= possibleVisitedNode unvisitedNodes += adjacentNode } } else { unvisitedNodes += adjacentNode } visitedNodes = addCurrentNodeToVisitedNodeIfItHasTheShortestPath(visitedNodes, currentNode) } } return visitedNodes.find { it.coordinate == targetCoordinate }!! } private fun addCurrentNodeToVisitedNodeIfItHasTheShortestPath(originalVisitedNodes: Set<NodeRoute>, currentNode: NodeRoute): Set<NodeRoute> { var newVisitedNodes = originalVisitedNodes val possibleVisitedNode: NodeRoute? = newVisitedNodes.find { it == currentNode } if (possibleVisitedNode != null) { if (possibleVisitedNode.shortestPath.size > currentNode.shortestPath.size) { newVisitedNodes -= possibleVisitedNode newVisitedNodes += currentNode } // else keep the original visited node with the shorter path } else { newVisitedNodes += currentNode } return newVisitedNodes } private fun buildAdjacentNodes(currentNode: NodeRoute, storageCluster: StorageCluster): List<NodeRoute> { val currentCoordinate = currentNode.coordinate return RelativePosition.values().map { it.coordinate + currentCoordinate } .filter { storageCluster.contains(it) } .filter { storageCluster.get(it).used <= storageCluster.get(currentCoordinate).size } .map { NodeRoute(it, currentNode.shortestPath.plus(it)) } } private fun getLowestDistanceNode(unvisitedNodes: Set<NodeRoute>): NodeRoute { return unvisitedNodes.minBy { it.shortestPath.size } ?: unvisitedNodes.first() } }
0
Kotlin
0
0
a8abc74816edf7cd63aae81cb856feb776452786
2,729
adventOfCode2016
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/LongestZigZagPath.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import kotlin.math.max /** * 1372. Longest ZigZag Path in a Binary Tree * @see <a href="https://leetcode.com/problems/longest-zigzag-path-in-a-binary-tree/">Source</a> */ fun interface LongestZigZagPath { fun longestZigZag(root: TreeNode?): Int } class LongestZigZagPathDFS : LongestZigZagPath { private var pathLength = 0 override fun longestZigZag(root: TreeNode?): Int { dfs(root, false, 0) dfs(root, true, 0) return pathLength } private fun dfs(node: TreeNode?, goLeft: Boolean, steps: Int) { if (node == null) { return } pathLength = max(pathLength, steps) if (goLeft) { dfs(node.left, false, steps + 1) dfs(node.right, true, 1) } else { dfs(node.left, false, 1) dfs(node.right, true, steps + 1) } } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,512
kotlab
Apache License 2.0
sandbox/src/main/kotlin/tomasvolker/numeriko/sandbox/quaternions/Quaternion.kt
TomasVolker
114,266,369
false
null
package tomasvolker.numeriko.sandbox.quaternions import kotlin.math.sqrt class Quaternion( val r: Double = 0.0, val x: Double = 0.0, val y: Double = 0.0, val z: Double = 0.0 ) { private inline fun elementWise(operation: (Double)->Double) = Quaternion( operation(r), operation(x), operation(y), operation(z) ) private inline fun elementWise(other: Quaternion, operation: (Double, Double)->Double) = Quaternion( operation(this.r, other.r), operation(this.x, other.x), operation(this.y, other.y), operation(this.z, other.z) ) operator fun plus(other: Quaternion): Quaternion = elementWise(other) { t, o -> t + o } operator fun minus(other: Quaternion): Quaternion = elementWise(other) { t, o -> t - o } operator fun times(other: Quaternion): Quaternion = Quaternion( this.r * other.r - this.x * other.x - this.y * other.y - this.z * other.z, this.r * other.x + this.x * other.r + this.y * other.z - this.z * other.y, this.r * other.y - this.x * other.z + this.y * other.r + this.z * other.x, this.r * other.z + this.x * other.y - this.y * other.x + this.z * other.r ) operator fun plus(other: Double): Quaternion = Quaternion(this.r + other, this.x, this.y, this.z) operator fun minus(other: Double): Quaternion = Quaternion(this.r - other, this.x, this.y, this.z) operator fun times(other: Double): Quaternion = elementWise { it * other } operator fun div(other: Double): Quaternion = elementWise { it / other } fun conjugate() = Quaternion(r, -x, -y, -z) val norm get() = sqrt(r * r + x * x + y * y + z * z) override fun toString(): String = "($r, $x, $y, $z)" } val Double.i get() = Quaternion(x = this) val Double.j get() = Quaternion(y = this) val Double.k get() = Quaternion(z = this) operator fun Double.plus(other: Quaternion) = other + this operator fun Double.minus(other: Quaternion) = Quaternion(this - other.r, -other.x, -other.y, -other.z) operator fun Double.times(other: Quaternion) = other * this
8
Kotlin
1
3
1e9d64140ec70b692b1b64ecdcd8b63cf41f97af
2,392
numeriko
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/FindUniqueBinaryString.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.stream.Collectors import java.util.stream.IntStream /** * 1980. Find Unique Binary String * @see <a href="https://leetcode.com/problems/find-unique-binary-string/">Source</a> */ fun interface FindUniqueBinaryString { operator fun invoke(nums: Array<String>): String } class FindUniqueBinaryStringImpl : FindUniqueBinaryString { override operator fun invoke(nums: Array<String>): String { val ans = StringBuilder() for (i in nums.indices) { ans.append(if (nums[i][i] == '0') '1' else '0') } return ans.toString() } } class FindUniqueBinaryStringStream : FindUniqueBinaryString { override operator fun invoke(nums: Array<String>): String { return IntStream.range(0, nums.size).mapToObj { i -> if (nums[i][i] == '0') "1" else "0" } .collect(Collectors.joining()) } } class FindUniqueBinaryStringOneLine : FindUniqueBinaryString { override operator fun invoke(nums: Array<String>): String { return nums.indices.joinToString("") { i -> if (nums[i][i] == '0') "1" else "0" } } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,739
kotlab
Apache License 2.0
app/src/main/java/com/exemple/scrabble/Trie.kt
gabriaraujo
315,707,735
false
null
package com.exemple.scrabble import java.lang.StringBuilder import java.util.ArrayList /** * Title: Trie * * Author: <NAME> * * Brief: * This object represents the implementation of a Trie tree for a 26 letter * alphabet. * * Descrição: * A Trie tree, or prefix tree, is an ordered tree that can be used to store an * array where the keys are usually strings. All descendants of any node have a * common prefix with the chain associated with that node, and the root is * associated with the empty chain. Normally, values ​​are not associated with * all nodes, only with the leaves and some internal nodes that correspond to * keys of interest. */ object Trie { const val alphabet = 26 private var root: TrieNode = TrieNode() class TrieNode { var child = arrayOfNulls<TrieNode>(alphabet) var leaf = false } /** * Brief: * Function responsible for inserting the dictionary words in the [Trie] * tree. * * Description: * This function inserts all the words in a dictionary into a tree [Trie]. * For the sake of simplicity, the dictionary is created in a 'hardcoded' * way, that is, its data is directly in the code. Each word in this * dictionary is added individually to the tree, the length of the string * is measured to find the index of each of its letters. The insertion * begins at the root of the tree, checking its descendants, if there is * already a node for that letter, then the root becomes that node, * otherwise a new node is created and defined as the root. Thus, with each * letter entered, a level is lowered in the tree. After the word has been * completely inserted, the last node is marked as a leaf node, indicating * the end of the word. This process is repeated for all words in the * dictionary. */ fun insert() { // dictionary containing all available words val dict = arrayOf( "pineapple", "herd", "order", "door", "table", "die", "mangoes", "go", "things", "radiography", "math", "drugs", "buildings", "implementation", "computer", "balloon", "cup", "boredom", "banner", "book", "leave", "superior", "profession", "meeting", "buildings", "mountain", "botany", "bathroom", "boxes", "cursing", "infestation", "termite", "winning", "breaded", "rats", "noise", "antecedent", "company", "emissary", "slack", "break", "guava", "free", "hydraulic", "man", "dinner", "games", "assembly", "manual", "cloud", "snow", "operation", "yesterday", "duck", "foot", "trip", "cheese", "room", "backyard", "loose", "route", "jungle", "tattoo", "tiger", "grape", "last", "reproach", "voltage", "angry", "mockery", "pain" ) // performs the individual insertion of each word in the tree for (key in dict) { // saves the word size and the root node val length = key.length var crawl = root // inserts each letter of the word in the tree for (i in 0 until length) { val index = key[i] - 'a' if (crawl.child[index] == null) crawl.child[index] = TrieNode() crawl = crawl.child[index]!! } // marks the current node as a leaf node crawl.leaf = true } } /** * Brief: * Function responsible for calculating the word score. * * Description: * Calculates the value of each valid word obtained from the input * characters. For each string, its characters are traversed and the value * assigned to them is added to an array of points, initialized with zeros, * in the index corresponding to the word in question. The set of words and * points are combined to form a set of pairs of (word, points). This set * is ordered by the size of the words, from smallest to largest, and then * the word with the highest score is selected; if there is a tie, the first * occurrence of that value is returned, that is, the smallest word. * * Params: * * arr (CharArray): Array of characters received as input for word * formation. * * Returns: * * (Pair<String, Int>?): Pair composed of the word with the highest * score and its value. */ fun highestScore(arr: CharArray): Pair<String, Int>? { // auxiliary variables for calculating the value of each letter val one = arrayOf('e', 'a', 'i', 'o', 'n', 'r', 't', 'l', 's', 'u') val two = arrayOf('w', 'd', 'g') val tree = arrayOf('b', 'c', 'm', 'p') val four = arrayOf('f', 'h', 'v') val eight = arrayOf('j', 'x') val ten = arrayOf('q', 'z') // searches for all words that can be formed from the entry val words = searchAllWords(arr) // filters the words to respect the frequency of characters wordFilter(arr, words) // calculates the value of each word and saves it in an array of points val points = IntArray(words.size) for (i in words.indices) for (letter in words[i]) when (letter) { in one -> points[i] += 1 in two -> points[i] += 2 in tree -> points[i] += 3 in four -> points[i] += 4 in eight -> points[i] += 8 in ten -> points[i] += 10 } // associates each word with its respective score var pair = words zip points.toTypedArray() // sorts pairs of (word, dots) by the length of each word pair = pair.sortedBy { it.first.length } // returns the first occurrence of the pair with the highest score return pair.maxBy { it.second } } /** * Brief: * Function responsible for finding the characters that were not used for * the composition of the final word. * * Description: * This function finds and saves all the characters that were not used for * the formation of the word with the highest score. From the input * characters and the chosen word, each letter of the word is traversed and * removes its first occurrence from the input set, so at the end of this * execution, there is a set with only the letters that were not used. * * Params: * * word (String): Highest scored word. * * arr (CharArray): Array of characters received as input for word * formation. * * Returns: * * (String): Set with all unused characters. */ fun getRest(word: String, arr: CharArray) : String { // auxiliary variable to store the input characters val rest = arr.toMutableList() // removes each character in the word from the input characters for (letter in word) rest.remove(letter) // returns all unused characters return String(rest.toCharArray()) } /** * Brief: * Function responsible for searching all words in the dictionary that can * be formed with the input characters. * * Description: * Searches for all words contained in the trees that can be formed with * the characters provided. Initially an array is created where the words * found will be saved and also an array of Booleans for each letter of the * alphabet. For each character received in the entry, it is marked as * 'true' in the array of Booleans in the index corresponding to that letter * in the alphabet. In sequence, this array is traversed and if any position * is marked as 'true' and there is a descendant in the tree for that * letter, then that letter is added to a string, which is initially empty, * so that a deep search can be performed for the descendants of that * letter. After all letters that have been received have been searched, the * words that were found are returned. * * Params: * * arr (CharArray): Array of characters received as input for word * formation. * * Returns: * * (ArrayList<String>): Set with all the words found by the search. */ private fun searchAllWords(arr: CharArray): ArrayList<String> { // initially empty word set and boolean array val words = arrayListOf("") val hash = BooleanArray(alphabet) // marks each letter of the entry as 'true' in the Boolean array for (element in arr) hash[element - 'a'] = true var str = StringBuilder() // scrolls through the alphabet to search each letter in the entry for (i in 0 until alphabet) if (hash[i] && root.child[i] != null) { // saves the letter that has descendants and is in the entry str.append((i + 'a'.toInt()).toChar()) // performs in-depth search for each letter searchWord(root.child[i], words, hash, str.toString()) str = StringBuilder() } // returns all words found in the tree return words } /** * Brief: * Recursive function responsible for searching in depth for each letter of * the entry. * * Description: * Searches each node for the existence of descendants and adds the * characters found to the string passed by parameter, which initially has * only the first letter of the word. If the node in question is a leaf * node, it means that a complete word has been found, then that word is * added to the set. The search continues until you scroll through all the * letters available at the entrance. * * Params: * * root (TrieNode?): Node through which the search will start. * * words (ArrayList<String>): Set with all the words found by the * search. * * hash (BooleanArray): Set of Booleans that indicate which letters of * the alphabets are present at the entrance. * * str (String): Word that will be constructed during the execution of * the search. */ private fun searchWord( root: TrieNode?, words: ArrayList<String>, hash: BooleanArray, str: String ) { // if the node in question is a leaf the word is saved in the set if (root!!.leaf) words.add(str) // performs the in-depth search for each valid descendant for (i in 0 until alphabet) if (hash[i] && root.child[i] != null) { val c = (i + 'a'.toInt()).toChar() searchWord(root.child[i], words, hash, str + c) } } /** * Brief: * Function responsible for filtering words that disregard the character * frequency of the entry. * * Description: * This function removes from the set of words those that violate the * acceptance criteria, in this case the frequency of each character. * Initially an array of integers saves how many occurrences there were of * each character in the entry, where the index corresponds to its position * in the alphabet. This array is then traversed and for each letter whose * frequency is not zero, it is verified how many occurrences of it exist * in each of the words in the set. If any word has more characters of that * type than are available, that word is removed from the set. * * Params: * * arr (CharArray): Array of characters received as input for word * formation. * * words (ArrayList<String>): Set with all the words found by the * search. */ private fun wordFilter(arr: CharArray, words: ArrayList<String>) { // array that stores the frequency of each letter in the alphabet val frequency = IntArray(alphabet) // auxiliary variable to store the words that must be removed val aux = arrayListOf<String>() // the frequency of each letter is calculated and the search begins for (element in arr) frequency[element - 'a']++ for (i in 0 until alphabet) if (frequency[i] > 0) for (word in words) { // the occurrences of the letter in question are counted in the word val n = word.count { c -> c == (i + 'a'.toInt()).toChar() } // save the word that must be removed from the set if (n > frequency[i]) aux.add(word) } // remove the invalid words from the solution set for (element in aux) words.remove(element) } }
0
Kotlin
0
2
9623ecc939fe6a654c219fd6ef1b857240b34eaa
13,107
scrabble
MIT License
aoc2023/src/main/kotlin/de/havox_design/aoc2023/day18/LavaductLagoon.kt
Gentleman1983
737,309,232
false
{"Kotlin": 746488, "Java": 441473, "Scala": 33415, "Groovy": 5725, "Python": 3319}
package de.havox_design.aoc2023.day18 import de.havox_design.aoc.utils.kotlin.model.coordinates.* import kotlin.math.abs class LavaductLagoon(private var filename: String) { private val BLACK = "#000000" private val ICON_UP = "U" private val ICON_DOWN = "D" private val ICON_LEFT = "L" private val ICON_RIGHT = "R" private val ELEMENT_DELIMITER = " " fun solvePart1(): Long = mutableMapOf(origin to BLACK) .processInstructions(origin, parseDigInstructions()) .calculateTrench() fun solvePart2(): Long { val polygon = parseDigInstructions() .map { it.transformInstruction() } .runningFold(origin) { current, instruction -> when (instruction.direction) { FourDirectionsFlipped.RIGHT -> Coordinate(current.x + instruction.amount, current.y) FourDirectionsFlipped.LEFT -> Coordinate(current.x - instruction.amount, current.y) FourDirectionsFlipped.DOWN -> Coordinate(current.x, current.y + instruction.amount) FourDirectionsFlipped.UP -> Coordinate(current.x, current.y - instruction.amount) } } .toList() val area = polygon.polygonArea() val boundary = polygon.pointsOnBoundary() return (area - boundary / 2 + 1).toLong() + boundary } private fun MutableMap<Coordinate, String>.processInstructions( start: Coordinate, instructions: List<DigInstruction> ): MutableMap<Coordinate, String> { var current = start instructions .forEach { instruction -> repeat(instruction.amount) { current = instruction.direction + current set(current, instruction.colorCode) } } return this } private fun MutableMap<Coordinate, String>.calculateTrench(): Long { val xRange = xRange() .let { (a, b) -> a..b } val yRange = yRange() .let { (a, b) -> a..b } val connectNorth = keys .filter { FourDirectionsFlipped.UP + it in this } .toSet() var count = 0L yRange.forEach { y -> var border = 0 xRange.forEach { x -> val coordinate = Coordinate(x, y) border += when { coordinate in connectNorth -> 1 else -> 0 } when { containsKey(coordinate) -> count++ border % 2 == 1 -> count++ } } } return count } private fun List<Coordinate>.polygonArea(): Double = abs((1..<size) .sumOf { value -> crossProduct(get(value), get(value - 1)) } / 2.0) private fun crossProduct(a: Coordinate, b: Coordinate) = a.x.toLong() * b.y.toLong() - b.x.toLong() * a.y.toLong() private fun List<Coordinate>.pointsOnBoundary(): Long = zipWithNext() .sumOf { (a, b) -> val delta = a - b abs(gcd(delta.x.toLong(), delta.y.toLong())) } .let { val delta = last() - first() abs(gcd(delta.x.toLong(), delta.y.toLong())) + it } private fun gcd(number1: Long, number2: Long): Long = when (number2) { 0L -> number1 else -> gcd(number2, number1 % number2) } private fun parseDigInstructions() = getResourceAsText(filename) .map { row -> row .split(ELEMENT_DELIMITER, limit = 3) .let { (direction, steps, color) -> DigInstruction( when (direction) { ICON_RIGHT -> FourDirectionsFlipped.RIGHT ICON_LEFT -> FourDirectionsFlipped.LEFT ICON_UP -> FourDirectionsFlipped.UP ICON_DOWN -> FourDirectionsFlipped.DOWN else -> error("Invalid input : $direction $steps $color") }, steps.toInt(), color.drop(1).dropLast(1) ) } } private fun getResourceAsText(path: String): List<String> = this.javaClass.classLoader.getResourceAsStream(path)!!.bufferedReader().readLines() }
4
Kotlin
0
1
35ce3f13415f6bb515bd510a1f540ebd0c3afb04
4,634
advent-of-code
Apache License 2.0
src/Day04.kt
ostersc
570,327,086
false
{"Kotlin": 9017}
data class BingoSpace(var num: Int, var marked: Boolean) class BingoBoard { var grid = Array(5) { row -> Array(5) { col -> BingoSpace(0, false) } } override fun toString(): String { var s="" for (col in 0..4) { for (row in 0..4) { val b =grid.get(col).get(row) if(b.marked) s=s.plus("[") else s=s.plus(" ") s=s.plus(b.num.toString().padStart(2)) if(b.marked) s=s.plus("]") else s=s.plus(" ") if(row==4) s=s.plus("\n") } } if(checkWin()){ s=s.plus(" WINNER\n") }else{ s=s.plus(" not a win\n") } return s } fun checkWin(): Boolean { return grid.any { row -> row.all { it.marked } } || (0..4).any {col -> (0..4).all{row->grid[row][col].marked }} } fun markNumber(number: Int): Boolean { //iterate each col searching for the number and mark bool to true if found for (row in grid.iterator()) { for (col in row.iterator()) { if (col.num == number) { col.marked = true return true } } } return false } fun getUncalledNumberSum(): Int { var sum = 0 for (row in grid.iterator()) { for (col in row.iterator()) { if (!col.marked) sum += col.num } } return sum } } class BingoGame(val calls: List<Int>, var boards: List<BingoBoard>) { var callIndex = -1 fun callNextNumber(): Int { callIndex++ if (callIndex >= calls.size) { return -1 } for (b in boards) { b.markNumber(calls.get(callIndex)) } return calls.get(callIndex) } } fun main() { fun readGame(input: List<String>): BingoGame { val boards = mutableListOf<BingoBoard>() var b = BingoBoard() var lineNum = 0 for (line in input.subList(1, input.size)) { if (line.length == 0) { b = BingoBoard() continue } val cells = line.split(" ").filter { it.isNotEmpty() } for (n in cells.indices) { b.grid[lineNum][n] = BingoSpace(cells[n].toInt(), false) } if (lineNum++ == 4) { boards.add(b) lineNum = 0 } } return BingoGame(input.first().split(",").map { it.toInt() }, boards) } fun part1(input: List<String>): Int { val g = readGame(input) var num = g.callNextNumber() while (num >= 0) { for (b in g.boards) { if (b.checkWin()) { return b.getUncalledNumberSum() * num } } num = g.callNextNumber() } return -1 } fun part2(input: List<String>): Int { val g = readGame(input) var num = g.callNextNumber() var lastWinSum = 0 val remainingBoards = ArrayList(g.boards) while (num >= 0) { //println("Just called ${num}") val iter = remainingBoards.iterator() while (iter.hasNext()) { val b = iter.next() //println(b) if (b.checkWin()) { lastWinSum = b.getUncalledNumberSum() * num iter.remove() } } num = g.callNextNumber() } return lastWinSum } // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") check(part1(testInput) == 4512) check(part2(testInput) == 1924) val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
836ff780252317ee28b289742396c74559dd2b6e
3,923
advent-of-code-2021
Apache License 2.0
src/main/kotlin/days/Day3.kt
felix-ebert
433,847,657
false
{"Kotlin": 12718}
package days class Day3 : Day(3) { override fun partOne(): Any { var gamma = "" var epsilon = "" for (i in inputList[0].indices) { gamma += inputList.groupingBy { it[i] }.eachCount().maxWithOrNull(compareBy { it.value })?.key epsilon += inputList.groupingBy { it[i] }.eachCount().minWithOrNull(compareBy { it.value })?.key } return gamma.toInt(2) * epsilon.toInt(2) } override fun partTwo(): Any { val o2Rating = getRating(inputList, true) val co2Rating = getRating(inputList, false) return o2Rating * co2Rating } private fun getRating(input: List<String>, isMostCommonRating: Boolean): Int { var report = input for (i in input[0].indices) { val mostCommonBit = report.groupingBy { it[i] }.eachCount().maxWithOrNull(compareBy { it.value })?.key val leastCommonBit = report.groupingBy { it[i] }.eachCount().minWithOrNull(compareBy { it.value })?.key val bitCriteria = if (mostCommonBit != leastCommonBit) { if (isMostCommonRating) { mostCommonBit!! } else { leastCommonBit!! } } else { if (isMostCommonRating) { '1' } else { '0' } } if (report.size > 1) { report = report.filter { it[i] == bitCriteria } } } return report[0].toInt(2) } }
0
Kotlin
0
2
cf7535d1c4f8a327de19660bb3a9977750894f30
1,568
advent-of-code-2021
Creative Commons Zero v1.0 Universal
src/Day03.kt
RichardLiba
572,867,612
false
{"Kotlin": 16347}
fun main() { fun getPriority(char: Char): Int { return if (char.isUpperCase()) char - 'A' + 27 else char - 'a' + 1 } fun part1(input: List<String>): Int { return input.sumOf { it.chunked(it.length / 2).let { it[0].toSet().intersect(it[1].toSet()).sumOf { getPriority(it) } } } } fun part2(input: List<String>): Int { return input.chunked(3).sumOf { it[0].toSet().intersect(it[1].toSet()).intersect(it[2].toSet()) .sumOf { getPriority(it) } } } val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
6a0b6b91b5fb25b8ae9309b8e819320ac70616ed
669
aoc-2022-in-kotlin
Apache License 2.0
jvm/src/main/kotlin/io/prfxn/aoc2021/day03.kt
prfxn
435,386,161
false
{"Kotlin": 72820, "Python": 362}
// Binary Diagnostic (https://adventofcode.com/2021/day/3) package io.prfxn.aoc2021 fun main() { fun part1() { val bitCounts = IntArray(12) { 0 } var numLines = 0 textResourceReader("input/03.txt").useLines { lineSeq -> for (line in lineSeq) { for (i in line.indices) { bitCounts[i] += when (line[i]) { '0' -> 0 '1' -> 1 else -> throw IllegalArgumentException() } } numLines += 1 } } val gammaRateBits = bitCounts .map { num1s -> val num0s = numLines - num1s if (num1s > num0s) '1' else if (num1s < num0s) '0' else throw IllegalArgumentException() } .joinToString("") val epsilonRateBits = gammaRateBits .map { when (it) { '0' -> '1' '1' -> '0' else -> throw IllegalArgumentException() } } .joinToString("") println( Integer.parseInt(gammaRateBits, 2) * Integer.parseInt(epsilonRateBits, 2) ) } fun part2() { val lines = textResourceReader("input/03.txt").readLines() fun getFilteredLineIndices(isFiltered: (Int) -> Boolean): Sequence<Int> = lines.indices.asSequence().filter { isFiltered(it) } fun getRating(getExpectedBit: (Int, Int) -> Int ): Int { val filterFlags = BooleanArray(lines.size) { true } var remaining = lines.size var bitIndex = 0 while (remaining > 1) { val num1s = getFilteredLineIndices(filterFlags::get).sumOf { lines[it][bitIndex].digitToInt() } val num0s = remaining - num1s val expectedBit = getExpectedBit(num0s, num1s) getFilteredLineIndices(filterFlags::get).forEach { lineIndex -> if (lines[lineIndex][bitIndex].digitToInt() != expectedBit) { filterFlags[lineIndex] = false remaining -= 1 } } bitIndex += 1 } if (remaining != 1) throw IllegalArgumentException() return Integer.parseInt(lines[getFilteredLineIndices(filterFlags::get).first()], 2) } val oxygenGeneratorBits = getRating { num0s, num1s -> if (num1s >= num0s) 1 else 0 } val co2ScrubberBits = getRating { num0s, num1s -> if (num1s < num0s) 1 else 0 } println(oxygenGeneratorBits * co2ScrubberBits) } part1() part2() } /** output * 4174964 * 4474944 */
0
Kotlin
0
0
148938cab8656d3fbfdfe6c68256fa5ba3b47b90
2,955
aoc2021
MIT License
src/main/kotlin/de/tek/adventofcode/y2022/day05/SupplyStacks.kt
Thumas
576,671,911
false
{"Kotlin": 192328}
package de.tek.adventofcode.y2022.day05 import de.tek.adventofcode.y2022.util.readInputLines typealias Item = Char data class MoveCommand(val from: Int, val to: Int, val numberOfCrates: Int) { companion object { fun fromDescription(description: String): MoveCommand? { val parsedInts = parseByRegex(description) return if (parsedInts != null && parsedInts.size == 3) { MoveCommand(correctOffset(parsedInts[1]), correctOffset(parsedInts[2]), parsedInts[0]) } else { null } } private fun correctOffset(position: Int) = position - 1 private fun parseByRegex(it: String) = """move (\d+) from (\d+) to (\d+)""".toRegex().matchEntire(it)?.groupValues?.drop(1)?.map { it.toInt() } } } class SupplyStacks(numberOfStacks: Int) { private val stacks = Array<MutableList<Item>>(numberOfStacks) { mutableListOf() } fun loadLineOfCrates(lineOfCrates: Array<Item?>) { lineOfCrates.mapIndexed { i, item -> if (item != null) put(i, item) } } private fun put(stack: Int, item: Item) { stacks[stack].add(item) } fun executeInSingleSteps(command: MoveCommand) { repeat(command.numberOfCrates) { val crane = loadCrane(command.from, 1) unloadCrane(command.to, crane) } } fun executeAsBatch(command: MoveCommand) { val crane = loadCrane(command.from, command.numberOfCrates) unloadCrane(command.to, crane) } private fun loadCrane(targetStack: Int, numberOfCrates: Int): ArrayDeque<Item> { val crane = ArrayDeque<Item>(numberOfCrates) repeat(numberOfCrates) { crane.addFirst(stacks[targetStack].removeLast()) } return crane } private fun unloadCrane( targetStack: Int, crane: ArrayDeque<Item> ) { stacks[targetStack].addAll(crane) } fun getTopCrates() = stacks.map { if (it.isEmpty()) ' ' else it.last() } override fun toString(): String { return stacks.foldIndexed("SupplyStacks@${super.toString()}:\n") { stackNo, string, stack -> string + "$stackNo: " + stack.joinToString(" ") { "[$it]" } + "\n" } } companion object { fun fromDescription(description: List<String>): SupplyStacks { if (description.isEmpty()) { throw IllegalArgumentException("The crate description must at least contain the footer line.") } val lines = description.toMutableList() val stackNumbering = lines.removeLast() val numberOfStacks = parseNumberOfColumns(stackNumbering) val stacks = SupplyStacks(numberOfStacks) lines.reversed().asSequence().map { parseCrates(it) }.forEach { stacks.loadLineOfCrates(it) } return stacks } private fun parseCrates(description: String) = splitColumns(description).map { it.removeSurrounding("[", "]") }.map { if (it.isEmpty()) null else it[0] } .toTypedArray() private fun parseNumberOfColumns(footerLine: String) = splitColumns(footerLine).size private fun splitColumns(line: String) = line.chunked(4).map { it.trim() } } } fun main() { val input = readInputLines(SupplyStacks::class) fun processInstructions(input: List<String>, craneFunction: SupplyStacks.(MoveCommand) -> Unit): String { val stackDescription = input.takeWhile { it.isNotBlank() } val stacks = SupplyStacks.fromDescription(stackDescription) val moveDescription = input.takeLastWhile { it.isNotBlank() } moveDescription.mapNotNull { MoveCommand.fromDescription(it) }.forEach { stacks.craneFunction(it) } return toString(stacks.getTopCrates()) } fun part1(input: List<String>) = processInstructions(input, SupplyStacks::executeInSingleSteps) fun part2(input: List<String>) = processInstructions(input, SupplyStacks::executeAsBatch) println("Using the CrateMover 9000, the top crates are ${part1(input)}.") println("Using the CrateMover 9001, The top crates are ${part2(input)}.") } fun toString(crates: List<Item>) = String(crates.toCharArray())
0
Kotlin
0
0
551069a21a45690c80c8d96bce3bb095b5982bf0
4,278
advent-of-code-2022
Apache License 2.0
src/day04/Day04.kt
pientaa
572,927,825
false
{"Kotlin": 19922}
package day04 import readLines fun main() { fun getEachElfSection(input: List<String>) = input.map { line -> line.split(",") .map { range -> range.split('-').map { it.toInt() } .let { it.first()..it.last() } .toSet() } } fun part1(input: List<String>): Int = getEachElfSection(input) .filter { (it.first() + it.last()).size == it.first().size || (it.first() + it.last()).size == it.last().size } .size fun part2(input: List<String>): Int = getEachElfSection(input) .filter { pair -> pair.first().any { sectionID -> pair.last().contains(sectionID) } } .size // test if implementation meets criteria from the description, like: val testInput = readLines("day04/Day04_test") val input = readLines("day04/Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
63094d8d1887d33b78e2dd73f917d46ca1cbaf9c
1,102
aoc-2022-in-kotlin
Apache License 2.0
jvm/src/main/kotlin/boj/CoffeeShopII.kt
imdudu1
196,377,985
false
{"Java": 47989, "Kotlin": 39952, "Python": 38168, "Go": 15491, "Rust": 2583, "JavaScript": 1023}
package boj import java.io.BufferedReader import java.io.InputStreamReader class CoffeeShopII constructor(private val numbers: Array<Long>) { private val segmentTree: Array<Long> = Array(numbers.size * 4) { 0 } init { initTree(0, numbers.size - 1) } private fun initTree(begin: Int, end: Int, root: Int = 1): Long { if (begin == end) { segmentTree[root] = numbers[begin] return numbers[begin] } val mid = (begin + end) / 2 segmentTree[root] = initTree(begin, mid, root * 2) + initTree(mid + 1, end, root * 2 + 1) return segmentTree[root] } private fun updateTree(begin: Int, end: Int, target: Int, diff: Long, root: Int = 1) { if (target in begin..end) { segmentTree[root] += diff if (begin != end) { val mid = (begin + end) / 2 updateTree(begin, mid, target, diff, root * 2) updateTree(mid + 1, end, target, diff, root * 2 + 1) } } } fun sum(x: Int, y: Int): Long = rangeSum(0, numbers.size - 1, x, y) private fun rangeSum(begin: Int, end: Int, x: Int, y: Int, root: Int = 1): Long { if (y < begin || end < x) { return 0 } if (x <= begin && end <= y) { return segmentTree[root] } val mid = (begin + end) / 2 return rangeSum(begin, mid, x, y, root * 2) + rangeSum(mid + 1, end, x, y, root * 2 + 1) } fun update(pos: Int, n: Long) { val diff = getDiff(pos, n) numbers[pos] = n updateTree(0, numbers.size - 1, pos, diff) } private fun getDiff(pos: Int, n: Long): Long { return n - numbers[pos] } } fun coffeeShopII(args: Array<String>) { val br = BufferedReader(InputStreamReader(System.`in`)) val (_, q) = br.readLine().trim().split(" ").map(String::toInt) val nums = br.readLine().trim().split(" ").map(String::toLong).toTypedArray() val solution = CoffeeShopII(nums) repeat(q) { var (x, y, a, b) = br.readLine().trim().split(" ").map(String::toLong) if (x > y) { x = y.also { y = x } } println(solution.sum((x - 1).toInt(), (y - 1).toInt())) solution.update((a - 1).toInt(), b) } }
0
Java
0
0
ee7df895761b095d02a08f762c682af5b93add4b
2,317
algorithm-diary
MIT License
src/main/kotlin/day04/CampCleanup.kt
iamwent
572,947,468
false
{"Kotlin": 18217}
package day04 import readInput import kotlin.math.max import kotlin.math.min class CampCleanup( private val name: String ) { private fun readAssignments(): List<Assignment> { return readInput(name).map { pair -> val (left, right) = pair.split(",") .map { section -> val (start, end) = section.split("-").map { it.toInt() } Section(start, end) } Assignment(left, right) } } fun part1(): Int { return readAssignments() .filter { it.isFullyContained } .size } fun part2(): Int { return readAssignments() .filter { it.isOverlap } .size } } data class Section( val start: Int, val end: Int, ) { fun contains(other: Section): Boolean { return start <= other.start && end >= other.end } fun overlap(other: Section): Boolean { val maxStart = max(start, other.start) val minEnd = min(end, other.end) return maxStart <= minEnd } } data class Assignment( val left: Section, val right: Section ) { val isFullyContained: Boolean get() { return left.contains(right) || right.contains(left) } val isOverlap: Boolean get() = left.overlap(right) }
0
Kotlin
0
0
77ce9ea5b227b29bc6424d9a3bc486d7e08f7f58
1,354
advent-of-code-kotlin
Apache License 2.0
src/main/kotlin/com/chriswk/aoc/advent2015/Day6.kt
chriswk
317,863,220
false
{"Kotlin": 481061}
package com.chriswk.aoc.advent2015 import com.chriswk.aoc.AdventDay import com.chriswk.aoc.util.Pos import com.chriswk.aoc.util.report import com.chriswk.aoc.util.toInt import java.lang.IllegalArgumentException import java.lang.IllegalStateException import kotlin.math.max class Day6 : AdventDay(2015, 6) { companion object { @JvmStatic fun main(args: Array<String>) { val day = Day6() report { day.part1() } report { day.part2() } } } fun part1(): Int { val grid: Array<Int> = Array(1000 * 1000) { 0 } inputAsLines.map { Instruction.fromInstructionString(it) }.forEach { it.actPart1(grid) } return grid.sum() } fun part2(): Int { val grid: Array<Int> = Array(1000 * 1000) { 0 } inputAsLines.map { Instruction.fromInstructionString(it) }.forEach { it.actPart2(grid) } return grid.sum() } } data class Instruction(val operation: Operation, val minX: Int, val minY: Int, val maxX: Int, val maxY: Int) { val points: List<Int> = (minY..maxY).flatMap { y -> (minX..maxX).map { x -> y*1000 + x } } fun actPart1(grid: Array<Int>) { points.forEach { idx -> when (operation) { Operation.ON -> grid[idx] = 1 Operation.OFF -> grid[idx] = 0 Operation.TOGGLE -> if (grid[idx] == 0) { grid[idx] = 1 } else { grid[idx] = 0 } } } } fun actPart2(grid: Array<Int>) { points.forEach { idx -> when (operation) { Operation.ON -> grid[idx]++ Operation.OFF -> grid[idx] = max(0, grid[idx] - 1) Operation.TOGGLE -> grid[idx] += 2 } } } companion object { val numberInstruction = """(\d+),(\d+) through (\d+),(\d+)""".toRegex() fun fromInstructionString(input: String): Instruction { val coords = numberInstruction.find(input) coords?.let { res -> return Instruction( Operation.fromString(input), toInt(res.groups[1]), toInt(res.groups[2]), toInt(res.groups[3]), toInt(res.groups[4]) ) } ?: throw IllegalStateException("Couldn't find coordinates in $input") } } } enum class Operation { OFF, ON, TOGGLE; companion object { fun fromString(input: String): Operation { return when { input.startsWith("turn on") -> { ON } input.startsWith("turn off") -> { OFF } input.startsWith("toggle") -> { TOGGLE } else -> { throw IllegalArgumentException("Don't know how to perform $input") } } } } }
116
Kotlin
0
0
69fa3dfed62d5cb7d961fe16924066cb7f9f5985
3,177
adventofcode
MIT License
src/Day06.kt
RaspiKonk
572,875,045
false
{"Kotlin": 17390}
/** * Day 6: Funkgerät reparieren: Die ersten 4 Character im String finden die sich nicht wiederholen. * * Part 1: Die ersten 4 Character im String finden die sich nicht wiederholen. * Part 2: same same with 14 chars */ fun main() { val start = System.currentTimeMillis() val DAY: String = "06" println("Advent of Code 2022 - Day $DAY") // Solve part 1. fun part1(input: List<String>, windowSize: Int): Int { for(line in input) { //print(line) // sliding window var windows = line.windowed(windowSize, 1) // println(windows) // [mjqj, jqjp, qjpq, jpqm, pqmg, ... for((index, w) in windows.withIndex()) { val array: CharArray = w.toCharArray() val tmp = array.distinct() //print(tmp.size) if(tmp.size == windowSize) { // first string with different characters found - show score var pos: Int = index + windowSize return pos } } } return 0 } // test if implementation meets criteria from the description, like: val testInput = readInput("Day${DAY}_test") val input = readInput("Day${DAY}") // Part 1 //check(part1(testInput) == 24000) println("Part 1: ${part1(input, 4)}") // 1235 // Part 2 //check(part2(testInput) == 24000) println("Part 2: ${part1(input, 14)}") // 3051 val elapsedTime = System.currentTimeMillis() - start println("Elapsed time: $elapsedTime ms") }
0
Kotlin
0
1
7d47bea3a5e8be91abfe5a1f750838f2205a5e18
1,369
AoC_Kotlin_2022
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/FindEventualSafeStates.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.util.LinkedList import java.util.Queue /** * 802. Find Eventual Safe States * @see <a href="https://leetcode.com/problems/find-eventual-safe-states/">Source</a> */ fun interface FindEventualSafeStates { fun eventualSafeNodes(graph: Array<IntArray>): List<Int> } /** * Approach 1: Topological Sort Using Kahn's Algorithm */ class FindEventualSafeStatesKahn : FindEventualSafeStates { override fun eventualSafeNodes(graph: Array<IntArray>): List<Int> { val n = graph.size val indegree = IntArray(n) val adj: MutableList<MutableList<Int>> = ArrayList() for (i in 0 until n) { adj.add(ArrayList()) } for (i in 0 until n) { for (node in graph[i]) { adj[node].add(i) indegree[i]++ } } val q: Queue<Int> = LinkedList() // Push all the nodes with indegree zero in the queue. for (i in 0 until n) { if (indegree[i] == 0) { q.add(i) } } val safe = BooleanArray(n) while (q.isNotEmpty()) { val node: Int = q.poll() safe[node] = true for (neighbor in adj[node]) { // Delete the edge "node -> neighbor". indegree[neighbor]-- if (indegree[neighbor] == 0) { q.add(neighbor) } } } val safeNodes: MutableList<Int> = ArrayList() for (i in 0 until n) { if (safe[i]) { safeNodes.add(i) } } return safeNodes } } /** * Approach 2: Depth First Search */ class FindEventualSafeStatesDFS : FindEventualSafeStates { override fun eventualSafeNodes(graph: Array<IntArray>): List<Int> { val n = graph.size val adj: MutableList<MutableList<Int>> = ArrayList() for (i in 0 until n) { adj.add(ArrayList()) for (node in graph[i]) { adj[i].add(node) } } val visit = BooleanArray(n) val inStack = BooleanArray(n) for (i in 0 until n) { safeStatesDFS(i, adj, visit, inStack) } val safeNodes: MutableList<Int> = ArrayList() for (i in 0 until n) { if (!inStack[i]) { safeNodes.add(i) } } return safeNodes } } fun safeStatesDFS(node: Int, adj: List<MutableList<Int>>, visit: BooleanArray, inStack: BooleanArray): Boolean { // If the node is already in the stack, we have a cycle. if (inStack[node]) { return true } if (visit[node]) { return false } // Mark the current node as visited and part of current recursion stack. visit[node] = true inStack[node] = true for (neighbor in adj[node]) { if (safeStatesDFS(neighbor, adj, visit, inStack)) { return true } } // Remove the node from the stack. inStack[node] = false return false }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,698
kotlab
Apache License 2.0
src/Day07.kt
calindumitru
574,154,951
false
{"Kotlin": 20625}
import java.util.function.Predicate const val TOTAL = 70000000 const val UNUSED = 30000000 fun main() { val part1 = Implementation("Find all of the directories with a total size of at most 100000. What is the sum of the total sizes of those directories?", 95437) { lines -> val root = convertToGraph(lines) return@Implementation root.find { t -> t.completeSize() <= 100000 }.sumOf { it.completeSize() } } val part2 = Implementation("Find the smallest directory that, if deleted, would free up enough space on the filesystem to run the update. What is the total size of that directory?", 24933642) { lines -> val root = convertToGraph(lines) val limit = UNUSED - (TOTAL - root.completeSize()) return@Implementation root.find { t -> t.completeSize() >= limit }.minOf { it.completeSize() } } OhHappyDay(7, part1, part2).checkResults() } fun convertToGraph(lines: List<String>): Dir { val root = Dir(name = "/") var current = root lines.forEach { line -> when { line == "$ cd /" -> {} line == "$ cd .." -> { current = current.parent!! } line.startsWith("$ cd") -> { val dirName = line.substringAfter("cd ") val dir = Dir(name = dirName) dir.parent = current current.add(dir) current = dir } line.first().isDigit() -> { val value = line.substringBefore(" ").toInt() current.size += value } line == "$ ls" -> {} } } return root } data class Dir(val name:String, val children: MutableList<Dir> = mutableListOf(), var size:Int = 0) { var parent: Dir? = null fun add(d: Dir) { children.add(d) } fun find(p: Predicate<Dir>): List<Dir> { val flattened = flatten() return flattened.filter { p.test(it) } } private fun flatten(): List<Dir> = children + children.flatMap { it.flatten() } fun completeSize() : Int = this.size + children.sumOf { cc -> cc.completeSize() } }
0
Kotlin
0
0
d3cd7ff5badd1dca2fe4db293da33856832e7e83
2,179
advent-of-code-2022
Apache License 2.0
hikotlin/src/main/java/me/li2/android/hikotlin/kotlin/Calculator.kt
li2
121,604,937
false
{"Kotlin": 81758, "Java": 4651}
package me.li2.android.hikotlin.kotlin import me.li2.android.hikotlin.kotlin.Operator.* import java.util.* /** + */ fun operatorPlus(input: Int): Int { return input + MY_PLUS } /** - */ fun operatorMinus(input: Int): Int { return input + MY_MINUS } /** x */ fun operatorMultiply(input: Int): Int { return input * MY_MULTIPLY } /** / */ fun operatorDivider(input: Int): Int { return input / MY_DIVIDER } /** reverse : 12 to 21 */ fun operatorReverse(input: Int): Int { var num = input var reversed = 0 while (num != 0) { val digit = num % 10 reversed = reversed * 10 + digit num /= 10 } return reversed } /** +/- */ fun operatorConvert(input: Int): Int { return -input } /** << */ fun operatorShift(input: Int): Int { return input / 10 } fun operatorInsert(input: Int): Int { return input * 10 + 1 } /** * THE METHOD THAT TAKES AN ARRAY OF STRINGS AND PRINTS THE * POSSIBLE COMBINATIONS. */ fun genOperatorsCombinations(operators: Array<Operator>): List<List<Operator>> { val results = ArrayList<List<Operator>>() /*COMBINATIONS OF LENGTH THREE*/ for (i in operators.indices) { for (j in operators.indices) { for (k in operators.indices) { for (l in operators.indices) { for (m in operators.indices) { // for (n in operators.indices) { // for (o in operators.indices) { val element = ArrayList<Operator>() element.add(operators[i]) element.add(operators[j]) element.add(operators[k]) element.add(operators[l]) element.add(operators[m]) // element.add(operators[n]) // element.add(operators[o]) results.add(element) } // } // } } } } } return results } enum class Operator(val alias: String) { PLUS("+"), MINUS("-"), MULTIPLY("x"), DIVIDE("/"), REVERSE("Reverse"), CONVERT("+/-"), SHIFT("<<"), INSERT("1"); } fun calculate(input: Int, operator: Operator): Int { return when(operator) { Operator.PLUS -> operatorPlus(input) Operator.MINUS-> operatorMinus(input) Operator.MULTIPLY -> operatorMultiply(input) Operator.REVERSE -> operatorReverse(input) Operator.CONVERT -> operatorConvert(input) Operator.SHIFT -> operatorShift(input) Operator.INSERT -> operatorInsert(input) else -> { 0 } } } fun chainCalculate(input: Int, operators: List<Operator>): Int { var result = input for (operator in operators) { result = calculate(result, operator) } return result } fun printGoal(operators: List<Operator>) { var result = "" for (operator in operators) { result += " ${operator.alias}" } println("Goal $MY_GOAL achieved with operators: $result") } var MY_MOVES: Int = 7 var MY_INIT: Int = 0 var MY_GOAL: Int = 136 var MY_OPERATORS: Array<Operator> = arrayOf(PLUS, MULTIPLY, REVERSE, INSERT) var MY_PLUS: Int = 2 var MY_MINUS: Int = -3 var MY_MULTIPLY: Int = 3 var MY_DIVIDER: Int = 2 // Goal 28 achieved with operators: + + << + + Reverse - fun main(args: Array<String>) { var result: Int var combinations = genOperatorsCombinations(MY_OPERATORS) for (operators in combinations) { result = chainCalculate(MY_INIT, operators) if (result == MY_GOAL) { printGoal(operators) break } } }
0
Kotlin
1
1
010d25e9d53b5b1d6355daa96b56071b82c28aae
3,830
android-architecture
Apache License 2.0
src/test/kotlin/dev/shtanko/algorithms/dp/LCSTest.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.dp import dev.shtanko.utils.Quintuple import java.util.stream.Stream import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.extension.ExtensionContext import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.Arguments import org.junit.jupiter.params.provider.ArgumentsProvider import org.junit.jupiter.params.provider.ArgumentsSource /** * The longest common subsequence test. */ abstract class LCSTest<out T : LCS>(private val strategy: T) { private class InputArgumentsProvider : ArgumentsProvider { override fun provideArguments(context: ExtensionContext?): Stream<out Arguments> = initialArgs.stream().map { (x: String, y: String, m: Int, n: Int, expected: Int) -> Arguments.of( x, y, m, n, expected, ) } private val initialArgs = listOf( Triple("AGGTAB", "GXTXAYB", 4), Triple("", "", 0), Triple("a", "a", 1), Triple("abcd", "ab", 2), ).map { Quintuple(it.first, it.second, it.first.length, it.second.length, it.third) } } @ParameterizedTest @ArgumentsSource(InputArgumentsProvider::class) fun `LCS test`(x: String, y: String, m: Int, n: Int, expected: Int) { val actual = strategy.perform(x, y, m, n) assertThat(actual).isEqualTo(expected) } } class LCSRecursiveTest : LCSTest<LCS>(LCSRecursive())
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,189
kotlab
Apache License 2.0
src/main/kotlin/com/hj/leetcode/kotlin/problem2404/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem2404 /** * LeetCode page: [2404. Most Frequent Even Element](https://leetcode.com/problems/most-frequent-even-element/); */ class Solution { /* Complexity: * Time O(N) and Space O(N) where N is the size of nums; */ fun mostFrequentEven(nums: IntArray): Int { val evenNumberFrequency = getEvenNumberFrequency(nums) return getMostFrequentEven(evenNumberFrequency) } private fun getEvenNumberFrequency(numbers: IntArray): Map<Int, Int> { val evenNumberFrequency = hashMapOf<Int, Int>() for (num in numbers) { if (num and 1 == 0) { evenNumberFrequency[num] = evenNumberFrequency.getOrDefault(num, 0) + 1 } } return evenNumberFrequency } private fun getMostFrequentEven(evenNumberFrequency: Map<Int, Int>): Int { var mostFrequentEven = -1 var mostFrequency = 0 for ((even, frequency) in evenNumberFrequency) { when { frequency > mostFrequency -> { mostFrequency = frequency mostFrequentEven = even } frequency == mostFrequency -> { mostFrequentEven = minOf(mostFrequentEven, even) } } } return mostFrequentEven } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
1,366
hj-leetcode-kotlin
Apache License 2.0
src/Day06.kt
lmoustak
573,003,221
false
{"Kotlin": 25890}
fun main() { fun part1(input: List<String>): Int { val chars = input[0].toCharArray() for (i in 3 until chars.size) { val charSet = setOf(chars[i - 3], chars[i - 2], chars[i - 1], chars[i]) if (charSet.size == 4) return i + 1 } return -1 } fun part2(input: List<String>): Int { val chars = input[0].toCharArray() val listOfChars = mutableListOf<Char>() for (i in 0 until 14) listOfChars.add(chars[i]) for (i in 14..chars.size) { val distinctCount = listOfChars.distinct().count() if (distinctCount == 14) return i if (i < chars.size) { listOfChars.removeAt(0) listOfChars.add(chars[i]) } } return -1 } val input = readInput("Day06") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
bd259af405b557ab7e6c27e55d3c419c54d9d867
899
aoc-2022-kotlin
Apache License 2.0
solver/src/commonMain/kotlin/org/hildan/sudoku/solver/techniques/PointingTuples.kt
joffrey-bion
9,559,943
false
{"Kotlin": 51198, "HTML": 187}
package org.hildan.sudoku.solver.techniques import org.hildan.sudoku.model.* /** * When the candidates for a digit in a box are all confined to a single line in that box, we know the digit for the * whole line must land in that box. Therefore, we can eliminate this digit from the candidates of other cells of the * line that are not in that box. */ object PointingTuples : Technique { override fun attemptOn(grid: Grid): List<PointingTupleStep> = ALL_DIGITS.flatMap { digit -> grid.findPointingTuples(digit) } private fun Grid.findPointingTuples(digit: Int): List<PointingTupleStep> = buildList { boxes.forEach { box -> val candidateCells = box.emptyCellsWithCandidate(digit) pointingTupleOrNull(box, digit, candidateCells) { rows[it.row] }?.let { add(it) } pointingTupleOrNull(box, digit, candidateCells) { cols[it.col] }?.let { add(it) } } } private inline fun pointingTupleOrNull( box: GridUnit, digit: Int, candidateCells: Set<Cell>, getLine: (Cell) -> GridUnit, ): PointingTupleStep? { val singleLine = candidateCells.mapTo(HashSet()) { getLine(it) }.singleOrNull() ?: return null val removals = candidateRemovals(box, singleLine, digit) if (removals.isEmpty()) { return null } return PointingTupleStep(box.id, singleLine.id, digit, candidateCells.mapToIndices(), removals) } private fun candidateRemovals(box: GridUnit, line: GridUnit, digit: Int): List<Action.RemoveCandidate> = line.cells .filter { it.isEmpty && it.box != box.id.index && digit in it.candidates } .map { Action.RemoveCandidate(digit, it.index) } } data class PointingTupleStep( val box: UnitId, val line: UnitId, val digit: Digit, val cells: Set<CellIndex>, override val actions: List<Action.RemoveCandidate>, ): Step { override val techniqueName: String = when (cells.size) { 2 -> "Pointing Pairs" 3 -> "Pointing Triples" else -> error("Cannot have a pointing tuple with more than 3 cells") } override val description: String get() = "" // TODO }
0
Kotlin
0
0
441fbb345afe89b28df9fe589944f40dbaccaec5
2,207
sudoku-solver
MIT License
2021/kotlin/src/main/kotlin/com/pietromaggi/aoc2021/day06/Day06.kt
pfmaggi
438,378,048
false
{"Kotlin": 113883, "Zig": 18220, "C": 7779, "Go": 4059, "CMake": 386, "Awk": 184}
/* * 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 com.pietromaggi.aoc2021.day06 import com.pietromaggi.aoc2021.readInput fun compute(input: List<String>, days: Int): Long { var fishArray = LongArray(9) input[0].split(",").map(String::toInt).map {fish -> fishArray[fish] = fishArray[fish] + 1} repeat(days) { val newGeneration = LongArray(9) for (idx in fishArray.indices) { if (idx == 0) { newGeneration[8] = fishArray[idx] newGeneration[6] = newGeneration[6] + fishArray[idx] } else { newGeneration[idx - 1] = newGeneration[idx - 1] + fishArray[idx] } } fishArray = newGeneration } return fishArray.sum() } fun main() { val input = readInput("Day06") println(compute(input, 80)) println(compute(input, 256)) }
0
Kotlin
0
0
7c4946b6a161fb08a02e10e99055a7168a3a795e
1,430
AdventOfCode
Apache License 2.0
src/main/kotlin/g2101_2200/s2170_minimum_operations_to_make_the_array_alternating/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2101_2200.s2170_minimum_operations_to_make_the_array_alternating // #Medium #Array #Hash_Table #Greedy #Counting // #2023_06_26_Time_531_ms_(100.00%)_Space_53.9_MB_(100.00%) class Solution { fun minimumOperations(nums: IntArray): Int { var maxOdd = 0 var maxEven = 0 var max = 0 val n = nums.size for (num in nums) { max = Math.max(max, num) } val even = IntArray(max + 1) val odd = IntArray(max + 1) for (i in 0 until n) { if (i % 2 == 0) { even[nums[i]]++ } else { odd[nums[i]]++ } } var t1 = 0 var t2 = 0 for (i in 0 until max + 1) { if (even[i] > maxEven) { maxEven = even[i] t1 = i } if (odd[i] > maxOdd) { maxOdd = odd[i] t2 = i } } val ans: Int if (t1 == t2) { var secondEven = 0 var secondOdd = 0 for (i in 0 until max + 1) { if (i != t1 && even[i] > secondEven) { secondEven = even[i] } if (i != t2 && odd[i] > secondOdd) { secondOdd = odd[i] } } ans = Math.min( n / 2 + n % 2 - maxEven + (n / 2 - secondOdd), n / 2 + n % 2 - secondEven + (n / 2 - maxOdd) ) } else { ans = n / 2 + n % 2 - maxEven + n / 2 - maxOdd } return ans } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,623
LeetCode-in-Kotlin
MIT License
solutions/aockt/y2022/Y2022D16.kt
Jadarma
624,153,848
false
{"Kotlin": 435090}
package aockt.y2022 import aockt.util.Graph import aockt.util.pathTo import aockt.util.search import io.github.jadarma.aockt.core.Solution object Y2022D16 : Solution { /** * A valve in the optimised volcano. * * @property index Numeric identifier of this valve, calculated as it's order in the lexicographic order of valves. * @property name The valve's original name, unused but useful for debugging. * @property flowRate How much pressure per minute this valve can release if open. * @property tunnels The cost to travel to and open a valve having the index the same as the position in the list. */ private data class Valve( val index: Int, val name: String, val flowRate: Int, val tunnels: List<Int>, ) /** * A minimalist bitset implementation for defining a set of up to sixteen [Valve]s. * * @property bits The value the bits are stored in. * In the binary representation, the N-th bit starting from the least significant is set if the valve with that * index belongs in the set this mask describes. */ @JvmInline private value class ValveMask(val bits: UShort) { /** Whether the mask contains the valve with this [index]. */ operator fun get(index: Int): Boolean = (1u shl index).toUShort() and bits != 0u.toUShort() /** Syntactic sugar for checking if the mask contains this [valve]. */ operator fun contains(valve: Valve): Boolean = this[valve.index] /** Returns a mask value identical to this one, but including or excluding the valve of an [index]. */ fun withValve(index: Int, isIncluded: Boolean = true): ValveMask { if (this[index] == isIncluded) return this val bitAtPosition = (1u shl index).toUShort() val correctedBits = when (isIncluded) { true -> bits or bitAtPosition false -> bits and bitAtPosition.inv() } return ValveMask(correctedBits) } } /** * A search state for exploring the volcano. * * @property timeLeft How many minutes are left to search. * @property lastValve What was the last opened valve. * @property releasedPressure The total pressure released up until this point. * @property openValves Which valves have already been opened. */ private data class State( val timeLeft: Int, val lastValve: Int, val releasedPressure: Int, val openValves: ValveMask, ) /** * Solver for a single player attempting to open volcano valves. * @param valves The list of valves this player has access to. */ private class VolcanoSolo(valves: List<Valve>) : Graph<State> { /** The total flow rate per minute if all of the [valves] would be open. */ private val maximumFlowRate = valves.sumOf { it.flowRate } /** Use an array for valves so that it can be indexed easily. */ private val valves: Array<Valve?> = Array(16) { null } init { require(valves.size <= 16) { "Your volcano is too big and would overheat the device." } valves.forEach { this.valves[it.index] = it } } /** * Computes all the possible decisions to take to produce new states starting from the current one. * - If no time left, stop here. * - If no valves can be opened (either because none left or not enough time to reach them), skip to the end. * - For all valid valve choices available, calculate the next state by traveling there. */ private fun neighbors(node: State): List<State> { if (node.timeLeft == 0) return emptyList() return valves .filterNotNull() .filter { it !in node.openValves } .map { next -> next.index to valves[node.lastValve]!!.tunnels[next.index] } .filter { it.second <= node.timeLeft } .ifEmpty { listOf(0 to node.timeLeft) } .map { (next, time) -> val flowRate = valves.filterNotNull().filter { it in node.openValves }.sumOf { it.flowRate } State( timeLeft = node.timeLeft - time, lastValve = next, releasedPressure = node.releasedPressure + flowRate * time, openValves = node.openValves.withValve(next), ) } } /** * Because we want to maximise the pressure released, the transition cost between two states is defined as the * total amount of pressure not released because of closed valves. */ private fun cost(from: State, to: State): Int = valves .filterNotNull() .filter { it in from.openValves } .sumOf(Valve::flowRate) .let { currentFlowRate -> maximumFlowRate - currentFlowRate } .times(from.timeLeft - to.timeLeft) override fun neighboursOf(node: State) = neighbors(node).map { next -> next to cost(node, next) } /** * Using Djikstra's algorithm, explore the volcano and find the maximum amount of pressure that can be released. * Unfortunately, due to "optimisations", the actual path to take is not returned, only the pressure value, * but it can be computed if you wanted to: `solution.path()!!.path.map { it.lastValve }`, and then convert the * map the valve indexes back to their names again. * * TODO: A possible optimisation is to find a heuristic function to speed up the search. * However, due to how the cost is calculated, initial attempts of a heuristic made it worse, because * estimation takes more than just "winging it". * * @param time How many minutes are available to explore. */ fun solve(time: Int): Int { val start = State(time, 0, 0, ValveMask(1u)) val solution = search(start) { it.timeLeft == 0 }.destination checkNotNull(solution) { "A solution must exist because time moves forwards." } return solution.releasedPressure } } /** * Solver for two players attempting to open volcano valves. * @param valves The list of all valves the players can split between themselves. */ private class VolcanoTeam(private val valves: List<Valve>) { init { require(valves.size <= 16) { "Your volcano is too big and would overheat the device." } } /** Divide the volcano into a smaller one using the [mask]. */ private fun partition(mask: ValveMask): VolcanoSolo = valves .filter { it in mask } .map { valve -> valve.copy(tunnels = valve.tunnels.mapIndexed { index, cost -> if (mask[index]) cost else -1 }) } .let(::VolcanoSolo) /** * Explore the volcano using two players and find the maximum amount of pressure that can be released. * Generates all possible partitions of the volcano, assigning a subset of valves to the first player and the * rest to the second, ensuring no overlaps. * Simulate all possibilities as a single player, then find the total best by adding the result of each one with * the result of its complement, and returning the maximum sum. * Again, because of optimisation, the actual path taken is not returned, though it could be determined in * theory. * * @param time How many minutes are available to explore. */ fun solve(time: Int): Int { val totalPartitions = (1u shl valves.size).dec().toUShort() val solutionCache: MutableMap<ValveMask, Int> = mutableMapOf() (0u..totalPartitions.toUInt()) .asSequence() .map { ValveMask((it shl 1).or(1u).toUShort()) } .forEach { solutionCache[it] = partition(it).solve(time) } return solutionCache.maxOf { (myValves, myPressure) -> val elephantValves = ValveMask(myValves.bits.inv() and totalPartitions or 1u) val elephantPressure = solutionCache.getValue(elephantValves) myPressure + elephantPressure } } } /** * Parses the [input] and returns the valves. * Instead of returning the actual graph of all the valves, returns an equivalent fully-connected graph that only * contains the valves that have a positive flow rate, with "virtual tunnels" to all other valves in the volcano, * with their cost adjusted to the minimum possible value for pathfinding in the real volcano, as well as the extra * minute required to open them. * * TODO: For computing the optimised valve graph, Floyd-Warshall would be nicer instead of searching from every * node, but for practical purposes it doesn't matter since the graphs are small enough not to have an impact * in performance. */ private fun parseInput(input: String): List<Valve> { val inputRegex = Regex("""^Valve ([A-Z]{2}) has flow rate=(\d+); tunnels? leads? to valves? ([A-Z, ]+)$""") data class RawValve(val name: String, val flowRate: Int, val tunnels: Map<String, Int>) val valves = input .lineSequence() .mapNotNull(inputRegex::matchEntire) .map(MatchResult::destructured) .associate { (name, flow, tunnel) -> name to RawValve( name, flow.toInt(), tunnel.split(", ").toSet().associateWith { 1 } ) } val unoptimisedVolcano = object : Graph<RawValve> { override fun neighboursOf(node: RawValve): List<Pair<RawValve, Int>> = valves .getValue(node.name) .tunnels.keys .map(valves::getValue) .map { it to 1 } } val importantValves = valves .filterValues { it.name == "AA" || it.flowRate > 0 } .map { it.value } .sortedBy { it.name } return importantValves .map { valve -> valve to unoptimisedVolcano.search(valve, goalFunction = { false }) } .map { (valve, search) -> Valve( index = importantValves.indexOf(valve), name = valve.name, flowRate = valve.flowRate, tunnels = run { val tunnelArray = IntArray(16) { -1 } importantValves .asSequence() .withIndex() .filterNot { it.value == valve || it.value.name == "AA" } .forEach { tunnelArray[it.index] = search.pathTo(it.value)!!.size } tunnelArray.toList() } ) } } override fun partOne(input: String) = parseInput(input).let(::VolcanoSolo).solve(30) override fun partTwo(input: String) = parseInput(input).let(::VolcanoTeam).solve(26) }
0
Kotlin
0
3
19773317d665dcb29c84e44fa1b35a6f6122a5fa
11,353
advent-of-code-kotlin-solutions
The Unlicense
src/main/kotlin/year2023/day19/Problem.kt
Ddxcv98
573,823,241
false
{"Kotlin": 154634}
package year2023.day19 import IProblem import substr import java.io.BufferedReader import java.util.Collections import java.util.Objects class Problem : IProblem { private val workflows = mutableMapOf<String, List<IRule>>() private val ratings = mutableListOf<Rating>() init { javaClass .getResourceAsStream("/2023/19.txt")!! .bufferedReader() .use { parseWorkflows(it) parseRatings(it) } } private fun parseWorkflows(br: BufferedReader) { while (true) { val line = br.readLine() if (line.isEmpty()) { break } val index = line.indexOf('{') val name = line.substring(0, index) val rules = line.substr(index + 1, -1).split(',') val workflow = mutableListOf<IRule>() for (rule in rules) { workflow.add(if (rule.contains(':')) Rule0(rule) else Rule1(rule)) } workflows[name] = workflow } } private fun parseRatings(br: BufferedReader) { while (true) { val line = br.readLine() ?: break val split = line.substr(1, -1).split(',') val x = split[0].split('=')[1].toInt() val m = split[1].split('=')[1].toInt() val a = split[2].split('=')[1].toInt() val s = split[3].split('=')[1].toInt() ratings.add(Rating(x, m, a, s)) } } private fun accepted(r: Rating): Boolean { var key = "in" while (key != "A" && key != "R") { key = workflows[key]!! .stream() .map { it.eval(r) } .filter(Objects::nonNull) .findFirst() .get() } return key == "A" } private fun dfs(key: String, bounds: Bounds): Set<Bounds> { if (key == "R") { return Collections.emptySet() } if (key == "A") { return Collections.singleton(bounds) } val rules = workflows[key]!! val set = mutableSetOf<Bounds>() var curr = bounds for (rule in rules) { if (rule is Rule0) { val (left, right) = curr.branch(rule) if (left.validate()) { set.addAll(dfs(rule.c, left)) } if (!right.validate()) { break } curr = right } else if (rule is Rule1) { set.addAll(dfs(rule.key, curr.copy())) } } return set } override fun part1(): Int { return ratings .stream() .filter(::accepted) .map { it.x + it.m + it.a + it.s } .reduce(0) { acc, x -> acc + x } } override fun part2(): Long { val intervals = dfs("in", Bounds(Pair(1, 4000), Pair(1, 4000), Pair(1, 4000),Pair(1, 4000))) return intervals.map(Bounds::combos).sum() } }
0
Kotlin
0
0
455bc8a69527c6c2f20362945b73bdee496ace41
3,085
advent-of-code
The Unlicense
src/main/kotlin/dev/shtanko/algorithms/leetcode/NumFactoredBinaryTrees.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 dev.shtanko.algorithms.MOD /** * 823. Binary Trees With Factors * @see <a href="https://leetcode.com/problems/binary-trees-with-factors">Source</a> */ fun interface NumFactoredBinaryTrees { operator fun invoke(arr: IntArray): Int } class NumFactoredBinaryTreesDFS : NumFactoredBinaryTrees { override fun invoke(arr: IntArray): Int { val set = arr.toSet() arr.sort() val dp = mutableMapOf<Int, Long>() fun dfs(a: Int): Long = dp.getOrPut(a) { 1L + arr.sumOf { if (a % it == 0 && set.contains(a / it)) { dfs(it) * dfs(a / it) } else { 0L } } } return (arr.sumOf { dfs(it) } % MOD).toInt() } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,417
kotlab
Apache License 2.0
src/main/kotlin/com/example/adventofcode2022/days/Day2.kt
matyig
575,497,931
false
{"Kotlin": 11004}
package com.example.adventofcode2022.days import org.springframework.stereotype.Component @Component class Day2 : Day { companion object { val scores = mapOf( // draw Pair('A', 'X') to 3 + 1, // rock-rock Pair('B', 'Y') to 3 + 2, // paper-paper Pair('C', 'Z') to 3 + 3, // scissor-scissor // you lose Pair('A', 'Z') to 0 + 3, // rock-scissor Pair('B', 'X') to 0 + 1, // paper-rock Pair('C', 'Y') to 0 + 2, // scissor-paper // you win Pair('A', 'Y') to 6 + 2, // rock-paper Pair('B', 'Z') to 6 + 3, // paper-scissor Pair('C', 'X') to 6 + 1, // scissor-rock ) val transformRules = mapOf( // you win Pair('A', 'Z') to Pair('A', 'Y'), // rock-paper Pair('B', 'Z') to Pair('B', 'Z'), // paper-scissor Pair('C', 'Z') to Pair('C', 'X'), // scissor-rock // you loose Pair('A', 'X') to Pair('A', 'Z'), // rock-scissor Pair('B', 'X') to Pair('B', 'X'), // paper-rock Pair('C', 'X') to Pair('C', 'Y'), // scissor-paper // draw Pair('A', 'Y') to Pair('A', 'X'), // rock-rock Pair('B', 'Y') to Pair('B', 'Y'), // paper-paper Pair('C', 'Y') to Pair('C', 'Z'), // scissor-scissor ) } fun List<String>.toCharPairList(): List<Pair<Char, Char>> = this.map { it.split(" ") } .filter { it.size == 2 && it[0].length == 1 && it[1].length == 1 } .map { Pair(it[0].first(), it[1].first())} fun List<Pair<Char, Char>>.toScores(): List<Int> = this.map { scores.getOrDefault(it, 0) } fun Pair<Char, Char>.transform() : Pair<Char, Char>? = transformRules.get(this) override fun part1(input: List<String>): Long = input.toCharPairList() .toScores() .sum() .toLong() override fun part2(input: List<String>): Long = input.toCharPairList() .mapNotNull { it.transform() } .toScores() .sum() .toLong() }
0
Kotlin
0
0
b34635978a9d6b4c622921d201965066fae2c8ad
2,180
adventofcode2022
MIT License
src/Day01.kt
wedrychowiczbarbara
573,185,235
false
null
fun main() { fun part1(input: List<String>): Int { var max=0 var suma=0 input.forEach{ if (it!="") suma+=it.toInt() else { if (suma > max) max = suma suma = 0 } } return max } fun part2(input: List<String>): Int { var maxThree = arrayListOf<Int>(0, 0, 0) var suma = 0 input.forEach { if (it != "") { suma =suma+ it.toInt() } else { if (maxThree.any{it<suma} ){ maxThree.add(suma) maxThree.sortDescending() maxThree.removeLast() } suma=0 } } return maxThree.sum() } val testInput = readInput("input1") println(part1(testInput)) println(part2(testInput)) }
0
Kotlin
0
0
04abc035c51649dffe1dde8a115d98640552a99d
938
AOC_2022_Kotlin
Apache License 2.0
src/Day10.kt
wgolyakov
572,463,468
false
null
import kotlin.math.absoluteValue fun main() { fun part1(input: List<String>): Int { var x = 1 var cycle = 0 var strengths = 0 for (line in input) { if (line == "noop") { cycle++ if ((cycle - 20) % 40 == 0) strengths += cycle * x } else { val a = line.substringAfter("addx ").toInt() cycle++ if ((cycle - 20) % 40 == 0) strengths += cycle * x cycle++ if ((cycle - 20) % 40 == 0) strengths += cycle * x x += a } } return strengths } fun part2(input: List<String>): String { var x = 1 var cycle = 0 val screen = List(6) { StringBuilder(".".repeat(40)) } for (line in input) { if (line == "noop") { val c = cycle % 40 if ((c - x).absoluteValue <= 1) screen[cycle / 40][c] = '#' cycle++ } else { val a = line.substringAfter("addx ").toInt() var c = cycle % 40 if ((c - x).absoluteValue <= 1) screen[cycle / 40][c] = '#' cycle++ c = cycle % 40 if ((c - x).absoluteValue <= 1) screen[cycle / 40][c] = '#' cycle++ x += a } } return screen.joinToString("\n") } val testInput = readInput("Day10_test") check(part1(testInput) == 13140) check(part2(testInput) == "##..##..##..##..##..##..##..##..##..##..\n" + "###...###...###...###...###...###...###.\n" + "####....####....####....####....####....\n" + "#####.....#####.....#####.....#####.....\n" + "######......######......######......####\n" + "#######.......#######.......#######....." ) val input = readInput("Day10") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
789a2a027ea57954301d7267a14e26e39bfbc3c7
1,567
advent-of-code-2022
Apache License 2.0
src/main/kotlin/design_patterns/Strategy.kt
DmitryTsyvtsyn
418,166,620
false
{"Kotlin": 223256}
package design_patterns /** * * Strategy is a behavioral design pattern used to define a family of algorithms, * * encapsulate each one and make them interchangeable * */ // encapsulates the filtering algorithm interface FoodFilterStrategy { fun filter(items: List<FoodEntity>): List<FoodEntity> } class OnlyChipsFilterStrategy : FoodFilterStrategy { override fun filter(items: List<FoodEntity>): List<FoodEntity> { return items.filter { it.category == "chips" } } } class OnlyChocolateFilterStrategy : FoodFilterStrategy { override fun filter(items: List<FoodEntity>): List<FoodEntity> { return items.filter { it.category == "chocolate" } } } class PriceFilterStrategy(private val price: Int) : FoodFilterStrategy { override fun filter(items: List<FoodEntity>): List<FoodEntity> { return items.filter { it.price >= price } } } class SearchWordFilterStrategy(private val search: String) : FoodFilterStrategy { override fun filter(items: List<FoodEntity>): List<FoodEntity> { return items.filter { it.title.contains(search, ignoreCase = true) } } } data class FoodEntity( val title: String, val price: Int, val category: String ) // FoodStore returns a list of food filtered by strategy class FoodStore(private var filterStrategy: FoodFilterStrategy) { // we can change strategy fun changeStrategy(strategy: FoodFilterStrategy) { filterStrategy = strategy } fun foodItems(): List<FoodEntity> { val foodItems = fetchFoodItems() return filterStrategy.filter(foodItems) } private fun fetchFoodItems() = listOf( FoodEntity( "Lays Potato Chips Fried Crab Flavor", 2, "chips" ), FoodEntity( "Lay's Potato Chips, Classic", 3, "chips" ), FoodEntity( "Dove Chocolate", 3, "chocolate" ), FoodEntity( "Ritter Sport Chocolate", 4, "chocolate" ) ) }
0
Kotlin
135
767
7ec0bf4f7b3767e10b9863499be3b622a8f47a5f
2,187
Kotlin-Algorithms-and-Design-Patterns
MIT License
src/Day01.kt
MerickBao
572,842,983
false
{"Kotlin": 28200}
fun main() { fun part1(input: List<String>): Int { var ans = 0 var now = 0 for (s in input) { if (s.equals("")) { ans = Math.max(ans, now) now = 0 } else { now += s.toInt() } } return Math.max(ans, now) } fun part2(input: List<String>): Int { val all = mutableListOf<Int>() var now = 0 for (s in input) { if (s.equals("")) { all.add(now) now = 0 } else { now += s.toInt() } } all.sort() var ans = 0 for (i in all.size - 1 downTo all.size - 3) { ans += all[i] } return ans } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 1) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
70a4a52aa5164f541a8dd544c2e3231436410f4b
1,024
aoc-2022-in-kotlin
Apache License 2.0
Kotlin/CountingSort.kt
argonautica
212,698,136
false
{"Java": 42011, "C++": 24846, "C#": 15801, "Python": 14547, "Kotlin": 11794, "C": 10528, "JavaScript": 9054, "Assembly": 5049, "Go": 3662, "Ruby": 1949, "Lua": 687, "Elixir": 589, "Rust": 447}
fun main(args : Array<String>) { val sorted = countingSort(intArrayOf(4, 4, -4, 1, 7, 9, 5, 37564, -54, 0, 100)) sorted.forEach { print("$it, ") } } * Kotlin Counting Sort that allows for negative numbers. */ fun countingSort(input:IntArray):IntArray{ if(input.size == 1){ return input } //max value in range val max= input.max() //min value in range val min = input.min() //the range of the values val len = max!! - min!! + 1 //Array for counting the number of occurrences of each value var count = IntArray(len) //Output array to store the sorted array var output = IntArray(input.size) input.forEach { value -> //Use Min to index the values into the correct spot in array var currentCount = count[value - min] currentCount++ count[value - min] = currentCount } //location in the output array var pointer = 0 for(j in count.indices){ //Uses For loop rather than foreach to preserve the location in the count array. for (i in 0..count[j]){ if(count[j] != 0) { output[pointer] = j+min pointer++ count[j]-- } } } return output }
4
Java
138
45
b9ebd2aadc6b59e5feba7d1fe9e0c6a036d33dba
1,261
sorting-algorithms
MIT License
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[102]二叉树的层序遍历.kt
maoqitian
175,940,000
false
{"Kotlin": 354268, "Java": 297740, "C++": 634}
import java.util.* import kotlin.collections.ArrayList //给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 (即逐层地,从左到右访问所有节点)。 // // // // 示例: //二叉树:[3,9,20,null,null,15,7], // // 3 // / \ // 9 20 // / \ // 15 7 // // // 返回其层次遍历结果: // // [ // [3], // [9,20], // [15,7] //] // // Related Topics 树 广度优先搜索 // 👍 718 👎 0 //leetcode submit region begin(Prohibit modification and deletion) /** * 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 levelOrder(root: TreeNode?): List<List<Int>> { //二叉树层序遍历 使用队列先进先出 val res : ArrayList<ArrayList<Int>> = ArrayList<ArrayList<Int>>() if(root == null) return res val queue = LinkedList<TreeNode>() queue.add(root) while (!queue.isEmpty()){ val count = queue.size val temp = ArrayList<Int>() for (i in 0 until count){ val node = queue.removeFirst() temp.add(node.`val`) if(node.left != null) queue.addLast(node.left) if(node.right != null) queue.addLast(node.right) } //保存一次遍历结果 res.add(temp) } return res } } //leetcode submit region end(Prohibit modification and deletion)
0
Kotlin
0
1
8a85996352a88bb9a8a6a2712dce3eac2e1c3463
1,591
MyLeetCode
Apache License 2.0
src/main/kotlin/com/ginsberg/advent2017/Day02.kt
tginsberg
112,672,087
false
null
/* * Copyright (c) 2017 by <NAME> */ package com.ginsberg.advent2017 /** * AoC 2017, Day 2 * * Problem Description: http://adventofcode.com/2017/day/2 * Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2017/day2/ */ class Day02(stringInput: List<String>) { private val input: List<List<Int>> = parseInput(stringInput) fun solvePart1(): Int = input .map { it.sorted() } .sumBy { it.last() - it.first() } fun solvePart2(): Int = input .map { findDivisiblePairForRow(it) } .sumBy { it.first / it.second } // Given a row, generate all possible Pair<Int,Int>, filter out // pairs matched with self, and filter down to the first one // that has a divisible pair. private fun findDivisiblePairForRow(row: List<Int>): Pair<Int, Int> = row .flatMap { x -> row.map { Pair(x, it) } } .filter { it.first != it.second } .first { it.first % it.second == 0 } private fun parseInput(s: List<String>): List<List<Int>> = s.map { it.split(Constants.WHITESPACE).map { it.toInt() } } }
0
Kotlin
0
15
a57219e75ff9412292319b71827b35023f709036
1,153
advent-2017-kotlin
MIT License
year2015/src/main/kotlin/net/olegg/aoc/year2015/day21/Day21.kt
0legg
110,665,187
false
{"Kotlin": 511989}
package net.olegg.aoc.year2015.day21 import net.olegg.aoc.someday.SomeDay import net.olegg.aoc.utils.Vector3D import net.olegg.aoc.utils.pairs import net.olegg.aoc.year2015.DayOf2015 /** * See [Year 2015, Day 21](https://adventofcode.com/2015/day/21) */ object Day21 : DayOf2015(21) { private const val HP = 100 private val BOSS = lines.map { it.substringAfterLast(": ").toInt() } private val WEAPONS = listOf( Vector3D(8, 4, 0), Vector3D(10, 5, 0), Vector3D(25, 6, 0), Vector3D(40, 7, 0), Vector3D(74, 8, 0), ) private val ARMOR = listOf( Vector3D(13, 0, 1), Vector3D(31, 0, 2), Vector3D(53, 0, 3), Vector3D(75, 0, 4), Vector3D(102, 0, 5), Vector3D(0, 0, 0), ) private val RINGS = listOf( Vector3D(25, 1, 0), Vector3D(50, 2, 0), Vector3D(100, 3, 0), Vector3D(20, 0, 1), Vector3D(40, 0, 2), Vector3D(80, 0, 3), Vector3D(0, 0, 0), ) private val RING_BUILDS = RINGS .pairs() .map { (left, right) -> left + right } + Vector3D(0, 0, 0) private val BUILDS = WEAPONS .flatMap { weapon -> ARMOR.map { armor -> weapon + armor } } .flatMap { set -> RING_BUILDS.map { ringBuild -> set + ringBuild } } .sortedBy { it.x } override fun first(): Any? { return BUILDS.first { (_, damage, armor) -> val my = (damage - BOSS[2]).coerceAtLeast(1) val his = (BOSS[1] - armor).coerceAtLeast(1) (BOSS[0] + my - 1) / my <= (HP + his - 1) / his }.x } override fun second(): Any? { return BUILDS.reversed().first { (_, damage, armor) -> val my = (damage - BOSS[2]).coerceAtLeast(1) val his = (BOSS[1] - armor).coerceAtLeast(1) (BOSS[0] + my - 1) / my > (HP + his - 1) / his }.x } } fun main() = SomeDay.mainify(Day21)
0
Kotlin
1
7
e4a356079eb3a7f616f4c710fe1dfe781fc78b1a
1,780
adventofcode
MIT License
src/main/kotlin/com/groundsfam/advent/y2022/d13/Day13.kt
agrounds
573,140,808
false
{"Kotlin": 281620, "Shell": 742}
package com.groundsfam.advent.y2022.d13 import com.groundsfam.advent.DATAPATH import com.groundsfam.advent.timed import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.int import kotlin.io.path.div import kotlin.io.path.useLines sealed class Packet data class PacketInt(val content: Int) : Packet() { override fun toString() = content.toString() } fun PacketInt.toList() = PacketList(listOf(this)) data class PacketList(val content: List<Packet>) : Packet() { override fun toString() = content.toString() } fun parsePacket(json: JsonElement): Packet = when (json) { is JsonPrimitive -> PacketInt(json.int) is JsonArray -> PacketList(json.map(::parsePacket)) else -> throw RuntimeException("Invalid packet: $json") } object PacketComparator : Comparator<Packet> { override fun compare(packetA: Packet?, packetB: Packet?): Int = when (packetA) { null -> if (packetB == null) 0 else 1 is PacketInt -> when (packetB) { null -> -1 is PacketInt -> packetA.content - packetB.content is PacketList -> compare(packetA.toList(), packetB) } is PacketList -> when (packetB) { null -> -1 is PacketInt -> compare(packetA, packetB.toList()) is PacketList -> packetA.content.indices.firstOrNull { i -> i < packetB.content.size && compare(packetA.content[i], packetB.content[i]) != 0 }.let { diffIdx -> if (diffIdx == null) packetA.content.size - packetB.content.size else compare(packetA.content[diffIdx], packetB.content[diffIdx]) } } } } val dividerPackets = listOf(2, 6).map { PacketList(listOf(PacketList(listOf(PacketInt(it))))) } fun main() = timed { val pairs = (DATAPATH / "2022/day13.txt").useLines { lines -> val linesList = lines.toList() (linesList.indices step 3).map { i -> listOf(i, i + 1) .map { parsePacket(Json.parseToJsonElement(linesList[it])) } .let { (a, b) -> a to b } } } pairs.mapIndexed { i, (a, b) -> if (PacketComparator.compare(a, b) <= 0) i + 1 else 0 } .sum() .also { println("Part one: $it") } pairs .flatMap { it.toList() } .let { it + dividerPackets } .sortedWith(PacketComparator) .let { sortedPackets -> dividerPackets.map { sortedPackets.indexOf(it) + 1 } } .let { (a, b) -> a * b } .also { println("Part two: $it") } }
0
Kotlin
0
1
c20e339e887b20ae6c209ab8360f24fb8d38bd2c
2,711
advent-of-code
MIT License
src/main/kotlin/day11/Day11.kt
cyril265
433,772,262
false
{"Kotlin": 39445, "Java": 4273}
package day11 import readToMatrix fun main() { println(part1(readInput())) println(part2(readInput())) } private fun readInput() = StateContainer( readToMatrix("day11.txt").map { row -> row.map { item -> Energy(item) }.toMutableList() } ) private fun part1(input: StateContainer): Int { (1..100).forEach { _ -> input.tick() } return input.flashedCount } private fun part2(input: StateContainer): Int { (1..1000).forEach { step -> if (input.tick()) { return step } } throw RuntimeException("No solution") } private data class StateContainer(val matrix: List<MutableList<Energy>>, var flashedCount: Int = 0) { fun tick(): Boolean { for ((rowIndex, row) in matrix.withIndex()) { for ((columnIndex, value) in row.withIndex()) { increaseEnergy(rowIndex, columnIndex) } } this.flashedCount += matrix.flatten().count { energy -> energy.flashed } val allFlashed = matrix.flatten().all { energy -> energy.flashed } resetFlashes() return allFlashed } private fun resetFlashes() { matrix.flatten().forEach { energy -> energy.flashed = false } } fun increaseEnergy(rowIndex: Int, columnIndex: Int) { val energy = get(rowIndex, columnIndex) ?: return if (energy.flashed) return energy.value = (energy.value + 1) % 10 if (energy.value == 0) { energy.flashed = true increaseEnergy(rowIndex + 1, columnIndex) increaseEnergy(rowIndex - 1, columnIndex) increaseEnergy(rowIndex, columnIndex + 1) increaseEnergy(rowIndex, columnIndex - 1) increaseEnergy(rowIndex + 1, columnIndex + 1) increaseEnergy(rowIndex - 1, columnIndex - 1) increaseEnergy(rowIndex + 1, columnIndex - 1) increaseEnergy(rowIndex - 1, columnIndex + 1) } } private fun get(rowIndex: Int, columnIndex: Int) = matrix.getOrNull(rowIndex)?.getOrNull(columnIndex) } private data class Energy(var value: Int, var flashed: Boolean = false)
0
Kotlin
0
0
1ceda91b8ef57b45ce4ac61541f7bc9d2eb17f7b
2,142
aoc2021
Apache License 2.0
2021/src/day10/day10.kt
scrubskip
160,313,272
false
{"Kotlin": 198319, "Python": 114888, "Dart": 86314}
package day10 import java.io.File fun main() { val input = File("src/day10", "day10input.txt").readLines() println(input.mapNotNull { getIllegalCharacter(it) }.sumOf { getScore(it) }) val scores = input.filter { getIllegalCharacter(it) == null } .map { scoreCompletionString(getCompletionString(it)) } println(scores) println(scores.sorted()[(scores.size - 1) / 2]) } private val CHAR_MAP: Map<Char, Char> = buildMap { put('(', ')') put('[', ']') put('{', '}') put('<', '>') } private val CLOSE_CHARS = listOf(')', ']', '}', '>') fun getIllegalCharacter(input: String): Char? { var openChars = ArrayDeque<Char>() for (char in input) { if (isClosedChar(char)) { // check the last open char if (openChars.size == 0) { // mismatched number return char } val lastOpenChar = openChars.removeLast() if (CHAR_MAP[lastOpenChar] != char) { return char } } if (isOpenChar(char)) { openChars.add(char) } } return null } fun getCompletionString(input: String): String { var openChars = ArrayDeque<Char>() for (char in input) { if (isClosedChar(char)) { // check the last open char if (openChars.size == 0) { throw Exception("Corrupted string") } val lastOpenChar = openChars.removeLast() if (CHAR_MAP[lastOpenChar] != char) { throw Exception("Corrupted string") } } if (isOpenChar(char)) { openChars.add(char) } } // now, go through the openChars, get the right closing chars in order return openChars.reversed().map { CHAR_MAP[it] }.joinToString(separator = "", postfix = "") } fun scoreCompletionString(input: String): Long { return input.toCharArray().fold(0) { acc, char -> CLOSE_CHARS.indexOf(char) + 1 + (acc * 5) } } fun isOpenChar(char: Char): Boolean { return listOf('(', '[', '{', '<').contains(char) } fun isClosedChar(char: Char): Boolean { return CLOSE_CHARS.contains(char) } fun getScore(char: Char): Int { return when (char) { ')' -> 3 ']' -> 57 '}' -> 1197 '>' -> 25137 else -> throw Exception("invalid char $char") } }
0
Kotlin
0
0
a5b7f69b43ad02b9356d19c15ce478866e6c38a1
2,401
adventofcode
Apache License 2.0
src/main/kotlin/Day10.kt
pavittr
317,532,861
false
null
import java.io.File import java.math.BigInteger import java.nio.charset.Charset fun main() { val testDocs = File("test/day10").readLines(Charset.defaultCharset()).map{it.toBigInteger()} val puzzles = File("puzzles/day10").readLines(Charset.defaultCharset()).map{it.toBigInteger()} val testEffectiveAdapters = testDocs.union(listOf(BigInteger.ZERO, testDocs.maxOrNull()!!.plus(BigInteger.valueOf(3) ?: BigInteger.valueOf(0)))).toList() val effectiveAdapters = puzzles.union(listOf(BigInteger.ZERO, puzzles.maxOrNull()!!.plus(BigInteger.valueOf(3) ?: BigInteger.valueOf(0)))).toList() println(testEffectiveAdapters.sorted().windowed(2,1).map { it.last() - it.first() }.groupBy { it }.mapValues { it.value.size }.values.reduce { acc, i -> acc *i }) println(testEffectiveAdapters.sorted().windowed(2,1).map { it.last() - it.first() }.joinToString("").split("3").filter { it.isNotEmpty() }.filter{it.length > 1}.map{if(it.length == 4) {BigInteger.valueOf(7)} else if (it.length == 3 ) {BigInteger.valueOf(4) } else {BigInteger.TWO} }.reduce{acc, i -> acc.multiply(i)}) println(effectiveAdapters.sorted().windowed(2,1).map { it.last() - it.first() }.groupBy { it }.mapValues { it.value.size }.values.reduce { acc, i -> acc *i }) println(effectiveAdapters.sorted().windowed(2,1).map { it.last() - it.first() }.joinToString("").split("3").filter { it.isNotEmpty() }.filter{it.length > 1}.map{if(it.length == 4) {BigInteger.valueOf(7)} else if (it.length == 3 ) {BigInteger.valueOf(4) } else {BigInteger.TWO} }.reduce{acc, i -> acc.multiply(i)}) }
0
Kotlin
0
0
3d8c83a7fa8f5a8d0f129c20038e80a829ed7d04
1,578
aoc2020
Apache License 2.0
src/Day01.kt
emmanueljohn1
572,809,704
false
{"Kotlin": 12720}
fun main() { fun getCalories(input: List<String>) = buildList { var currentSum = 0L for ((idx, value) in input.withIndex()) { if (value.isEmpty()) { add(currentSum) currentSum = 0 } else { currentSum += value.toLong() if (idx == input.size - 1) { add(currentSum) } } } } fun part1(input: List<String>): Long { val calories = getCalories(input) return calories.asSequence().sorted().drop(calories.size - 1).sum() } fun part2(input: List<String>): Long { val calories = getCalories(input) return calories.asSequence().sorted().drop(calories.size - 3).sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("inputs/Day01_test") println(part1(testInput)) println(part2(testInput)) println("----- Real input -------") val input = readInput("inputs/Day01") println(part1(input)) println(part2(input)) } // Output: // 24000 // 45000 // ----- Real input ------- // 67633 // 199628
0
Kotlin
0
0
154db2b1648c9d12f82aa00722209741b1de1e1b
1,174
advent22
Apache License 2.0
archive/src/main/kotlin/com/grappenmaker/aoc/year18/Day13.kt
770grappenmaker
434,645,245
false
{"Kotlin": 409647, "Python": 647}
package com.grappenmaker.aoc.year18 import com.grappenmaker.aoc.* fun PuzzleSet.day13() = puzzle(day = 13) { val parseGrid = inputLines.asCharGrid() data class CartData( val pos: Point, val direction: Direction, val happy: Boolean = true, val intersectionDirection: Int = -1 ) data class GameState(val carts: List<CartData>, val crashes: List<Point> = listOf()) val initialCarts = parseGrid.points.mapNotNull { p -> parseGrid[p].toDirectionOrNull()?.let { CartData(p, it) } } fun GameState.update(): GameState { val toMove = carts.sortedWith(compareBy<CartData> { it.pos.y }.thenBy { it.pos.x }).toMutableList() val newCrashes = crashes.toMutableList() toMove.mapInPlace { data -> val (pos, dir, interactable, intersectDir) = data if (!interactable) return@mapInPlace data val nextPos = pos + dir val crashed = toMove.withIndex().find { it.value.happy && it.value.pos == nextPos } if (crashed != null) { newCrashes += nextPos toMove[crashed.index] = toMove[crashed.index].copy(happy = false) } data.copy( pos = nextPos, direction = when(parseGrid[nextPos]) { '\\' -> dir.next(if (dir.isVertical) -1 else 1) '/' -> dir.next(if (dir.isHorizontal) -1 else 1) '+' -> dir.next(intersectDir) else -> dir }, happy = crashed == null, intersectionDirection = if (parseGrid[nextPos] == '+') ((intersectDir + 2) % 3) - 1 else intersectDir ) } return GameState(toMove, newCrashes) } fun seq() = generateSequence(GameState(initialCarts)) { it.update() } fun Point.format() = "$x,$y" partOne = seq().flatMap { it.crashes }.first().format() partTwo = seq().first { it.carts.count(CartData::happy) == 1 }.carts.single { it.happy }.pos.format() }
0
Kotlin
0
7
92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585
2,044
advent-of-code
The Unlicense
src/main/kotlin/day17.kt
bfrengley
318,716,410
false
null
package aoc2020.day17 import aoc2020.util.loadTextResource import kotlin.math.max import kotlin.math.min fun main(args: Array<String>) { val initialState = loadTextResource("/day17.txt").lines().flatMapIndexed { y, line -> line.mapIndexedNotNull { x, cell -> when (cell) { '#' -> Point(x, y, 0) else -> null } } }.toSet().let(State::new) println("Part 1: ${initialState.successors().drop(6).first().countActive()}") } val OFFSETS = sequence { for (xOff in -1..1) for (yOff in -1..1) for (zOff in -1..1) if (!(xOff == 0 && yOff == 0 && zOff == 0)) { yield(Point(xOff, yOff, zOff)) } }.toList() data class Point(val x: Int, val y: Int, val z: Int) { operator fun plus(p: Point) = Point(x + p.x, y + p.y, z + p.z) fun neighbours() = OFFSETS.map(this::plus) } data class State(val world: Set<Point>, val dims: Pair<Point, Point>) { fun countActive() = world.size private fun countLivingNeighbours(p: Point) = p.neighbours().count { it in world } fun tick(): State { val (low, high) = dims val nextState = mutableSetOf<Point>() for (x in (low.x - 1)..(high.x + 1)) for (y in (low.y - 1)..(high.y + 1)) for (z in (low.z - 1)..(high.z + 1)) { val p = Point(x, y, z) val livingNeighbours = countLivingNeighbours(p) if (p in world && livingNeighbours in 2..3 || p !in world && livingNeighbours == 3) { nextState.add(p) } } return State(nextState, dims(nextState)) } companion object { fun dims(world: Set<Point>): Pair<Point, Point> { if (world.isEmpty()) { throw IllegalArgumentException("world") } var minX = Int.MAX_VALUE var minY = Int.MAX_VALUE var minZ = Int.MAX_VALUE var maxX = Int.MIN_VALUE var maxY = Int.MIN_VALUE var maxZ = Int.MIN_VALUE for (p in world) { minX = min(p.x, minX) minY = min(p.y, minY) minZ = min(p.z, minZ) maxX = max(p.x, maxX) maxY = max(p.y, maxY) maxZ = max(p.z, maxZ) } return Pair(Point(minX, minY, minZ), Point(maxX, maxY, maxZ)) } fun new(world: Set<Point>) = State(world, dims(world)) } fun successors() = this.let { sequence { var s = it while (true) { yield(s) s = s.tick() } } } }
0
Kotlin
0
0
088628f585dc3315e51e6a671a7e662d4cb81af6
2,654
aoc2020
ISC License
src/main/java/tarehart/rlbot/math/Plane.kt
tarehart
101,009,961
true
{"Kotlin": 781564, "Python": 29120, "Batchfile": 324}
package tarehart.rlbot.math import tarehart.rlbot.math.vector.Vector3 import java.util.* class Plane(normal: Vector3, position: Vector3): Ray(position, normal) { val normal get() = this.direction private val constant get() = normal.dotProduct(position) /** * This is direction sensitive. Distance will be negative if the point is * behind the plane! */ fun distance(point: Vector3): Float { return (point - this.position).dotProduct(this.normal) } fun projectPoint(point: Vector3): Vector3 { return point - normal.scaled(distance(point)) } /** * Code taken from https://stackoverflow.com/a/38437831 * * Algorithm taken from http://geomalgorithms.com/a05-_intersect-1.html. See the * section 'Intersection of 2 Planes' and specifically the subsection * (A) Direct Linear Equation */ fun intersect(p2: Plane): Ray? { // the cross product gives us the direction of the line at the intersection // of the two planes, and gives us an easy way to check if the two planes // are parallel - the cross product will have zero magnitude val direction = normal.crossProduct(p2.normal) if (direction.isZero) { return null } // now find a point on the intersection. We use the 'Direct Linear Equation' // method described in the linked page, and we choose which coordinate // to set as zero by seeing which has the largest absolute value in the // directional vector val x = Math.abs(direction.x) val y = Math.abs(direction.y) val z = Math.abs(direction.z) val point: Vector3 point = if (z >= x && z >= y) { solveIntersectingPoint(2, 0, 1, this, p2) } else if (y >= z && y >= x){ solveIntersectingPoint(1, 2, 0, this, p2) } else { solveIntersectingPoint(0, 1, 2, this, p2) } return Ray(point, direction) } /** * This method helps finding a point on the intersection between two planes. * Depending on the orientation of the planes, the problem could solve for the * zero point on either the x, y or z axis */ private fun solveIntersectingPoint(zeroIndex: Int, aIndex: Int, bIndex: Int, p1: Plane, p2: Plane): Vector3 { val a1 = p1.normal[aIndex] val b1 = p1.normal[bIndex] val d1 = p1.constant val a2 = p2.normal[aIndex] val b2 = p2.normal[bIndex] val d2 = p2.constant val a0 = ((b2 * d1) - (b1 * d2)) / ((a1 * b2 - a2 * b1)) val b0 = ((a1 * d2) - (a2 * d1)) / ((a1 * b2 - a2 * b1)) val components = LinkedList<Pair<Int, Float>>() components.add(Pair(zeroIndex, 0F)) components.add(Pair(aIndex, a0)) components.add(Pair(bIndex, b0)) components.sortBy { pair -> pair.first } return Vector3(components[0].second, components[1].second, components[2].second) } }
0
Kotlin
7
10
8a5ba0ba751235e775d383c9796ee8fa966030b9
3,025
ReliefBot
MIT License
core/src/main/kotlin/com/acmerobotics/roadrunner/util/MathUtil.kt
henopied
242,858,073
true
{"Kotlin": 346152, "Java": 184}
package com.acmerobotics.roadrunner.util import kotlin.math.* /** * Various math utilities. */ object MathUtil { /** * Returns the real solutions to the quadratic [a]x^2 + [b]x + [c] = 0. */ @JvmStatic fun solveQuadratic(a: Double, b: Double, c: Double): DoubleArray { if (a epsilonEquals 0.0) { return doubleArrayOf(-c / b) } val disc = b * b - 4 * a * c return when { disc epsilonEquals 0.0 -> doubleArrayOf(-b / (2 * a)) disc > 0.0 -> doubleArrayOf( (-b + sqrt(disc)) / (2 * a), (-b - sqrt(disc)) / (2 * a) ) else -> doubleArrayOf() } } /** * Similar to Java cbrt, but implemented with kotlin math (preserves sign) */ @JvmStatic fun cbrt(x: Double) = sign(x) * abs(x).pow(1.0 / 3.0) /** * Returns real solutions to the cubic [a]x^3 + [b]x^2 + [c]x + [d] = 0 * [Reference](https://github.com/davidzof/wattzap/blob/a3065da/src/com/wattzap/model/power/Cubic.java#L125-L182) */ @JvmStatic fun solveCubic(a: Double, b: Double, c: Double, d: Double): DoubleArray { if (a epsilonEquals 0.0) { return solveQuadratic(b, c, d) } val a2 = b / a val a1 = c / a val a0 = d / a val lambda = a2 / 3.0 val Q = (3.0 * a1 - a2 * a2) / 9.0 val R = (9.0 * a1 * a2 - 27.0 * a0 - 2.0 * a2 * a2 * a2) / 54.0 val Q3 = Q * Q * Q val R2 = R * R val D = Q3 + R2 return when { D < 0.0 -> { // 3 unique reals val theta = acos(R / sqrt(-Q3)) val sqrtQ = sqrt(-Q) doubleArrayOf( 2.0 * sqrtQ * cos(theta / 3.0) - lambda, 2.0 * sqrtQ * cos((theta + 2.0 * PI) / 3.0) - lambda, 2.0 * sqrtQ * cos((theta + 4.0 * PI) / 3.0) - lambda ) } D > 0.0 -> { // 1 real val sqrtD = sqrt(D) val S = cbrt(R + sqrtD) val T = cbrt(R - sqrtD) doubleArrayOf(S + T - lambda) } else -> { // 2 unique (3 total) reals val cbrtR = cbrt(R) doubleArrayOf(2.0 * cbrtR - lambda, -cbrtR - lambda) } } } } const val EPSILON = 1e-6 infix fun Double.epsilonEquals(other: Double) = abs(this - other) < EPSILON
0
Kotlin
1
2
19d779986d174601e08dda636cb043b1dddd84d7
2,498
road-runner
MIT License
src/main/kotlin/days/aoc2022/Day25.kt
bjdupuis
435,570,912
false
{"Kotlin": 537037}
package days.aoc2022 import days.Day import kotlin.math.abs class Day25 : Day(2022, 25) { override fun partOne(): Any { return calculateSumInSnafu(inputList) } override fun partTwo(): Any { return 0 } fun calculateSumInSnafu(input: List<String>): String { val sum = input.sumOf { Snafu(it).toLong() } return sum.toSnafu().value } } class Snafu(val value: String) { fun toLong(): Long { var multiplier = 1L var total = 0L for (i in value.lastIndex downTo 0) { when (value[i]) { '2' -> total += 2 * multiplier '1' -> total += multiplier '-' -> total += multiplier * -1 '=' -> total += multiplier * -2 } multiplier *= 5L } return total } } fun Long.toSnafu(): Snafu { var multiplicand = 1L var maxForDigit = 0L while (maxForDigit + multiplicand * 2 < this) { maxForDigit += multiplicand * 2 multiplicand *= 5 } val sb = StringBuilder() var remainder = this while (multiplicand >= 1) { if (remainder > 0) { if (remainder > multiplicand + maxForDigit) { sb.append('2') remainder -= 2 * multiplicand } else if (remainder > maxForDigit) { sb.append('1') remainder -= multiplicand } else { sb.append('0') } } else if (remainder < 0) { if (abs(remainder) > multiplicand + maxForDigit) { sb.append('=') remainder += 2 * multiplicand } else if (abs(remainder) > maxForDigit) { sb.append('-') remainder += multiplicand } else { sb.append('0') } } else { sb.append('0') } multiplicand /= 5 maxForDigit -= multiplicand * 2 } return Snafu(sb.toString()) }
0
Kotlin
0
1
c692fb71811055c79d53f9b510fe58a6153a1397
2,025
Advent-Of-Code
Creative Commons Zero v1.0 Universal
2017/src/main/kotlin/Day22.kt
dlew
498,498,097
false
{"Kotlin": 331659, "TypeScript": 60083, "JavaScript": 262}
import grid.Direction import grid.Point import grid.Turn import utils.splitNewlines object Day22 { fun part1(input: String, iterations: Int): Int { val midpoint = (input.splitNewlines().size / 2) val infections = parse(input).toMutableSet() var carrier = Point(midpoint, midpoint) var direction = Direction.NORTH var infectionCount = 0 for (iteration in 0 until iterations) { // Step 1 val pointInfected = carrier in infections val turn = if (pointInfected) Turn.RIGHT else Turn.LEFT direction = direction.turn(turn) // Step 2 if (!pointInfected) { infections.add(carrier) infectionCount++ } else { infections.remove(carrier) } // Step 3 carrier = carrier.move(direction) } return infectionCount } fun part2(input: String, iterations: Int): Int { val midpoint = (input.splitNewlines().size / 2) val infections = parse(input).associate { it to State.INFECTED }.toMutableMap() var carrier = Point(midpoint, midpoint) var direction = Direction.NORTH var infectionCount = 0 for (iteration in 0 until iterations) { // Step 1 val pointState = infections[carrier] ?: State.CLEAN direction = when (pointState) { State.CLEAN -> direction.turn(Turn.LEFT) State.WEAKENED -> direction State.INFECTED -> direction.turn(Turn.RIGHT) State.FLAGGED -> direction.turn(Turn.LEFT).turn(Turn.LEFT) } // Step 2 when (pointState) { State.CLEAN -> infections[carrier] = State.WEAKENED State.WEAKENED -> { infections[carrier] = State.INFECTED infectionCount++ } State.INFECTED -> infections[carrier] = State.FLAGGED State.FLAGGED -> infections.remove(carrier) } // Step 3 carrier = carrier.move(direction) } return infectionCount } private enum class State { CLEAN, WEAKENED, INFECTED, FLAGGED } private fun parse(input: String): Set<Point> { val infections = mutableSetOf<Point>() input.splitNewlines().forEachIndexed { y, line -> line.forEachIndexed { x, char -> if (char == '#') { infections.add(Point(x = x, y = y)) } } } return infections } }
0
Kotlin
0
0
6972f6e3addae03ec1090b64fa1dcecac3bc275c
2,316
advent-of-code
MIT License
day05/src/Day05.kt
simonrules
491,302,880
false
{"Kotlin": 68645}
import java.io.File class Day05(path: String) { data class Line(val x1: Int, val y1: Int, val x2: Int, val y2:Int) private val regex = "(\\d+),(\\d+) -> (\\d+),(\\d+)".toRegex() private val lines = mutableListOf<Line>() private val size = 1000 private val map = IntArray(size * size) init { File(path).forEachLine { line -> var matchResult = regex.find(line) if (matchResult != null) { val (a, b, c, d) = matchResult.destructured val line = Line(a.toInt(), b.toInt(), c.toInt(), d.toInt()) lines.add(line) } } } private fun getMapAt(x: Int, y: Int): Int { return map[y * size + x] } private fun setMapAt(x: Int, y: Int, value: Int) { map[y * size + x] = value } private fun plotLine(line: Line, diagonals: Boolean) { if (line.x1 == line.x2) { if (line.y1 < line.y2) { for (y in line.y1..line.y2) { setMapAt(line.x1, y, getMapAt(line.x1, y) + 1) } } else { for (y in line.y2..line.y1) { setMapAt(line.x1, y, getMapAt(line.x1, y) + 1) } } } else if (line.y1 == line.y2) { if (line.x1 < line.x2) { for (x in line.x1..line.x2) { setMapAt(x, line.y1, getMapAt(x, line.y1) + 1) } } else { for (x in line.x2..line.x1) { setMapAt(x, line.y1, getMapAt(x, line.y1) + 1) } } } else if (diagonals) { // diagonal if (line.x1 < line.x2) { if (line.y1 < line.y2) { var y = line.y1 for (x in line.x1..line.x2) { setMapAt(x, y, getMapAt(x, y) + 1) y++ } } else { var y = line.y1 for (x in line.x1..line.x2) { setMapAt(x, y, getMapAt(x, y) + 1) y-- } } } else { if (line.y1 < line.y2) { var y = line.y2 for (x in line.x2..line.x1) { setMapAt(x, y, getMapAt(x, y) + 1) y-- } } else { var y = line.y2 for (x in line.x2..line.x1) { setMapAt(x, y, getMapAt(x, y) + 1) y++ } } } } } fun part1(): Int { lines.forEach { l -> plotLine(l, diagonals = false) } return map.count { it > 1 } } fun part2(): Int { lines.forEach { l -> plotLine(l, diagonals = true) } return map.count { it > 1 } } } fun main(args: Array<String>) { val aoc = Day05("day05/input.txt") //println(aoc.part1()) println(aoc.part2()) }
0
Kotlin
0
0
d9e4ae66e546f174bcf66b8bf3e7145bfab2f498
3,149
aoc2021
Apache License 2.0
src/Day08.kt
JohannaGudmandsen
573,090,573
false
{"Kotlin": 19316}
import java.io.File import kotlin.collections.* fun getViewingScore(height:Int, trees:List<Int>):Int{ var viewingScore = 0 for (tree in trees){ viewingScore++ if (tree >= height){ break; } } return viewingScore; } fun Day08() { val input = File("src/input/day08.txt").readLines() var forest = input.map { treeLine -> treeLine.map { tree -> Integer.parseInt("" + tree) }} var task1 = 0 var task2 = 0 for (i in 0..forest.size-1 step 1){ var treeLine = forest[i] for (j in 0..treeLine.size-1 step 1){ val treeHeight = treeLine[j] // Check right var treesToRight = treeLine.subList(j+1, treeLine.size) var viewingscoreRight = getViewingScore(treeHeight, treesToRight) // Check left var treesToLeft = treeLine.subList(0, j).reversed() var viewingscoreLeft = getViewingScore(treeHeight, treesToLeft) // Check down var treesToDown = forest.subList(i+1, forest.size).map { it -> it.get(j) } var viewingscoreDown = getViewingScore(treeHeight, treesToDown) // Check up var treesToUp = forest.subList(0, i).map { it -> it.get(j) }.reversed() var viewingscoreUp = getViewingScore(treeHeight, treesToUp) val visible = !treesToRight.any { it -> it >= treeHeight } || !treesToLeft.any { it -> it >= treeHeight } || !treesToUp.any { it -> it >= treeHeight } || !treesToDown.any { it -> it >= treeHeight } if (visible){ task1++ } var totalViewingScore = viewingscoreRight * viewingscoreLeft * viewingscoreDown * viewingscoreUp if (totalViewingScore > task2){ task2 = totalViewingScore } } } println("Day 8 Task 1: $task1") //1794 println("Day 8 Task 2: $task2") // 199272 }
0
Kotlin
0
1
21daaa4415bd20c14d67132e615971519211ab16
2,055
aoc-2022
Apache License 2.0
src/main/kotlin/org/domnikl/data_structures/BTree.kt
domnikl
231,452,742
false
null
package org.domnikl.data_structures class BTree<K : Comparable<K>, V> { private var root = Node<K, V>(0) var height = 0 private set var size = 0 private set fun isEmpty() = size == 0 operator fun get(key: K): V? { return search(root, key, height) } private fun search(tree: Node<K, V>?, key: K, height: Int): V? { val children = tree?.children if (height == 0) { children ?.firstOrNull { it?.key == key } ?.let { return it.value } } else { children?.forEachIndexed { j, c -> if (j + 1 == tree.size || key < children[j + 1]!!.key) { return search(c?.next, key, height - 1) } } } return null } operator fun set(key: K, value: V) { insert(root, key, value, height)?.let { splitRoot(it) } size++ } private fun splitRoot(newNode: Node<K, V>) { val newRoot = Node<K, V>(2) newRoot.children[0] = Entry(root.children[0]!!.key, null, root) newRoot.children[1] = Entry(newNode.children[0]!!.key, null, newNode) root = newRoot height++ } private fun insert(tree: Node<K, V>?, key: K, value: V, height: Int): Node<K, V>? { var j = 0 val newEntry = Entry(key, value) if (height == 0) { while (j < tree!!.size) { if (key < tree.children[j]!!.key) break j++ } } else { while (j < tree!!.size) { if (j + 1 == tree.size || key < tree.children[j + 1]!!.key) { val u = insert(tree.children[j++]!!.next, key, value, height - 1) ?: return null newEntry.key = u.children[0]!!.key newEntry.next = u break } j++ } } for (i in tree.size downTo j + 1) { tree.children[i] = tree.children[i - 1] } tree.children[j] = newEntry tree.size++ return if (tree.size < CHILDREN) null else split(tree) } private fun split(node: Node<K, V>): Node<K, V> { val movedChildren = CHILDREN / 2 val newNode = Node<K, V>(movedChildren) node.children.takeLast(movedChildren).forEachIndexed { i, child -> newNode.children[i] = child } node.size = CHILDREN - movedChildren return newNode } companion object { const val CHILDREN = 4 } private class Node<K, V>(var size: Int) { val children = arrayOfNulls<Entry<K, V>>(CHILDREN) } private class Entry<K, V>( var key: K, val value: V?, var next: Node<K, V>? = null ) }
5
Kotlin
3
13
3b2c191876e58415d8221e511e6151a8747d15dc
2,819
algorithms-and-data-structures
Apache License 2.0
AdventOfCodeDay06/src/nativeMain/kotlin/Day06.kt
bdlepla
451,510,571
false
{"Kotlin": 165771}
class Day06(private val lines:List<String>) { fun solvePart1():Long = simulate(80) fun solvePart1a():Long = simulateAlt(80) fun solvePart2():Long = simulate(256) fun solvePart2a():Long = simulateAlt(256) private fun simulateAlt(days:Int):Long { val fishPerDay = LongArray(9) .apply { lines.first().split(",") .map { it.toInt() }.forEach { this[it] += 1L } } repeat(days) { fishPerDay.rotateLeftInPlace() fishPerDay[6] += fishPerDay[8] } return fishPerDay.sum() } fun simulate(days:Int):Long { val initial = lines .first() .split(",") .map{it.toInt()} .groupBy{it} .map{kv -> kv.key to kv.value.count().toLong()} .toMap() return doSimulation(days, initial).values.sum() } private tailrec fun doSimulation(days:Int, fishMap:Map<Int,Long>):Map<Int,Long> { if (days == 0) return fishMap //println("") //println("$days left") //println("fishMap is $fishMap") val newFishCount = fishMap.getOrElse(0){ 0L } //println("newFishCount is $newFishCount") val newFish = if (newFishCount > 0) listOf(8 to newFishCount).toMap() else emptyMap() //println("NewFish is $newFish") val updatedFish = fishMap .map{(if (it.key == 0) 6 else it.key-1) to (if (it.key == 7 || it.key == 0) fishMap.getOrElse(0){0} + fishMap.getOrElse(7){0} else it.value) } .toMap() //println("updatedFish is $updatedFish") val keys = updatedFish.keys.toSet() + newFish.keys.toSet() val newFishMap = keys.associateWith { (updatedFish.getOrElse(it) { 0 } + newFish.getOrElse(it) { 0 }) } //println("newFishMap is $newFishMap") return doSimulation(days-1, newFishMap) } private fun LongArray.rotateLeftInPlace() { val leftMost = first() this.copyInto(this, startIndex = 1) this[this.lastIndex] = leftMost } }
0
Kotlin
0
0
1d60a1b3d0d60e0b3565263ca8d3bd5c229e2871
2,160
AdventOfCode2021
The Unlicense
src/main/kotlin/day01/Day01.kt
tiefenauer
727,712,214
false
{"Kotlin": 11843}
/** * --- Day 1: Trebuchet?! --- * Something is wrong with global snow production, and you've been selected to take a look. The Elves have even given you a map; on it, they've used stars to mark the top fifty locations that are likely to be having problems. * * You've been doing this long enough to know that to restore snow operations, you need to check all fifty stars by December 25th. * * Collect stars by solving puzzles. Two puzzles will be made available on each day in the Advent calendar; the second puzzle is unlocked when you complete the first. Each puzzle grants one star. Good luck! * * You try to ask why they can't just use a weather machine ("not powerful enough") and where they're even sending you ("the sky") and why your map looks mostly blank ("you sure ask a lot of questions") and hang on did you just say the sky ("of course, where do you think snow comes from") when you realize that the Elves are already loading you into a trebuchet ("please hold still, we need to strap you in"). * * As they're making the final adjustments, they discover that their calibration document (your puzzle input) has been amended by a very young Elf who was apparently just excited to show off her art skills. Consequently, the Elves are having trouble reading the values on the document. * * The newly-improved calibration document consists of lines of text; each line originally contained a specific calibration value that the Elves now need to recover. On each line, the calibration value can be found by combining the first digit and the last digit (in that order) to form a single two-digit number. * * For example: * * 1abc2 * pqr3stu8vwx * a1b2c3d4e5f * treb7uchet * In this example, the calibration values of these four lines are 12, 38, 15, and 77. Adding these together produces 142. * * Consider your entire calibration document. What is the sum of all of the calibration values? */ package day01 import readLines private val NUMBERS = listOf("one", "two", "three", "four", "five", "six", "seven", "eight", "nine") private val NUMBERS_TO_INT = NUMBERS.associateWith { NUMBERS.indexOf(it) + 1 } fun main() { val lines = "day01-2.txt".readLines() val part1 = lines.part1() println(part1) // 54708 val part2 = lines.part2() println(part2) // 54087 } private fun List<String>.part1() = sumOf { "${it.first { it.isDigit() }}${it.last { it.isDigit() }}".toInt() } private fun List<String>.part2() = sumOf { val first = it.findFirstNumber() val last = it.findLastNumber() "$first$last".toInt() } private fun String.findFirstNumber(): Int { val firstDigit = firstOrNull { it.isDigit() } val firstNumber = findNumbers().minByOrNull { indexOf(it) } if (firstNumber == null || firstDigit != null && indexOf(firstDigit) < indexOf(firstNumber)) { return "$firstDigit".toInt() } return NUMBERS_TO_INT[firstNumber]!! } private fun String.findLastNumber(): Int { val lastDigit = lastOrNull { it.isDigit() } val lastNumber = findNumbers().maxByOrNull { lastIndexOf(it) } if (lastNumber == null || lastDigit != null && lastIndexOf(lastDigit) > lastIndexOf(lastNumber)) { return "$lastDigit".toInt() } return NUMBERS_TO_INT[lastNumber]!! } private fun String.findNumbers() = NUMBERS.filter { contains(it) }
0
Kotlin
0
0
ffa90fbdaa779cfff956fab614c819274b793d04
3,326
adventofcode-2023
MIT License
src/main/kotlin/com/hj/leetcode/kotlin/problem2210/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem2210 /** * LeetCode page: [2210. Count Hills and Valleys in an Array](https://leetcode.com/problems/count-hills-and-valleys-in-an-array/); */ class Solution { private enum class LevelTrend { INCREASE, DECREASE, UNKNOWN } /* Complexity: * Time O(N) and Space O(1) where N is the size of nums; */ fun countHillValley(nums: IntArray): Int { var hillValleyCount = 0 var prevLevelTrend = LevelTrend.UNKNOWN for (index in 0 until nums.lastIndex) { val currLevelTrend = getLevelTrend(index, nums) if (isHillOrValley(currLevelTrend, prevLevelTrend)) hillValleyCount++ if (currLevelTrend != LevelTrend.UNKNOWN) prevLevelTrend = currLevelTrend } return hillValleyCount } private fun getLevelTrend(indexOfLevel: Int, levels: IntArray): LevelTrend { return when { levels[indexOfLevel] > levels[indexOfLevel + 1] -> LevelTrend.DECREASE levels[indexOfLevel] < levels[indexOfLevel + 1] -> LevelTrend.INCREASE else -> LevelTrend.UNKNOWN } } private fun isHillOrValley(currLevelTrend: LevelTrend, prevLevelTrend: LevelTrend): Boolean { return when (currLevelTrend) { LevelTrend.INCREASE -> prevLevelTrend == LevelTrend.DECREASE LevelTrend.DECREASE -> prevLevelTrend == LevelTrend.INCREASE LevelTrend.UNKNOWN -> false } } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
1,473
hj-leetcode-kotlin
Apache License 2.0
app/src/main/kotlin/day07/Day07.kt
StylianosGakis
434,004,245
false
{"Kotlin": 56380}
package day07 import common.InputRepo import common.readSessionCookie import common.solve import kotlin.math.absoluteValue fun main(args: Array<String>) { val day = 7 val input = InputRepo(args.readSessionCookie()).get(day = day) solve(day, input, ::solveDay07Part1, ::solveDay07Part2) } private fun List<String>.toCrabs(): List<Long> = first() .split(",") .map(String::toLong) fun solveDay07Part1(input: List<String>): Long { val crabPositions = input.toCrabs() return (crabPositions.minOrNull()!!..crabPositions.maxOrNull()!!).minOf { possiblePosition -> crabPositions.sumOf { crabPosition -> crabPosition distanceTo possiblePosition } } } private infix fun Long.distanceTo(other: Long): Long = (this - other).absoluteValue fun solveDay07Part2(input: List<String>): Long { val crabPositions = input.toCrabs() return (crabPositions.minOrNull()!!..crabPositions.maxOrNull()!!).minOf { possiblePosition -> crabPositions.sumOf { crabPosition -> crabPosition exponentialDistanceTo possiblePosition } } } private infix fun Long.exponentialDistanceTo( other: Long, ): Long = (0..this.distanceTo(other)).sum()
0
Kotlin
0
0
a2dad83d8c17a2e75dcd00651c5c6ae6691e881e
1,176
advent-of-code-2021
Apache License 2.0
src/main/kotlin/day03/Day03.kt
vitalir2
572,865,549
false
{"Kotlin": 89962}
package day03 import Challenge import split object Day03 : Challenge(3) { override fun part1(input: List<String>): Int { return input.sumOf(::calculatePriority) } override fun part2(input: List<String>): Int { return input.chunked(3) .sumOf { rucksacks -> val commonItem = rucksacks .drop(1) .fold(rucksacks.first().toSet()) { acc, rucksack -> acc.intersect(rucksack.toSet()) } .first() calculateItemPriority(commonItem) } } private fun calculatePriority(rucksack: String): Int { val (firstCompartment, secondCompartment) = rucksack.split(numberOfParts = 2) val commonItem = firstCompartment.toSet().intersect(secondCompartment.toSet()).first() return calculateItemPriority(commonItem) } private fun calculateItemPriority(item: Char): Int { return when { item.isLowerCase() -> item.code - 96 item.isUpperCase() -> item.code - 38 else -> error("Invalid item type") } } }
0
Kotlin
0
0
ceffb6d4488d3a0e82a45cab3cbc559a2060d8e6
1,116
AdventOfCode2022
Apache License 2.0
src/main/kotlin/leetcode/problem0051/NQueens.kt
ayukatawago
456,312,186
false
{"Kotlin": 266300, "Python": 1842}
package leetcode.problem0051 class NQueens { fun solveNQueens(n: Int): List<List<String>> { val answer = arrayListOf<List<String>>() val board = Array(n) { CharArray(n) { '.' } } solve(board, 0, answer) return answer } private fun solve(board: Array<CharArray>, row: Int, answer: ArrayList<List<String>>) { if (row == board.size) { answer.add(board.map { it.joinToString("") }) return } board[row].indices.forEach { column -> if (canPlace(board, row, column)) { board[row][column] = 'Q' solve(board, row + 1, answer) board[row][column] = '.' } } } private fun canPlace(board: Array<CharArray>, row: Int, column: Int): Boolean { if ('Q' in board[row]) { return false } if ('Q' in board.map { it[column] }) { return false } val leftDiagonal = (0 until row).mapNotNull { val diff = column - row if (it + diff >= 0 && it + diff <= board.lastIndex) board[it][it + diff] else null } if ('Q' in leftDiagonal) { return false } val rightDiagonal = (0 until row).mapNotNull { val sum = row + column if (it <= sum && sum - it <= board.lastIndex) board[it][sum - it] else null } if ('Q' in rightDiagonal) { return false } return true } }
0
Kotlin
0
0
f9602f2560a6c9102728ccbc5c1ff8fa421341b8
1,517
leetcode-kotlin
MIT License
src/Day05.kt
acrab
573,191,416
false
{"Kotlin": 52968}
import com.google.common.truth.Truth.assertThat fun main() { fun part1(input: List<String>): String { val (moves, initialCrates) = input.partition { line -> line.any { it.isDigit() } } //Build crates val crates = mutableListOf<MutableList<Char>>() for (pile in initialCrates) { crates.add( pile.split(",").reversed().map { it[0] }.toMutableList() ) } println("Initial state") println(crates) //do moves moves.forEach { val parts = it.split(" ") val toMove = parts[1].toInt() val from = crates[parts[3].toInt() - 1] val to = crates[parts[5].toInt() - 1] println("Moving $toMove from $from to $to") repeat(toMove) { to.add(from.removeLast()) } println(crates) } println("Final state") println(crates) return crates.map { it.last() }.joinToString(separator = "") } fun part2(input: List<String>): String { val (moves, initialCrates) = input.partition { line -> line.any { it.isDigit() } } //Build crates val crates = mutableListOf<MutableList<Char>>() for (pile in initialCrates) { crates.add( pile.split(",").reversed().map { it[0] }.toMutableList() ) } println("Initial state") println(crates) //do moves moves.forEach { val parts = it.split(" ") val toMove = parts[1].toInt() val from = crates[parts[3].toInt() - 1] val to = crates[parts[5].toInt() - 1] val movedCrates = from.takeLast(toMove) crates[parts[3].toInt() - 1] = from.take(from.size - toMove).toMutableList() to.addAll(movedCrates) println(crates) } println("Final state") println(crates) return crates.map { it.last() }.joinToString(separator = "") } val testInput = readInput("Day05_test") assertThat(part1(testInput)).isEqualTo("CMZ") val input = readInput("Day05") println(part1(input)) assertThat(part2(testInput)).isEqualTo("MCD") println(part2(input)) }
0
Kotlin
0
0
0be1409ceea72963f596e702327c5a875aca305c
2,262
aoc-2022
Apache License 2.0
2022/Day14.kt
amelentev
573,120,350
false
{"Kotlin": 87839}
fun main() { val input = readInput("Day14") val m = 1000 val n = 1000 val map = Array(n) { BooleanArray(m) } var maxy = 0 for (s in input) { val trace = s.split(" -> ").map { p -> p.split(',').map { it.toInt() } } fun range(a: Int, b: Int) = if (a <= b) a..b else b..a for ((p0, p1) in trace.zipWithNext()) { for (x in range(p0[0], p1[0])) { for (y in range(p0[1], p1[1])) { map[y][x] = true maxy = maxOf(maxy, y) } } } } val floor = maxy + 2 var res1 = 0 var res2 = 0 while (true) { var sandx = 500 var sandy = 0 if (map[sandy][sandx]) break while (sandy < floor - 1) { when { !map[sandy+1][sandx] -> sandy++ !map[sandy+1][sandx-1] -> { sandx-- sandy++ } !map[sandy+1][sandx+1] -> { sandx++ sandy++ } else -> { map[sandy][sandx] = true break } } } if (sandy > maxy && res1 == 0) { res1 = res2 } map[sandy][sandx] = true res2++ } println(res1) println(res2) }
0
Kotlin
0
0
a137d895472379f0f8cdea136f62c106e28747d5
1,404
advent-of-code-kotlin
Apache License 2.0
leetcode2/src/leetcode/SubtreeOfAnotherTree.kt
hewking
68,515,222
false
null
package leetcode import leetcode.structure.TreeNode /** * 572. 另一个树的子树 * https://leetcode-cn.com/problems/subtree-of-another-tree/ * @program: leetcode * @description: ${description} * @author: hewking * @create: 2019-05-17 09:42 * 给定两个非空二叉树 s 和 t,检验 s 中是否包含和 t 具有相同结构和节点值的子树。s 的一个子树包括 s 的一个节点和这个节点的所有子孙。s 也可以看做它自身的一棵子树。 * * 示例 1: * 给定的树 s: * * 3 * / \ * 4 5 * / \ * 1 2 * 给定的树 t: * * 4 * / \ * 1 2 * 返回 true,因为 t 与 s 的一个子树拥有相同的结构和节点值。 * * 示例 2: * 给定的树 s: * * 3 * / \ * 4 5 * / \ * 1 2 * / * 0 * 给定的树 t: * * 4 * / \ * 1 2 * 返回 false。 **/ object SubtreeOfAnotherTree{ @JvmStatic fun main(args : Array<String>) { } /** * 思路: * 1.非空 * 2.遍历s 的每个节点,如果相等则t节点也向下移动 */ fun isSubtree(s: TreeNode?, t: TreeNode?): Boolean { return if(isSameTree(s,t)) { return true } else { isSubtree(s?.left,t).or(isSubtree(s?.right,t)) } } // 局限性s [1,1] t[1] // fun isSubtree2(s : TreeNode?,t: TreeNode?) : Boolean { // // 都为Null // if (s == t) { // return true // } else if (s == null && t != null || s != null && t == null) { // return false // } // return if (s?.`val` != t?.`val`) { // isSubtree(s?.left,t).or(isSubtree(s?.right,t)) // } else { // isSubtree(s?.left,t?.left).and(isSubtree(s?.right,t?.right)) // } // } fun isSameTree(s: TreeNode? , t : TreeNode?) : Boolean{ // 都为Null if (s == t) { return true } else if (s == null && t != null || s != null && t == null) { return false } if (s?.`val` != t?.`val`) return false return isSameTree(s?.left,t?.left).and(isSameTree(s?.right,t?.right)) } }
0
Kotlin
0
0
a00a7aeff74e6beb67483d9a8ece9c1deae0267d
2,183
leetcode
MIT License
src/Day03.kt
aadityaguptaa
572,618,899
false
null
fun main() { fun part1(input: List<String>): Int { var score = 0; for(i in input.indices){ var len = input[i].length/2 var mp1 = mutableMapOf<Char, Int>() var mp2 = mutableMapOf<Char, Int>() for(j in 0 until len){ mp1[input[i][j]] = 1 } for(j in len until (input[i].length)){ if(mp1[input[i][j]] == 1){ var c = input[i][j].lowercaseChar() var x = c.code - 96 if(input[i][j].isUpperCase()){ x+=26 } score += x break } } } return score } fun part2(input: List<String>): Int { var score = 0; for(i in input.indices step 3){ var mp1 = mutableMapOf<Char, Int>() var mp2 = mutableMapOf<Char, Int>() for(j in 0 until input[i].length){ mp1[input[i][j]] = 1 } for(j in 0 until input[i+1].length){ mp2[input[i+1][j]] = 1 } for(j in 0 until (input[i+2].length)){ if(mp1[input[i+2][j]] == 1 && mp2[input[i+2][j]] == 1){ var c = input[i+2][j].lowercaseChar() var x = c.code - 96 if(input[i+2][j].isUpperCase()){ x+=26 } score += x break } } } return score } val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Python
2
10
d76ac48851a9b833fbbd3493a7730f7e0b365da8
1,709
advent-of-code-2022
Apache License 2.0
src/main/kotlin/dfa/dfaUtils.kt
rwwiv
161,536,383
false
{"Kotlin": 13029}
package dfa import kotlin.system.exitProcess fun prettyPrintDFA(input: DFA) { print("(states, ") println("${input.states.joinToString(",", "(", ")")})") print("(alpha, ") when { input.alpha.contains(' ') -> { println("())") } else -> { println("${input.alpha.joinToString(",", "(", ")")})") } } print("(trans-func, (") when { input.transFun.contains(Triple(" ", ' ', " ")) -> { println("()))") } else -> { for (i in 0..(input.transFun.size - 2)) { print(input.transFun[i].toList().joinToString(",", "(", ")")) print(",") } println("${input.transFun[input.transFun.size - 1].toList().joinToString(",", "(", ")")}))") } } println("(start, (${input.start}))") print("(final, ") println("${input.final.joinToString(",", "(", ")")})") } fun dfaMinAlgo(dfa: DFA): DFA { fun dfaRunFun(q: String, a: Char): String { dfa.transFun.forEachIndexed { index, triple -> if (triple.first == q) { if (triple.second == a) { return triple.third } } } return "" } fun finalAndNotFinal(p: String, q: String): Boolean { return ((dfa.final.contains(p) != dfa.final.contains(q))) } val distinct = mutableListOf<MutableList<Boolean>>() var equivSetList = mutableListOf<MutableSet<String>>() dfa.states.forEachIndexed { pIndex, s -> distinct.add(mutableListOf()) for (qIndex in 0..(pIndex - 1)) { distinct[pIndex].add(finalAndNotFinal(dfa.states[pIndex], dfa.states[qIndex])) } } val temp2DListComp = mutableListOf<MutableList<Boolean>>() var testBool: Boolean do { temp2DListComp.clear() distinct.forEachIndexed { mIndex, mutableList -> temp2DListComp.add(mutableListOf()) mutableList.forEachIndexed { bIndex, b -> temp2DListComp[mIndex].add(b) } } distinct.forEachIndexed { pIndex, mutableList -> distinct[pIndex].forEachIndexed { qIndex, b -> for (alpha in dfa.alpha) { val p = dfa.states[pIndex] val q = dfa.states[qIndex] var deltaPIndex = dfa.states.indexOf(dfaRunFun(p, alpha)) var deltaQIndex = dfa.states.indexOf(dfaRunFun(q, alpha)) if (deltaPIndex == deltaQIndex) continue if (deltaPIndex < deltaQIndex) { val oldDQI = deltaQIndex deltaQIndex = deltaPIndex deltaPIndex = oldDQI } if (distinct[deltaPIndex][deltaQIndex] && !distinct[pIndex][qIndex]) { distinct[pIndex][qIndex] = true } } } } testBool = (temp2DListComp != distinct) } while (testBool) distinct.forEachIndexed { pIndex, mutableList -> distinct[pIndex].forEachIndexed { qIndex, b -> if (!b) { equivSetList.add(mutableSetOf(dfa.states[pIndex], dfa.states[qIndex])) val tempSet = mutableSetOf<String>() equivSetList.forEachIndexed { sIndex, set -> when { set.contains(dfa.states[pIndex]) -> set.add(dfa.states[qIndex]) set.contains(dfa.states[qIndex]) -> set.add(dfa.states[pIndex]) else -> { tempSet.add(dfa.states[pIndex]) tempSet.add(dfa.states[qIndex]) } } } equivSetList.add(tempSet) } } } equivSetList = equivSetList.distinct().toMutableList() var newStates = dfa.states var newTransFun = dfa.transFun var newFinal = dfa.final for (set in equivSetList) { for (item in set) { if (dfa.states.contains(item)) { newStates[dfa.states.indexOf(item)] = set.toList().joinToString(",", "[", "]") } dfa.transFun.forEachIndexed { tIndex, triple -> if (triple.first == item) { newTransFun[tIndex] = Triple( set.toList().joinToString(",", "[", "]"), dfa.transFun[tIndex].second, dfa.transFun[tIndex].third ) } if (triple.third == item) { newTransFun[tIndex] = Triple( dfa.transFun[tIndex].first, dfa.transFun[tIndex].second, set.toList().joinToString(",", "[", "]") ) } } if (dfa.final.contains(item)) { newFinal[dfa.final.indexOf(item)] = set.toList().joinToString(",", "[", "]") } } } newStates = newStates.distinct().toMutableList() newTransFun = dfa.transFun.distinct().toMutableList() newFinal = dfa.final.distinct().toMutableList() return DFA(newStates, dfa.alpha, newTransFun, dfa.start, newFinal) }
0
Kotlin
0
0
13ae3efc52862ed96f08f33e957cb614903a168f
5,596
dfamin
MIT License
src/main/kotlin/_2019/Day4.kt
thebrightspark
227,161,060
false
{"Kotlin": 548420}
package _2019 import aocRun import java.util.stream.Stream import kotlin.streams.toList fun main() { aocRun(puzzleInput) { input -> return@aocRun getRangeStream(input) .filter { hasAscendingDigits(it) } .filter { hasAdjacentDigits(it) } .count() } aocRun(puzzleInput) { input -> val result = getRangeStream(input) .filter { hasAscendingDigits(it) } .filter { hasAdjacentDigitsDoubles(it) } .toList() // .count() repeat(20) { println(result.random()) } return@aocRun result.size } /*listOf("112233", "123444", "111122").forEach { println(it) println("\tAscending: ${hasAscendingDigits(it)}") println("\tAdjacent: ${hasAdjacentDigits(it)}") println("\tAdjacent Doubles: ${hasAdjacentDigitsDoubles(it)}") }*/ } private fun hasAscendingDigits(number: String): Boolean { (1 until number.length).forEach { i -> if (number[i].toString().toInt() < number[i - 1].toString().toInt()) return false } return true } private fun hasAdjacentDigits(number: String): Boolean { (1 until number.length).forEach { i -> if (number[i] == number[i - 1]) return true } return false } private fun hasAdjacentDigitsDoubles(number: String): Boolean { val adjacentCounts = mutableMapOf<Char, Int>() (1 until number.length).forEach { i -> if (number[i] == number[i - 1]) adjacentCounts.compute(number[i]) { _, v -> v?.plus(1) ?: 2 } } return adjacentCounts.containsValue(2) || adjacentCounts.isEmpty() } private fun getRangeStream(input: String): Stream<String> = input.split('-').let { (it[0].toInt()..it[1].toInt()).toSet().stream().map { v -> v.toString() } } private const val puzzleInput = "271973-785961"
0
Kotlin
0
0
ac62ce8aeaed065f8fbd11e30368bfe5d31b7033
1,865
AdventOfCode
Creative Commons Zero v1.0 Universal
src/day01/Day01.kt
voom
573,037,586
false
{"Kotlin": 12156}
package day01 import readInput /** * --- Day 1: Calorie Counting --- */ fun main() { fun groupByElf(input: List<String>) = input // group calories carried by each elf .fold<String, ArrayList<ArrayList<Int>>>(ArrayList()) { acc, s -> acc.apply { if (isEmpty()) add(arrayListOf()) if (s.isBlank()) { add(arrayListOf()) } else { last().add(s.toInt()) } } } fun part1(input: List<String>): Int = groupByElf(input) .maxOf { it.sum() } fun part2(input: List<String>): Int = groupByElf(input) .map { it.sum() } .sortedDescending() .take(3) .sum() // test if implementation meets criteria from the description, like: val testInput = readInput("day01/test_input") // test part1 check(part1(testInput) == 24000) // test part2 check(part2(testInput) == 45000) val input = readInput("day01/input") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
a8eb7f7b881d6643116ab8a29177d738d6946a75
1,090
aoc2022
Apache License 2.0
src/main/kotlin/sorting/MergeSort.kt
parmeshtoyou
470,239,301
false
{"Kotlin": 28087, "Java": 5414}
package sorting //sort the left half //sort the right half //merge both the half fun main() { val input = intArrayOf(23, 47, 81, -1, 95, 7, 14, 39, 55, 63, 74) val temp = IntArray(input.size) { -1 } println("before sorting") for (i in input) { println(i) } mergeSort(input, temp) println("after sorting") for (i in input) { println(i) } } fun mergeSort(input: IntArray, temp: IntArray) { val start = 0 val end = input.size - 1 mergeSortRec(input, temp, start, end) } fun mergeSortRec(input: IntArray, temp: IntArray, lowerBound: Int, upperBound: Int) { if (lowerBound == upperBound) { return } val mid = lowerBound + (upperBound - lowerBound) / 2 mergeSortRec(input, temp, lowerBound, mid) mergeSortRec(input, temp, mid + 1, upperBound) merge(input, temp, lowerBound, mid + 1, upperBound) } fun merge(input: IntArray, temp: IntArray, start: Int, middle: Int, upperBound: Int) { var j = 0 val mid = middle - 1 var highPtr = middle var lowPtr = start val size = upperBound - start + 1 while (lowPtr <= mid && highPtr <= upperBound) { if (input[lowPtr] < input[highPtr]) { temp[j++] = input[lowPtr++] } else { temp[j++] = input[highPtr++] } } while (lowPtr <= mid) { temp[j++] = input[lowPtr++] } while (highPtr <= upperBound) { temp[j++] = input[highPtr++] } for (k in 0 until size) { input[start + k] = temp[k] } }
0
Kotlin
0
0
aea9c82a6faebae741bd9b0f2c6ad3a930b60ef1
1,546
DSAPlaybook
Apache License 2.0
src/day23/Day23.kt
EndzeitBegins
573,569,126
false
{"Kotlin": 111428}
package day23 import day23.LookupDirection.* import readInput import readTestInput import kotlin.LazyThreadSafetyMode.NONE private data class ElfPosition(val x: Int, val y: Int) { val northernNeighbors by lazy(mode = NONE) { listOf( ElfPosition(x - 1, y - 1), ElfPosition(x, y - 1), ElfPosition(x + 1, y - 1), ) } val southernNeighbors by lazy(mode = NONE) { listOf( ElfPosition(x - 1, y + 1), ElfPosition(x, y + 1), ElfPosition(x + 1, y + 1), ) } val westernNeighbors by lazy(mode = NONE) { listOf( ElfPosition(x - 1, y - 1), ElfPosition(x - 1, y), ElfPosition(x - 1, y + 1), ) } val easternNeighbors by lazy(mode = NONE) { listOf( ElfPosition(x + 1, y - 1), ElfPosition(x + 1, y), ElfPosition(x + 1, y + 1), ) } } private fun ElfPosition.neighborPositionsTo(direction: LookupDirection) = when (direction) { NORTH -> northernNeighbors SOUTH -> southernNeighbors WEST -> westernNeighbors EAST -> easternNeighbors } private fun ElfPosition.hasNeighborTo(direction: LookupDirection, elfPositions: List<ElfPosition>): Boolean = neighborPositionsTo(direction).any { neighborPosition -> neighborPosition in elfPositions } private fun ElfPosition.hasNeighbor(elfPositions: List<ElfPosition>): Boolean = LookupDirection.values().any { direction -> hasNeighborTo(direction, elfPositions) } private fun List<String>.toElfPositions() = flatMapIndexed { y: Int, row: String -> row.mapIndexedNotNull { x, cell -> if (cell == '#') ElfPosition(x, y) else null } } private sealed interface Action { data class Stay(val elfPosition: ElfPosition) : Action data class Move(val from: ElfPosition, val to: ElfPosition) : Action } private fun List<ElfPosition>.diffuse(rounds: Int): Pair<List<ElfPosition>, Int> { val lookupOrder = listOf(NORTH, SOUTH, WEST, EAST) var elfPositions = this var roundsApplied = 0 while (roundsApplied < rounds) { val rotationIndex = roundsApplied % lookupOrder.size val roundLookupOrder = lookupOrder.drop(rotationIndex) + lookupOrder.take(rotationIndex) roundsApplied += 1 val (stayActions, moveActions) = calculateActionsToPropose(elfPositions, roundLookupOrder) if (stayActions.size == elfPositions.size) { break } elfPositions = executeActions(moveActions, stayActions) } return elfPositions to roundsApplied } private fun calculateActionsToPropose( elfPositions: List<ElfPosition>, lookupOrder: List<LookupDirection> ): Pair<List<Action.Stay>, List<Action.Move>> { val actions = elfPositions.map { elfPosition -> when { elfPosition.hasNeighbor(elfPositions) -> { lookupOrder .firstOrNull { direction -> !elfPosition.hasNeighborTo(direction, elfPositions) } ?.let { direction -> elfPosition.movingTo(direction) } ?: Action.Stay(elfPosition) } else -> Action.Stay(elfPosition) } } return actions.filterIsInstance<Action.Stay>() to actions.filterIsInstance<Action.Move>() } private fun executeActions( moveActions: List<Action.Move>, stayActions: List<Action.Stay> ): List<ElfPosition> { val positionsAfterMoveActions = moveActions .groupBy { move -> move.to } .flatMap { (_, movesToPosition) -> if (movesToPosition.size == 1) listOf(movesToPosition.single().to) else movesToPosition.map { it.from } } return stayActions.map { it.elfPosition } + positionsAfterMoveActions } private fun ElfPosition.movingTo(direction: LookupDirection): Action.Move = Action.Move( from = this, to = neighborPositionsTo(direction)[1] ) private enum class LookupDirection { NORTH, EAST, SOUTH, WEST } private fun List<ElfPosition>.determineEmptyGroundTiles(): Int { val elfPositions = this val minX = elfPositions.minOf { it.x } val maxX = elfPositions.maxOf { it.x } val minY = elfPositions.minOf { it.y } val maxY = elfPositions.maxOf { it.y } val area = (maxX - minX + 1) * (maxY - minY + 1) return area - elfPositions.size } private fun part1(input: List<String>): Int { val elfPositions = input.toElfPositions() val (finalElfPositions, _) = elfPositions.diffuse(rounds = 10) return finalElfPositions.determineEmptyGroundTiles() } private fun part2(input: List<String>): Int { val elfPositions = input.toElfPositions() val (_, roundsNeeded) = elfPositions.diffuse(rounds = Int.MAX_VALUE) return roundsNeeded } fun main() { // test if implementation meets criteria from the description, like: val testInput = readTestInput("Day23") check(part1(testInput) == 110) check(part2(testInput) == 20) val input = readInput("Day23") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
ebebdf13cfe58ae3e01c52686f2a715ace069dab
5,097
advent-of-code-kotlin-2022
Apache License 2.0
src/Day04.kt
Kanialdo
573,165,497
false
{"Kotlin": 15615}
import kotlin.math.max import kotlin.math.min fun main() { fun part1(input: List<String>): Int { return input.count { line -> val (a1, a2, b1, b2) = line.split(",").map { it.split("-").map { it.toInt() } }.flatten() if (a2 - a1 >= b2 - b1) { a1 <= b1 && b2 <= a2 } else { b1 <= a1 && a2 <= b2 } } } fun part2(input: List<String>): Int { return input.count { line -> val (a1, a2, b1, b2) = line.split(",").map { it.split("-").map { it.toInt() } }.flatten() min(a2, b2) - max(a1, b1) >= 0 } } 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
10a8550a0a85bd0a928970f8c7c5aafca2321a4b
842
advent-of-code-2022
Apache License 2.0
src/year2021/16/Day16.kt
Vladuken
573,128,337
false
{"Kotlin": 327524, "Python": 16475}
package year2021.`16` import readInput import utils.parseToLongRadix import utils.printlnDebug // region Models for task data class Packet( val header: Header, val packetType: PacketType, val packetValue: Long?, val subPackets: List<Packet>, ) { /** * Finds sum of this packet and its subpackets */ fun versionSum(): Long = header.version + subPackets.sumOf { it.versionSum() } /** * Calculate value for part 2 */ fun calculateValue(): Long { return when (packetType.id) { 0L -> subPackets.sumOf { it.calculateValue() } 1L -> subPackets.fold(1) { a, b -> a * b.calculateValue() } 2L -> subPackets.minOf { it.calculateValue() } 3L -> subPackets.maxOf { it.calculateValue() } 4L -> packetValue ?: error("") 5L -> 1L.takeIf { subPackets.first().calculateValue() > subPackets[1].calculateValue() } ?: 0 6L -> 1L.takeIf { subPackets.first().calculateValue() < subPackets[1].calculateValue() } ?: 0 7L -> 1L.takeIf { subPackets.first().calculateValue() == subPackets[1].calculateValue() } ?: 0 else -> error("IllegalState") } } class Builder { private var header: Header? = null private var _packetType: PacketType? = null val packetType: PacketType get() = _packetType ?: error("Illegal Impossible State") private var packetValue: String = "" private var subPackets: List<Packet> = emptyList() fun header(header: String) { this.header = Header(header.parseToLongRadix(2)) } fun packetType(packetType: String) { this._packetType = PacketType(packetType.parseToLongRadix(2)) } fun packetValue(packetValue: String) { this.packetValue += packetValue.drop(1) } fun subPackets(subPackets: List<Packet>) { this.subPackets = subPackets } fun build(): Packet { return Packet( header = header ?: error("header is null"), packetType = _packetType ?: error("packetType is null"), packetValue = packetValue.ifBlank { null }?.parseToLongRadix(2), subPackets = subPackets, ) } } } data class Header( val version: Long, ) data class PacketType( val id: Long, ) sealed class CurrentCalculatingThing { data object Header : CurrentCalculatingThing() data object PacketType : CurrentCalculatingThing() data object Datagram : CurrentCalculatingThing() data object LengthType : CurrentCalculatingThing() sealed class SubPacket : CurrentCalculatingThing() { data object Zero : SubPacket() data object One : SubPacket() } } // endregion // region Helper Methods private fun mapHexToBitArray(char: Char): List<Boolean> { val biteString = when (char) { '0' -> "0000" '1' -> "0001" '2' -> "0010" '3' -> "0011" '4' -> "0100" '5' -> "0101" '6' -> "0110" '7' -> "0111" '8' -> "1000" '9' -> "1001" 'A' -> "1010" 'B' -> "1011" 'C' -> "1100" 'D' -> "1101" 'E' -> "1110" 'F' -> "1111" else -> error("Illegal char: $char") } return biteString.map { when (it) { '1' -> true '0' -> false else -> error("Illegal state: $it") } } } // endregion private fun iterateAndCollectPackets( iterator: CharIterator, limit: Long = -1, ): List<Packet> { val resultList = mutableListOf<Packet>() var packetBuilder = Packet.Builder() var currentEvent: CurrentCalculatingThing = CurrentCalculatingThing.Header val buffer = StringBuilder("") var counterOfPackets = 0L while (iterator.hasNext() && counterOfPackets != limit) { val currentChar = iterator.next() buffer.append(currentChar) when (currentEvent) { CurrentCalculatingThing.Header -> { if (buffer.length == 3) { packetBuilder.header(buffer.toString()) buffer.clear() currentEvent = CurrentCalculatingThing.PacketType } } CurrentCalculatingThing.PacketType -> { if (buffer.length == 3) { packetBuilder.packetType(buffer.toString()) buffer.clear() currentEvent = when (packetBuilder.packetType.id) { 4L -> CurrentCalculatingThing.Datagram else -> CurrentCalculatingThing.LengthType } } } CurrentCalculatingThing.Datagram -> { if (buffer.length == 5) { when (buffer.first()) { '0' -> { packetBuilder.packetValue(buffer.toString()) currentEvent = CurrentCalculatingThing.Header counterOfPackets++ resultList.add(packetBuilder.build()) packetBuilder = Packet.Builder() buffer.clear() } '1' -> { packetBuilder.packetValue(buffer.toString()) buffer.clear() } else -> error("Illegal State") } } } CurrentCalculatingThing.LengthType -> { when (buffer.toString()) { "0" -> { currentEvent = CurrentCalculatingThing.SubPacket.Zero buffer.clear() } "1" -> { currentEvent = CurrentCalculatingThing.SubPacket.One buffer.clear() } else -> error("CurrentCalculatingThing.LengthType Illegal State") } } is CurrentCalculatingThing.SubPacket.Zero -> { if (buffer.length == 15) { val amountOfBitsForSubpackets = buffer.toString().parseToLongRadix(2) printlnDebug { "buffer = $buffer amountOfSubPackets=$amountOfBitsForSubpackets" } var collector = "" repeat(amountOfBitsForSubpackets.toInt()) { collector += iterator.next() } val packets = iterateAndCollectPackets(collector.iterator()) printlnDebug { "$packets" } packetBuilder.subPackets(packets) resultList.add(packetBuilder.build()) packetBuilder = Packet.Builder() currentEvent = CurrentCalculatingThing.Header counterOfPackets++ buffer.clear() } } is CurrentCalculatingThing.SubPacket.One -> { if (buffer.length == 11) { val amountOfSubpackets = buffer.toString().parseToLongRadix(2) printlnDebug { "buffer = $buffer amountOfSubPackets=$amountOfSubpackets" } val packets = iterateAndCollectPackets(iterator, amountOfSubpackets) printlnDebug { "$packets" } packetBuilder.subPackets(packets) resultList.add(packetBuilder.build()) packetBuilder = Packet.Builder() buffer.clear() currentEvent = CurrentCalculatingThing.Header counterOfPackets++ } } } } printlnDebug { "COUNTER OF PACKETS: $counterOfPackets" } return resultList } fun main() { fun part1(input: List<String>): Long { val output = input.first() .trimEnd('0') .map { mapHexToBitArray(it) } .flatten() val mappedBiteString = output.joinToString("") { if (it) "1" else "0" } printlnDebug { mappedBiteString } val mappedResult = iterateAndCollectPackets(mappedBiteString.iterator()) printlnDebug { "mappedResult$mappedResult" } return mappedResult.sumOf { it.versionSum() } } fun part2(input: List<String>): Long { val output = input.first() .trimEnd('0') .map { mapHexToBitArray(it) } .flatten() val mappedBiteString = output.joinToString("") { if (it) "1" else "0" } printlnDebug { mappedBiteString } val mappedResult = iterateAndCollectPackets(mappedBiteString.iterator()) printlnDebug { "mappedResult$mappedResult" } return mappedResult.sumOf { it.calculateValue() } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day16_test") val part1Test = part2(testInput) println(part1Test) check(part1Test == 54L) val input = readInput("Day16") val part1Result = part1(input) val part2Result = part2(input) println(part1Result) println(part2Result) check(part1Result == 993L) check(part2Result == 144595909277L) }
0
Kotlin
0
5
c0f36ec0e2ce5d65c35d408dd50ba2ac96363772
9,487
KotlinAdventOfCode
Apache License 2.0
kotlin/0343-integer-break.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}
/* * DP solution O(n^2) time and space */ class Solution { fun integerBreak(n: Int): Int { val cache = IntArray(n + 1) {-1} cache[1] = 1 for (num in 2..n) { cache[num] = if (num == n) 0 else num for (i in 1..num) { val res = cache[i] * cache[num - i] cache[num] = maxOf(cache[num], res) } } return cache[n] } } /* * DFS + memoization solution O(n^2) time and space */ class Solution { fun integerBreak(n: Int): Int { val cache = IntArray(n + 1) {-1} fun dfs(num: Int): Int { if (cache[num] != -1) return cache[num] cache[num] = if (num == n) 0 else num for (i in 1 until num) { val res = dfs(i) * dfs(num - i) cache[num] = maxOf(cache[num], res) } return cache[num] } return dfs(n) } } // Math solution O(n) time and O(1) space class Solution { fun integerBreak(n: Int): Int { if (n < 4) return n - 1 var res = 1 var n2 = n while (n2 > 4) { res *= 3 n2 -=3 } res *= n2 return res } } // Mathimatically solved O(1) class Solution { fun integerBreak(n: Int): Int { if (n < 4) return n - 1 var res = n / 3 var rem = n % 3 if (rem == 1) { rem = 4 res-- } else if (rem == 0) { rem = 1 } return (Math.pow(3.toDouble(), res.toDouble()) * rem).toInt() } }
337
JavaScript
2,004
4,367
0cf38f0d05cd76f9e96f08da22e063353af86224
1,614
leetcode
MIT License
src/net/sheltem/aoc/y2022/Day19.kt
jtheegarten
572,901,679
false
{"Kotlin": 178521}
package net.sheltem.aoc.y2022 import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.runBlocking import net.sheltem.common.mapParallel suspend fun main() { Day19().run() } class Day19 : Day<Int>(33, 3472) { override suspend fun part1(input: List<String>): Int = runBlocking(Dispatchers.Default) { input .map { it.toBlueprint() } .mapParallel { it.toMaxGeodes(robots = intArrayOf(1, 0, 0, 0)) } .mapIndexed { i, quality -> (i + 1) * quality } .sum() } override suspend fun part2(input: List<String>): Int = runBlocking(Dispatchers.Default) { input .map { it.toBlueprint() } .take(3) .mapParallel { it.toMaxGeodes(robots = intArrayOf(1, 0, 0, 0), time = 32) } .reduce { acc, i -> acc * i } } } private fun String.toBlueprint(): List<Robot> = Regex("\\d+") .findAll(this) .toList() .map { it.value.toInt() } .let { listOf(Robot(it[1]), Robot(it[2]), Robot(it[3], it[4]), Robot(it[5], 0, it[6])) } private fun List<Robot>.toMaxGeodes(resources: IntArray = IntArray(4), robots: IntArray = IntArray(4), time: Int = 24, maxGeodes: Int = 0): Int { if ((0 until time).sumOf { it } + robots[3] * time + resources[3] <= maxGeodes) return 0 if (time == 0) return robots[3] val maxPrices = listOf(maxOf { it.ore }, maxOf { it.clay }, maxOf { it.obsidian }, 9999) var currentResources: IntArray var currentRobots: IntArray var max = resources[3] + robots[3] * time var wait: Int for (i in indices.reversed()) { // always try building the higher value robots first if (robots[i] >= maxPrices[i]) continue if (i == 2 && robots[1] == 0) continue if (i == 3 && robots[2] == 0) continue wait = this[i].resourceWait(resources, robots) + 1 if (time - wait < 1) continue currentResources = resources.clone() currentRobots = robots.clone() for (j in resources.indices) currentResources[j] += robots[j] * wait currentResources[0] -= this[i].ore currentResources[1] -= this[i].clay currentResources[2] -= this[i].obsidian currentRobots[i]++ max = max.coerceAtLeast(this.toMaxGeodes(currentResources, currentRobots, time - wait, max)) } return max } private data class Robot(val ore: Int = 0, val clay: Int = 0, val obsidian: Int = 0) { fun resourceWait(resources: IntArray, robots: IntArray): Int { val costs = listOf(ore, clay, obsidian) var maxTime = 0 for (i in costs.indices) { if (costs[i] == 0) continue if (costs[i] > 0 && robots[i] == 0) return 9999 maxTime = maxTime.coerceAtLeast((costs[i] - resources[i] - 1 + robots[i]) / robots[i]) } return maxTime } }
0
Kotlin
0
0
ac280f156c284c23565fba5810483dd1cd8a931f
2,843
aoc
Apache License 2.0
src/main/kotlin/g1701_1800/s1735_count_ways_to_make_array_with_product/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1701_1800.s1735_count_ways_to_make_array_with_product // #Hard #Array #Dynamic_Programming #Math #2023_06_16_Time_394_ms_(100.00%)_Space_50.6_MB_(100.00%) @Suppress("NAME_SHADOWING") class Solution { private lateinit var tri: Array<LongArray> private var primes: List<Int>? = null fun waysToFillArray(queries: Array<IntArray>): IntArray { val len: Int = queries.size val res = IntArray(len) primes = getPrimes(100) tri = getTri(10015, 15) for (i in 0 until len) { res[i] = calculate(queries[i][0], queries[i][1]) } return res } private fun getPrimes(limit: Int): List<Int> { val notPrime = BooleanArray(limit + 1) val res: MutableList<Int> = ArrayList() for (i in 2..limit) { if (!notPrime[i]) { res.add(i) var j: Int = i * i while (j <= limit) { notPrime[j] = true j += i } } } return res } private fun getTri(m: Int, n: Int): Array<LongArray> { val res: Array<LongArray> = Array(m + 1) { LongArray(n + 1) } for (i in 0..m) { res[i][0] = 1 for (j in 1..Math.min(n, i)) { res[i][j] = (res[i - 1][j - 1] + res[i - 1][j]) % MOD } } return res } private fun calculate(n: Int, target: Int): Int { var target: Int = target var res: Long = 1 for (prime: Int in primes!!) { if (prime > target) { break } var cnt = 0 while (target % prime == 0) { cnt++ target /= prime } res = (res * tri[cnt + n - 1][cnt]) % MOD } return if (target > 1) (res * n % MOD).toInt() else res.toInt() } companion object { private val MOD: Int = 1000000007 } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,982
LeetCode-in-Kotlin
MIT License
src/main/kotlin/endredeak/aoc2023/Day15.kt
edeak
725,919,562
false
{"Kotlin": 26575}
package endredeak.aoc2023 fun main() { solve("Lens Library") { val input = text.replace("\n", "").split(",") fun String.hash(): Int { var current = 0 forEach { c -> current += c.code current *= 17 current %= 256 } return current } part1(505459) { input.sumOf { it.hash() } } data class Lens(val label: String, var focal: Int) part2(228508) { val boxes = (0..255).associateWith { mutableListOf<Lens>() }.toMutableMap() input.forEach { step -> if (step.contains("-")) { step.replace("-", "") .let { label -> boxes[label.hash()]!!.removeIf { it.label == label } } } if (step.contains("=")) { step.split("=") .let { (a, b) -> a to b.toInt() } .let { (label, focal) -> boxes[label.hash()]!! .let { box -> box.singleOrNull { it.label == label } ?.apply { this.focal = focal } ?: box.add(Lens(label, focal)) } } } } boxes.flatMap { (box, lenses) -> lenses.mapIndexed { i, l -> (box + 1) * (i + 1) * l.focal } }.sum() } } }
0
Kotlin
0
0
92c684c42c8934e83ded7881da340222ff11e338
1,611
AdventOfCode2023
Do What The F*ck You Want To Public License
src/main/kotlin/09-aug.kt
aladine
276,334,792
false
{"C++": 70308, "Kotlin": 53152, "Java": 10020, "Makefile": 511}
import java.util.* typealias Pii = Pair<Int, Int> class Solution09Aug{ fun orangesRotting(grid: Array<IntArray>): Int { var res = 0 var totalFresh = 0 val q: Queue<Pii> = LinkedList<Pii>() //val queue = LinkedList<IntArray>() val n= grid.size val m = grid[0].size for (i in 0 until n) { for (j in 0 until m) { when(grid[i][j]){ 1 -> ++totalFresh 2 -> q.offer(i to j) } } } // if there is no rotten orange, we can return if (q.isEmpty() ) return if (totalFresh > 0) -1 else 0 while (q.isNotEmpty()){ var hasChanges = false // indicate there is a change in this round repeat(q.size) { val o = q.poll() // check all the adjacent oranges for ((i, j) in dirs) { val x = o.first + i val y = o.second + j if (isValid(x, n, y, m) && grid[x][y] == 1) { grid[x][y] = 2 q.offer(x to y) --totalFresh hasChanges = true } } } if(hasChanges) res++ } return if (totalFresh>0) -1 else res } private fun isValid(x: Int, n: Int, y: Int, m: Int) = (x in 0 until n) && (y in 0 until m) companion object { val dirs = listOf(Pair(0,-1),Pair(0,1),Pair(-1,0),Pair(1,0)) // val directions = arrayOf(intArrayOf(0, 1), intArrayOf(0, -1), intArrayOf(1, 0), intArrayOf(-1, 0)) } }
0
C++
1
1
54b7f625f6c4828a72629068d78204514937b2a9
1,676
awesome-leetcode
Apache License 2.0
src/test/kotlin/nl/dirkgroot/adventofcode/year2022/Day08Test.kt
dirkgroot
317,968,017
false
{"Kotlin": 187862}
package nl.dirkgroot.adventofcode.year2022 import io.kotest.core.spec.style.StringSpec import io.kotest.matchers.shouldBe import nl.dirkgroot.adventofcode.util.input import nl.dirkgroot.adventofcode.util.invokedWith private fun solution1(input: String): Int { val grid = createGrid(input) val width = grid[0].size val height = grid.size val visibility = List(height) { BooleanArray(width) { false } } for (y in grid.indices) { var maxHeight = -1 for (x in grid[y].indices) { if (grid[y][x] > maxHeight) { maxHeight = grid[y][x] visibility[y][x] = true } } } for (y in grid.indices) { var maxHeight = -1 for (x in grid[y].indices.reversed()) { if (grid[y][x] > maxHeight) { maxHeight = grid[y][x] visibility[y][x] = true } } } for (x in grid[0].indices) { var maxHeight = -1 for (y in grid.indices) { if (grid[y][x] > maxHeight) { maxHeight = grid[y][x] visibility[y][x] = true } } } extracted(grid, visibility) return visibility.asSequence().flatMap { it.asSequence() }.count { it } } private fun extracted(grid: List<IntArray>, visibility: List<BooleanArray>) { for (x in grid[0].indices) { var maxHeight = -1 for (y in grid.indices.reversed()) { if (grid[y][x] > maxHeight) { maxHeight = grid[y][x] visibility[y][x] = true } } } } private fun solution2(input: String): Int { val grid = createGrid(input) return grid.flatMapIndexed { y, row -> row.indices.map { x -> score(grid, y, x) } } .max() } private fun createGrid(input: String) = input.lineSequence().map { it.map { c -> c - '0' }.toIntArray() }.toList() private fun score(grid: List<IntArray>, y: Int, x: Int): Int { var n = 0 var e = 0 var s = 0 var w = 0 for (i in (x - 1) downTo 0 step 1) { w++ if (grid[y][i] >= grid[y][x]) break } for (i in (x + 1) until grid[0].size) { e++ if (grid[y][i] >= grid[y][x]) break } for (i in (y - 1) downTo 0) { n++ if (grid[i][x] >= grid[y][x]) break } for (i in (y + 1) until grid.size) { s++ if (grid[i][x] >= grid[y][x]) break } return n * e * s * w } //===============================================================================================\\ private const val YEAR = 2022 private const val DAY = 8 class Day08Test : StringSpec({ "example part 1" { ::solution1 invokedWith exampleInput shouldBe 21 } "part 1 solution" { ::solution1 invokedWith input(YEAR, DAY) shouldBe 1849 } "example part 2" { ::solution2 invokedWith exampleInput shouldBe 8 } "part 2 solution" { ::solution2 invokedWith input(YEAR, DAY) shouldBe 201600 } }) private val exampleInput = """ 30373 25512 65332 33549 35390 """.trimIndent()
1
Kotlin
1
1
ffdffedc8659aa3deea3216d6a9a1fd4e02ec128
3,149
adventofcode-kotlin
MIT License
solutions/src/main/kotlin/fr/triozer/aoc/y2022/Day04.kt
triozer
573,964,813
false
{"Kotlin": 16632, "Shell": 3355, "JavaScript": 1716}
package fr.triozer.aoc.y2022 import fr.triozer.aoc.utils.readInput // #region part1 private fun part1(input: List<String>) = input.count { val (start1, end1, start2, end2) = it .split(",") .flatMap { pair -> pair.split("-").map { n -> n.toInt() } } val (start, end) = start1..end1 to start2..end2 start.toList().containsAll(end.toList()) || end.toList().containsAll(start.toList()) } // #endregion part1 // #region part2 private fun part2(input: List<String>) = input.count { val (start1, end1, start2, end2) = it .split(",") .flatMap { pair -> pair.split("-").map { n -> n.toInt() } } (start1 in start2..end2) || (end1 in start2..end2) || (start2 in start1..end1) || (end2 in start1..end1) } // #endregion part2 private fun main() { val testInput = readInput(2022, 4, "test") check(part1(testInput) == 2) check(part2(testInput) == 4) println("Checks passed ✅") val input = readInput(2022, 4, "input") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
a9f47fa0f749a40e9667295ea8a4023045793ac1
1,090
advent-of-code
Apache License 2.0
src/main/kotlin/Classify.kt
fcruzel
183,215,777
false
{"Kotlin": 17006, "Java": 6293, "Assembly": 154}
import kotlin.math.ln enum class Classification(val sym: String) { TROLL("T"), NOT_TROLL("nT"); } fun classify( corpus: List<String>, learnT: LearnInfo, learnNT: LearnInfo ): List<Classification> { val classification = ArrayList<Classification>() val probT = learnT.corpusSize.toDouble() / (learnT.corpusSize + learnNT.corpusSize) val probNT = learnNT.corpusSize.toDouble() / (learnT.corpusSize + learnNT.corpusSize) for ((i, tweet) in corpus.withIndex()) { print("${(i + 1) * 100 / corpus.size} %\r") // estimate the probability of the line to be troll or not troll val jointProbT = jointProb(tweet, learnT.frequencies) + ln(probT) val jointProbNT = jointProb(tweet, learnNT.frequencies) + ln(probNT) // save to respective file if (jointProbT > jointProbNT) { classification.add(Classification.TROLL) } else { classification.add(Classification.NOT_TROLL) } } return classification } fun jointProb(tweet: String, learn: List<Word>): Double { val words: List<String> = makeTokens(tweet) var prob = 0.0 for (word in words) { val found = learn.find { it.word == word } prob += found?.prob ?: learn.find { it.word == "<UNK>" }!!.prob } return prob }
0
Kotlin
0
0
ecf073f58ff077064b6fc3e021d1f5b54db128b0
1,318
pln-iaa
MIT License
src/main/kotlin/DamerauLevensthein.kt
javacook
111,961,341
false
null
package de.kotlincook.textmining import java.lang.Math.max import java.util.HashMap /** * The Damerau-Levenshtein Algorithm is an extension to the Levenshtein * Algorithm which solves the edit distance problem between a source string and * a target string with the following operations: * * Character Insertion * Character Deletion * Character Replacement * Adjacent Character Swap * * Note that the adjacent character swap operation is an edit that may be * applied when two adjacent characters in the source string match two adjacent * characters in the target string, but in reverse order, rather than a * general allowance for adjacent character swaps. * * This implementation allows the client to specify the costs of the various * edit operations with the restriction that the cost of two swap operations * must not be less than the cost of a delete operation followed by an insert * operation. This restriction is required to preclude two swaps involving the * same character being required for optimality which, in turn, enables a fast * dynamic programming solution. * * The running time of the Damerau-Levenshtein algorithm is O(n*m) where n * is the length of the source string and m is the length of the target * string. This implementation consumes O(n*m) space. * * @author <NAME> and <NAME> (JavaCook & KotlinCook) * @param deleteCost the cost of deleting a character. * @param insertCost the cost of inserting a character. * @param replaceCost the cost of replacing a character. * @param swapCost the cost of swapping two adjacent characters. */ class DamerauLevenshtein(private val deleteCost: Int, private val insertCost: Int, private val replaceCost: Int, private val swapCost: Int) { init { check(deleteCost >= 0) check(insertCost >= 0) check(replaceCost >= 0) check(swapCost >= 0) check(2 * swapCost >= insertCost + deleteCost) } /** * Compute the Damerau-Levenshtein distance between the specified source * string and the specified target string. */ fun compute(source: String, target: String): Int { if (source.isEmpty()) { return target.length * insertCost } if (target.isEmpty()) { return source.length * deleteCost } val table = Array(source.length) { IntArray(target.length) } val sourceIndexByCharacter = HashMap<Char, Int>() if (source[0] != target[0]) { table[0][0] = Math.min(replaceCost, deleteCost + insertCost) } sourceIndexByCharacter.put(source[0], 0) for (i in 1 until source.length) { val deleteDistance = table[i - 1][0] + deleteCost val insertDistance = (i + 1) * deleteCost + insertCost val matchDistance = i * deleteCost + if (source[i] == target[0]) 0 else replaceCost table[i][0] = intArrayOf(deleteDistance, insertDistance, matchDistance).min()!! } for (j in 1 until target.length) { val deleteDistance = table[0][j - 1] + insertCost val insertDistance = (j + 1) * insertCost + deleteCost val matchDistance = j * insertCost + if (source[0] == target[j]) 0 else replaceCost table[0][j] = intArrayOf(deleteDistance, insertDistance, matchDistance).min()!! } for (i in 1 until source.length) { var maxSourceLetterMatchIndex = if (source[i] == target[0]) 0 else -1 for (j in 1 until target.length) { val candidateSwapIndex:Int? = sourceIndexByCharacter[target[j]] val jSwap = maxSourceLetterMatchIndex val deleteDistance = table[i - 1][j] + deleteCost val insertDistance = table[i][j - 1] + insertCost var matchDistance = table[i - 1][j - 1] if (source[i] != target[j]) { matchDistance += replaceCost } else { maxSourceLetterMatchIndex = j } var swapDistance = Integer.MAX_VALUE; if (candidateSwapIndex != null && jSwap != -1) { swapDistance = 0 if (candidateSwapIndex > 0 || jSwap > 0) { swapDistance = table[max(0, candidateSwapIndex - 1)][max(0, jSwap - 1)] } swapDistance += (i - candidateSwapIndex - 1) * deleteCost swapDistance += (j - jSwap - 1) * insertCost + swapCost } table[i][j] = intArrayOf(deleteDistance, insertDistance, matchDistance, swapDistance).min()!! } sourceIndexByCharacter.put(source[i], i) } return table[source.length - 1][target.length - 1] } }
0
Kotlin
0
0
79fd08394b50016f8174f922abbea8c3cb506e49
4,871
dameraulevenshtein
Apache License 2.0
LeetCode/Kotlin/SearchInRotatedSortedArray.kt
vale-c
177,558,551
false
null
/** * 33. Search in Rotated Sorted Array * https://leetcode.com/problems/search-in-rotated-sorted-array/ */ class Solution { fun search(nums: IntArray, target: Int): Int { val pivotIndex = searchPivot(nums, 0, nums.size - 1) if (pivotIndex == -1) { return binarySearch(nums, target, 0, nums.size - 1) } else { if(nums[pivotIndex] == target) { return pivotIndex } if (target <= nums[nums.size - 1]) { return binarySearch(nums, target, pivotIndex, nums.size - 1) } return binarySearch(nums, target, 0, pivotIndex - 1) } } /** * Searches for the pivot position * O(log n) */ fun searchPivot(nums: IntArray, begin: Int, end: Int): Int { var begin = begin var end = end while (begin < end) { val mid = begin + (end - begin) / 2 if (mid > begin && nums[mid-1] > nums[mid]) { return mid } else if (mid < end && nums[mid+1] < nums[mid]) { return mid + 1 } else { if (nums[begin] >= nums[mid]) { end = mid -1 } else { begin = mid + 1 } } } return -1 } fun binarySearch(nums: IntArray, target: Int, begin: Int, end: Int): Int { var begin = begin var end = end while (begin <= end) { val mid = begin + (end - begin) / 2 println("mid "+mid) if (target == nums[mid]) { return mid } if (target > nums[mid]) { begin = mid + 1 } else { end = mid - 1 } } return -1 } }
0
Java
5
9
977e232fa334a3f065b0122f94bd44f18a152078
1,896
CodingInterviewProblems
MIT License
kotlin/src/com/s13g/aoc/aoc2021/Day17.kt
shaeberling
50,704,971
false
{"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245}
package com.s13g.aoc.aoc2021 import com.s13g.aoc.Result import com.s13g.aoc.Solver import com.s13g.aoc.XY import com.s13g.aoc.addTo import kotlin.math.max import kotlin.math.min import kotlin.math.sign /** * --- Day 17: * https://adventofcode.com/2021/day/17 */ class Day17 : Solver { override fun solve(lines: List<String>): Result { val input = lines[0].substring(13) .split(',') .map { it.trim() .substring(2) .split("..") } .map { Pair(it[0].toInt(), it[1].toInt()) } val result = runSimulation(input[0].first, input[0].second, input[1].first, input[1].second) return Result("${result.first}", "${result.second}") } private fun runSimulation(x1: Int, x2: Int, y1: Int, y2: Int): Pair<Int, Int> { var highestY = 0 var numHittingVelocities = 0 // Based on our input, both x values are positive. for (dX in 0..300) { for (dY in -200..200) { val highY = simulate(dX, dY, x1, x2, y1, y2) if (highY != Int.MIN_VALUE) numHittingVelocities++ highestY = max(highestY, highY) } } return Pair(highestY, numHittingVelocities) } private fun simulate(dX: Int, dY: Int, x1: Int, x2: Int, y1: Int, y2: Int): Int { val vel = XY(dX, dY) val pos = XY(0, 0) var maxY = Int.MIN_VALUE // Note, this only works if x values are positive and y values are negative. Check your input! while (pos.x <= max(x1, x2) && pos.y >= min(y1, y2)) { pos.addTo(vel) maxY = max(maxY, pos.y) if (pos.x in x1..x2 && pos.y in y1..y2) { return maxY } vel.x += -vel.x.sign vel.y -= 1 } return Int.MIN_VALUE } }
0
Kotlin
1
2
7e5806f288e87d26cd22eca44e5c695faf62a0d7
1,685
euler
Apache License 2.0
app/src/main/java/com/skt/nugu/sampleapp/utils/SimilarityChecker.kt
umrhiumrhi
515,390,621
false
{"Kotlin": 2646293, "Java": 1646, "Ruby": 1432}
package com.skt.nugu.sampleapp.utils import java.lang.Integer.max import java.lang.Math.min class SimilarityChecker { companion object { private const val korBegin = 44032 private const val korEnd = 55203 private const val chosungBase = 588 private const val jungsungBase = 28 private const val jaumBegin = 12593 private const val jaumEnd = 12622 private const val moumBegin = 12623 private const val moumEnd = 12643 private val chosungList = listOf('ㄱ', 'ㄲ', 'ㄴ', 'ㄷ', 'ㄸ', 'ㄹ', 'ㅁ', 'ㅂ', 'ㅃ', 'ㅅ', 'ㅆ', 'ㅇ' , 'ㅈ', 'ㅉ', 'ㅊ', 'ㅋ', 'ㅌ', 'ㅍ', 'ㅎ') private val jungsungList = listOf('ㅏ', 'ㅐ', 'ㅑ', 'ㅒ', 'ㅓ', 'ㅔ', 'ㅕ', 'ㅖ', 'ㅗ', 'ㅘ', 'ㅙ', 'ㅚ', 'ㅛ', 'ㅜ', 'ㅝ', 'ㅞ', 'ㅟ', 'ㅠ', 'ㅡ', 'ㅢ', 'ㅣ') private val jongsungList = listOf(' ', 'ㄱ', 'ㄲ', 'ㄳ', 'ㄴ', 'ㄵ', 'ㄶ', 'ㄷ', 'ㄹ', 'ㄺ', 'ㄻ', 'ㄼ', 'ㄽ', 'ㄾ', 'ㄿ', 'ㅀ', 'ㅁ', 'ㅂ', 'ㅄ', 'ㅅ', 'ㅆ', 'ㅇ', 'ㅈ', 'ㅊ', 'ㅋ', 'ㅌ', 'ㅍ', 'ㅎ') } private fun getLevenshteinDistance(s1 : List<Char>, s2 : List<Char>): Int { val m = s1.size val n = s2.size val dp = Array(m + 1) { IntArray(n + 1) } for (i in 1..m) { dp[i][0] = i } for (j in 1..n) { dp[0][j] = j } var cost : Int for (i in 1..m) { for (j in 1..n) { cost = if (s1[i - 1] == s2[j - 1]) 0 else 1 dp[i][j] = min(min(dp[i - 1][j] + 1, dp[i][j - 1] + 1), dp[i - 1][j - 1] + cost) } } return dp[m][n] } private fun getJamoLevenshteinDistance(s1 : String, s2 : String): Double { val m = s1.length val n = s2.length val dp = Array(m + 1) { DoubleArray(n + 1) } for (i in 1..m) { dp[i][0] = i.toDouble() } for (j in 1..n) { dp[0][j] = j.toDouble() } var cost : Double for (i in 1..m) { for (j in 1..n) { cost = subCost(s1[i-1], s2[j-1]) dp[i][j] = min(min(dp[i - 1][j] + 1, dp[i][j - 1] + 1), dp[i - 1][j - 1] + cost) } } return dp[m][n] } private fun subCost(c1 : Char, c2 : Char) : Double { if (c1 == c2) { return 0.0 } return getLevenshteinDistance(decompose(c1), decompose(c2)) / 3.0 } fun findSimilarity(s1: String?, s2: String?): Double { if (s1.isNullOrEmpty() or s2.isNullOrEmpty()) return -1.0 var result = -1.0 val maxLength = max(s1!!.length, s2!!.length) if (maxLength > 0) { result = (maxLength * 1.0 - getJamoLevenshteinDistance(s1, s2)) / maxLength * 1.0 } else { result = 1.0 } return result } fun decompose(c : Char) : List<Char> { if (!checkKorean(c)) { return emptyList() } var i = c.code if (i in jaumBegin..jaumEnd) { return listOf(c, ' ', ' ') } if (i in moumBegin..moumEnd) { return listOf(' ', c, ' ') } i -= korBegin val cho : Int = i / chosungBase val jung : Int = ( i - cho * chosungBase ) / jungsungBase val jong : Int = ( i - cho * chosungBase - jung * jungsungBase) return listOf(chosungList[cho], jungsungList[jung], jongsungList[jong]) } fun compose(chosung : Char, jungsung : Char, jongsung : Char) : Char { val tmp = korBegin + chosungBase * chosungList.indexOf(chosung) + jungsungBase * jungsungList.indexOf(jungsung) + jongsungList.indexOf(jongsung) return tmp.toChar() } fun checkKorean(c : Char) : Boolean { val i = c.code return (i in korBegin..korEnd) or (i in jaumBegin..jaumEnd) or (i in moumBegin..moumEnd) } }
0
Kotlin
0
0
6c4bc151d2cfe4d18e409c04e66c190f49d4e284
4,002
skt-summer-internship-2022
Apache License 2.0
src/main/kotlin/Day10.kt
uipko
572,710,263
false
{"Kotlin": 25828}
fun main() { val signal = signalStrength("Day10.txt") println("Signal strength: $signal") renderText("Day10.txt").map { line -> line.map { pixel -> print(pixel) }; print("\n")} } fun signalStrength(fileName: String): Int { var cycles = 0 var registerX = 1 val addOpcode = "addx" val strength = readInput(fileName).fold(0) { acc, line -> var currVal = 0 val currOpcode = line.substringBefore(" ") when (currOpcode) { addOpcode -> { cycles += 2 currVal = line.split(" ").last().toInt() registerX += currVal } else -> cycles++ } when(cycles) { in listOf(20, 60, 100, 140, 180, 220) -> { acc + cycles * (registerX-currVal) } in listOf(21, 61, 101, 141, 181, 221) -> { if (currOpcode == addOpcode) { acc + (cycles-1) * (registerX - currVal) } else acc } else -> acc } } return strength } fun renderText(fileName: String): List<List<Char>> { var cycles = 0 var registerX = 1 val addOpcode = "addx" return readInput(fileName).fold(mutableListOf<MutableList<Char>>(mutableListOf())) { acc, line -> fun addToScreen(cycle: Int){ var pixel = if ((cycle-1)%40 in registerX-1..registerX+1) '#' else '.' when { cycle > 40 && cycle%40 == 1 -> acc.add((mutableListOf(pixel))) else -> acc.last().add(pixel) } } var currVal = 0 val currOpcode = line.substringBefore(" ") cycles++ addToScreen(cycles) if (currOpcode == addOpcode) { cycles++ addToScreen(cycles) currVal = line.split(" ").last().toInt() registerX += currVal } acc } }
0
Kotlin
0
0
b2604043f387914b7f043e43dbcde574b7173462
1,974
aoc2022
Apache License 2.0
src/main/kotlin/com/github/thibseisel/diff/myers/MyersDiffAlgorithm.kt
thibseisel
329,431,410
false
null
package com.github.thibseisel.diff.myers import com.github.thibseisel.diff.DeltaType import com.github.thibseisel.diff.Equalizer internal class MyersDiffAlgorithm<T>( private val equalizer: Equalizer<T> ) { /** * Computes the change set to patch the source list to the target list. * * @param source Source data * @param target Target data */ fun computeDiff(source: List<T>, target: List<T>): List<Change> { val path = buildPath(source, target) return buildRevision(path) } /** * Computes the minimum diffpath that expresses the differences between te original and revised * sequences, according to Gene Myers differencing algorithm. * * @param orig The original sequence. * @param rev The revised sequence. * @return A minimum [Path][PathNode] across the differences graph. */ private fun buildPath(orig: List<T>, rev: List<T>): PathNode { val N = orig.size val M = rev.size val MAX = N + M + 1 val size = 1 + 2 * MAX val middle = size / 2 val diagonal = arrayOfNulls<PathNode>(size) diagonal[middle + 1] = PathNode(0, -1, snake = true, bootstrap = true, null) for (d in 0 until MAX) { for (k in -d..d step 2) { val kmiddle = middle + k val kplus = kmiddle + 1 val kminus = kmiddle - 1 var prev: PathNode var i: Int if ((k == -d) || (k != d && diagonal[kminus]!!.i < diagonal[kminus]!!.i)) { i = diagonal[kplus]!!.i prev = diagonal[kplus]!! } else { i = diagonal[kminus]!!.i + 1 prev = diagonal[kminus]!! } diagonal[kminus] = null var j = i - k var node = PathNode(i, j, snake = false, bootstrap = false, prev) while (i < N && j < M && equalizer.areEquals(orig[i], rev[j])) { i++ j++ } if (i != node.i) { node = PathNode(i, i, true, bootstrap = false, prev = node) } diagonal[kmiddle] = node if (i >= N && j >= M) { return diagonal[kmiddle]!! } } diagonal[middle + d - 1] = null } // According to Myers, this can't happen error("Could not find a diff path") } private fun buildRevision(actualPath: PathNode): List<Change> { var path: PathNode? = actualPath val changes = mutableListOf<Change>() if (actualPath.snake) { path = actualPath.prev } while (path?.prev != null && path.prev!!.j >= 0) { check(!path.snake) { "bad diffpath: found snake when looking for diff" } val i = path.i val j = path.j path = path.prev!! val ianchor = path.i val janchor = path.j if (ianchor == i && janchor != j) { changes.add(Change(DeltaType.INSERT, ianchor, i, janchor, j)) } else if (ianchor != i && janchor == j) { changes.add(Change(DeltaType.DELETE, ianchor, i, janchor, j)) } else { changes.add(Change(DeltaType.CHANGE, ianchor, i, janchor, j)) } if (path.snake) { path = path.prev } } return changes } }
0
Kotlin
0
0
aae1e13aac0c19b86855c4ba7eaa238f9681b867
3,576
kotlin-diff
Apache License 2.0
src/main/kotlin/day11.kt
p88h
317,362,882
false
null
internal data class Seat(val pos: Pair<Int, Int>) { var adj = ArrayList<Pair<Int, Int>>() var nc = 0 fun InitAdj(area: List<CharArray>, maxd: Int) { adj.clear() for (ii in -1..1) for (jj in -1..1) { if (ii == 0 && jj == 0) continue for (k in 1..maxd) { val i = pos.first + k * ii val j = pos.second + k * jj if (!(i >= 0 && i < area.size && j >= 0 && j < area[i].size)) break if (area[i][j] != '.') { adj.add(i to j) break } } } } fun ComputeNC(area: List<CharArray>) { nc = adj.count { area[it.first][it.second] == '#' } } fun Update(area: List<CharArray>, maxc: Int): Boolean { val p = area[pos.first][pos.second] if (nc == 0) area[pos.first][pos.second] = '#' if (nc >= maxc) area[pos.first][pos.second] = 'L' return area[pos.first][pos.second] != p } } fun main(args: Array<String>) { var area = allLines(args, "day11.in").map { it.toCharArray() }.toList() var seats = ArrayList<Seat>() for (i in area.indices) for (j in area[i].indices) if (area[i][j] != '.') seats.add(Seat(i to j)) seats.forEach { it.InitAdj(area, 1) } do { seats.forEach { it.ComputeNC(area) } } while (seats.count { it.Update(area, 4) } > 0) println(seats.count { area[it.pos.first][it.pos.second] == '#' }); seats.forEach { it.Update(area, 0) } seats.forEach { it.InitAdj(area, 999999) } do { seats.forEach { it.ComputeNC(area) } } while (seats.count { it.Update(area, 5) } > 0) println(seats.count { area[it.pos.first][it.pos.second] == '#' }); }
0
Kotlin
0
5
846ad4a978823563b2910c743056d44552a4b172
1,744
aoc2020
The Unlicense
src/main/kotlin/solutions/day06/Day6.kt
Dr-Horv
112,381,975
false
null
package solutions.day06 import solutions.Solver import utils.splitAtWhitespace data class Tuple(val index: Int, val value: Int) class Day6 : Solver { override fun solve(input: List<String>, partTwo: Boolean): String { val banks = input.first() .splitAtWhitespace() .map(String::toInt) .toMutableList() var steps = 0 val history = LinkedHashSet<List<Int>>() history.add(banks.toList()) while (true) { redistribute(banks) steps++ val copiedBanks = banks.toList() if (history.contains(copiedBanks)) { return if(!partTwo) { steps.toString() } else { (steps - history.indexOf(copiedBanks)).toString() } } else { history.add(copiedBanks) } } } private fun redistribute(banks: MutableList<Int>) { val (index, blocks) = banks.foldIndexed(Tuple(-1, -1), this::findFullestBank) banks[index] = 0 var currentIndex = index for (b in 1..blocks) { currentIndex = (currentIndex + 1) % banks.size banks[currentIndex]++ } } private fun findFullestBank(index: Int, acc: Tuple, curr: Int): Tuple { return if (curr > acc.value) { Tuple(index, curr) } else if (curr == acc.value && index < acc.index) { Tuple(index, curr) } else { acc } } }
0
Kotlin
0
2
975695cc49f19a42c0407f41355abbfe0cb3cc59
1,557
Advent-of-Code-2017
MIT License
src/Day01.kt
gojoel
573,543,233
false
{"Kotlin": 28426}
import kotlin.math.max fun main() { val input = readInput("01") // val input = readInput("01_test") // calculate total from elf with most calories fun part1(input: List<String>): Int { var total = 0 var current = 0 input.forEachIndexed { index, calories -> current += if (calories.isBlank()) { 0 } else { calories.toInt() } if (calories.isBlank() || index == input.size - 1) { total = max(total, current) current = 0 } } return total } // calculate total from top three elves fun part2(input: List<String>): Int { val totals = arrayListOf<Int>() var current = 0 input.forEachIndexed { index, calories -> current += if (calories.isBlank()) { 0 } else { calories.toInt() } if (calories.isBlank() || index == input.size - 1) { totals.add(current) current = 0 } } totals.sortDescending() return totals.take(3).sum() } println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
0690030de456dad6dcfdcd9d6d2bd9300cc23d4a
1,132
aoc-kotlin-22
Apache License 2.0
Kotlin/src/MinimumPathSum.kt
TonnyL
106,459,115
false
null
/** * Given a m x n grid filled with non-negative numbers, * find a path from top left to bottom right which minimizes the sum of all numbers along its path. * * Note: You can only move either down or right at any point in time. * * Example 1: * [[1,3,1], * [1,5,1], * [4,2,1]] * Given the above grid map, return 7. Because the path 1→3→1→1→1 minimizes the sum. * * Accepted. */ class MinimumPathSum { fun minPathSum(grid: Array<IntArray>): Int { if (grid.isEmpty()) { return 0 } if (grid.size == 1) { if (grid[0].isEmpty()) { return 0 } if (grid[0].size == 1) { return grid[0][0] } } val matrix = Array(grid.size) { IntArray(grid[0].size) } matrix[0][0] = grid[0][0] (1 until grid.size).forEach { matrix[it][0] = matrix[it - 1][0] + grid[it][0] } (1 until grid[0].size).forEach { matrix[0][it] = matrix[0][it - 1] + grid[0][it] } (1 until grid.size).forEach { i -> (1 until grid[0].size).forEach { matrix[i][it] = Math.min(matrix[i - 1][it] + grid[i][it], matrix[i][it - 1] + grid[i][it]) } } return matrix[grid.size - 1][grid[0].size - 1] } }
1
Swift
22
189
39f85cdedaaf5b85f7ce842ecef975301fc974cf
1,360
Windary
MIT License
src/main/kotlin/com/sk/set9/935. Knight Dialer.kt
sandeep549
262,513,267
false
{"Kotlin": 530613}
package com.sk.set9 class Solution935 { /** * DP top-down */ val max = 1e9.toInt() + 7 fun knightDialer(n: Int): Int { var s = 0L val dp = Array(n + 1) { Array(4) { LongArray(3) } } for (i in 0 until 4) { for (j in 0 until 3) { s = (s + ways(i, j, n, dp)) % max } } return s.toInt() } private fun ways(i: Int, j: Int, n: Int, dp: Array<Array<LongArray>>): Long { if (i < 0 || i > 3 || j < 0 || j > 2 || (i == 3 && j != 1)) return 0 if (n == 1) return 1 // base case if (dp[n][i][j] == 0L) { dp[n][i][j] = ways(i - 1, j - 2, n - 1, dp) % max + ways(i - 1, j + 2, n - 1, dp) % max + ways(i + 1, j - 2, n - 1, dp) % max + ways(i + 1, j + 2, n - 1, dp) % max + ways(i - 2, j - 1, n - 1, dp) % max + ways(i + 2, j - 1, n - 1, dp) % max + ways(i - 2, j + 1, n - 1, dp) % max + ways(i + 2, j + 1, n - 1, dp) % max } return dp[n][i][j] } // /** // * dp bottom up // */ // fun knightDialer2(n: Int): Int { // var dp = Array(4) { LongArray(3) } // // for (k in 1..n) { // val dp1 = Array(4) { LongArray(3) } // for (i in 0 until 4) { // for (j in 0 until 3) { // // ways to get here(i,j) from 8 different location using k-1 steps // dp1[i][j] = ways(i, j, dp) // } // } // dp = dp1 // } // // var s = 0L // for (i in 0 until 4) { // for (j in 0 until 3) { // s = (s + dp[i][j]) % max // } // } // return s.toInt() // } // // // No of ways to come at r,c // private fun ways(r: Int, c: Int, dp: Array<LongArray>): Long { // var s = 0L // if (r + 1 <= 3) { // if (c - 2 >= 0) s = (s + dp[r + 1][c - 2]) % max // if (c + 2 <= 2) s = (s + dp[r + 1][c + 2]) % max // } // if (r - 1 >= 0) { // if (c - 2 >= 0) s = (s + dp[r - 1][c - 2]) % max // if (c + 2 <= 2) s = (s + dp[r - 1][c + 2]) % max // } // if (c + 1 <= 2) { // if (r - 2 >= 0) s = (s + dp[r - 2][c + 1]) % max // if (r + 2 <= 3) s = (s + dp[r + 2][c + 1]) % max // } // if (c - 1 >= 0) { // if (r - 2 >= 0) s = (s + dp[r - 2][c - 1]) % max // if (r + 2 <= 3) s = (s + dp[r + 2][c - 1]) % max // } // // return s // } // }
1
Kotlin
0
0
cf357cdaaab2609de64a0e8ee9d9b5168c69ac12
2,668
leetcode-kotlin
Apache License 2.0
kotlin/src/main/kotlin/adventofcode/y2018/Day8.kt
3ygun
115,948,057
false
null
package adventofcode.y2018 import adventofcode.DataLoader import adventofcode.Day object Day8 : Day { val STAR1_DATA = DataLoader.readLinesFromFor("/y2018/Day8Star1.txt").first() val STAR2_DATA = STAR1_DATA override val day: Int = 8 override fun star1Run(): String { val result = star1Calc(STAR1_DATA) return "Metadata sum is $result" } override fun star2Run(): String { val result = star2Calc(STAR2_DATA) return "Root node is $result" } fun star1Calc(rawInput: String): Int { return parse(rawInput).metadataSum() } fun star2Calc(rawInput: String): Int { return parse(rawInput).star2Sum } //<editor-fold desc="work"> private fun parse(rawInput: String): Node { val input = rawInput .split(" ") .map { Integer.parseInt(it) } return parseInputToNodes(input).second } private fun parseInputToNodes( inputs: List<Int>, index: Int = 0 ): Pair<Int /* index */, Node /* nodes */> { if (inputs.isEmpty()) return index to Day8.Node.EMPTY val children = mutableListOf<Node>() val metadata = mutableListOf<Int>() val numChildren = inputs[index] val numMetadata = inputs[index + 1] var newIndex = index + 2 // Children (0 until numChildren) .forEach { _ -> val (endIndex, endResult) = parseInputToNodes(inputs, newIndex) newIndex = endIndex children.add(endResult) } // Metadata (0 until numMetadata) .forEach { i -> metadata.add(inputs[newIndex + i]) } return (newIndex + numMetadata) to Node(children, metadata) } private data class Node( val children: List<Node>, val metadata: List<Int> ) { fun metadataSum(): Int { if (children.isEmpty()) return metadata.sum() return children .map { it.metadataSum() } .sum() + metadata.sum() } val star2Sum: Int by lazy { if (children.isEmpty()) return@lazy metadata.sum() metadata .map { it - 1 } // Index to element 1 is at 0 .map { when { it < 0 -> 0 it < children.size -> children[it].star2Sum else -> 0 } } .sum() } companion object { val EMPTY = Node(emptyList(), emptyList()) } } //</editor-fold> }
0
Kotlin
0
0
69f95bca3d22032fba6ee7d9d6ec307d4d2163cf
2,595
adventofcode
MIT License
src/Day03.kt
anilkishore
573,688,256
false
{"Kotlin": 27023}
fun main() { fun part1(input: List<String>): Int { return input.asSequence().map { val first = it.substring(0, it.length / 2).toSet() val second = it.substring(it.length / 2).toSet() val ch = first.intersect(second).first() if (ch in 'a'..'z') (ch - 'a' + 1) else 26 + (ch - 'A' + 1) }.sum() } fun part2(input: List<String>): Int { return input.asSequence() .chunked(3) .map { val ch = it.map { s -> s.toSet() }.reduce { a, b -> a.intersect(b)}.first() if (ch in 'a'..'z') (ch - 'a' + 1) else 26 + (ch - 'A' + 1) }.sum() } val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
f8f989fa400c2fac42a5eb3b0aa99d0c01bc08a9
770
AOC-2022
Apache License 2.0
kotlin/src/com/daily/algothrim/dp/MinDist.kt
idisfkj
291,855,545
false
null
package com.daily.algothrim.dp import kotlin.math.min /** * 棋盘最小路径 * * 假设我们有一个 n 乘以 n 的矩阵 matrix[n][n]。矩阵存储的都是正整数。棋子起始位置在左上角,终止位置在右下角。 * 我们将棋子从左上角移动到右下角。每次只能向右或者向下移动一位。从左上角到右下角,会有很多不同的路径可以走。 * 我们把每条路径经过的数字加起来看作路径的长度。那从左上角移动到右下角的最短路径长度是多少呢? */ class MinDist { companion object { @JvmStatic fun main(args: Array<String>) { println(MinDist().minDist(4, arrayOf( intArrayOf(1, 3, 5, 9), intArrayOf(2, 1, 3, 4), intArrayOf(5, 2, 6, 7), intArrayOf(6, 8, 4, 3) ))) println(MinDist().minDist2(4, arrayOf( intArrayOf(1, 3, 5, 9), intArrayOf(2, 1, 3, 4), intArrayOf(5, 2, 6, 7), intArrayOf(6, 8, 4, 3) ))) } } /** * 状态转移表法 */ fun minDist(n: Int, matrix: Array<IntArray>): Int { val status = Array(n) { IntArray(n) } var i = 0 var rowSum = 0 var columnSum = 0 while (i < n) { // 初始化第一行 rowSum += matrix[0][i] status[0][i] = rowSum // 初始化第一列 columnSum += matrix[i][0] status[i][0] = columnSum i++ } var k = 1 // 剩余的按行填充 while (k < n) { var m = 1 while (m < n) { status[k][m] = matrix[k][m] + min(status[k - 1][m], status[k][m - 1]) m++ } k++ } return status[n - 1][n - 1] } /** * 状态转移方程法 */ fun minDist2(n: Int, matrix: Array<IntArray>): Int { val status = Array(n) { IntArray(n) } var k = 0 while (k < n) { var m = 0 while (m < n) { var left = 0 var up = 0 if (k > 0) { up = status[k - 1][m] } if (m > 0) { left = status[k][m - 1] } when { k == 0 -> status[k][m] = matrix[k][m] + left // 只能从左边过来 m == 0 -> status[k][m] = matrix[k][m] + up // 只能从上边过来 else -> status[k][m] = matrix[k][m] + min(up, left) // 左边、上边都可以过来 } m++ } k++ } return status[n - 1][n - 1] } }
0
Kotlin
9
59
9de2b21d3bcd41cd03f0f7dd19136db93824a0fa
2,847
daily_algorithm
Apache License 2.0
src/main/kotlin/com/groundsfam/advent/y2020/d18/Day18.kt
agrounds
573,140,808
false
{"Kotlin": 281620, "Shell": 742}
package com.groundsfam.advent.y2020.d18 import com.groundsfam.advent.DATAPATH import kotlin.io.path.div import kotlin.io.path.useLines fun evaluatePartOne(token: Token): Long = when (token) { is NumberToken -> token.value is TokenList -> { val tokens = token.tokens var ret = evaluatePartOne(tokens[0]) for (i in 1 until tokens.size step 2) { val opToken = tokens[i] if (opToken !is OpToken) throw RuntimeException("Illegal token $opToken") if (i+1 >= tokens.size) throw RuntimeException("Missing right operand for token $opToken") ret = opToken.op.eval(ret, evaluatePartOne(tokens[i+1])) } ret } is OpToken -> throw RuntimeException("Cannot evaluate an operation without operands") } fun evaluatePartTwo(token: Token): Long = when (token) { is NumberToken -> token.value is TokenList -> { // evaluate parentheses groups first, so all that remains is numbers and operations val tokens = token.tokens.map { if (it is TokenList) NumberToken(evaluatePartTwo(it)) else it } // evaluate PLUSes val firstPass = mutableListOf((tokens.first() as NumberToken).value) for (i in 1 until tokens.size step 2) { val opToken = tokens[i] if (opToken !is OpToken) throw RuntimeException("Illegal token $opToken") when (opToken.op) { Operation.PLUS -> { val prev = firstPass.removeLast() if (i+1 >= tokens.size) throw RuntimeException("Missing right operand for token $opToken") firstPass.add(opToken.op.eval(prev, (tokens[i+1] as NumberToken).value)) } Operation.TIMES -> { if (i+1 >= tokens.size) throw RuntimeException("Missing right operand for token $opToken") firstPass.add((tokens[i+1] as NumberToken).value) } } } // evaluate TIMESes firstPass.reduce(Operation.TIMES::eval) } is OpToken -> throw RuntimeException("Cannot evaluate an operation without operands") } fun main() { val tokenizedLines: List<Token> = (DATAPATH / "2020/day18.txt").useLines { lines -> lines.toList() .map { parseLine(it) } } tokenizedLines.sumOf(::evaluatePartOne) .also { println("Part one: $it") } tokenizedLines.sumOf(::evaluatePartTwo) .also { println("Part two: $it") } }
0
Kotlin
0
1
c20e339e887b20ae6c209ab8360f24fb8d38bd2c
2,527
advent-of-code
MIT License
src/test/kotlin/amb/aoc2020/day7.kt
andreasmuellerbluemlein
318,221,589
false
null
package amb.aoc2020 import org.junit.jupiter.api.Test class Day7 : TestBase() { companion object { } fun loadRegulations(inputFile: String) : Map<String,List<Pair<String,Int>>>{ val data = getTestData(inputFile).map { line -> line.split(" bags contain ", " bags, ", " bag, "," bags."," bag.","no other") } return data.map{ regulation -> val innerBags = regulation.filter { it.isNotEmpty() }.drop(1).map { Pair(it.drop(2),Character.getNumericValue(it.first())) } Pair(regulation[0], innerBags) }.toMap() } fun findOuterBags(regulations: Map<String,List<Pair<String,Int>>>, bag: String) : List<String> { return regulations.filter { regulation -> regulation.value.any{it.first == bag} }.map { it.key } } fun getCountOfReferencingRegulations(regulations: Map<String,List<Pair<String,Int>>>, bag: String) : Int{ if (skipThose.contains(bag)) return 0 val outerBags = findOuterBags(regulations,bag) logger.info { "$bag - ${outerBags.joinToString(", ")}"} skipThose.add(bag) return 1 + outerBags.map { getCountOfReferencingRegulations(regulations,it) }.sum() } private val skipThose = emptyList<String>().toMutableList() @Test fun task1() { val regulations = loadRegulations("input7") val countOfReferencingRegulations = getCountOfReferencingRegulations(regulations,"shiny gold") logger.info { "${countOfReferencingRegulations-1} are referencing shiny gold bag" } } fun getCountOfIncludingPackages(regulations: Map<String,List<Pair<String,Int>>>, bag: String) : Int { return 1 + regulations[bag]!!.map { getCountOfIncludingPackages(regulations,it.first) * it.second }.sum() } @Test fun task2() { val regulations = loadRegulations("input7") var count = getCountOfIncludingPackages(regulations,"shiny gold") logger.info { "${count - 1} are referencing shiny gold bag" } } }
1
Kotlin
0
0
dad1fa57c2b11bf05a51e5fa183775206cf055cf
2,054
aoc2020
MIT License
src/main/kotlin/aoc2022/Day05.kt
lukellmann
574,273,843
false
{"Kotlin": 175166}
package aoc2022 import AoCDay import util.* private typealias Crate = Char // https://adventofcode.com/2022/day/5 object Day05 : AoCDay<String>( title = "Supply Stacks", part1ExampleAnswer = "CMZ", part1Answer = "QNHWJVJZW", part2ExampleAnswer = "MCD", part2Answer = "BPCZJLFJW", ) { // parsing crate stacks assumes single digit stack numbers and will otherwise break private const val STACK_WIDTH = 4 private fun parseCrateStacks(input: String): Array<Stack<Crate>> { // the lines in the crate part of the input all have the same length, filled with trailing spaces when needed val lineLength = input.lineSequence().first().length val stackCount = (lineLength + 1) / STACK_WIDTH // last stack doesn't have a space at the end -> + 1 val crateStacks = Array(size = stackCount) { Stack<Crate>() } input // drop line containing stack numbers, we know they start at 1 and that we have stackCount stacks .substringBeforeLast('\n') .lineSequence() .forEach { line -> // read stacks from top to bottom -> push crates from bottom for ((stackIndex, linePosition) in (1..lineLength step STACK_WIDTH).withIndex()) { val crate = line[linePosition] if (crate != ' ') crateStacks[stackIndex].pushFromBottom(crate) } } return crateStacks } // parsing steps assumes single digit stack numbers (but could easily be changed by adjusting the regex) private data class Step(val amount: Int, val origin: Int, val target: Int) private val STEP_REGEX = Regex("""move (\d+) from (\d) to (\d)""") private fun parseSteps(input: String) = input .lineSequence() .map { line -> STEP_REGEX.match(line).toList().map(String::toInt) } .map { (amount, from, to) -> Step(amount, origin = from - 1, target = to - 1) } // 0-based indexing private fun rearrangeCrateStacksAndGetTopCrates( input: String, step: (amount: Int, origin: Stack<Crate>, target: Stack<Crate>) -> Unit, ): String { val (crateStacksInput, stepsInput) = input.split("\n\n", limit = 2) val crateStacks = parseCrateStacks(crateStacksInput) for ((amount, origin, target) in parseSteps(stepsInput)) { step(amount, crateStacks[origin], crateStacks[target]) } return crateStacks.map { it.lastOrNull() ?: ' ' }.joinToString(separator = "") } override fun part1(input: String) = rearrangeCrateStacksAndGetTopCrates( input, step = { amount, origin, target -> repeat(amount) { target.push(origin.pop()) } }, ) override fun part2(input: String) = rearrangeCrateStacksAndGetTopCrates( input, step = { amount, origin, target -> List(size = amount) { origin.pop() }.asReversed().forEach(target::push) }, ) }
0
Kotlin
0
1
344c3d97896575393022c17e216afe86685a9344
2,952
advent-of-code-kotlin
MIT License
src/main/kotlin/pl/bizarre/day2_2.kt
gosak
572,644,357
false
{"Kotlin": 26456}
package pl.bizarre import pl.bizarre.Day2Move.Companion.findMove import pl.bizarre.Day2Move.Paper import pl.bizarre.Day2Move.Rock import pl.bizarre.Day2Move.Scissors import pl.bizarre.common.loadInput import java.util.regex.Pattern fun main() { val input = loadInput(2) println("result ${day2_2(input)}") } fun day2_2(input: List<String>): Int { val whitespace = Pattern.compile("\\s+") return input.sumOf { line -> val moveToResult = whitespace.split(line) val opponentMove = findMove(moveToResult[0]) val requiredResult = result(moveToResult[1]) matchResult(opponentMove, moveForResult(opponentMove, requiredResult)) } } fun result(value: String): Int = when (value) { "X" -> -1 "Y" -> 0 "Z" -> 1 else -> error("Invalid key $value") } fun moveForResult(opponentMove: Day2Move, result: Int): Day2Move = when { // on nozyczki, to ja musze kamien bo result == 1 result == 0 -> opponentMove opponentMove == Rock -> if (result > 0) Paper else Scissors opponentMove == Scissors -> if (result > 0) Rock else Paper opponentMove == Paper -> if (result > 0) Scissors else Rock else -> error("Impossible") }
0
Kotlin
0
0
aaabc56532c4a5b12a9ce23d54c76a2316b933a6
1,228
adventofcode2022
Apache License 2.0
Kotlin for Java Developers. Week 3/Taxi Park/Task/src/taxipark/TaxiParkTask.kt
Anna-Sentyakova
186,426,055
false
null
package taxipark /* * Task #1. Find all the drivers who performed no trips. */ fun TaxiPark.findFakeDrivers(): Set<Driver> = allDrivers.associate { driver -> driver to findAllTrips(driver) } .filterValues { trips -> trips.isEmpty() } .keys fun TaxiPark.findAllTrips(driver: Driver): List<Trip> = trips.filter { trip -> trip.driver == driver } /* * Task #2. Find all the clients who completed at least the given number of trips. */ fun TaxiPark.findFaithfulPassengers(minTrips: Int): Set<Passenger> = allPassengers.associate { passenger -> passenger to findAllTrips(passenger) } .filterValues { trips -> trips.size >= minTrips } .keys fun TaxiPark.findAllTrips(passenger: Passenger): List<Trip> = trips.filter { trip -> passenger in trip.passengers } /* * Task #3. Find all the passengers, who were taken by a given driver more than once. */ fun TaxiPark.findFrequentPassengers(driver: Driver): Set<Passenger> = allPassengers.associate { passenger -> passenger to findAllTrips(passenger) } .filterValues { trips -> trips.count { trip -> trip.driver == driver } > 1 } .keys /* * Task #4. Find the passengers who had a discount for majority of their trips. */ fun TaxiPark.findSmartPassengers(): Set<Passenger> = allPassengers.associate { passenger -> passenger to findAllTrips(passenger) } .filterValues { trips -> val (tripsWithDiscount, tripsNoDiscount) = trips.partition { trip -> trip.discount != null } tripsWithDiscount.size > tripsNoDiscount.size } .keys /* * Task #5. Find the most frequent trip duration among minute periods 0..9, 10..19, 20..29, and so on. * Return any period if many are the most frequent, return `null` if there're no trips. */ fun TaxiPark.findTheMostFrequentTripDurationPeriod(): IntRange? = trips.groupBy { trip -> val start = trip.duration / 10 * 10 val end = start + 9 start..end } .maxBy { (_, trips) -> trips.size } ?.key /* * Task #6. * Check whether 20% of the drivers contribute 80% of the income. */ fun TaxiPark.checkParetoPrinciple_(): Boolean = trips.isNotEmpty() && findIncomeOf20PercentDrivers() / findTotalIncome() >= 0.8 fun TaxiPark.findIncomeOf20PercentDrivers(): Double = allDrivers.map { driver -> findIncome(driver) } .sortedByDescending { it } .take((allDrivers.size * 0.2).toInt()) .sumByDouble { it } fun TaxiPark.findIncome(driver: Driver): Double = trips.filter { trip -> trip.driver == driver } .sumByDouble { trip -> trip.cost } fun TaxiPark.findTotalIncome(): Double = trips.sumByDouble { trip -> trip.cost } fun TaxiPark.checkParetoPrinciple(): Boolean { if (trips.isEmpty()) return false val totalIncome = trips.sumByDouble(Trip::cost) val sortedDriversIncome: List<Double> = trips .groupBy(Trip::driver) .map { (_, tripsByDriver) -> tripsByDriver.sumByDouble(Trip::cost) } .sortedDescending() val numberOfTopDrivers = (0.2 * allDrivers.size).toInt() val incomeByTopDrivers = sortedDriversIncome .take(numberOfTopDrivers) .sum() return incomeByTopDrivers >= 0.8 * totalIncome }
0
Kotlin
0
1
e5db4940fa844aa8a5de7f90dd872909a06756e6
3,463
coursera
Apache License 2.0
src/main/kotlin/be/tabs_spaces/advent2021/days/Day10.kt
janvryck
433,393,768
false
{"Kotlin": 58803}
package be.tabs_spaces.advent2021.days class Day10 : Day(10) { override fun partOne() = inputList .mapNotNull { SyntaxChecker.firstIllegalClosingCharIn(it) } .sumOf { Syntax.syntaxErrorScoreFor(it) } override fun partTwo() = inputList .mapNotNull { SyntaxChecker.missingClosingCharsIn(it) } .map { it.fold(0L) { score, character -> 5 * score + Syntax.autocompleteScoreFor(character) } } .sorted() .run { this[size / 2] } object Syntax { private val syntax = mapOf( ('(' to ')') to Scores(3, 1), ('[' to ']') to Scores(57, 2), ('{' to '}') to Scores(1197, 3), ('<' to '>') to Scores(25137, 4), ) val startingCharacters = syntax.keys.map { it.first } val endingCharacters = syntax.keys.map { it.second } fun syntaxForStart(char: Char) = syntax.keys.first { it.first == char } fun syntaxErrorScoreFor(char: Char) = findByClosingChar(char).value.syntaxErrorScore fun autocompleteScoreFor(char: Char) = findByClosingChar(char).value.autocompleteScore private fun findByClosingChar(char: Char) = syntax.entries.first { it.key.second == char } data class Scores(val syntaxErrorScore: Int, val autocompleteScore: Int) } object SyntaxChecker { fun firstIllegalClosingCharIn(line: String): Char? { val syntaxStack = mutableListOf<Pair<Char, Char>>() line.forEach { when (it) { in Syntax.startingCharacters -> syntaxStack.add(Syntax.syntaxForStart(it)) in Syntax.endingCharacters -> if (syntaxStack.last().second == it) syntaxStack.removeLast() else return it } } return null } fun missingClosingCharsIn(line: String): List<Char>? { val syntaxStack = mutableListOf<Pair<Char, Char>>() line.forEach { when (it) { in Syntax.startingCharacters -> syntaxStack.add(Syntax.syntaxForStart(it)) in Syntax.endingCharacters -> if (syntaxStack.last().second == it) syntaxStack.removeLast() else return null } } return syntaxStack.reversed().map { it.second } } } }
0
Kotlin
0
0
f6c8dc0cf28abfa7f610ffb69ffe837ba14bafa9
2,317
advent-2021
Creative Commons Zero v1.0 Universal
kotlin/problems/src/solution/TreeProblems.kt
lunabox
86,097,633
false
{"Kotlin": 146671, "Python": 38767, "JavaScript": 19188, "Java": 13966}
package solution import data.structure.TreeNode import java.util.* import java.util.concurrent.ArrayBlockingQueue import kotlin.collections.ArrayList import kotlin.collections.HashMap import kotlin.math.max import kotlin.math.min class TreeProblems { /** * 由数组创建二叉树 */ fun createTree(element: List<Int?>): TreeNode? { if (element.isEmpty()) { return null } return createNode(element, 0) } private fun createNode(element: List<Int?>, index: Int): TreeNode? { if (index >= 0 && index < element.size && element[index] != null) { val root = TreeNode(element[index]!!) root.left = createNode(element, index * 2 + 1) root.right = createNode(element, index * 2 + 2) return root } return null } fun printTree(root: TreeNode?) { val queue = ArrayBlockingQueue<TreeNode?>(20) queue.add(root) while (queue.isNotEmpty()) { val node = queue.poll() if (node != null) { println("${node.`val`} ") if (node.left != null) { queue.add(node.left) } if (node.right != null) { queue.add(node.right) } } } } /** * https://leetcode-cn.com/problems/binary-tree-level-order-traversal-ii/ * 给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历) */ fun levelOrderBottom(root: TreeNode?): List<List<Int>> { val result = ArrayList<List<Int>>() if (root == null) { return result } val queue = LinkedList<TreeNode>() queue.add(root) while (queue.isNotEmpty()) { val list = ArrayList<Int>() repeat(queue.size) { val s = queue.removeFirst() list.add(s.`val`) // add child tree node if (s.left != null) { queue.addLast(s.left) } if (s.right != null) { queue.addLast(s.right) } } result.add(0, list) } return result } /** * */ fun averageOfLevels(root: TreeNode?): DoubleArray { val result = ArrayList<Double>() if (root == null) { return result.toDoubleArray() } val queue = LinkedList<TreeNode>() queue.add(root) while (queue.isNotEmpty()) { var sum: Long = 0 val count = queue.size repeat(count) { val node = queue.removeFirst() sum += node.`val` if (node.left != null) { queue.addLast(node.left) } if (node.right != null) { queue.addLast(node.right) } } result.add(sum / count.toDouble()) } return result.toDoubleArray() } /** * https://leetcode-cn.com/problems/binary-tree-level-order-traversal/ * 给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点) */ fun levelOrder(root: TreeNode?): List<List<Int>> { val result = ArrayList<List<Int>>() if (root == null) { return result } val queue = LinkedList<TreeNode>() queue.add(root) while (queue.isNotEmpty()) { val list = ArrayList<Int>() repeat(queue.size) { val s = queue.removeFirst() list.add(s.`val`) // add child tree node if (s.left != null) { queue.addLast(s.left) } if (s.right != null) { queue.addLast(s.right) } } result.add(list) } return result } private var xpar = 0 private var ypar = 0 private var xdep = 0 private var ydep = 0 /** * https://leetcode-cn.com/problems/cousins-in-binary-tree/ */ fun isCousins(root: TreeNode?, x: Int, y: Int): Boolean { if (root == null) { return false } dfs(root.left, 1, x, y, root.`val`) dfs(root.right, 1, x, y, root.`val`) return xdep == ydep && xpar != ypar } private fun dfs(node: TreeNode?, dep: Int, x: Int, y: Int, par: Int) { if (node == null) { return } if (node.`val` == x) { xdep = dep xpar = par } if (node.`val` == y) { ydep = dep ypar = par } dfs(node.left, dep + 1, x, y, node.`val`) dfs(node.right, dep + 1, x, y, node.`val`) } /** * https://leetcode-cn.com/problems/convert-sorted-array-to-binary-search-tree/ */ fun sortedArrayToBST(nums: IntArray): TreeNode? { return null } /** * https://leetcode-cn.com/problems/binary-tree-preorder-traversal/ * 给定一个二叉树,返回它的 前序 遍历,使用迭代法 */ fun preorderTraversal(root: TreeNode?): List<Int> { val list = ArrayList<Int>() if (root == null) { return list } val stack = LinkedList<TreeNode>() stack.addFirst(root) while (stack.isNotEmpty()) { val node = stack.pollFirst() list.add(node.`val`) if (node.right != null) { stack.addFirst(node.right) } if (node.left != null) { stack.addFirst(node.left) } } return list } /** * https://leetcode-cn.com/problems/binary-tree-inorder-traversal/ * 迭代法,中序遍历 */ fun inorderTraversal(root: TreeNode?): List<Int> { if (root == null) { return emptyList() } val list = ArrayList<Int>() val stack = LinkedList<TreeNode>() var p: TreeNode? = root while (p != null || stack.isNotEmpty()) { while (p != null) { stack.addFirst(p) p = p.left } val n = stack.pollFirst() list.add(n.`val`) p = n.right } return list } /** * https://leetcode-cn.com/problems/binary-tree-postorder-traversal/ * 迭代法的后续遍历 */ fun postorderTraversal(root: TreeNode?): List<Int> { if (root == null) { return emptyList() } val result = ArrayList<Int>() val stack = LinkedList<TreeNode>() stack.addFirst(root) while (stack.isNotEmpty()) { val node = stack.pollFirst() result.add(0, node.`val`) node.left?.let { stack.addFirst(it) } node.right?.let { stack.addFirst(it) } } return result } /** * https://leetcode-cn.com/problems/minimum-distance-between-bst-nodes/ */ fun minDiffInBST(root: TreeNode?): Int { var last = Int.MAX_VALUE var minValue = Int.MAX_VALUE val stack = LinkedList<TreeNode>() var p: TreeNode? = root while (p != null || stack.isNotEmpty()) { while (p != null) { stack.addFirst(p) p = p.left } val n = stack.pollFirst() if (last != Int.MAX_VALUE) { minValue = min(minValue, n.`val` - last) } last = n.`val` p = n.right } return minValue } var preNode: TreeNode? = null var minValue = Int.MAX_VALUE /** * 递归实现 */ fun minDiffInBSTStack(root: TreeNode?): Int { dfs(root) return minValue } private fun dfs(root: TreeNode?) { root?.let { dfs(it.left) if (preNode != null) { minValue = min(minValue, it.`val` - preNode!!.`val`) } preNode = root dfs(it.right) } } var last = Long.MIN_VALUE /** * https://leetcode-cn.com/problems/validate-binary-search-tree/ */ fun isValidBST(root: TreeNode?): Boolean { if (root == null) { return true } if (isValidBST(root.left)) { if (root.`val` > last) { last = root.`val`.toLong() return isValidBST(root.right) } } return false } /** * https://leetcode-cn.com/problems/find-mode-in-binary-search-tree/ * 给定一个有相同值的二叉搜索树(BST),找出 BST 中的所有众数(出现频率最高的元素) */ fun findMode(root: TreeNode?): IntArray { val map = HashMap<Int, Int>() val result = ArrayList<Int>() val stack = LinkedList<TreeNode>() var p = root while (p != null || stack.isNotEmpty()) { while (p != null) { stack.addFirst(p) p = p.left } val node = stack.pollFirst() map[node.`val`] = if (node.`val` in map.keys) map[node.`val`]!! + 1 else 1 p = node.right } val maxCount = map.values.max() map.forEach { (t, u) -> if (u == maxCount) { result.add(t) } } return result.toIntArray() } /** * https://leetcode-cn.com/problems/kth-smallest-element-in-a-bst/ */ fun kthSmallest(root: TreeNode?, k: Int): Int { val stack = LinkedList<TreeNode>() var p = root var count = 0 while (p != null || stack.isNotEmpty()) { while (p != null) { stack.addFirst(p) p = p.left } val node = stack.pollFirst() if (++count == k) { return node.`val` } p = node.right } return 0 } /** * https://leetcode-cn.com/problems/second-minimum-node-in-a-binary-tree/ */ fun findSecondMinimumValue(root: TreeNode?): Int { return search(root, root!!.`val`) } private fun search(root: TreeNode?, value: Int): Int { if (root == null) { return -1 } if (root.`val` > value) { return root.`val` } val left = search(root.left, value) val right = search(root.right, value) if (left > value && right > value) { return min(left, right) } return max(left, right) } }
0
Kotlin
0
0
cbb2e3ad8f2d05d7cc54a865265561a0e391a9b9
10,872
leetcode
Apache License 2.0
solutions/src/solutions/y19/day 22.kt
Kroppeb
225,582,260
false
null
@file:Suppress("PackageDirectoryMismatch") package solutions.solutions.y19.d22 import helpers.* import kotlin.collections.* import java.math.BigInteger private fun part1(data: Data) { var pos = 2020L val l = 119315717514047 repeat(50030000) { for (i in data) { val p = i.split(' ') when (p[0]) { "deal" -> pos = when (val q = p.last().toIntOrNull()) { null -> l - pos - 1 else -> (q * pos) % l } "cut" -> { val q = p.last().toInt() pos = (l + pos - q) % l } } } if (pos == 2020L) { println(it + 1) } } print("no") } private tailrec fun getAtPos(data: Iterator<Pair<Int, Int>>, pos: Long, l: Long): Long = if (data.hasNext()) { val (a, q) = data.next() when (a) { 0 -> getAtPos(data, l - pos - 1, l) 1 -> getAtPos(data, (q * pos) % l, l) 2 -> getAtPos(data, (l + pos - q) % l, l) else -> error("") } } else { pos } private fun getOff(a: BigInteger): BigInteger { return a.modPow(l2, ll)!! } val l = 119315717514047L val repeat = 101741582076661L val ll = BigInteger.valueOf(l) val m = BigInteger.valueOf(-1) val l1 = BigInteger.valueOf(l - 1) val l2 = BigInteger.valueOf(l - 2) val mm = m to l1 fun comb(p1: Pair<BigInteger, BigInteger>, p2: Pair<BigInteger, BigInteger>): Pair<BigInteger, BigInteger> { val (off, st) = p1 val (nOff, nst) = p2 return (off + st * nOff) % ll to (st * nst) % ll } fun pow(p1: Pair<BigInteger, BigInteger>, t : Long): Pair<BigInteger, BigInteger> { if(t == 1L){ return p1 }else if(t % 2 == 0L){ val q = pow(p1, t / 2) return comb(q, q) }else{ val q = pow(p1, t / 2) return comb(p1, comb(q, q)) } } private fun part2(data: Data) { var card = BigInteger.valueOf(2020) val pb = data.map { val p = it.split(' ') when (p[0]) { "deal" -> when (val q = p.last().toIntOrNull()) { null -> mm else -> BigInteger.ZERO to getOff(BigInteger.valueOf(q.toLong())) } "cut" -> { val q = p.last().toInt() BigInteger.valueOf(q.toLong()) to BigInteger.ONE } else -> error("") } }.fold(BigInteger.ZERO to BigInteger.ONE) { p1, p2 -> comb(p1, p2) } val(off, st) = pow(pb, repeat) println((( ll + (off + st * card)) % ll) % ll) //println((0 until l).map{(( ll + (off + st * BigInteger.valueOf(it))) % ll) % ll}.indexOf(BigInteger.valueOf(2019))) } typealias Data = List<String> fun main() { val data: Data = getLines(2019_22) part2(data) }
0
Kotlin
0
1
744b02b4acd5c6799654be998a98c9baeaa25a79
2,425
AdventOfCodeSolutions
MIT License