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
leetcode-75-kotlin/src/main/kotlin/LongestSubarrayOf1sAfterDeletingOneElement.kt
Codextor
751,507,040
false
{"Kotlin": 49566}
/** * Given a binary array nums, you should delete one element from it. * * Return the size of the longest non-empty subarray containing only 1's in the resulting array. * Return 0 if there is no such subarray. * * * * Example 1: * * Input: nums = [1,1,0,1] * Output: 3 * Explanation: After deleting the number in position 2, [1,1,1] contains 3 numbers with value of 1's. * Example 2: * * Input: nums = [0,1,1,1,0,1,1,0,1] * Output: 5 * Explanation: After deleting the number in position 4, * [0,1,1,1,1,1,0,1] longest subarray with value of 1's is [1,1,1,1,1]. * Example 3: * * Input: nums = [1,1,1] * Output: 2 * Explanation: You must delete one element. * * * Constraints: * * 1 <= nums.length <= 10^5 * nums[i] is either 0 or 1. * @see <a href="https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element/">LeetCode</a> */ fun longestSubarray(nums: IntArray): Int { var startIndex = 0 var numberOfZeros = 0 var maxConsecutiveOnes = 0 for ((endIndex, endDigit) in nums.withIndex()) { if (endDigit == 0) { numberOfZeros++ } while (numberOfZeros > 1) { if (nums[startIndex] == 0) { numberOfZeros-- } startIndex++ } maxConsecutiveOnes = maxOf(maxConsecutiveOnes, endIndex - startIndex) } return maxConsecutiveOnes }
0
Kotlin
0
0
0511a831aeee96e1bed3b18550be87a9110c36cb
1,395
leetcode-75
Apache License 2.0
src/main/kotlin/g1501_1600/s1515_best_position_for_a_service_centre/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1501_1600.s1515_best_position_for_a_service_centre // #Hard #Math #Geometry #Randomized #2023_06_12_Time_183_ms_(100.00%)_Space_34.5_MB_(100.00%) class Solution { fun getMinDistSum(positions: Array<IntArray>): Double { var minX = Int.MAX_VALUE.toDouble() var minY = Int.MAX_VALUE.toDouble() var maxX = Int.MIN_VALUE.toDouble() var maxY = Int.MIN_VALUE.toDouble() for (pos in positions) { maxX = Math.max(maxX, pos[0].toDouble()) maxY = Math.max(maxY, pos[1].toDouble()) minX = Math.min(minX, pos[0].toDouble()) minY = Math.min(minY, pos[1].toDouble()) } var xMid = minX + (maxX - minX) / 2 var yMid = minY + (maxY - minY) / 2 var jump = Math.max(maxX - minX, maxY - minY) var ans = getTotalDistance(xMid, yMid, positions) while (jump > 0.00001) { val list = getFourCorners(xMid, yMid, jump) var found = false for (point in list) { val pointAns = getTotalDistance(point[0], point[1], positions) if (ans > pointAns) { xMid = point[0] yMid = point[1] ans = pointAns found = true } } if (!found) { jump = jump / 2 } } return ans } private fun getFourCorners(xMid: Double, yMid: Double, jump: Double): List<DoubleArray> { val list: MutableList<DoubleArray> = ArrayList() list.add(doubleArrayOf(xMid - jump, yMid + jump)) list.add(doubleArrayOf(xMid + jump, yMid + jump)) list.add(doubleArrayOf(xMid - jump, yMid - jump)) list.add(doubleArrayOf(xMid + jump, yMid - jump)) return list } private fun getTotalDistance(x: Double, y: Double, positions: Array<IntArray>): Double { var totalDistanceSum = 0.0 for (point in positions) { val xDistance = x - point[0] val yDistance = y - point[1] totalDistanceSum += Math.sqrt(xDistance * xDistance + yDistance * yDistance) } return totalDistanceSum } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,209
LeetCode-in-Kotlin
MIT License
src/Day05.kt
cerberus97
579,910,396
false
{"Kotlin": 11722}
fun main() { fun parseInputStacks(input: List<String>): List<MutableList<Char>> { val numStacks = (input[0].length + 1) / 4 val stacks = List(numStacks) { mutableListOf<Char>() } input.forEach { row -> if (row.contains('[')) { row.forEachIndexed { idx, crate -> if (crate.isUpperCase()) { val stackIdx = ((idx - 1) / 4) stacks[stackIdx] += crate } } } } stacks.forEach { it.reverse() } return stacks } fun part1(input: List<String>): String { val stacks = parseInputStacks(input) input.forEach { row -> if (row.contains("move")) { val tokens = row.split(' ') val cnt = tokens[1].toInt() val from = tokens[3].toInt() - 1 val to = tokens[5].toInt() - 1 repeat(cnt) { stacks[to] += stacks[from].removeLast() } } } return stacks.joinToString("") { stack -> stack.last().toString() } } fun part2(input: List<String>): String { val stacks = parseInputStacks(input) input.forEach { row -> if (row.contains("move")) { val tokens = row.split(' ') val cnt = tokens[1].toInt() val from = tokens[3].toInt() - 1 val to = tokens[5].toInt() - 1 val toMove = mutableListOf<Char>() repeat(cnt) { toMove += stacks[from].removeLast() } stacks[to] += toMove.reversed() } } return stacks.joinToString("") { stack -> stack.last().toString() } } val input = readInput("in") part1(input).println() part2(input).println() }
0
Kotlin
0
0
ed7b5bd7ad90bfa85e868fa2a2cdefead087d710
1,585
advent-of-code-2022-kotlin
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/TwoSumLessThanK.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.util.Arrays import kotlin.math.max fun interface TwoSumLessThanKStrategy { operator fun invoke(nums: IntArray, k: Int): Int } class TwoSumLessThanKBruteForce : TwoSumLessThanKStrategy { override operator fun invoke(nums: IntArray, k: Int): Int { var answer = -1 for (i in nums.indices) { for (j in i + 1 until nums.size) { val sum = nums[i] + nums[j] if (sum < k) { answer = max(answer, sum) } } } return answer } } class TwoSumLessThanKTwoPointers : TwoSumLessThanKStrategy { override operator fun invoke(nums: IntArray, k: Int): Int { nums.sort() var answer = -1 var left = 0 var right: Int = nums.size - 1 while (left < right) { val sum = nums[left] + nums[right] if (sum < k) { answer = max(answer, sum) left++ } else { right-- } } return answer } } class TwoSumLessThanKBinarySearch : TwoSumLessThanKStrategy { override operator fun invoke(nums: IntArray, k: Int): Int { var answer = -1 nums.sort() for (i in nums.indices) { val idx: Int = Arrays.binarySearch(nums, i + 1, nums.size, k - nums[i] - 1) var j = if (idx >= 0) idx else idx.inv() if (j == nums.size || nums[j] > k - nums[i] - 1) { j-- } if (j > i) { answer = max(answer, nums[i] + nums[j]) } } return answer } } class TwoSumLessThanKCountingSort : TwoSumLessThanKStrategy { override operator fun invoke(nums: IntArray, k: Int): Int { var answer = -1 val count = IntArray(ARRAY_SIZE) for (num in nums) { count[num]++ } var lo = 1 var hi = MAX while (lo <= hi) { if (lo + hi >= k || count[hi] == 0) { hi-- } else { if (count[lo] > (if (lo < hi) 0 else 1)) { answer = max(answer, lo + hi) } lo++ } } return answer } companion object { private const val ARRAY_SIZE = 1001 private const val MAX = 1000 } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,013
kotlab
Apache License 2.0
src/main/kotlin/com/colinodell/advent2022/Day23.kt
colinodell
572,710,708
false
{"Kotlin": 105421}
package com.colinodell.advent2022 class Day23(input: List<String>) { private val elves = input.toGrid().filter { it.value == '#' }.keys fun solvePart1() = simulate() .take(10) .last() .let { elves -> (elves.width() * elves.height()) - elves.count() } fun solvePart2() = simulate().indexOfLast { true } + 2 // +1 because we're 0-indexed, and another +1 because our sequence excludes the next state where everything stays the same private fun simulate() = sequence { var elves = elves var round = 0 while (true) { // First half val proposedPositions = elves .associateWith { elf -> proposeNextMove(elf, elves, round) } .also { p -> if (p.all { it.value == null }) { // No moves to make, we're done! return@sequence } } .mapValues { (current, move) -> move?.let { current + move } ?: current } // Second half val countAtPosition = proposedPositions.values.groupingBy { it }.eachCount() elves = proposedPositions.map { (originalPos, proposedPos) -> if (countAtPosition[proposedPos]!! > 1) { originalPos } else { proposedPos } }.toSet() yield(elves) round++ } } private val proposalOffsets = listOf( listOf(Vector2(0, -1), Vector2(-1, -1), Vector2(1, -1)), // North listOf(Vector2(0, 1), Vector2(-1, 1), Vector2(1, 1)), // South listOf(Vector2(-1, 0), Vector2(-1, -1), Vector2(-1, 1)), // West listOf(Vector2(1, 0), Vector2(1, -1), Vector2(1, 1)) // East ) /** * Returns the direction the elf should move, or null if it should stay put */ private fun proposeNextMove(currentPos: Vector2, elves: Set<Vector2>, round: Int): Vector2? { // Are all surrounding spaces empty? if (currentPos.neighborsIncludingDiagonals().none { it in elves }) { return null } // Consider each of the four directions (in the order we prefer this round) for (i in 0..3) { val movesToConsider = proposalOffsets[(i + round) % 4] // Are any of these three spaces occupied? if (movesToConsider.none { elves.contains(currentPos + it) }) { return movesToConsider[0] } } return null } }
0
Kotlin
0
1
32da24a888ddb8e8da122fa3e3a08fc2d4829180
2,624
advent-2022
MIT License
src/main/kotlin/day03/Main.kt
jhreid
739,775,732
false
{"Kotlin": 13073}
package day03 import java.io.File fun main() { val input = File("./day03.txt").readLines(Charsets.UTF_8) val valid = input.filter { line -> val sides = line.trim().split("\\s+".toRegex()).map { it.toInt() } val (one, two, three) = Triple(sides[0], sides[1], sides[2]) one + two > three && one + three > two && two + three > one } println("Part 1 valid: ${valid.size}") val valid1 = input.map { line -> val sides = line.trim().split("\\s+".toRegex()).map { it.toInt() } sides[0] }.chunked(3).filter { chunk -> val (one, two, three) = Triple(chunk[0], chunk[1], chunk[2]) one + two > three && one + three > two && two + three > one }.size val valid2 = input.map { line -> val sides = line.trim().split("\\s+".toRegex()).map { it.toInt() } sides[1] }.chunked(3).filter { chunk -> val (one, two, three) = Triple(chunk[0], chunk[1], chunk[2]) one + two > three && one + three > two && two + three > one }.size val valid3 = input.map { line -> val sides = line.trim().split("\\s+".toRegex()).map { it.toInt() } sides[2] }.chunked(3).filter { chunk -> val (one, two, three) = Triple(chunk[0], chunk[1], chunk[2]) one + two > three && one + three > two && two + three > one }.size println("Part 2 valid ${valid1 + valid2 + valid3}") }
0
Kotlin
0
0
8eeb2bc6b13e76d83a5403ae087729e2c3bbadb1
1,409
AdventOfCode2016
Apache License 2.0
src/main/kotlin/com/resnik/intel/similarity/Extensions.kt
mtresnik
389,683,705
false
null
package com.resnik.intel.similarity import java.util.* fun String.lcs(other: String): String { val numArray = Array(this.length + 1) { IntArray(other.length + 1) { 0 } } for (i in 1 until this.length + 1) { val c1 = this[i - 1] for (j in 1 until other.length + 1) { val c2 = other[j - 1] if (c1 == c2) { numArray[i][j] = numArray[i - 1][j - 1] + 1; } else { numArray[i][j] = numArray[i - 1][j].coerceAtLeast(numArray[i][j - 1]) } } } val retStack = Stack<Char>() var i = numArray.size - 1 var j = numArray[0].size - 1 var currNum = numArray[i][j] while (currNum != 0) { when { numArray[i - 1][j] == currNum -> { i-- } numArray[i][j - 1] == currNum -> { j-- } numArray[i - 1][j - 1] != currNum -> { i-- j-- retStack.push(this[i]) } } currNum = numArray[i][j] } var retString: String = "" while (!retStack.isEmpty()) { retString += retStack.pop() } return retString } fun String.lcsSimilarity(other: String): Double = this.lcs(other).length.toDouble() / this.length.coerceAtLeast(other.length) fun String.jaro(other: String): Double { if (this.isEmpty() && other.isEmpty()) return 1.0 val maxMatchDistance = this.length.coerceAtLeast(other.length) / 2 - 1 val thisMatchArray = BooleanArray(this.length) val otherMatchArray = BooleanArray(other.length) var matches = 0 for (i in this.indices) { val start = 0.coerceAtLeast(i - maxMatchDistance) val end = (i + maxMatchDistance + 1).coerceAtMost(other.length) (start until end).find { j -> !otherMatchArray[j] && this[i] == other[j] }?.let { thisMatchArray[i] = true otherMatchArray[it] = true matches++ } } if (matches == 0) return 0.0 var t = 0.0 var k = 0 (this.indices).filter { thisMatchArray[it] }.forEach { i -> while (!otherMatchArray[k]) k++ if (this[i] != other[k]) t += 0.5 k++ } val m = matches.toDouble() return (m / this.length + m / other.length + (m - t) / m) / 3.0 } fun String.jaroWinkler(other: String, scalingFactor: Double = 0.1): Double { val sJ = this.jaro(other) if (sJ <= 0.7) return sJ val prefix = (0 until this.length.coerceAtMost(other.length)) .count { this[it] == other[it] } .coerceAtMost(4) .toDouble() println(prefix) return sJ + scalingFactor * prefix * (1.0 - sJ) }
0
Kotlin
0
0
46f23b3033a385e29c043712c0edf9b7023de316
2,773
intel
Apache License 2.0
src/Day08.kt
ostersc
572,991,552
false
{"Kotlin": 46059}
fun main() { data class Tree(val x: Int, val y: Int) fun parseTrees( input: List<String>, treeMap: MutableList<MutableList<Int>>, visibleTrees: MutableSet<Tree> ) { //LOOK FROM LEFT //parsing populates the treemap, and also does the look from left for (yIndex in 0..input.lastIndex) { var rowMax = -1 treeMap.add(yIndex, mutableListOf()) for (xIndex in 0..input[yIndex].lastIndex) { val currHeight = input[yIndex][xIndex].digitToInt() treeMap[yIndex].add(xIndex, currHeight) if (currHeight > rowMax) { //println("Adding visible tree with height $currHeight from LEFT at $xIndex,$yIndex") visibleTrees.add(Tree(xIndex, yIndex)) rowMax = currHeight } } } //LOOK FROM RIGHT //Walk array from right, x n ..0, increasing y //Add to set each (x,y) that is > than rowMax and update rowMax for (yIndex in 0..treeMap.lastIndex) { var rowMax = -1 for (xIndex in treeMap[yIndex].lastIndex downTo 0) { val currHeight = treeMap[yIndex][xIndex] if (currHeight > rowMax) { //println("Adding visible tree with height $currHeight from RIGHT at $xIndex,$yIndex") visibleTrees.add(Tree(xIndex, yIndex)) rowMax = currHeight } } } //LOOK FROM TOP //Walk array from top, y 0..n, increasing x //Add to set each (x,y) that is > than colMax and update colMax for (xIndex in 0..treeMap[0].lastIndex) { var colMax = -1 for (yIndex in 0..treeMap.lastIndex) { val currHeight = treeMap[yIndex][xIndex] if (currHeight > colMax) { //println("Adding visible tree with height $currHeight from TOP at $xIndex,$yIndex") visibleTrees.add(Tree(xIndex, yIndex)) colMax = currHeight } } } //LOOK FROM BOTTOM //Walk array from bottom , y n ..0, increasing x //Add to set each (x,y) that is > than colMax and update colMax for (xIndex in 0..treeMap[0].lastIndex) { var colMax = -1 for (yIndex in treeMap.lastIndex downTo 0) { val currHeight = treeMap[yIndex][xIndex] if (currHeight > colMax) { //println("Adding visible tree with height $currHeight from BOTTOM at $xIndex,$yIndex") visibleTrees.add(Tree(xIndex, yIndex)) colMax = currHeight } } } } fun part1(input: List<String>): Int { val treeMap = MutableList(0) { mutableListOf<Int>() } val visibleTrees = mutableSetOf<Tree>() parseTrees(input, treeMap, visibleTrees) return visibleTrees.size } fun scenicScoreFor(t: Tree, treeMap: MutableList<MutableList<Int>>): Int { var score: Int val height = treeMap[t.y][t.x] var dirScore = 0 //UP for (y in t.y - 1 downTo 0) { if (treeMap[y][t.x] < height) { dirScore++ } else if (treeMap[y][t.x] >= height) { dirScore++ break } } score = dirScore //DOWN dirScore = 0 for (y in t.y + 1..treeMap.lastIndex) { if (treeMap[y][t.x] < height) { dirScore++ } else if (treeMap[y][t.x] >= height) { dirScore++ break } } score *= dirScore //RIGHT dirScore = 0 for (x in t.x + 1..treeMap.lastIndex) { if (treeMap[t.y][x] < height) { dirScore++ } else if (treeMap[t.y][x] >= height) { dirScore++ break } } score *= dirScore //LEFT dirScore = 0 for (x in t.x - 1 downTo 0) { if (treeMap[t.y][x] < height) { dirScore++ } else if (treeMap[t.y][x] >= height) { dirScore++ break } } score *= dirScore return score } fun part2(input: List<String>): Int { val treeMap = MutableList(0) { mutableListOf<Int>() } val visibleTrees = mutableSetOf<Tree>() parseTrees(input, treeMap, visibleTrees) var max = -1 for (t in visibleTrees) { val tScore = scenicScoreFor(t, treeMap) if (tScore > max) { max = tScore } } return max } val testInput = readInput("Day08_test") val part1Test = part1(testInput) check(part1Test == 21) val part2Test = part2(testInput) check(part2Test == 8) val input = readInput("Day08") val part1 = part1(input) println(part1) check(part1 == 1798) val part2 = part2(input) println(part2) check(part2==259308) }
0
Kotlin
0
1
3eb6b7e3400c2097cf0283f18b2dad84b7d5bcf9
5,210
advent-of-code-2022
Apache License 2.0
src/2021/Day4_1.kts
Ozsie
318,802,874
false
{"Kotlin": 99344, "Python": 1723, "Shell": 975}
import java.io.File import kotlin.collections.HashMap import kotlin.collections.ArrayList class Box(val value: Int, val x: Int, val y: Int, var selected: Boolean = false) class Board(val boxes: ArrayList<Box>) { fun selectIf(number: Int) = boxes.filter { it.value == number }.forEach { it.selected = true } fun bingo(): Boolean { for (rowOrColumn in 0..5) { if (boxes.filter { it.x == rowOrColumn }.filter { it.selected }.size == 5 || boxes.filter { it.y == rowOrColumn }.filter { it.selected }.size == 5) { return true } } return false } fun won(number: Int) = println(boxes.filter { !it.selected }.map { it.value }.sum() * number) } var numbers = ArrayList<Int>() var boards = ArrayList<Board>() var currentBoardY = 0 File("input/2021/day4").forEachLine { line -> if (numbers.isEmpty()) { numbers.addAll(line.split(",").map { it.toInt() }) } else if (line.isBlank()) { currentBoardY = 0 var currentBoard = Board(ArrayList<Box>()) boards.add(currentBoard) } else { var row = line.split(" ") .filter { it.isNotBlank() } .mapIndexed { index, s -> Box(s.trim().toInt(), index, currentBoardY) } boards.last().boxes.addAll(row) currentBoardY++ } } var won = false for (number in numbers) { for (board in boards) { board.selectIf(number) if (board.bingo() && !won) { won = true board.won(number) } } if (winner != null) break }
0
Kotlin
0
0
d938da57785d35fdaba62269cffc7487de67ac0a
1,581
adventofcode
MIT License
2022/src/main/kotlin/de/skyrising/aoc2022/day20/solution.kt
skyrising
317,830,992
false
{"Kotlin": 411565}
package de.skyrising.aoc2022.day20 import de.skyrising.aoc.* class CircularLongListItem(val value: Long) { var next = this var prev = this fun connect(next: CircularLongListItem) { next.prev = this this.next = next } fun move(steps: Int) { if (steps == 0) return val dest = this + steps val p = prev val n = next next = dest.next prev = dest prev.next = this next.prev = this p.next = n n.prev = p } operator fun plus(steps: Int): CircularLongListItem { var dest = this if (steps > 0) { repeat(steps) { dest = dest.next } } else if (steps < 0) { repeat(-steps + 1) { dest = dest.prev } } return dest } } private fun parseInput(input: PuzzleInput, multiplier: Long): Pair<List<CircularLongListItem>, CircularLongListItem> { val numbers = input.lines.map { CircularLongListItem(it.toLong() * multiplier) } var zero: CircularLongListItem? = null for (i in numbers.indices) { val n = numbers[i] if (n.value == 0L) zero = n n.connect(numbers[(i + 1) % numbers.size]) } if (zero == null) error("No zero") return numbers to zero } private fun groveCoordinates(input: PuzzleInput, multiplier: Long, mixes: Int): Long { val (numbers, zero) = parseInput(input, multiplier) repeat(mixes) { for (item in numbers) { item.move((item.value % (numbers.size - 1)).toInt()) } } val a = zero + 1000 val b = a + 1000 val c = b + 1000 return a.value + b.value + c.value } val test = TestInput(""" 1 2 -3 3 -2 0 4 """) @PuzzleName("Grove Positioning System") fun PuzzleInput.part1() = groveCoordinates(this, 1, 1) fun PuzzleInput.part2() = groveCoordinates(this, 811589153, 10)
0
Kotlin
0
0
19599c1204f6994226d31bce27d8f01440322f39
1,945
aoc
MIT License
src/Day21.kt
jvmusin
572,685,421
false
{"Kotlin": 86453}
import java.math.BigInteger import java.util.* fun main() { fun part1(input: List<String>): Long { val monkeys = HashMap<String, () -> Long>() val cache = HashMap<String, Long>() fun get(name: String): Long = cache.getOrPut(name) { return monkeys[name]!!() } for (m in input) { val parts = m.split(": ") val name = parts[0] val right = parts[1].split(" ") if (right.size == 1) { val x = right[0].toLong() monkeys[name] = { x } } else { val x = right[0] val y = right[2] val op = when (right[1].single()) { '+' -> { { get(x) + get(y) } } '-' -> { { get(x) - get(y) } } '/' -> { { get(x) / get(y) } } '*' -> { { get(x) * get(y) } } else -> error("") } monkeys[name] = { op() } } } return monkeys["root"]!!() } val U = BigInteger.valueOf(100).pow(10000).times(BigInteger.valueOf(-1)) fun part2(input: List<String>): BigInteger { val names = input.map { it.split(": ")[0] } val depX = IntArray(names.size) { -1 } val depY = IntArray(names.size) { -1 } val op = CharArray(names.size) val value = Array(names.size) { BigInteger.ZERO } val cache = Array(names.size) { U } for (m in input) { val parts = m.split(": ") val name = names.indexOf(parts[0]) val right = parts[1].split(" ") if (right.size == 1) { val x = right[0].toBigInteger() value[name] = x } else { depX[name] = names.indexOf(right[0]) depY[name] = names.indexOf(right[2]) op[name] = right[1].single() } } fun get(idx: Int): BigInteger { val ready = cache[idx] if (ready != U) return ready val res = when (op[idx]) { '+' -> get(depX[idx]) + get(depY[idx]) '-' -> get(depX[idx]) - get(depY[idx]) '/' -> get(depX[idx]) / get(depY[idx]) '*' -> get(depX[idx]) * get(depY[idx]) else -> value[idx] } cache[idx] = res return res } val rootIndex = names.indexOf("root") val rootXIndex = depX[rootIndex] val rootYIndex = depY[rootIndex] val humanIndex = names.indexOf("humn") cache.fill(U) val rootYValue = get(rootYIndex) println("ROOT Y VALUE = $rootYValue") val variable = cache.indices.filter { cache[it] == U }.toIntArray() println("Human index $humanIndex") println("Variables ${variable.toList()}") require(humanIndex in variable) require(rootXIndex in variable) fun getXWithHuman(human: BigInteger): BigInteger { cache.fill(U) value[humanIndex] = human return get(rootXIndex) } var step = BigInteger.ONE while (getXWithHuman(step) >= rootYValue) { require(getXWithHuman(step) >= getXWithHuman(step * BigInteger.TWO)) { "$step" } step *= BigInteger.TWO } var L = step / BigInteger.TWO var R = step while (R - L > BigInteger.ONE) { val M = (L + R) / BigInteger.TWO val xWithHuman = getXWithHuman(M) if (xWithHuman > rootYValue) L = M else R = M } println("Right is $R value is ${getXWithHuman(R)} yValue is $rootYValue") var prev = (-1).toBigInteger() var humanValue = L.dec() while (true) { humanValue = humanValue.inc() if (humanValue % BigInteger.valueOf(1_000_000) == BigInteger.ZERO) { println("Time $humanValue") } for (i in variable) cache[i] = U value[humanIndex] = humanValue val rootXValue = get(rootXIndex) if (rootXValue == get(rootYIndex)) { return humanValue } if (rootXValue != prev) { prev = rootXValue require(rootXValue > prev) println("New rootX = $rootXValue, rootY = $rootYValue") } } } @Suppress("DuplicatedCode") run { val day = String.format("%02d", 21) val testInput = readInput("Day${day}_test") val input = readInput("Day$day") println("Part 1 test - " + part1(testInput)) println("Part 1 real - " + part1(input)) println("---") // println("Part 2 test - " + part2(testInput)) println("Part 2 real - " + part2(input)) } }
1
Kotlin
0
0
4dd83724103617aa0e77eb145744bc3e8c988959
5,023
advent-of-code-2022
Apache License 2.0
src/array/TwoSums.kt
develNerd
456,702,818
false
{"Kotlin": 37635, "Java": 5892}
/* * * * * Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order. Example 1: Input: nums = [2,7,11,15], target = 9 Output: [0,1] Explanation: Because nums[0] + nums[1] == 9, we return [0, 1]. Example 2: Input: nums = [3,2,4], target = 6 Output: [1,2] Example 3: Input: nums = [3,3], target = 6 Output: [0,1] Constraints: 2 <= nums.length <= 104 -109 <= nums[i] <= 109 -109 <= target <= 109 Only one valid answer exists. Follow-up: Can you come up with an algorithm that is less than O(n2) time complexity? Accepted 5,872,105 Submissions 12,180,827 * * * * * * * * */ /** * Solution * Summary : Given the array and the target we find the complement of each integer in the array and add it to a key value pair data structure. We will be using a map in this tutorial. We store the complement as a key and it's index as the value. As we iterate through the loop we check through the list of keys to see if our current number exists. If it exits then we can return the required indexes. * * 1. Corner Case - if @param[nums] we return an integer array of 00 2. Create a key-value pair to hold the complement, and it's index 3. As we Iterate, we calculate the current complement 4. Check if the current value @param[nums[i]] exists in the complements(keys) 5. Return the value of the complement (index) and the current index if "step 4" is true 6. We then add if "Step 4" is false 7. Return an intArrayOf (0,0) if we did not find the target indexes. * * */ fun main(){ println(twoSum(intArrayOf(2,7,11,15),9).asList()) } fun twoSum(nums: IntArray, target: Int): IntArray { /** * Corner Case * if @param[nums] we return intArrayOf(0,0) * */ //1 if (nums.isEmpty()) return intArrayOf(0,0) //2 val complements = mutableMapOf<Int,Int>() for(i in nums.indices){ //3 var complement = target.minus(nums[i]) //4 if(nums[i] in complements.keys ){ //5 return intArrayOf(complements.get(nums[i])!!,i) } //6 complements.put(complement,i) } //7 return intArrayOf(0,0) }
0
Kotlin
0
0
4e6cc8b4bee83361057c8e1bbeb427a43622b511
2,351
Blind75InKotlin
MIT License
src/Day05.kt
a-glapinski
572,880,091
false
{"Kotlin": 26602}
import utils.component6 import utils.readInputAsLines fun main() { val (stacksInput, proceduresInput) = readInputAsLines("day05_input").asSequence() .filter { it.isNotBlank() } .partition { !it.startsWith("move") } val stackIndices = stacksInput.last().withIndex() .filter { (_, c) -> c.isDigit() } .map { (index, _) -> index } val stacks = List(stackIndices.size) { ArrayDeque<Char>() }.apply { stacksInput.dropLast(1) .map { it.filterIndexed { index, _ -> index in stackIndices } } .forEach { level -> level.forEachIndexed { index, c -> if (c.isLetter()) get(index).addLast(c) } } } val procedures = proceduresInput.asSequence() .map { it.split(' ') } .map { (_, quantity, _, from, _, to) -> Triple(quantity.toInt(), from.toInt(), to.toInt()) } fun part1(): String { val s = stacks.map(::ArrayDeque) procedures.forEach { (quantity, from, to) -> repeat(quantity) { s[to - 1].addFirst(s[from - 1].removeFirst()) } } return s.map { it.first() }.joinToString("") } println(part1()) fun part2(): String { val s = stacks.map(::ArrayDeque) procedures.forEach { (quantity, from, to) -> List(quantity) { s[from - 1].removeFirst() }.asReversed() .forEach { s[to - 1].addFirst(it) } } return s.map { it.first() }.joinToString("") } println(part2()) }
0
Kotlin
0
0
c830d23ffc2ab8e9a422d015ecd413b5b01fb1a8
1,586
advent-of-code-2022
Apache License 2.0
src/Day04.kt
lmoustak
573,003,221
false
{"Kotlin": 25890}
fun main() { fun stringToRange(s: String): IntRange { val endpoints = s.split('-') val start = endpoints[0].toInt() val end = endpoints[1].toInt() return start..end } fun part1(input: List<String>): Int { var overlaps = 0 for (line in input) { val ranges = line.split(',') val range1 = stringToRange(ranges[0]) val range2 = stringToRange(ranges[1]) if (range1 contains range2 || range2 contains range1) overlaps++ } return overlaps } fun part2(input: List<String>): Int { var overlaps = 0 for (line in input) { val ranges = line.split(',') val range1 = stringToRange(ranges[0]) val range2 = stringToRange(ranges[1]) if (range1 overlaps range2 || range2 overlaps range1) overlaps++ } return overlaps } val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
bd259af405b557ab7e6c27e55d3c419c54d9d867
1,014
aoc-2022-kotlin
Apache License 2.0
14/kotlin/src/main/kotlin/se/nyquist/Day14.kt
erinyq712
437,223,266
false
{"Kotlin": 91638, "C#": 10293, "Emacs Lisp": 4331, "Java": 3068, "JavaScript": 2766, "Perl": 1098}
package se.nyquist 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) private fun parseTemplate(input: String): Map<String, Long> = input .windowed(2) .groupingBy { it } .eachCount().mapValues { it.value.toLong() } private fun parseRules(input: List<String>): Map<String, Char> = input.drop(2).associate { it.substring(0..1) to it[6] } fun solvePart0(): Long = solve(1) 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 } }
0
Kotlin
0
0
b463e53f5cd503fe291df692618ef5a30673ac6f
1,676
adventofcode2021
Apache License 2.0
src/main/kotlin/com/manalili/advent/Day07.kt
maines-pet
162,116,190
false
null
package com.manalili.advent import java.util.* class Day07(input: List<String>) { private val instructions: MutableMap<Char, MutableList<Char>> = mutableMapOf() private val regex = Regex("""Step ([A-z]) must be finished before step ([A-z]) can begin.""") init { input.forEach { val (step: String, next: String) = regex.find(it)!!.destructured instructions.getOrPut(step[0]) { mutableListOf() } .add(next[0]) } } fun orderOfInstructions(): String { val stepsWithPrereqs = instructions.flatMap { it.value } .groupingBy { it }.eachCount().toMutableMap() val edges = instructions.keys.filterNot { stepsWithPrereqs.contains(it) } val queue = TreeSet<Char>(edges) val result = StringBuilder() while (true) { val current = queue.pollFirst() .also { result.append(it) } instructions[current]?.let { it.forEach { requisite -> val lock = stepsWithPrereqs.merge(requisite, 1, Int::minus) if (lock == 0) { queue.add(requisite) } } } if (queue.size == 0) break } return result.toString() } fun part2(): Int { val workers = 5 val steps = instructions.values.flatten() //Steps and their NUMBER of prerequisites to be fulfilled before they can be started val stepsWithPrereqCount: MutableMap<Char, Int> = ('A'..'Z').associateWith { steps.count { c -> c == it } }.toMutableMap() //Use SortedMap data structure to keep the priorities of steps according to //their alphabetical order and put time remaining as Value val workQueue = sortedMapOf<Char, Int>() //get all edges ie steps with no prerequisites stepsWithPrereqCount.filterValues { it == 0 }.keys.forEach { workQueue[it] = it.toDuration() } //Steps with time remaining var totalTimeWorked = 0 while (workQueue.isNotEmpty()) { val inProgress = workQueue.keys.take(minOf(workers, workQueue.size)) val min = workQueue[inProgress.minBy { workQueue[it]!! }]!! totalTimeWorked += min //subtract to inprogress inProgress.forEach { //subtract the time spent val timeRemaining = workQueue.merge(it, min, Int::minus) if (timeRemaining == 0) { //remove from queue workQueue.remove(it) //inspect children instructions[it]?.forEach { child -> val numOfStepsLeft = stepsWithPrereqCount.merge(child, 1, Int::minus) //release and add to queue if no more prereq if (numOfStepsLeft == 0) { workQueue[child] = child.toDuration() } } } } } return totalTimeWorked } private fun Char.toDuration() = this - 'A' + 61 }
0
Kotlin
0
0
25a01e13b0e3374c4abb6d00cd9b8d7873ea6c25
3,194
adventOfCode2018
MIT License
untitled/src/main/kotlin/Day4.kt
jlacar
572,845,298
false
{"Kotlin": 41161}
class Day4(private val fileName: String) : AocSolution { override val description: String get() = "Day 4 - Camp Cleanup ($fileName)" private val input = InputReader(fileName).lines override fun part1() = input.count { hasFullContainment(it) } override fun part2() = input.count { hasOverlap(it) } } fun hasFullContainment(it: String): Boolean { val (assignment1, assignment2) = it.split(",") val section1 = Section(assignment1) //.also(::println) val section2 = Section(assignment2) //.also(::println) return section1.contains(section2) || section2.contains(section1) } fun hasOverlap(it: String): Boolean { val (assignment1, assignment2) = it.split(",") return Section(assignment1).overlaps(Section(assignment2)) } class Section(specifier: String) { private val range: IntRange init { val (from, to) = specifier.split("-") range = from.toInt()..to.toInt() } fun contains(other: Section) = other.range.first in range && other.range.last in range fun overlaps(other: Section) = range.first <= other.range.last && range.last >= other.range.first override fun toString(): String = range.toString() } fun main() { Day4("Day4-sample.txt") solution { part1() shouldBe 2 part2() shouldBe 4 } Day4("Day4.txt") solution { part1() shouldBe 471 part2() shouldBe 888 } Day4("Day4-alt.txt") solution { part1() shouldBe 507 part2() shouldBe 897 } }
0
Kotlin
0
2
dbdefda9a354589de31bc27e0690f7c61c1dc7c9
1,511
adventofcode2022-kotlin
The Unlicense
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[108]将有序数组转换为二叉搜索树.kt
maoqitian
175,940,000
false
{"Kotlin": 354268, "Java": 297740, "C++": 634}
//给你一个整数数组 nums ,其中元素已经按 升序 排列,请你将其转换为一棵 高度平衡 二叉搜索树。 // // 高度平衡 二叉树是一棵满足「每个节点的左右两个子树的高度差的绝对值不超过 1 」的二叉树。 // // // // 示例 1: // // //输入:nums = [-10,-3,0,5,9] //输出:[0,-3,9,-10,null,5] //解释:[0,-10,5,null,-3,null,9] 也将被视为正确答案: // // // // 示例 2: // // //输入:nums = [1,3] //输出:[3,1] //解释:[1,3] 和 [3,1] 都是高度平衡二叉搜索树。 // // // // // 提示: // // // 1 <= nums.length <= 104 // -104 <= nums[i] <= 104 // nums 按 严格递增 顺序排列 // // Related Topics 树 二叉搜索树 数组 分治 二叉树 // 👍 863 👎 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 sortedArrayToBST(nums: IntArray): TreeNode? { return buildTree(nums,0,nums.size-1) } //中序遍历 private fun buildTree(nums: IntArray, left: Int, right: Int): TreeNode? { //递归 //递归结束条件 if (left>right) return null //逻辑处理进入下层循环 var mid = left + (right-left)/2 TreeNode treeNode = TreeNode(nums[mid]) //左子树 treeNode.left = buildTree(nums,left,mid-1) treeNode.right = buildTree(nums,mid+1,right) //右子树 //数据 reverse return treeNode } } //leetcode submit region end(Prohibit modification and deletion)
0
Kotlin
0
1
8a85996352a88bb9a8a6a2712dce3eac2e1c3463
1,766
MyLeetCode
Apache License 2.0
src/Day03.kt
Advice-Dog
436,116,275
true
{"Kotlin": 25836}
fun main() { fun part1(input: List<String>): Int { val counts = Array(input.first().length) { 0 } for (binary in input) { for ((index, c) in binary.withIndex()) { counts[index] += c.digitToInt() } } val gammaRate = Integer.parseInt(counts.joinToString("") { if (it > input.size / 2) "1" else "0" }, 2) val epsilonRate = Integer.parseInt(counts.joinToString("") { if (it < input.size / 2) "1" else "0" }, 2) return gammaRate * epsilonRate } fun part2(input: List<String>): Int { val maxLength = input.first().length var index = 0 var temp = input while (temp.size > 1 && index < maxLength) { val count = temp.count { it[index] == '1' } val common = if (count >= temp.size - count) { '1' } else { '0' } temp = temp.filter { it[index] == common } index++ } val oxygenGenerationRate = Integer.parseInt(temp.first(), 2) index = 0 temp = input while (temp.size > 1 && index < maxLength) { val count = temp.count { it[index] == '1' } val common = if (count >= temp.size - count) { '1' } else { '0' } temp = temp.filter { it[index] != common } index++ } val co2ScrubberRating = Integer.parseInt(temp.first(), 2) return oxygenGenerationRate * co2ScrubberRating } // test if implementation meets criteria from the description, like: val testInput = getTestData("Day03") check(part1(testInput) == 198) check(part2(testInput) == 230) val input = getData("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
2a2a4767e7f0976dba548d039be148074dce85ce
1,890
advent-of-code-kotlin-template
Apache License 2.0
src/Day01.kt
malteesch
573,138,358
false
{"Kotlin": 1690}
fun main() { fun part1(input: String): Int = input .splitToSequence("\n{2}".toRegex()) .map { it.split("\n".toRegex()) } .maxOf { list -> list .filter { string -> string.isNotEmpty() } .map(String::toInt) .sum() } fun part2(input: String): Int = input .splitToSequence("\n{2}".toRegex()) .map { it.split("\n".toRegex()) } .map { list -> list .filter { string -> string.isNotEmpty() } .map(String::toInt) .sum() }.sortedDescending() .take(3) .sum() val testInput = readInputText("Day01_test") check(part1(testInput) == 24_000) check(part2(testInput) == 45_000) val input = readInputText("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
2c26cdf0134742628e06782f1fd930a4b257105b
876
advent-of-code-2022
Apache License 2.0
src/main/kotlin/adventofcode/day05/Mapping.kt
jwcarman
731,408,177
false
{"Kotlin": 137289}
/* * Copyright (c) 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 adventofcode.day05 import adventofcode.util.intersection import adventofcode.util.translate data class Mapping(val inputRange: LongRange, val offset: Long) { val outputRange = inputRange.translate(offset) init { require(inputRange.first <= inputRange.last) { "Input range must not be empty!" } } fun map(srcValue: Long): Long { require(srcValue in inputRange) { "Source value not in range $inputRange" } return offset + srcValue } fun feedsInto(successor: Mapping): Boolean = successor.inputRange.first <= outputRange.last && successor.inputRange.last >= outputRange.first fun feedsFrom(predecessor: Mapping): Boolean = predecessor.inputRange.last + predecessor.offset >= inputRange.first && predecessor.inputRange.first + predecessor.offset <= inputRange.last operator fun plus(successor: Mapping): List<Mapping> { require(feedsInto(successor)) { "Cannot add successor $successor to $this" } val intersection = successor.inputRange.intersection(outputRange) val results = mutableListOf(Mapping(intersection.translate(-offset), offset + successor.offset)) if(outputRange.first < intersection.first) { results.add(Mapping((outputRange.first..<intersection.first).translate(-offset), offset)) } if(outputRange.last > intersection.last) { results.add(Mapping((intersection.last + 1..outputRange.last).translate(-offset), offset)) } if(successor.inputRange.first < intersection.first) { results.add(Mapping((successor.inputRange.first..<intersection.first), successor.offset)) } if(successor.inputRange.last > intersection.last) { results.add(Mapping((intersection.last + 1..successor.inputRange.last), successor.offset)) } return results } companion object { fun parse(input: String): Mapping { val splits = input.split("\\s+".toRegex()) val destStart = splits[0].toLong() val srcStart = splits[1].toLong() val rangeLength = splits[2].toLong() val srcRange = srcStart..<srcStart + rangeLength val offset = destStart - srcStart return Mapping(srcRange, offset) } } }
0
Kotlin
0
0
dfb226e92a03323ad48c50d7e970d2a745b479bb
2,905
adventofcode2023
Apache License 2.0
src/main/kotlin/aoc2016/Day04.kt
lukellmann
574,273,843
false
{"Kotlin": 175166}
package aoc2016 import AoCDay import util.illegalInput // https://adventofcode.com/2016/day/4 object Day04 : AoCDay<Int>( title = "Security Through Obscurity", part1ExampleAnswer = 1514, part1Answer = 409147, part2Answer = 991, ) { private class Room(val encryptedName: String, val sectorId: Int, val checksum: String) private fun parseRoom(input: String): Room { val encryptedName = input.substringBeforeLast('-') val (sectorId, checksum) = input.substringAfterLast('-').split('[', limit = 2) return Room(encryptedName, sectorId.toInt(), checksum.substringBeforeLast(']')) } private val Room.isReal: Boolean get() { if (checksum.length != 5) return false val counts = encryptedName.filter { it != '-' }.groupingBy { it }.eachCount() var letter = checksum[0] var count = counts[letter] ?: return false if (count != counts.values.maxOrNull()) return false for (i in 1..4) { val l = checksum[i] val c = counts[l] ?: return false if (c > count || c == count && l <= letter) return false letter = l count = c } return true } private const val LETTER_COUNT = 'z' - 'a' + 1 private val Room.name get() = encryptedName.map { letter -> when (letter) { in 'a'..'z' -> 'a' + (letter - 'a' + sectorId) % LETTER_COUNT '-' -> ' ' else -> illegalInput(letter) } }.joinToString(separator = "") override fun part1(input: String) = input .lineSequence() .map(::parseRoom) .filter { it.isReal } .sumOf { it.sectorId } override fun part2(input: String) = input .lineSequence() .map(::parseRoom) .single { it.name == "northpole object storage" } .sectorId }
0
Kotlin
0
1
344c3d97896575393022c17e216afe86685a9344
1,961
advent-of-code-kotlin
MIT License
day10/kotlin/bit-jkraushaar/solution.kts
mehalter
317,661,818
true
{"HTML": 2739009, "Java": 348790, "Kotlin": 271602, "TypeScript": 262310, "Python": 198318, "JetBrains MPS": 191916, "Groovy": 125347, "Jupyter Notebook": 116902, "C++": 101742, "Dart": 47762, "Haskell": 43633, "CSS": 35030, "Ruby": 27091, "JavaScript": 13242, "Scala": 11409, "Dockerfile": 10370, "PHP": 4152, "Go": 2838, "Shell": 2651, "Rust": 2082, "Clojure": 567, "Cypher": 515, "Tcl": 46}
#!/usr/bin/env -S kotlinc-jvm -script import java.io.File import kotlin.math.atan2 // tag::asteroids[] typealias Asteroid = Pair<Int, Int> fun convertToAsteroidSet(map: List<CharArray>): Set<Asteroid> { val asteroidSet = mutableSetOf<Asteroid>() for (row in map.withIndex()) { for (column in row.value.withIndex()) { if (column.value == '#') { asteroidSet.add(Asteroid(column.index, row.index)) } } } return asteroidSet } // end::asteroids[] // tag::lineOfSight[] typealias LineOfSight = Pair<Asteroid, Asteroid> fun LineOfSight.asteroids(asteroidSet: Set<Asteroid>): List<Asteroid> { val resultList = mutableListOf(first) val xDiff = second.first - first.first val yDiff = second.second - first.second val otherAsteroids = (asteroidSet - first) - second if (xDiff == 0) { val yRange = if (yDiff > 0) (first.second..second.second) else (second.second..first.second) for (asteroid in otherAsteroids) { if (asteroid.first == first.first && yRange.contains(asteroid.second)) { resultList.add(asteroid) } } } else { val gradient = yDiff.toDouble() / xDiff.toDouble() val xRange = if (xDiff > 0) (first.first..second.first) else (second.first..first.first) for (asteroid in otherAsteroids) { val expectedY = ((asteroid.first - first.first) * gradient) + first.second if (xRange.contains(asteroid.first) && expectedY == asteroid.second.toDouble()) { resultList.add(asteroid) } } } resultList.add(second) return resultList } fun LineOfSight.obstructed(asteroidSet: Set<Asteroid>) = this.asteroids(asteroidSet).size > 2 // end::lineOfSight[] // tag::firstStar[] fun firstStar(asteroids: Set<Asteroid>): Asteroid { val asteroidLosCount = mutableListOf<Pair<Asteroid, Int>>() for (asteroid in asteroids) { val otherAsteroids = asteroids - asteroid var losCount = 0 for (otherAsteroid in otherAsteroids) { val los = LineOfSight(asteroid, otherAsteroid) if (!los.obstructed(asteroids)) { losCount++ } } asteroidLosCount.add(Pair(asteroid, losCount)) } val bestMatch: Pair<Asteroid, Int>? = asteroidLosCount.maxBy { pair -> pair.second } println("${bestMatch?.first} with ${bestMatch?.second}") return bestMatch!!.first } val asteroids = convertToAsteroidSet(File("./input.txt").readLines().map { it.toCharArray() }) val bestMatch = firstStar(asteroids) // end::firstStar[] // tag::secondStar[] fun secondStar(bestMatch: Asteroid, otherAsteroids: Set<Asteroid>) { var clockwiseSortedAsteroids = otherAsteroids.toList().sortedBy { val xDiff = it.first - bestMatch.first val yDiff = it.second - bestMatch.second atan2(xDiff.toDouble(), yDiff.toDouble()) }.reversed() var survivingAsteroids = clockwiseSortedAsteroids.toList() var destroyCounter = 0 while (clockwiseSortedAsteroids.size > 0) { for (asteroid in clockwiseSortedAsteroids) { if (!LineOfSight(bestMatch, asteroid).obstructed(clockwiseSortedAsteroids.toSet())) { destroyCounter++ survivingAsteroids = survivingAsteroids - asteroid println("PENG! ($destroyCounter) $asteroid") } } clockwiseSortedAsteroids = survivingAsteroids.toList() } } secondStar(bestMatch, asteroids - bestMatch) // end::secondStar[]
0
HTML
0
0
afcaede5326b69fedb7588b1fe771fd0c0b3f6e6
3,584
docToolchain-aoc-2019
MIT License
app/src/main/kotlin/me/mataha/misaki/solutions/adventofcode/aoc2015/d16/Day.kt
mataha
302,513,601
false
{"Kotlin": 92734, "Gosu": 702, "Batchfile": 104, "Shell": 90}
package me.mataha.misaki.solutions.adventofcode.aoc2015.d16 import com.github.h0tk3y.betterParse.grammar.parseToEnd import me.mataha.misaki.domain.adventofcode.AdventOfCode import me.mataha.misaki.domain.adventofcode.AdventOfCodeDay /** See the puzzle's full description [here](https://adventofcode.com/2015/day/16). */ @AdventOfCode("Aunt Sue", 2015, 16) class AuntSue : AdventOfCodeDay<List<Memoir>, Int>() { override fun parse(input: String): List<Memoir> = MemoirGrammar.parseToEnd(input) override fun solvePartOne(input: List<Memoir>): Int = match(input) { a, b, _ -> a == b } override fun solvePartTwo(input: List<Memoir>): Int = match(input) { a, b, key -> when (key) { "cats", "trees" -> a > b "pomeranians", "goldfish" -> a < b else -> a == b } } companion object { const val ANALYSIS_INCONCLUSIVE = -1 } } private fun match(input: List<Memoir>, comparator: CompoundComparator): Int = input.singleOrNull { memoir -> memoir.compareTo(SAMPLE, comparator) }?.aunt?.number ?: AuntSue.ANALYSIS_INCONCLUSIVE private val SAMPLE = Memoir( "children" to 3, "cats" to 7, "samoyeds" to 2, "pomeranians" to 3, "akitas" to 0, "vizslas" to 0, "goldfish" to 5, "trees" to 3, "cars" to 2, "perfumes" to 1 )
0
Kotlin
0
0
748a5b25a39d01b2ffdcc94f1a99a6fbc8a02685
1,343
misaki
MIT License
src/Day02.kt
Jintin
573,640,224
false
{"Kotlin": 30591}
fun main() { fun part1(input: List<String>): Int { var score = 0 input.forEach { score += it[2] - 'X' + 1 if (it[2] - 'X' == it[0] - 'A') { score += 3 } else if (it[2] - 'X' == (it[0] - 'A' + 1) % 3) { score += 6 } } return score } fun part2(input: List<String>): Int { var score = 0 input.forEach { score += (it[2] - 'X') * 3 when (it[2]) { 'X' -> score += (it[0] - 'A' + 2) % 3 + 1 'Y' -> score += it[0] - 'A' + 1 'Z' -> score += (it[0] - 'A' + 1) % 3 + 1 } } return score } val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
2
4aa00f0d258d55600a623f0118979a25d76b3ecb
812
AdventCode2022
Apache License 2.0
src/main/aoc2019/Day10.kt
nibarius
154,152,607
false
{"Kotlin": 963896}
package aoc2019 import kotlin.math.PI import kotlin.math.abs import kotlin.math.atan2 import Pos class Day10(input: List<String>) { data class Angle(val value: Double) { var pos = Pos(0, 0) var distance: Int = 0 companion object { fun calculate(self: Pos, other: Pos): Angle { // Atan2 - PI gives angle 0 for straight up and negative angles for everything else // with angle decreasing further while rotating clockwise return Angle(atan2((other.x - self.x).toDouble(), (other.y - self.y).toDouble()) - PI) .apply { distance = self.distanceTo(other) pos = other } } } } private fun List<Pos>.inSightOf(other: Pos): Int { return this.filterNot { it == other } .map { Angle.calculate(other, it) } .toSet() .size } private val asteroids = parseInput(input) private fun parseInput(input: List<String>): List<Pos> { return mutableListOf<Pos>().apply { input.forEachIndexed { y, s -> s.forEachIndexed { x, c -> if (c == '#') this.add(Pos(x, y)) } } } } fun solvePart1(): Int { return asteroids.maxOfOrNull { asteroids.inSightOf(it) } ?: 0 } fun solvePart2(): Int { val best = asteroids.map { it to asteroids.inSightOf(it) }.maxByOrNull { it.second }!!.first val targets: MutableMap<Double, MutableList<Angle>> = asteroids.filterNot { it == best } .map { Angle.calculate(best, it) } // smallest angle (from up) first, then smallest distance .sortedWith(compareBy({ abs(it.value) }, { it.distance })) .groupByTo(mutableMapOf()) { it.value } var key = 1.0 var lastKill = best repeat(200) { // Keep moving clockwise to next angle each time, or wrap around if needed key = targets.keys.firstOrNull { it < key } ?: targets.keys.first() lastKill = targets[key]!!.first().pos if (targets[key]!!.size <= 1) { // No other asteroids hides behind this one targets.remove(key) } else { // Other asteroids hides behind this, only destroy the first one targets[key]!!.removeAt(0) } if (targets.isEmpty()) { // Incomplete test case only return -1 } } return lastKill.x * 100 + lastKill.y } }
0
Kotlin
0
6
f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22
2,615
aoc
MIT License
src/main/kotlin/g2701_2800/s2741_special_permutations/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2701_2800.s2741_special_permutations // #Medium #Array #Dynamic_Programming #Bit_Manipulation #Bitmask // #2023_08_07_Time_623_ms_(82.35%)_Space_60.8_MB_(52.94%) class Solution { private var dp = HashMap<Pair<Int, Int>, Long>() private var adj = HashMap<Int, HashSet<Int>>() private var mod = 1000000007 private fun count(destIdx: Int, set: Int): Long { if (Integer.bitCount(set) == 1) return 1 val p = destIdx to set if (dp.containsKey(p)) { return dp[p]!! } var sum = 0L val newSet = set xor (1 shl destIdx) for (i in adj[destIdx]!!) { if ((set and (1 shl i)) == 0) continue sum += count(i, newSet) % mod sum %= mod } dp[p] = sum return sum } fun specialPerm(nums: IntArray): Int { for (i in nums.indices) adj[i] = hashSetOf() for ((i, vI) in nums.withIndex()) { for ((j, vJ) in nums.withIndex()) { if (vI != vJ && vI % vJ == 0) { adj[i]!!.add(j) adj[j]!!.add(i) } } } if (adj.all { it.value.size == nums.size - 1 }) { return (fact(nums.size.toLong()) % mod).toInt() } var total = 0 for (i in nums.indices) { total += (count(i, (1 shl nums.size) - 1) % mod).toInt() total %= mod } return total } private fun fact(n: Long): Long { if (n == 1L) return n return n * fact(n - 1) } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,579
LeetCode-in-Kotlin
MIT License
2023/src/main/kotlin/net/daams/solutions/5b.kt
Michiel-Daams
573,040,288
false
{"Kotlin": 39925, "Nim": 34690}
package net.daams.solutions import net.daams.Solution class `5b`(input: String): Solution(input) { override fun run() { val splitInput = input.split("\n\n") val seeds = splitInput[0].removePrefix("seeds: ").split(" ").map{ it.toLong() } val seedRanges = mutableListOf<LongRange>() for (i in 0 .. seeds.lastIndex step 2) { seedRanges.add(seeds[i]..<seeds[i] + seeds[i + 1]) } val maps = mutableListOf<List<Pair<LongRange, LongRange>>>() splitInput.subList(1, splitInput.size).forEach { val destinationRanges = mutableListOf<Pair<LongRange, LongRange>>() val rangeText = it.split("\n") rangeText.subList(1, rangeText.size).forEach { val meuk = it.split(" ").map { it.toLong() } val destinationRange = meuk[0]..< meuk[0] + meuk[2] val sourceRange = meuk[1]..< meuk[1] + meuk[2] destinationRanges.add(Pair(sourceRange, destinationRange)) } maps.add(destinationRanges) } val destinations = mutableListOf<LongRange>() seedRanges.forEach {seedRange -> var prevDestinations = mutableListOf(seedRange) maps.forEach { map -> val evaluatedDestinations = mutableListOf<LongRange>() prevDestinations.forEach { destination -> val moddedDestinations = getDestinationRanges(map, destination).toMutableList() if (moddedDestinations.isEmpty()) evaluatedDestinations.add(destination) else evaluatedDestinations.addAll(moddedDestinations) } prevDestinations = evaluatedDestinations } destinations.addAll(prevDestinations.toList()) } println(destinations.map { it.first }.min()) } fun getDestinationRanges(rangesToTarget: List<Pair<LongRange, LongRange>>, sourceRange: LongRange): List<LongRange> { val destinationRanges = mutableListOf<LongRange>() val remainingSourceRange = mutableListOf(sourceRange) rangesToTarget.forEach { rangeToTarget -> val remainingRanges = mutableListOf<LongRange>() val toRemove = mutableListOf<Int>() remainingSourceRange.forEachIndexed{ index, sourceRange -> val splitRanges = getCollidingRange(sourceRange, rangeToTarget.first) if (!splitRanges.isEmpty()) toRemove.add(index) splitRanges.getOrNull(0)?.let { destinationRanges.add((it.first - rangeToTarget.first.first + rangeToTarget.second.first) .. (it.last - rangeToTarget.first.first + rangeToTarget.second.first)) } splitRanges.getOrNull(1)?.let { remainingRanges.add(it)} splitRanges.getOrNull(2)?.let { remainingRanges.add(it)} } remainingSourceRange.addAll(remainingRanges) toRemove.forEach { remainingSourceRange.removeAt(it) } } destinationRanges.addAll(remainingSourceRange) return destinationRanges } // returns 0 ranges if no overlap // returns 1 range if source range is entirely contained in target // returns 2 ranges if source range partially overlaps target // returns 3 ranges if source range is bigger than target fun getCollidingRange(source: LongRange, target: LongRange): List<LongRange?> { val output = mutableListOf<LongRange>() if (source.first < target.first && source.last >= target.first && source.last <= target.last) { // left partial overlap output.add(target.first .. source.last) output.add(source.first..< target.first) return output } if (source.last > target.last && source.first <= target.last && source.first >= target.first) { // right partial overlap output.add(source.first .. target.last) output.add(target.last + 1 .. source.last) return output } if (source.first >= target.first && source.last <= target.last) { // entirely contained output.add(source) return output } if (source.first < target.first && source.last > target.last) { // source is bigger than target output.add(target) output.add(source.first..<target.first) output.add(target.last + 1 .. source.last) return output } return output } }
0
Kotlin
0
0
f7b2e020f23ec0e5ecaeb97885f6521f7a903238
4,461
advent-of-code
MIT License
2020/day/21/allergens.kt
mboos
318,232,614
false
{"Python": 45197, "Swift": 25305, "Kotlin": 3701}
/** * Solution to https://adventofcode.com/2020/day/21 */ import java.io.File fun main(args: Array<String>) { var input: String = args[0] var potentialAllergens = mutableMapOf<String, MutableSet<String>>() var allIngredients = mutableListOf<String>() var pattern: Regex = Regex("((\\w+ )+)\\(contains (\\w+(, \\w+)*)\\)\n?") File(input).forEachLine { line -> var match = pattern.matchEntire(line) var ingredients = match!!.groupValues[1].split(" ").filter { it.isNotBlank() } allIngredients.addAll(ingredients) match.groupValues[3].split(", ").forEach { element -> if (element.isNotBlank()) { if (element in potentialAllergens) { potentialAllergens[element] = potentialAllergens[element]!!.intersect(ingredients) as MutableSet<String> } else { potentialAllergens[element] = ingredients.toMutableSet() } } } } var allPotentialIngredients = mutableSetOf<String>() potentialAllergens.values.forEach { ingredients -> allPotentialIngredients.addAll(ingredients) } var safeIngredients = 0 allIngredients.forEach { ingredient -> if (!allPotentialIngredients.contains(ingredient)) { safeIngredients += 1 } } println("Safe ingredients: ${safeIngredients}") val foundIngredients = mutableSetOf<String>() val foundAllergens = mutableMapOf<String,String>() var unmatchedAllergens = true while (unmatchedAllergens) { unmatchedAllergens = false potentialAllergens.forEach { allergen, ingredients -> if (!(allergen in foundAllergens)) { unmatchedAllergens = true if (potentialAllergens[allergen]!!.size == 1) { foundIngredients.addAll(ingredients) foundAllergens[allergen] = ingredients.first() } else { potentialAllergens[allergen]!!.removeAll(foundIngredients) } } } } println("Ingredients: ${foundAllergens.toSortedMap().values.joinTo(StringBuffer(""), ",").toString()}") }
0
Python
0
0
4477bb32c50b951b0a1be4850ed28a2c6f78e65d
1,949
advent-of-code
Apache License 2.0
src/leetcodeProblem/leetcode/editor/en/SearchA2dMatrix.kt
faniabdullah
382,893,751
false
null
//Write an efficient algorithm that searches for a value in an m x n matrix. //This matrix has the following properties: // // // Integers in each row are sorted from left to right. // The first integer of each row is greater than the last integer of the //previous row. // // // // Example 1: // // //Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3 //Output: true // // // Example 2: // // //Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13 //Output: false // // // // Constraints: // // // m == matrix.length // n == matrix[i].length // 1 <= m, n <= 100 // -10⁴ <= matrix[i][j], target <= 10⁴ // // Related Topics Array Binary Search Matrix 👍 4843 👎 223 package leetcodeProblem.leetcode.editor.en class SearchA2dMatrix { fun solution() { } //below code will be used for submission to leetcode (using plugin of course) //leetcode submit region begin(Prohibit modification and deletion) class Solution { fun searchMatrix(matrix: Array<IntArray>, target: Int): Boolean { for (i in matrix.indices) { if (matrix[i][matrix.size - 1] == target) { return true } if (matrix[i][matrix.size] > target) { var rightSearch = matrix[i].size - 1 var leftSearch = 0 while (leftSearch <= rightSearch) { val middleSearch = leftSearch + (rightSearch - leftSearch) / 2 val valueNow = matrix[i][middleSearch] if (valueNow == target) { return true } else if (valueNow > target) { rightSearch = middleSearch - 1 } else { leftSearch = middleSearch + 1 } } break } } return false } } //leetcode submit region end(Prohibit modification and deletion) } fun main() {}
0
Kotlin
0
6
ecf14fe132824e944818fda1123f1c7796c30532
2,111
dsa-kotlin
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/ShortestPath.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.util.LinkedList import java.util.Queue /** * 1293. Shortest Path in a Grid with Obstacles Elimination * @see <a href="https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/">Source</a> */ fun interface ShortestPath { operator fun invoke(grid: Array<IntArray>, k: Int): Int } class ShortestPathBFS : ShortestPath { private val dirs = arrayOf(intArrayOf(0, 1), intArrayOf(0, -1), intArrayOf(1, 0), intArrayOf(-1, 0)) override operator fun invoke(grid: Array<IntArray>, k: Int): Int { val n: Int = grid.size val m: Int = grid[0].size if (n <= 1 && m <= 1) return 0 val dp = Array(n) { Array(m) { BooleanArray( k + 1, ) } } dp[0][0][0] = true val ls: LinkedList<IntArray> = LinkedList() ls.offer(intArrayOf(0, 0, 0)) return helper(ls, n, m, dp, grid, k) } private fun helper( ls: LinkedList<IntArray>, n: Int, m: Int, dp: Array<Array<BooleanArray>>, grid: Array<IntArray>, k: Int, ): Int { var step = 0 while (ls.isNotEmpty()) { var size: Int = ls.size step++ while (size-- > 0) { val start: IntArray = ls.poll() val x = start[0] val y = start[1] val curK = start[2] loop1@ for (d in dirs) { val xx = x + d[0] val yy = y + d[1] if (xx == n - 1 && yy == m - 1) return step if (xx < 0 || yy < 0 || xx >= n || yy >= m) continue for (i in 0..curK) { if (dp[xx][yy][i]) continue@loop1 } if (grid[xx][yy] == 1 && curK < k) { dp[xx][yy][curK + 1] = true ls.offer(intArrayOf(xx, yy, curK + 1)) } else if (grid[xx][yy] == 0) { dp[xx][yy][curK] = true ls.offer(intArrayOf(xx, yy, curK)) } } } } return -1 } } class ShortestPathBFS2 : ShortestPath { private val dirs = intArrayOf(0, 1, 0, -1, 0) override operator fun invoke(grid: Array<IntArray>, k: Int): Int { val m: Int = grid.size val n: Int = grid[0].size if (k >= m + n - 2) return m + n - 2 // if we can go by manhattan distance -> let's go val visited = Array(m) { Array(n) { BooleanArray(k + 1) } } val q: Queue<IntArray> = LinkedList() q.offer(intArrayOf(0, 0, k, 0)) // r, c, k, dist visited[0][0][k] = true return helper(grid, q, m, n, visited) } private fun helper( grid: Array<IntArray>, q: Queue<IntArray>, m: Int, n: Int, visited: Array<Array<BooleanArray>>, ): Int { while (q.isNotEmpty()) { val top: IntArray = q.poll() val r = top[0] val c = top[1] val curK = top[2] val dist = top[3] if (r == m - 1 && c == n - 1) return dist // Found the result for (i in 0..3) { val nr = r + dirs[i] val nc = c + dirs[i + 1] if (nr < 0 || nr == m || nc < 0 || nc == n) { continue } val newK = curK - grid[nr][nc] if (newK >= 0 && !visited[nr][nc][newK]) { visited[nr][nc][newK] = true q.offer(intArrayOf(nr, nc, newK, dist + 1)) } } } return -1 // Not found } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
4,469
kotlab
Apache License 2.0
src/main/kotlin/com/github/michaelbull/advent2021/day4/Day4.kt
michaelbull
433,565,311
false
{"Kotlin": 162839}
package com.github.michaelbull.advent2021.day4 import com.github.michaelbull.advent2021.Puzzle object Day4 : Puzzle<Day4.Input, Int>(day = 4) { data class Input( val draws: List<List<Int>>, val boards: List<BingoBoard> ) private fun List<Int>.toDraws(): List<List<Int>> { return mapIndexed { i1, value -> filterIndexed { i2, _ -> i2 < i1 } + value } } override fun parse(input: Sequence<String>): Input { val it = input.iterator() val draws = it.next() .split(",") .map(String::toInt) .toDraws() val boards = buildList { while (it.hasNext()) { require(it.next().isEmpty()) add(it.toBingoBoard(size = 5)) } } return Input(draws, boards) } override fun solutions() = listOf( ::part1, ::part2 ) fun part1(input: Input): Int { val (draws, boards) = input for (draw in draws) { val board = boards.find { it.solvedBy(draw) } if (board != null) { return board.score(draw) } } error("no winning board") } fun part2(input: Input): Int { val (draws, boards) = input val winners = mutableSetOf<BingoBoard>() for (draw in draws) { for (board in boards) { val solved = board.solvedBy(draw) if (solved && board !in winners) { winners += board if (winners.size == boards.size) { return board.score(draw) } } } } error("no winning board") } }
0
Kotlin
0
4
7cec2ac03705da007f227306ceb0e87f302e2e54
1,765
advent-2021
ISC License
2022/21/21.kt
LiquidFun
435,683,748
false
{"Kotlin": 40554, "Python": 35985, "Julia": 29455, "Rust": 20622, "C++": 1965, "Shell": 1268, "APL": 191}
fun main() { val input = generateSequence(::readlnOrNull).map { it.split(": ") }.toList() val known = input .filter { (_, value) -> value[0].isDigit() } .associate { (name, value) -> name to value.toDouble() } .toMutableMap() val inputsWithOps = input.filter { " " in it[1] }.map { (n, v) -> n to v.split(" ") } fun updateKnown() { for (i in 1..50) for ((name, value) in inputsWithOps) { var (var1, op, var2) = value if (var1 in known && var2 in known) known[name] = when (op) { "+" -> known[var1]!! + known[var2]!! "-" -> known[var1]!! - known[var2]!! "*" -> known[var1]!! * known[var2]!! "/" -> known[var1]!! / known[var2]!! else -> 0.0 } } } updateKnown() println(Math.round(known["root"]!!)) val (rootVar1, _, rootVar2) = inputsWithOps.single { it.first == "root" }.second fun binSearch(increasing: Boolean): Long? { var (lo, hi) = -1e20 to 1e20 repeat (100) { val mid = (lo + hi) / 2L known["humn"] = Math.round(mid).toDouble() updateKnown() if (known[rootVar1]!! == known[rootVar2]!!) return Math.round(mid) if ((known[rootVar1]!! > known[rootVar2]!!) xor increasing) hi = mid else lo = mid } return null } println(listOf(binSearch(true), binSearch(false)).firstNotNullOf { it }) }
0
Kotlin
7
43
7cd5a97d142780b8b33b93ef2bc0d9e54536c99f
1,582
adventofcode
Apache License 2.0
src/SeqRanking.kt
nkkarpov
302,503,568
false
null
import java.lang.Math.* fun SeqRanking(env: Environment, initM: List<Int>, budget: Int): List<List<Int>> { env.reset() val n = env.n val m = initM.toIntArray() val C = List<MutableList<Int>>(m.size - 1) { mutableListOf() } fun ilog(n: Int) = 0.5 + (2..n).map { 1.0 / it }.sum() fun t(r: Int, alpha: Double) = if (r == 0) 0 else max((alpha / (n + 1 - r)).toInt(), 0) var left = 0.0 var right = budget.toDouble() repeat(100) { val ave = (left + right) / 2 var current = 0 for (r in 1 until n) { current += (t(r, ave) - t(r - 1, ave)) * (n - r + 1) } if (current <= budget) { left = ave } else { right = ave } } val sr = DoubleArray(n) { 0.0 } val nt = IntArray(n) { 0 } fun est(a: Int) = sr[a] / nt[a] val S = (0 until n).toMutableSet() val cluster = IntArray(n) { 0 } val gap = DoubleArray(n) { 0.0 } // println((1..n).map { t(it) }) var total = 0 for (r in 1 until n) { total += (t(r, left) - t(r - 1, left)) * (n - r + 1) } // println("budget = $budget, rem = ${budget - total}") for (i in 0 until (budget - total)) { val a = i % n sr[a] += env.pull(a) nt[a] += 1 } var q = emptyList<Int>() run { val p = S.sortedBy { est(it) }.reversed() for (j in 0 until m.lastIndex) { for (i in m[j] until m[j + 1]) { val x = p[i] cluster[x] = j gap[x] = 1.0 if (m[j] > 0) gap[x] = min(gap[x], est(p[m[j] - 1]) - est(x)) if (m[j + 1] < p.size) gap[x] = min(gap[x], est(x) - est(p[m[j + 1]])) } } q = S.sortedBy { gap[it] } } // println() var cnt = 0 for (r in 1 until n) { val tt = t(r, left) - t(r - 1, left) if (tt > 0) { cnt++ for (a in S) { val na = tt nt[a] += na repeat(na) { sr[a] += env.pull(a) } } val p = S.sortedBy { est(it) }.reversed() for (j in 0 until m.lastIndex) { for (i in m[j] until m[j + 1]) { val x = p[i] cluster[x] = j gap[x] = 1.0 if (m[j] > 0) gap[x] = min(gap[x], est(p[m[j] - 1]) - est(x)) if (m[j + 1] < p.size) gap[x] = min(gap[x], est(x) - est(p[m[j + 1]])) } } q = S.sortedBy { gap[it] } } val x = q[n - r] val c = cluster[x] C[c].add(x) S.remove(x) for (i in (c + 1)..m.lastIndex) m[i]-- } // println("cnt = ${cnt}") if (S.size != 1) { TODO() } for (x in S) { C[cluster[x]].add(x) } if (env.numberOfPulls > budget) { println("budget = ${budget} number = ${env.numberOfPulls}") TODO() } return C }
0
Kotlin
0
0
0d0db3fe0c6e465eb7c7d49b6f284473138d9117
3,031
batched-sorting
MIT License
103_-_Stacking_Boxes/src/Main.kt
JeanCarlosSC
274,552,136
false
null
import java.lang.NumberFormatException import javax.swing.JOptionPane import kotlin.system.exitProcess fun main(){ val numBox = nextInt(1, 30, "enter the number of boxes", "Input", JOptionPane.QUESTION_MESSAGE) val numDimensions = nextInt(1, 15, "Enter the dimension of the boxes", "Input", JOptionPane.QUESTION_MESSAGE) val arrayOfBox: MutableList<Box> = mutableListOf() for(i in 1..numBox) { arrayOfBox.add(Box(i)) //I list and create the boxes //enter the values of each box for(j in 1..numDimensions) { arrayOfBox[i - 1].addNumber(nextInt(1, 3000, "Enter length of dimension $j of box $i", "Input", JOptionPane.QUESTION_MESSAGE)) } arrayOfBox[i - 1].sort() //organize the contents of the boxes from smallest to largest arrayOfBox[i - 1].calculateWeight() //calculate the weight of each box } arrayOfBox.sortBy { it.weight } //organize the boxes by weight //look for the longest list val path = searchBestPath(arrayOfBox) //return to the user the best combination var orderBox = "" for(i in 0 until path.size){ orderBox += "${path[i]} " } JOptionPane.showMessageDialog(null, "number of boxes that meet the condition: ${path.size}\n" + "order of the boxes: $orderBox") } fun MutableList<Box>.getWeights(): MutableList<Int> { val temp: MutableList<Int> = mutableListOf() for(i in this) { if(!temp.contains(i.weight)) { temp.add(i.weight) } } return temp } fun searchPathStartingAt(selectBoxIndex: Int, listOfBox: MutableList<Box>, finalList: MutableList<Box>): MutableList<Box> { if(listOfBox[selectBoxIndex].weight != listOfBox.getWeights().last()) { var nextWeight = 0 for(i in selectBoxIndex until listOfBox.size) { if (listOfBox[i].weight > listOfBox[selectBoxIndex].weight) { nextWeight = listOfBox[i].weight break } } var temp: MutableList<Box> var maxSize: Int? = null var maxSizeIndex: Int? = null for(i in 0 until listOfBox.size) { if(listOfBox[i].weight >= nextWeight && listOfBox[selectBoxIndex].canBeWithinOf(listOfBox[i])) { temp = searchPathStartingAt(i, listOfBox, mutableListOf()) if(maxSize == null || temp.size > maxSize) { maxSize = temp.size maxSizeIndex = i } } } if(maxSizeIndex != null) { searchPathStartingAt(maxSizeIndex, listOfBox, finalList) } } finalList.add(listOfBox[selectBoxIndex]) finalList.sortBy { it.weight } return finalList } fun searchBestPath(arrayOfBox: MutableList<Box>): MutableList<Int> { var maxSize = 0 var bestPath: MutableList<Box> = mutableListOf() for(i in 0 until arrayOfBox.size) { val path = searchPathStartingAt(i, arrayOfBox, mutableListOf()) if(path.size > maxSize) { maxSize = path.size bestPath = path } } bestPath.sortBy { it.weight } val bestPathNumbers: MutableList<Int> = mutableListOf() for(i in 0 until bestPath.size) { bestPathNumbers.add(bestPath[i].number) } return bestPathNumbers } fun Box.canBeWithinOf(box: Box): Boolean { for(i in 0 until this.numbers.size) { if(this.numbers[i] >= box.numbers[i]) { return false } } return true } fun nextInt(min: Int, max: Int, message: String, title: String, messageType: Int): Int { val value: Int return try { value = JOptionPane.showInputDialog(null, message, title, messageType).toInt() if(value < min || value > max) { throw InvalidInputException() } else value }catch (invalidInput: InvalidInputException) { JOptionPane.showMessageDialog(null, "Please enter a value from $min until $max", "Error", JOptionPane.ERROR_MESSAGE) nextInt(min, max, message, title, messageType) } catch (numberFormat: NumberFormatException) { JOptionPane.showMessageDialog(null, "Please enter an integer number", "Error", JOptionPane.ERROR_MESSAGE) nextInt(min, max, message, title, messageType) } catch (nullException: NullPointerException) { JOptionPane.showMessageDialog(null, "application closed successfully", "Exit", JOptionPane.INFORMATION_MESSAGE) exitProcess(0) } }
0
Kotlin
0
0
82f43d45aa5c5bf570691f9c811a286e27b39a0e
4,527
problem-set-volume1
Apache License 2.0
src/Day06.kt
rifkinni
573,123,064
false
{"Kotlin": 33155, "Shell": 125}
fun main() { fun traverseWindows(input: MutableList<Char>, size: Int): Int { val windows = input.windowed(size) for (i in windows.indices) { if (windows[i].distinct().size == size) { return i + size } } return 0 } fun part1(input: MutableList<Char>): Int { return traverseWindows(input, 4) } fun part2(input: MutableList<Char>): Int { return traverseWindows(input, 14) } // test if implementation meets criteria from the description, like: val testCases = listOf( TestCase(0, 7, 19), TestCase(1, 5, 23), TestCase(2, 6, 23), TestCase(3, 10, 29), TestCase(4, 11, 26) ) for (case in testCases) { val testInput = readInput("Day06_test")[case.index].toCharArray().toMutableList() check(part1(testInput) == case.part1) check(part2(testInput) == case.part2) } val input = readInput("Day06")[0].toCharArray().toMutableList() println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
c2f8ca8447c9663c0ce3efbec8e57070d90a8996
1,077
2022-advent
Apache License 2.0
src/Day04.kt
ricardorlg-yml
573,098,872
false
{"Kotlin": 38331}
fun main() { data class Section(val x: Int, val y: Int) { infix fun fullyContains(other: Section): Boolean { return x <= other.x && y >= other.y } infix fun overlaps(other: Section): Boolean { return !(other.x > y || other.y < x) } } fun String.toSection(): Section { val (x, y) = split("-").map { it.toInt() } return Section(x, y) } fun part1(input: List<String>): Int { return input.count { l -> val (a, b) = l.split(",").map { it.toSection() } a fullyContains b || b fullyContains a } } fun part2(input: List<String>): Int { return input.count { l -> val (a, b) = l.split(",").map { it.toSection() } a overlaps b || b overlaps a } } val testInput = readInput("Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("Day04") println(part1(input)) print(part2(input)) }
0
Kotlin
0
0
d7cd903485f41fe8c7023c015e4e606af9e10315
1,021
advent_code_2022
Apache License 2.0
src/Day03.kt
lassebe
573,423,378
false
{"Kotlin": 33148}
import kotlin.streams.toList fun main() { fun itemPriority(c: Int): Int = if (c >= 97) (c - 97 + 1) else (c - 65 + 27) fun part1Alt(input: List<String>) = input.sumOf { bag -> val wholeBag = bag.chars().toList() val (firstBagItems, secondBagItems) = wholeBag.chunked(wholeBag.size / 2).map { it.toSet() } for (item in firstBagItems) { if (secondBagItems.contains(item)) { return@sumOf itemPriority(item) } } return@sumOf 0 } fun String.toCharSet() = this.chars().toList().toSet() fun part2(input: List<String>) = input.chunked(3).sumOf { bagGroup -> val firstBag = bagGroup[0].toCharSet() val secondBag = bagGroup[1].toCharSet() val thirdBag = bagGroup[2].toCharSet() for (item in firstBag) { if (secondBag.contains(item) && thirdBag.contains(item)) { return@sumOf itemPriority(item) } } return@sumOf 0 } val testInput = readInput("Day03_test") println(part1Alt(testInput)) check(part1Alt(testInput) == 157) val input = readInput("Day03") check(part2(testInput) == 70) println(part1Alt(input)) println(part2(input)) }
0
Kotlin
0
0
c3157c2d66a098598a6b19fd3a2b18a6bae95f0c
1,357
advent_of_code_2022
Apache License 2.0
src/main/kotlin/solutions/day21/Day21.kt
Dr-Horv
112,381,975
false
null
package solutions.day21 import solutions.Solver import utils.Coordinate import utils.plus fun printMap(map: Map<Coordinate, Boolean>) { val size = determineSize(map) for (y in 0 until size) { for(x in 0 until size) { val value = map.getOrDefault(Coordinate(x, y), false) if(value) { print("#") } else { print(".") } } println() } println() } private fun determineSize(map: Map<Coordinate, Boolean>): Int { return Math.sqrt(map.keys.size.toDouble()).toInt() } fun Char.toBoolean() = when(this) { '#' -> true '.' -> false else -> throw RuntimeException("Unparsable char $this") } class Rule(from: String, to: String) { private val orig: Map<Coordinate, Boolean> private val cases: List<Map<Coordinate, Boolean>> val result: Map<Coordinate, Boolean> val size: Int private val resultSize: Int init { orig = mutableMapOf() cases = mutableListOf() result = mutableMapOf() val split = from.split("/") size = split.size val one = mutableMapOf<Coordinate, Boolean>() val two = mutableMapOf<Coordinate, Boolean>() val three = mutableMapOf<Coordinate, Boolean>() val four = mutableMapOf<Coordinate, Boolean>() val five = mutableMapOf<Coordinate, Boolean>() val six= mutableMapOf<Coordinate, Boolean>() val seven = mutableMapOf<Coordinate, Boolean>() split.map { it.map(Char::toBoolean) } .forEachIndexed { y, bl -> bl.forEachIndexed { x, b -> orig.put(Coordinate(x,y), b) one.put((Coordinate(size-1-x, y)), b) two.put(Coordinate(size-1-y, x), b) three.put(Coordinate(size-1-y, size-1-x), b) four.put(Coordinate(size-1-x, size-1-y), b) five.put(Coordinate(x, size-1-y), b) six.put(Coordinate(y, size-1-x), b) seven.put(Coordinate(y, x), b) } } cases.add(orig) cases.add(one) cases.add(two) cases.add(three) cases.add(four) cases.add(five) cases.add(six) cases.add(seven) val toSplit = to.split("/") resultSize = toSplit.size toSplit.map { it.map(Char::toBoolean) } .forEachIndexed { y, bl -> bl.forEachIndexed {x, b -> result.put(Coordinate(x,y), b) } } } fun match(grid: Map<Coordinate, Boolean>): Boolean { return cases.any { match(it, grid) } } private fun match(rule: Map<Coordinate, Boolean>, grid: Map<Coordinate, Boolean>): Boolean { rule.keys.forEach { if(grid.getOrDefault(it, false) != rule.getValue(it)) { return false } } return true } } class Day21: Solver { override fun solve(input: List<String>, partTwo: Boolean): String { var grid = mutableMapOf<Coordinate, Boolean>() grid.put(Coordinate(0,0), false) grid.put(Coordinate(1,0), true) grid.put(Coordinate(2, 0), false) grid.put(Coordinate(0,1), false) grid.put(Coordinate(1,1), false) grid.put(Coordinate(2,1), true) grid.put(Coordinate(0,2), true) grid.put(Coordinate(1,2), true) grid.put(Coordinate(2,2), true) val rules = input.map { val (from, to) = it.split("=>").map(String::trim) Rule(from, to) } val rulesEven = rules.filter { it.size == 2 } val rulesOdd = rules.filter { it.size == 3 } var iterations = 0 val goal = if(!partTwo) { 5 } else { 18 } while (true) { if(iterations == goal) { break } grid = if(determineSize(grid) % 2 == 0) { enhance(2, grid, rulesEven) } else { enhance(3, grid, rulesOdd) } iterations++ } return grid.values.filter { it }.size.toString() } private fun enhance(step: Int, grid: Map<Coordinate, Boolean>, rules: List<Rule>): MutableMap<Coordinate, Boolean> { val newGrid = mutableMapOf<Coordinate, Map<Coordinate, Boolean>>() val size = determineSize(grid) val sides = size / step val squareGrids = mutableMapOf<Coordinate, Map<Coordinate, Boolean>>() for (s1 in 0 until sides) { for (s2 in 0 until sides) { val sGrid = mutableMapOf<Coordinate, Boolean>() for (y in 0 until step) { for (x in 0 until step) { val readCoordinate = Coordinate(x + s1 * step, y + s2 * step) readCoordinate.x readCoordinate.y sGrid.put(Coordinate(x, y), grid.getOrDefault(readCoordinate, false)) } } squareGrids.put(Coordinate(s1*step, s2*step), sGrid) } } squareGrids.forEach { c, g -> for(r in rules) { if(r.match(g)) { newGrid.put(c, r.result) break } } } val retMap = mutableMapOf<Coordinate, Boolean>() val gridsPerRow = Math.sqrt(newGrid.size.toDouble()).toInt() val rows = newGrid.size / gridsPerRow val newSize = determineSize(newGrid.values.first()) var writeX = 0 var writeY = 0 for (r in 0 until rows) { for (y in 0 until newSize) { for (g in 0 until gridsPerRow) { val grid = newGrid.getValue(Coordinate(step*g, step*r)) for (x in 0 until newSize) { val value = grid.getValue(Coordinate(x, y)) retMap.put(Coordinate(writeX, writeY), value) writeX++ } } writeY++ writeX = 0 } } return retMap } }
0
Kotlin
0
2
975695cc49f19a42c0407f41355abbfe0cb3cc59
6,303
Advent-of-Code-2017
MIT License
src/year2020/day5/Solution.kt
Niallfitzy1
319,123,397
false
null
package year2020.day5 import java.io.File fun main() { val totalRows = 127 val totalColumns = 7 val passes = File("src/year2020/day5/input").readLines().map { BoardingPass(it.take(7), it.takeLast(3)) } var largestId = 0 val seatIds = passes.map { var rowRange = 0..totalRows var colRange = 0..totalColumns for (direction in it.col) { val seatsToExclude = colRange.count() / 2 colRange = if (direction == 'L') { colRange.first..(colRange.last - seatsToExclude) } else { (colRange.first + seatsToExclude)..colRange.last } } for (direction in it.row) { val seatsToExclude = rowRange.count() / 2 rowRange = if (direction == 'F') { rowRange.first..(rowRange.last - seatsToExclude) } else { (rowRange.first + seatsToExclude)..rowRange.last } } val seatId = (rowRange.last * 8) + colRange.last if (seatId > largestId) largestId = seatId println("${rowRange.last}, ${colRange.last} with ID $seatId") seatId }.sorted() println(largestId) for (seat in seatIds.indices) { val currentSeat = seatIds[seat] if (seat == seatIds.lastIndex) { break } val nextSeatId = seatIds[seat + 1] if (nextSeatId != currentSeat + 1) { println(currentSeat + 1) } } } data class BoardingPass(val row: String, val col: String)
0
Kotlin
0
0
67a69b89f22b7198995d5abc19c4840ab2099e96
1,563
AdventOfCode
The Unlicense
aoc-2023/src/main/kotlin/aoc/aoc18.kts
triathematician
576,590,518
false
{"Kotlin": 615974}
import aoc.AocParser.Companion.parselines import aoc.* import aoc.util.* val testInput = """ R 6 (#70c710) D 5 (#0dc571) L 2 (#5713f0) D 2 (#d2c081) R 2 (#59c680) D 2 (#411b91) L 5 (#8ceee2) U 2 (#caa173) L 1 (#1b58a2) U 2 (#caa171) R 2 (#7807d2) U 3 (#a77fa3) L 2 (#015232) U 2 (#7a21e3) """.parselines class Direction(val dir: Char, val n: Int, val col: String) fun String.parseDirection(): Direction { val dir = first() val n = chunkint(1) val col = chunk(2).drop(1).dropLast(1) return Direction(dir, n, col) } fun String.parseDirection2(): Direction { val col = chunk(2).drop(2).dropLast(1) val dir = when (col.last()) { '0' -> 'R' '1' -> 'D' '2' -> 'L' '3' -> 'U' else -> error("Unknown direction $col") } val dist = col.dropLast(1).toInt(radix = 16) return Direction(dir, dist, col) } // part 1 fun List<String>.part1(): Int { val dirs = map { it.parseDirection() } var grid = Array(1000) { Array(1000) { '.' } } fun at(c: Coord) = grid[c.y][c.x] fun dig(c: Coord) { grid[c.y][c.x] = '#' } var pos = Coord(200, 200) dig(pos) dirs.forEach { when (it.dir) { 'R' -> { repeat(it.n) { grid[pos.y][pos.x + it + 1] = '#' } pos = Coord(pos.x + it.n, pos.y) } 'L' -> { repeat(it.n) { grid[pos.y][pos.x - it - 1] = '#' } pos = Coord(pos.x - it.n, pos.y) } 'U' -> { repeat(it.n) { grid[pos.y - it - 1][pos.x] = '#' } pos = Coord(pos.x, pos.y - it.n) } 'D' -> { repeat(it.n) { grid[pos.y + it + 1][pos.x] = '#' } pos = Coord(pos.x, pos.y + it.n) } } } // check grid val minX = grid.minOfOrNull { it.indexOfFirst { it == '#' }.let { if (it < 0) Int.MAX_VALUE else it } }!! val maxX = grid.maxOfOrNull { it.indexOfLast { it == '#' } }!! val minY = grid.indexOfFirst { it.indexOfFirst { it == '#' } >= 0 } val maxY = grid.indexOfLast { it.indexOfLast { it == '#' } >= 0 } val countHash = grid.sumOf { it.count { it == '#' } } println("Dug path in ${maxX-minX+1} x ${maxY-minY+1} grid, path length $countHash") // trim grid grid = grid.drop(minY).take(maxY-minY+1).map { it.drop(minX).take(maxX-minX+1).toTypedArray() }.toTypedArray() println(grid.joinToString("\n") { it.joinToString("") }) // fill in grid val maxX2 = grid[0].size val maxY2 = grid.size grid.indices.forEach { if (grid[it][0] == '.') grid[it][0] = 'o' if (grid[it][maxX2-1] == '.') grid[it][maxX2-1] = 'o' } grid[0].indices.forEach { if (grid[0][it] == '.') grid[0][it] = 'o' if (grid[maxY2-1][it] == '.') grid[maxY2-1][it] = 'o' } var countFill = 1 while (countFill > 0) { countFill = 0 grid.allIndices().filter { at(it) == '.' }.forEach { if (at(it.left) == 'o' || at(it.right) == 'o' || at(it.top) == 'o' || at(it.bottom) == 'o') { grid[it.y][it.x] = 'o' countFill++ } } } // replace all non o's with hashes grid.allIndices().filter { at(it) != 'o' }.forEach { dig(it) } // check grid a second time val countHash2 = grid.sumOf { it.count { it == '#' } } val countOs = grid.sumOf { it.count { it == 'o' } } println("I filled everything in, there are now $countHash2 square meters dug, and $countOs squares not dug") println(grid.joinToString("\n") { it.joinToString("") }) return countHash2 } // part 2 class Corner(val pos: Coord, val dir1: Char, val dir2: Char) { val x = pos.x val y = pos.y override fun toString() = "${pos.x} $dir1$dir2" } fun List<String>.part2(): Long { val dirs = map { it.parseDirection2() } /** Track all corner positions and type. */ val corners = mutableListOf<Corner>() var pos = Coord(0, 0) var lastDir: Char? = null dirs.forEach { if (lastDir != null) { corners += Corner(pos, lastDir!!, it.dir) } lastDir = it.dir when (it.dir) { 'R' -> pos = Coord(pos.x + it.n, pos.y) 'L' -> pos = Coord(pos.x - it.n, pos.y) 'U' -> pos = Coord(pos.x, pos.y - it.n) 'D' -> pos = Coord(pos.x, pos.y + it.n) } } corners += Corner(pos, lastDir!!, dirs[0].dir) // check grid val minX = corners.minOf { it.x } val maxX = corners.maxOf { it.x } val minY = corners.minOf { it.y } val maxY = corners.maxOf { it.y } val countHash = corners.count() println("Dug path in ${maxX-minX+1} x ${maxY-minY+1} grid, # of corners = $countHash") // count dugout areas for each row val cornerPairs = (corners + corners[0]).zipWithNext() val res = (minY..maxY).sumOf { countDugRow(cornerPairs, it) } println("Completed the dig with $res square meters of dugout area") return res } /** Find all times the pattern intersects with the given row. */ fun countDugRow(cornerPairs: List<Pair<Corner, Corner>>, y: Int): Long { val res = mutableMapOf<Int, Char>() cornerPairs.filter { y in it.first.y..it.second.y || y in it.second.y..it.first.y }.forEach { if (it.first.y != y && it.second.y != y) { // path crosses here res[it.first.x] = '+' } else if (it.first.y == y && it.second.y == y) { val dirFirst = if (it.first.dir1 in "LR") it.first.dir2 else it.first.dir1 val dirSecond = if (it.second.dir1 in "LR") it.second.dir2 else it.second.dir1 if (dirFirst == dirSecond) { // path temporarily on this row but doesn't cross res[it.first.x] = 'Z' res[it.second.x] = 'Z' } else { // path temporarily on this row and does cross res[it.first.x] = 'U' res[it.second.x] = 'U' } } else { // ignore this case, since it's covered with other lines } } var side = Inside.OUTSIDE var prevSide: Inside? = null var count = 0L var pos = Int.MIN_VALUE res.entries.sortedBy { it.key }.forEach { (x, type) -> // add up number of dugout cells in this row from last position up to and including x if (type == '+') { when (side) { Inside.INSIDE -> { count += x - pos side = Inside.OUTSIDE } Inside.OUTSIDE -> { count++ side = Inside.INSIDE } else -> error("Invalid state $side") } } else if (type == 'U') { when (side) { Inside.ON_LINE -> { count += x - pos side = prevSide!! } else -> { if (side == Inside.INSIDE) count += x - pos else count++ prevSide = side side = Inside.ON_LINE } } } else if (type == 'Z') { when (side) { Inside.ON_LINE -> { count += x - pos side = if (prevSide == Inside.INSIDE) Inside.OUTSIDE else if (prevSide == Inside.OUTSIDE) Inside.INSIDE else error("Invalid state $prevSide") } else -> { if (side == Inside.INSIDE) count += x - pos else count++ prevSide = side side = Inside.ON_LINE } } } else { error("Invalid type $type") } pos = x } return count } enum class Inside { OUTSIDE, INSIDE, ON_LINE } // calculate answers val day = 18 val input = getDayInput(day, 2023) val testResult = testInput.part1() val testResult2 = testInput.part2() val answer1 = input.part1().also { it.print } val answer2 = input.part2().also { it.print } // print results AocRunner(day, test = { "$testResult, $testResult2" }, part1 = { answer1 }, part2 = { answer2 } ).run()
0
Kotlin
0
0
7b1b1542c4bdcd4329289c06763ce50db7a75a2d
8,345
advent-of-code
Apache License 2.0
src/exercises/Day19.kt
Njko
572,917,534
false
{"Kotlin": 53729}
// ktlint-disable filename package exercises import readInput data class Blueprint( val index: Int, val oreRobotCost: Int, val clayRobotCost: Int, val obsidianRobotCost: Pair<Int, Int>, val geodeRobotConst: Pair<Int, Int> ) fun extractBlueprints(input: List<String>): List<Blueprint> { val pattern = "^Blueprint (\\d*).*ore robot costs (\\d*).*clay robot costs (\\d*).*obsidian robot costs (\\d*) ore and (\\d*).*geode robot costs (\\d*) ore and (\\d*).*\$".toRegex() val blueprints = mutableListOf<Blueprint>() for (line in input) { pattern.findAll(line).forEach { matchResult -> val index = matchResult.groupValues[1].toInt() val oreRobotCost = matchResult.groupValues[2].toInt() val clayRobotCost = matchResult.groupValues[3].toInt() val obsidianRobotCostInOre = matchResult.groupValues[4].toInt() val obsidianRobotCostInClay = matchResult.groupValues[5].toInt() val geodeRobotCostInOre = matchResult.groupValues[6].toInt() val geodeRobotCostInClay = matchResult.groupValues[7].toInt() blueprints.add( Blueprint( index, oreRobotCost, clayRobotCost, Pair(obsidianRobotCostInOre, obsidianRobotCostInClay), Pair(geodeRobotCostInOre, geodeRobotCostInClay) ) ) } } return blueprints.toList() } fun main() { fun part1(input: List<String>): Int { return input.size } fun part2(input: List<String>): Int { return input.size } // test if implementation meets criteria from the description, like: val testInput = readInput("DayTemplate_test") println("Test results:") println(part1(testInput)) check(part1(testInput) == 0) println(part2(testInput)) check(part2(testInput) == 0) val input = readInput("DayTemplate") println("Final results:") println(part1(input)) check(part1(input) == 0) println(part2(input)) check(part2(input) == 0) }
0
Kotlin
0
2
68d0c8d0bcfb81c183786dfd7e02e6745024e396
2,125
advent-of-code-2022
Apache License 2.0
src/Day03.kt
Excape
572,551,865
false
{"Kotlin": 36421}
fun main() { fun Char.toPriority() = if (this.isUpperCase()) this.code - 65 + 27 else this.code - 96 fun part1(input: List<String>): Int { return input.map { it.chunked(it.length / 2).map {it.toSet()} } .map { (it[0] intersect it[1]).first() } .sumOf { it.toPriority() } } fun part2(input: List<String>): Int { return input.map { it.toSet() } .chunked(3) .map { it.reduce { i, r -> i intersect r } } .sumOf { it.first().toPriority() } } val testInput = readInput("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day03") println("part 1: ${part1(input)}") println("part 2: ${part2(input)}") }
0
Kotlin
0
0
a9d7fa1e463306ad9ea211f9c037c6637c168e2f
787
advent-of-code-2022
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/sorts/InsertionSorts.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.sorts import dev.shtanko.algorithms.extensions.swap /** * Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list. * Each iteration, insertion sort removes one element from the input data, finds the location it belongs within * the sorted list, and inserts it there. It repeats until no input elements remain. */ class InsertionSort : AbstractSortStrategy { override fun <T : Comparable<T>> perform(arr: Array<T>) { for (i in 1 until arr.size) { for (j in i downTo 1) { if (arr[j - 1] < arr[j]) break arr.swap(j, j - 1) } } } } /** * This method implements the Generic Insertion Sort * Sorts the array in increasing order * * Worst-case performance O(n^2) * Best-case performance O(n) * Average performance O(n^2) * Worst-case space complexity O(1) **/ class InsertionSort2 : AbstractSortStrategy { /** * * @param arr The array to be sorted * * Sorts the array in increasing order */ override fun <T : Comparable<T>> perform(arr: Array<T>) { for (i in 1 until arr.size) { val x = arr[i] var j = i while (j > 0 && arr[j - 1] > x) { arr[j] = arr[j - 1] j-- } arr[j] = x } } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,009
kotlab
Apache License 2.0
src/day09/Day09.kt
taer
573,051,280
false
{"Kotlin": 26121}
package day09 import readInput import java.io.File import kotlin.math.abs fun main() { data class Location(var x: Int = 0, var y: Int = 0) fun Location.move(direction: String) { when (direction) { "U" -> y++ "D" -> y-- "L" -> x-- "R" -> x++ } } fun Location.touching(other: Location): Boolean { return abs(this.x - other.x) <= 1 && abs(this.y - other.y) <= 1 } fun Location.follow(whoToFollow: Location) { val me = this if (!whoToFollow.touching(me)) { if (whoToFollow.x > me.x) me.x++ if (whoToFollow.x < me.x) me.x-- if (whoToFollow.y > me.y) me.y++ if (whoToFollow.y < me.y) me.y-- } } fun simulateRealSnake(input: List<String>, length: Int): Int { val tailLocations = hashSetOf<Location>() val snake = List(length) { Location() } input.forEach { cmd -> val (direction, count) = cmd.split(" ") repeat(count.toInt()) { _ -> snake.first().move(direction) snake.windowed(2) { it[1].follow(it[0]) } tailLocations.add(snake.last().copy()) } } return tailLocations.size } fun part1(input: List<String>): Int { return simulateRealSnake(input, 2) } fun part2(input: List<String>): Int { return simulateRealSnake(input, 10) } val testInput = readInput("day09", true) val testInput2 = File("src/${"day09"}", "data_test2.txt").readLines() val input = readInput("day09") check(part1(testInput) == 13) check(part2(testInput2) == 36) println(part1(input)) println(part2(input)) check(part1(input) == 6522) check(part2(input) == 2717) }
0
Kotlin
0
0
1bd19df8949d4a56b881af28af21a2b35d800b22
1,847
aoc2022
Apache License 2.0
2022/src/main/kotlin/org/suggs/adventofcode/Day08TreetopTreeHouse.kt
suggitpe
321,028,552
false
{"Kotlin": 156836}
package org.suggs.adventofcode object Day08TreetopTreeHouse { fun countAllVisibleTreesFrom(listOfRows: List<List<Int>>): Int { val listOfColumns = createListOfColumnsFrom(listOfRows) var count = 0 listOfRows.forEachIndexed { y, ints -> ints.forEachIndexed { x, data -> count += isCoOrdinateVisible(x, y, data, listOfRows, listOfColumns) } } return count } fun isCoOrdinateVisible(x: Int, y: Int, data: Int, listOfRows: List<List<Int>>, listOfColumns: List<List<Int>>) = // checks that when row/column is split that no items are larger than the data value when { listOfRows[y].subList(0, x).none { it >= data } -> 1 listOfRows[y].subList(x + 1, listOfRows[y].size).none { it >= data } -> 1 listOfColumns[x].subList(0, y).none { it >= data } -> 1 listOfColumns[x].subList(y + 1, listOfRows[x].size).none { it >= data } -> 1 else -> 0 } fun findHighestScenicScoreFrom(listOfRows: List<List<Int>>): Int { val listOfColumns = createListOfColumnsFrom(listOfRows) var max = 0 listOfRows.forEachIndexed { y, ints -> ints.forEachIndexed { x, data -> max = maxOf(max, calculateScenicScore(x, y, data, listOfRows, listOfColumns)) } } return max } private fun calculateScenicScore(x: Int, y: Int, data: Int, listOfRows: List<List<Int>>, listOfColumns: List<List<Int>>): Int { return listOfRows[y].subList(0, x).reversed().countWhileGreaterThan(data) * listOfRows[y].subList(x + 1, listOfRows[y].size).countWhileGreaterThan(data) * listOfColumns[x].subList(0, y).reversed().countWhileGreaterThan(data) * listOfColumns[x].subList(y + 1, listOfRows[x].size).countWhileGreaterThan(data) } private fun List<Int>.countWhileGreaterThan(data: Int): Int { val list = ArrayList<Int>() for (item in this) { if ((item >= data)) return list.count() + 1 list.add(item) } return list.count() } private fun createListOfColumnsFrom(listOfRows: List<List<Int>>): List<List<Int>> { val listOfColumns: MutableList<MutableList<Int>> = mutableListOf() fun addPointToColumnList(y: Int, data: Int) { if (listOfColumns.size <= y) listOfColumns.add(mutableListOf()) listOfColumns[y].add(data) } listOfRows.forEach { ints -> ints.forEachIndexed { innerIndex, innerInt -> addPointToColumnList(innerIndex, innerInt) } } return listOfColumns } }
0
Kotlin
0
0
9485010cc0ca6e9dff447006d3414cf1709e279e
2,729
advent-of-code
Apache License 2.0
KameleBeladen.kt
UlrichBerntien
156,849,364
false
null
/** * Programmieraufgabe: * * Kamele beladen * https://www.programmieraufgaben.ch/aufgabe/kamele-beladen/6gddr4zm * * Ein Kamel soll optimal beladen werden. Das Kamel kann maximal 270 kg tragen. * Aktuell sind Waren mit den folgenden Gewichten zu transportieren: 5, 18, 32, * 34, 45, 57, 63, 69, 94, 98 und 121 kg. Nicht alle Gewichte müssen verwendet * werden; die 270 kg sollen aber möglichst gut, wenn nicht sogar ganz ohne * Rest beladen werden. Die Funktion * beladeOptimal(kapazitaet: integer, vorrat: integer[]): integer[] * erhält die maximal tragbare Last (kapazitaet) und eine Menge von * aufzuteilenden Gewichten (vorrat). Das Resultat (hier integer[]) ist die * Auswahl aus dem Vorrat, die der Belastbarkeit möglichst nahe kommt. Gehen * Sie wie folgt rekursiv vor: Für jedes vorhandene Gewicht g aus dem Vorrat * soll das Problem vereinfacht werden. Dazu wird dieses Gewicht probehalber * aufgeladen: * tmpLadung: integer[] * tmpLadung := beladeOptimal(kapazitaet - g, "vorrat ohne g") * Danach wird das beste Resultat tmpLadung + g gesucht und als Array * zurückgegeben. Behandeln Sie in der Methode beladeOptimal() zunächst die * Abbruchbedingungen: * Vorrat leer * alle vorhandenen Gewichte sind zu schwer * nur noch ein Gewicht im Vorrat * * Autor: * <NAME> 2018-06-24 * * Sprache: * Kotlin 1.2.51 */ /** * Bestimmt die optimale Beladung. * @param capacity Die maximale Beladung. * @param pool Die zur Beladung möglichen Elemente. * @return Die optimale Beladung, ein Teilmenge von pool. */ fun optimalLoad(capacity: Int, pool: IntArray): IntArray { var tmpOptimalLoad = 0 var tmpOptimalBag = IntArray(0) for (index in pool.indices) if (pool[index] <= capacity) { val bag = optimalLoad(capacity - pool[index], pool.sliceArray(pool.indices - index)) val total = bag.sum() + pool[index] if (total > tmpOptimalLoad) { tmpOptimalLoad = total tmpOptimalBag = bag + pool[index] } } return tmpOptimalBag } /** * Hauptprogramm. * @param argv Aufrufparamter werden ignotiert. */ fun main(argv: Array<String>) { val capacity = 270 val pool = intArrayOf(18, 32, 34, 45, 57, 63, 69, 94, 98, 121) // Mit mehr Elementen dauert es wesentlioh länger: //val capacity = 1000 //val pool = arrayOf(181, 130, 128, 125, 124, 121, 104, 101, 98, 94, 69, 61, 13) val bag = optimalLoad(capacity, pool) val load = bag.sum() println(""" |Beladung: ${bag.contentToString()} |Summe Beladung: $load |Freie Kapazität: ${capacity - load} """.trimMargin()) }
0
Kotlin
1
0
0b4c6085584c972ab3e8dd8b9f49ab77c751df7f
2,721
Uebungen-Kotlin
Apache License 2.0
archive/2022/Day24.kt
mathijs81
572,837,783
false
{"Kotlin": 167658, "Python": 725, "Shell": 57}
private const val EXPECTED_1 = 18 private const val EXPECTED_2 = 54 private class Day24(isTest: Boolean) : Solver(isTest) { // 4 moves + stay in place val dirs = listOf(1 to 0, 0 to 1, -1 to 0, 0 to -1, 0 to 0) val dirMap = mapOf('>' to 0, 'v' to 1, '<' to 2, '^' to 3) val map = readAsLines() var startBlizzards = map.withIndex().flatMap { (y, row) -> row.withIndex().mapNotNull { (x, char) -> if (char in dirMap) { Triple(x, y, dirMap[char]!!) } else { check(char == '.' || char == '#') null } } } val Y = map.size val X = map[0].length fun part1(): Any { var blizzards = startBlizzards.toList() var t = 0 var positions = setOf(map[0].indexOf('.') to 0) while (positions.maxOf { it.second } < Y - 1) { var newBlizzards = moveBlizzards(blizzards) val blizzardSet = newBlizzards.map { it.first to it.second }.toSet() var newPositions = mutableSetOf<Pair<Int, Int>>() for (pos in positions) { for (dir in dirs) { val newPos = pos.first + dir.first to pos.second + dir.second if (newPos !in blizzardSet && newPos.first in 0 until X && newPos.second in 0 until Y && map[newPos.second][newPos.first] != '#') { newPositions.add(newPos) } } } positions = newPositions blizzards = newBlizzards t++ } return t } private fun moveBlizzards(blizzards: List<Triple<Int, Int, Int>>): List<Triple<Int, Int, Int>> { var newBlizzards = blizzards.map { var newX = it.first + dirs[it.third].first var newY = it.second + dirs[it.third].second if (map[newY][newX] == '#') { when (it.third) { 0 -> newX = 1 1 -> newY = 1 2 -> newX = X - 2 3 -> newY = Y - 2 } } Triple(newX, newY, it.third) } return newBlizzards } fun part2(): Any { var blizzards = startBlizzards.toList() var t = 0 // state: (position) to (leg of trip) var states = setOf((map[0].indexOf('.') to 0) to 0) while ((states.filter { it.second == 2 }.maxOfOrNull { it.first.second } ?: 0) < Y - 1) { var newBlizzards = moveBlizzards(blizzards) val blizzardSet = newBlizzards.map { it.first to it.second }.toSet() var newStates = mutableSetOf<Pair<Pair<Int, Int>, Int>>() fun Pair<Pair<Int, Int>, Int>.newState(pos: Pair<Int, Int>): Pair<Pair<Int, Int>, Int> { return if (second == 0 && pos.second == Y - 1) { pos to 1 } else if (second == 1 && pos.second == 0) { pos to 2 } else pos to second } for (state in states) { val pos = state.first for (dir in dirs) { val newPos = pos.first + dir.first to pos.second + dir.second if (newPos !in blizzardSet && newPos.first in 0 until X && newPos.second in 0 until Y && map[newPos.second][newPos.first] != '#') { newStates.add(state.newState(newPos)) } } } states = newStates blizzards = newBlizzards t++ } return t } } fun main() { val testInstance = Day24(true) val instance = Day24(false) testInstance.part1().let { check(it == EXPECTED_1) { "part1: $it != $EXPECTED_1" } } println("part1 ANSWER: ${instance.part1()}") testInstance.part2().let { check(it == EXPECTED_2) { "part2: $it != $EXPECTED_2" } println("part2 ANSWER: ${instance.part2()}") } }
0
Kotlin
0
2
92f2e803b83c3d9303d853b6c68291ac1568a2ba
4,002
advent-of-code-2022
Apache License 2.0
solutions/src/main/kotlin/de/thermondo/solutions/advent2022/day01/Part2Solution.kt
thermondo
552,876,124
false
{"Kotlin": 23756, "Makefile": 274}
package de.thermondo.solutions.advent2022.day01 import de.thermondo.utils.Exclude import de.thermondo.utils.stringFromFile /** * By the time you calculate the answer to the Elves' question, they've already realized that the Elf carrying the most * Calories of food might eventually run out of snacks. * * To avoid this unacceptable situation, the Elves would instead like to know the total Calories carried by the top * three Elves carrying the most Calories. That way, even if one of those Elves runs out of snacks, they still have * two backups. * * In the example above, the top three Elves are the fourth Elf (with 24000 Calories), then the third Elf * (with 11000 Calories), then the fifth Elf (with 10000 Calories). The sum of the Calories carried by these three * elves is 45000. * * Find the top three Elves carrying the most Calories. How many Calories are those Elves carrying in total? */ @Exclude fun main() { val input = stringFromFile("/advent2022/InputDay01.txt") val calories = input?.let { calculateCaloriesPartTwo(input = it, count = 3) } println("The Elf is carrying $calories calories.") } fun calculateCaloriesPartTwo(input: String, count: Int): Int { val elves = input.split("\n\n") val calories = mutableListOf<Int>() for (elf in elves) { calories.add(elf.split("\n").sumOf { it.toInt() }) } calories.sortDescending() return calories.take(count).sum() }
6
Kotlin
1
0
ef413904ce4bbe82861776f2efe5efd43dd5dc99
1,441
lets-learn-kotlin
MIT License
src/Day05.kt
maciekbartczak
573,160,363
false
{"Kotlin": 41932}
import java.util.* import kotlin.collections.ArrayDeque import kotlin.text.StringBuilder fun main() { fun part1(input: String): String { return getTopCratesAfterRearrangement(input, false) } fun part2(input: String): String { return getTopCratesAfterRearrangement(input, true) } val testInput = readInputAsString("Day05_test") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readInputAsString("Day05") println(part1(input)) println(part2(input)) } private fun getTopCratesAfterRearrangement(input: String, maintainCrateOrder: Boolean): String { val (crates, instructions) = parseInput(input) val stacks = parseCrates(crates) executeInstructions(stacks, instructions, maintainCrateOrder) val result = StringBuilder() stacks.forEach { result.append(it.last()) } return result.toString() } private fun parseInput(input: String): Pair<String, String> { val split = input.split("\n\n") return split[0] to split[1] } private fun parseCrates(crates: String): List<Stack<Char>> { val crateLines = crates.split("\n") val stackCount = crateLines.last().last().digitToInt() val stacks = mutableListOf<Stack<Char>>() for (i in 0 until stackCount) { stacks.add(Stack()) } for (i in crateLines.size - 1 downTo 0) { for (j in 1 until crateLines[i].length step 4) { val crate = crateLines[i][j] val stackIndex = j / 4 if (crate.isLetter()) { stacks[stackIndex].push(crate) } } } return stacks } private fun executeInstructions( stacks: List<Stack<Char>>, instructions: String, maintainCrateOrder: Boolean ) { instructions .split("\n") .forEach { val (count, source, target) = it.parseInstruction() val cratesToMove = ArrayDeque<Char>() repeat(count) { cratesToMove.add(stacks[source].pop()) } repeat(count) { val currentCrate = if (maintainCrateOrder) cratesToMove.removeLast() else cratesToMove.removeFirst() stacks[target].push(currentCrate) } } } private fun String.parseInstruction(): Triple<Int, Int, Int> { val scanner = Scanner(this).useDelimiter("\\D+") return Triple(scanner.nextInt(), scanner.nextInt() - 1, scanner.nextInt() - 1) }
0
Kotlin
0
0
53c83d9eb49d126e91f3768140476a52ba4cd4f8
2,481
advent-of-code-2022
Apache License 2.0
src/Day06.kt
ds411
573,543,582
false
{"Kotlin": 16415}
fun main() { fun part1(input: List<String>): Int { val str = input.joinToString("") val len = 4 val pos = distinctStringEndPos(str, len) return pos } fun part2(input: List<String>): Int { val str = input.joinToString("") val len = 14 val pos = distinctStringEndPos(str, len) return pos } // test if implementation meets criteria from the description, like: val testInput = readInput("Day06_test") check(part1(testInput) == 7) check(part2(testInput) == 19) val input = readInput("Day06") println(part1(input)) println(part2(input)) } private fun distinctStringEndPos(str: String, len: Int): Int { val pos = (0 until str.length+1-len).first { start -> val substr = str.substring(start, start+len) substr.toSet().size == len } return pos + len }
0
Kotlin
0
0
6f60b8e23ee80b46e7e1262723960af14670d482
884
advent-of-code-2022
Apache License 2.0
src/main/kotlin/com/hj/leetcode/kotlin/problem1615/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem1615 /** * LeetCode page: [1615. Maximal Network Rank](https://leetcode.com/problems/maximal-network-rank/); */ class Solution { /* Complexity: * Time O(n^2) and Space O(n+E) where E is the size of roads; */ fun maximalNetworkRank(n: Int, roads: Array<IntArray>): Int { val roadsSet = roadsSet(roads) val cityDegrees = cityDegrees(n, roads) var result = 0 forAllCityPairs(n) { aCity, bCity -> val hasDirectRoad = Pair(aCity, bCity) in roadsSet || Pair(bCity, aCity) in roadsSet val pairRank = cityDegrees[aCity] + cityDegrees[bCity] - (if (hasDirectRoad) 1 else 0) result = maxOf(result, pairRank) } return result } private fun roadsSet(roads: Array<IntArray>): Set<Pair<Int, Int>> { val result = hashSetOf<Pair<Int, Int>>() for ((u, v) in roads) { result.add(Pair(u, v)) } return result } private fun cityDegrees(n: Int, roads: Array<IntArray>): IntArray { val result = IntArray(n) for ((u, v) in roads) { result[u]++ result[v]++ } return result } private inline fun forAllCityPairs(n: Int, onEachPair: (aCity: Int, bCity: Int) -> Unit) { for (aCity in 0 until n) { for (bCity in 0 until aCity) { onEachPair(aCity, bCity) } } } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
1,477
hj-leetcode-kotlin
Apache License 2.0
src/dynamicprogramming/LongestValidParenthesis.kt
faniabdullah
382,893,751
false
null
package dynamicprogramming class LongestValidParenthesis { fun longestValidParentheses(s: String): Int { var maxans = 0 val dp = IntArray(s.length) for (i in 1 until s.length) { // ( ) ) ( ( ( ) ) // 0 0 0 0 0 0 0 0 // 0 2 0 0 0 0 2 if (s[i] == ')') { if (s[i - 1] == '(') { // i = 5 dp[i] = (if (i >= 2) dp[i - 2] else 0) + 2 } else if (i - dp[i - 1] > 0 && s[i - dp[i - 1] - 1] == '(') { // i= 7, 7 > 2 = &&s[ 7 - 2 - 1] , s[4] == '(' dp[i] = dp[i - 1] + (if (i - dp[i - 1] >= 2) dp[i - dp[i - 1] - 2] else 0) + 2 // 7 - 1 + 7 - 2 , dp[ 7 - 2 - 2] + 2 // 4 . } maxans = maxOf(maxans, dp[i]) } } return maxans } } fun main() { val longestValidParenthesis = LongestValidParenthesis() .longestValidParentheses("()()") println(longestValidParenthesis) }
0
Kotlin
0
6
ecf14fe132824e944818fda1123f1c7796c30532
1,078
dsa-kotlin
MIT License
kotlinP/src/main/java/com/jadyn/kotlinp/leetcode/thought/DoublePointer.kt
JadynAi
136,196,478
false
null
package com.jadyn.kotlinp.leetcode.thought import org.w3c.dom.Node import java.util.* import kotlin.math.max /** *JadynAi since 3/21/21 * * 双指针 */ fun main() { // print("find two sub ${findTwoNumSub(arrayOf(1, 2, 4, 6, 9), 14)}") print("judgeSquareSum ${judgeSquareSum(1000)}") } // 在有序数组中找出两个数,使它们的和为 target,返回index fun findTwoNumSub(array: Array<Int>, target: Int): IntArray? { if (array.isEmpty()) return null var leftIndex = 0 var rightIndex = array.lastIndex // 想一下这里能用这个判断条件吗?不可以,这里的判断条件就是假设一定可以找到 // while (array[leftIndex] + array[rightIndex] != target) { while (leftIndex < rightIndex) { val left = array[leftIndex] val right = array[rightIndex] when { left + right > target -> { rightIndex-- } left + right < target -> { leftIndex++ } else -> { return intArrayOf(leftIndex, rightIndex) } } } return null } // 给定一个非负整数 c ,你要判断是否存在两个整数 a 和 b,使得 a2 + b2 = c fun judgeSquareSum(target: Int): Boolean { if (target <= 0) return false var left = 0 // 双指针,关键是右侧指针的选取值,可以将target的sqrt值看作最大值 var right = Math.sqrt(target.toDouble()).toInt() while (left <= right) { val squareSum = left * left + right * right when { squareSum == target -> return true squareSum > target -> { right-- } else -> { left++ } } } return false } // 给你两个有序整数数组 nums1 和 nums2,请你将 nums2 合并到 nums1 中,使 nums1 成为一个有序数组。 //初始化 nums1 和 nums2 的元素数量分别为 m 和 n 。你可以假设 nums1 的空间大小等于 m + n,这样它就有足够的空间保存来自 nums2 的元素 fun merge(nums1: IntArray, m: Int, nums2: IntArray, n: Int): Unit { val nums1Copy = Arrays.copyOfRange(nums1, 0, m) var i = 0 var j = 0 var index = 0 // 双指针比较,小的放进去nums1数组,然后数值小的指针继续走 // 最后结束的条件,肯定就是有一方的指针走到了尽头 while (i < m && j < n) { if (nums1Copy[i] < nums2[j]) { nums1[index] = nums1Copy[i] i++ } else { nums1[index] = nums2[j] j++ } index++ } // 有一方的指针走到了尽头,那就ok,另外的那个数组剩下的值直接copy进去nums1数组就ok if (i == m) { System.arraycopy(nums2, j, nums1, index, n - j - 1) } else { System.arraycopy(nums1Copy, i, nums1, index, m - i - 1) } }
0
Kotlin
6
17
9c5efa0da4346d9f3712333ca02356fa4616a904
2,938
Kotlin-D
Apache License 2.0
src/AoC14.kt
Pi143
317,631,443
false
null
import java.io.File import kotlin.math.pow fun main() { println("Starting Day 14 A Test 1") calculateDay14PartA("Input/2020_Day14_A_Test1") println("Starting Day 14 A Real") calculateDay14PartA("Input/2020_Day14_A") println("Starting Day 14 B Test 1") calculateDay14PartB("Input/2020_Day14_B_Test1") println("Starting Day 14 B Real") calculateDay14PartB("Input/2020_Day14_A") } fun calculateDay14PartA(file: String): Long { var memory: MutableMap<Long, Long> = HashMap() var orMask: Long = 0 //Ones var andMask: Long = Long.MAX_VALUE //Zeroes val commandLines = File(localdir + file).readLines() for (line in commandLines) { val (command, paramList) = parseCommand(line) when (command) { "mask" -> { val (orTemp, andTemp) = readMask(paramList[0].toString()) orMask = orTemp andMask = andTemp } "mem" -> { memory[paramList[0].toString().toLong()] = applyBitmask(number = paramList[1].toString().toLong(), orMask = orMask, andMask = andMask) } } } val memorySum = memory.map { it.value }.sum() println(memory) println("Memorysum: $memorySum") return memorySum } fun parseCommand(line: String): Pair<String, List<Any>> { val split = line.split(" = ") val command = split[0] val value = split[1] if (command.contains("mem")) { val position = "\\d+".toRegex().find(command) val paramList = listOf(position?.value.toString().toInt(), value.toInt()) return Pair("mem", paramList) } val paramList = listOf(value) return Pair(command, paramList) } fun calculateDay14PartB(file: String): Long { var memory: MutableMap<Long, Long> = HashMap() var mask = "" val commandLines = File(localdir + file).readLines() for (line in commandLines) { val (command, paramList) = parseCommand(line) when (command) { "mask" -> { mask = paramList[0].toString() } "mem" -> { val addressList = applyBitmask(number = paramList[0].toString().toLong(), mask = mask) for(address in addressList){ memory[address]= paramList[1].toString().toLong() } } } } val memorySum = memory.map { it.value }.sum() println(memory) println("Memorysum: $memorySum") return memorySum } fun applyBitmask(number: Long, orMask: Long = 0, andMask: Long = Long.MAX_VALUE): Long { return (number or orMask) and andMask } fun readMask(maskString: String): Pair<Long, Long> { var orMask: Long = 0 //Ones -> Zeroes do nothing var andMask: Long = Long.MAX_VALUE //Zeroes -> Ones do nothing val reversed = maskString.reversed() for (charIndex in maskString.indices) { when (reversed[charIndex]) { '1' -> { orMask += 2.toDouble().pow(charIndex).toLong() } '0' -> { andMask -= 2.toDouble().pow(charIndex).toLong() } 'X' -> { } } } return Pair(orMask, andMask) } fun applyBitmask(number: Long, mask: String): MutableSet<Long> { val reversed = mask.reversed() var numberList: MutableSet<Long> = mutableSetOf(number) for (charIndex in mask.indices) { var tempNumberList: MutableSet<Long> = numberList.toMutableSet() when (reversed[charIndex]) { '1' -> { for (n in numberList) { tempNumberList.remove(n) tempNumberList.add(n or 2.toDouble().pow(charIndex).toLong()) } } '0' -> { /* for (n in numberList) { tempNumberList.remove(n) tempNumberList.add(n and Long.MAX_VALUE - 2.toDouble().pow(charIndex).toLong()) } */ } 'X' -> { for (n in numberList) { tempNumberList.remove(n) tempNumberList.add(n and Long.MAX_VALUE - 2.toDouble().pow(charIndex).toLong()) tempNumberList.add(n or 2.toDouble().pow(charIndex).toLong()) } } } numberList = tempNumberList } return numberList } class Command(command: String, paramList: ArrayList<Int>)
0
Kotlin
0
1
fa21b7f0bd284319e60f964a48a60e1611ccd2c3
4,510
AdventOfCode2020
MIT License
src/main/Day04.kt
lifeofchrome
574,709,665
false
{"Kotlin": 19233}
package main import readInput fun main() { val input = readInput("Day04") val day4 = Day04(input) print("Part 1: ${day4.part1()}\n") print("Part 2: ${day4.part2()}") } class Day04(input: List<String>) { private val ranges : List<Pair<IntRange, IntRange>> init { ranges = input.map { line -> val (p1, p2) = line.split(',') val (p1start, p1end) = p1.split('-').map { it.toInt() } val (p2start, p2end) = p2.split('-').map { it.toInt() } return@map Pair(p1start..p1end, p2start..p2end) } } private fun rangeFullOverlap(first: IntRange, second: IntRange) = first.toSet().containsAll(second.toSet()) || second.toSet().containsAll(first.toSet()) private fun rangePartialOverlap(first: IntRange, second: IntRange) = first.toSet().intersect(second.toSet()).isNotEmpty() fun part1() = ranges.count { rangeFullOverlap(it.first, it.second) } fun part2() = ranges.count { rangePartialOverlap(it.first, it.second) } }
0
Kotlin
0
0
6c50ea2ed47ec6e4ff8f6f65690b261a37c00f1e
1,032
aoc2022
Apache License 2.0
src/Day01.kt
izyaboi
572,898,317
false
{"Kotlin": 4047}
fun main() { fun part1(input: List<String>): Int { return input .split { line -> line.isBlank() } .map { listOfCalories -> listOfCalories.map { calorie -> calorie.toInt() }.sumOf { it } } .maxOf { it } } fun part2(input: List<String>): Int { return input.split { line -> line.isBlank() } .map { listOfCalories -> listOfCalories.map { calorie -> calorie.toInt() }.sumOf { it } } .sortedByDescending { it } .take(3) .sum() } /* // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 0)*/ val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
b0c8cafc5fe610b088d7ca4d10e2deef8d418f96
786
advent-of-code-2022
Apache License 2.0
src/main/kotlin/org/jetbrains/bio/genome/query/LocusQuery.kt
JetBrains-Research
173,494,429
false
{"Kotlin": 1220056}
package org.jetbrains.bio.genome.query import org.jetbrains.bio.genome.* import org.jetbrains.bio.genome.containers.locationList import org.jetbrains.bio.genome.containers.minus import org.jetbrains.bio.util.Lexeme import org.jetbrains.bio.util.RegexLexeme import org.jetbrains.bio.util.Tokenizer import org.jetbrains.bio.util.parseInt import java.util.* abstract class TranscriptLocusQuery(override val id: String) : Query<Transcript, Collection<Location>> { override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is TranscriptLocusQuery) return false if (id != other.id) return false return true } override fun hashCode(): Int { return id.hashCode() } fun toGeneQuery(): Query<Gene, Collection<Location>> { return object : Query<Gene, Collection<Location>> { override val id: String get() = this@TranscriptLocusQuery.id override fun apply(t: Gene): Collection<Location> { // Take the longest transcript return this@TranscriptLocusQuery.apply( t.transcripts.maxByOrNull { it.length() }!! ) } } } override fun toString(): String = id companion object { /** * Locus for given string * TSS[500] * TSS[-2000..2000] */ fun parse(text: String): TranscriptLocusQuery? { val lcText = text.lowercase() if (lcText in TRANSCRIPT_LOCUS_QUERIES) { return TRANSCRIPT_LOCUS_QUERIES[lcText]!! } val delimiter = RegexLexeme("[_;]|\\.\\.") val lBracket = Lexeme("[") val rBracket = Lexeme("]") // Only TSS and TES can have params if (!text.startsWith("tss") && !text.startsWith("tes")) { return null } val tokenizer = Tokenizer(lcText.substring(3), setOf(delimiter, lBracket, rBracket)) val bracketsFound = tokenizer.fetch() == lBracket if (bracketsFound) { tokenizer.next() } return try { val value = tokenizer.parseInt() if (tokenizer.fetch() == delimiter) { tokenizer.next() val end = tokenizer.parseInt() when (lcText.subSequence(0, 3)) { "tss" -> TssQuery(value, end) "tes" -> TesQuery(value, end) else -> error("Unsupported query: $text") } } else { when (lcText.subSequence(0, 3)) { "tss" -> TssQuery(-Math.abs(value), Math.abs(value)) "tes" -> TesQuery(-Math.abs(value), Math.abs(value)) else -> error("Unsupported query: $text") } } } finally { if (bracketsFound) { tokenizer.check(rBracket) } tokenizer.checkEnd() } } } } val TRANSCRIPT_LOCUS_QUERIES = mapOf( "tss" to TssQuery(), "tes" to TesQuery(), "transcript" to TranscriptQuery(), "cds" to CDSQuery(), "utr5" to UTR5Query(), "utr3" to UTR3Query(), "introns" to IntronsQuery(), "exons" to ExonsQuery() ) class CDSQuery : TranscriptLocusQuery("cds") { // All exons intersecting CDS override fun apply(input: Transcript) = input.cds } class ExonsQuery : TranscriptLocusQuery("exons") { override fun apply(input: Transcript) = input.exons } class TranscriptQuery : TranscriptLocusQuery("transcript") { override fun apply(input: Transcript) = listOf(input.location) } class IntronsQuery : TranscriptLocusQuery("introns") { override fun apply(input: Transcript) = input.introns } /** Transcription end site query. */ class TesQuery @JvmOverloads constructor( private val leftBound: Int = -2000, private val rightBound: Int = 2000 ) : TranscriptLocusQuery("tes") { init { check(leftBound < rightBound) } override fun apply(input: Transcript): Collection<Location> { return listOf(RelativePosition.THREE_PRIME.of(input.location, leftBound, rightBound)) } override val id: String get() = "${super.id}[$leftBound..$rightBound]" override fun equals(other: Any?) = when { this === other -> true other == null || other !is TesQuery -> false else -> leftBound == other.leftBound && rightBound == other.rightBound } override fun hashCode() = Objects.hash(super.hashCode(), leftBound, rightBound) } /** Transcription start site query. */ class TssQuery @JvmOverloads constructor( private val leftBound: Int = -2000, private val rightBound: Int = 2000 ) : TranscriptLocusQuery("tss") { init { check(leftBound < rightBound) } override fun apply(input: Transcript): Collection<Location> { return listOf(RelativePosition.FIVE_PRIME.of(input.location, leftBound, rightBound)) } override val id: String get() = "${super.id}[$leftBound..$rightBound]" override fun equals(other: Any?) = when { this === other -> true other == null || other !is TssQuery -> false else -> leftBound == other.leftBound && rightBound == other.rightBound } override fun hashCode() = Objects.hash(super.hashCode(), leftBound, rightBound) } class UTR3Query : TranscriptLocusQuery("utr3") { override fun apply(input: Transcript) = input.utr3 } class UTR5Query : TranscriptLocusQuery("utr5") { override fun apply(input: Transcript) = input.utr5 } class NearbyTranscriptQuery : TranscriptLocusQuery("nearby_transcript") { override fun apply(input: Transcript): List<Location> { return listOf(RelativePosition.ALL.of(input.location, -2000, 2000)) } } abstract class ChromosomeLocusQuery(override val id: String) : Query<Chromosome, Collection<Location>> { override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is ChromosomeLocusQuery) return false if (id != other.id) return false return true } override fun hashCode(): Int { return id.hashCode() } override fun toString(): String = id } val CHROMOSOME_LOCUS_QUERIES = mapOf( "repeats" to RepeatsQuery(), "non_repeats" to NonRepeatsQuery(), "cpg_islands" to CGIQuery() ) class CGIQuery : ChromosomeLocusQuery("cgi") { override fun apply(input: Chromosome): Collection<Location> { return input.cpgIslands.map { it.location } } } class RepeatsQuery(private val repeatClass: String? = null) : ChromosomeLocusQuery("repeats") { override fun apply(input: Chromosome): Collection<Location> { return input.repeats.asSequence().filter { repeat -> repeatClass == null || repeat.repeatClass == repeatClass }.map { it.location }.toList() } override val id: String get() { return super.id + if (repeatClass == null) "" else "[$repeatClass]" } } class NonRepeatsQuery : ChromosomeLocusQuery("non_repeats") { override fun apply(input: Chromosome): Collection<Location> { val genomeQuery = GenomeQuery(input.genome, input.name) val repeats = locationList(genomeQuery, input.repeats.map { it.location }) return Strand.values().flatMap { val location = input.range.on(input, it) location - repeats[input, Strand.PLUS] } } }
2
Kotlin
3
30
3f806c069e127430b91712a003e552490bff0820
7,626
bioinf-commons
MIT License
src/main/kotlin/codes/hanno/adventofcode/day3/Day3Runner.kt
hannotify
572,944,980
false
{"Kotlin": 7464}
import java.io.File import java.nio.file.Path fun main(args: Array<String>) { Day3Runner().run(Path.of("src/main/resources/day3/input.txt")) } class Day3Runner { fun run(input: Path) { File(input.toString()).useLines { lines -> val groups = mutableListOf<Group>() val rucksacks = mutableListOf<Rucksack>() lines.forEachIndexed { index, line -> rucksacks.add(Rucksack(line)) if ((index + 1) % 3 == 0) { groups.add(Group(rucksacks.toList())) rucksacks.clear() } } val sumOfProrities = groups.map { it.determineBadgeItem().priority() }.toList().sum() println(sumOfProrities) } } data class Group(val rucksacks: List<Rucksack>) { fun determineBadgeItem(): Item { val itemsRucksack1 = rucksacks.get(0).getAllItems() val itemsRucksack2 = rucksacks.get(1).getAllItems() val itemsRucksack3 = rucksacks.get(2).getAllItems() return itemsRucksack1.intersect(itemsRucksack2).intersect(itemsRucksack3).first() } } class Rucksack(input: String) { val firstCompartment: MutableList<Item> = mutableListOf() val secondCompartment: MutableList<Item> = mutableListOf() init { val indexHalf = (input.length / 2 - 1) for (firstHalfChar in input.substring(IntRange(0, indexHalf)).toList()) firstCompartment.add(Item(firstHalfChar)) for (secondHalfChar in input.substring(IntRange(indexHalf + 1, input.length - 1)).toList()) secondCompartment.add(Item(secondHalfChar)) assert(firstCompartment.size == secondCompartment.size) } fun determineDuplicateItem(): Item { return firstCompartment.intersect(secondCompartment).first() } fun getAllItems(): Set<Item> { return firstCompartment.union(secondCompartment) } } data class Item(val value: Char) { fun priority(): Int = if (value.isUpperCase()) value.code - 38 else value.code - 96 } }
0
Kotlin
0
0
ccde130e52f5637f140b331416634b8ce86bc401
2,211
advent-of-code
Apache License 2.0
year2020/src/main/kotlin/net/olegg/aoc/year2020/day22/Day22.kt
0legg
110,665,187
false
{"Kotlin": 511989}
package net.olegg.aoc.year2020.day22 import net.olegg.aoc.someday.SomeDay import net.olegg.aoc.utils.toPair import net.olegg.aoc.year2020.DayOf2020 /** * See [Year 2020, Day 22](https://adventofcode.com/2020/day/22) */ object Day22 : DayOf2020(22) { override fun first(): Any? { val (p1, p2) = data .split("\n\n") .map { it.lines().drop(1) } .map { ArrayDeque(it.map { card -> card.toInt() }) } .toPair() while (p1.isNotEmpty() && p2.isNotEmpty()) { val v1 = p1.removeFirst() val v2 = p2.removeFirst() if (v1 > v2) { p1 += v1 p1 += v2 } else { p2 += v2 p2 += v1 } } val result = p1 + p2 return result.mapIndexed { index, value -> (result.size - index) * value }.sum() } override fun second(): Any? { val (p1, p2) = data .split("\n\n") .map { it.lines().drop(1) } .map { ArrayDeque(it.map { card -> card.toInt() }) } .toPair() while (p1.isNotEmpty() && p2.isNotEmpty()) { val v1 = p1.removeFirst() val v2 = p2.removeFirst() val p1win = if (v1 <= p1.size && v2 <= p2.size) { val l1 = p1.take(v1) val l2 = p2.take(v2) playRecursive(l1, l2) } else { v1 > v2 } if (p1win) { p1 += v1 p1 += v2 } else { p2 += v2 p2 += v1 } } val result = p1 + p2 return result.mapIndexed { index, value -> (result.size - index) * value }.sum() } private fun playRecursive( in1: List<Int>, in2: List<Int> ): Boolean { val cache = mutableSetOf<Pair<List<Int>, List<Int>>>() val p1 = ArrayDeque(in1) val p2 = ArrayDeque(in2) while (p1.isNotEmpty() && p2.isNotEmpty()) { val l1 = p1.toList() val l2 = p2.toList() if (l1 to l2 in cache) { return true } cache.add(l1 to l2) val v1 = p1.removeFirst() val v2 = p2.removeFirst() val p1win = if (v1 <= p1.size && v2 <= p2.size) { val q1 = p1.take(v1) val q2 = p2.take(v2) playRecursive(q1, q2) } else { v1 > v2 } if (p1win) { p1 += v1 p1 += v2 } else { p2 += v2 p2 += v1 } } return p1.isNotEmpty() } } fun main() = SomeDay.mainify(Day22)
0
Kotlin
1
7
e4a356079eb3a7f616f4c710fe1dfe781fc78b1a
2,333
adventofcode
MIT License
version-utils/src/commonMain/kotlin/org/jetbrains/packagesearch/packageversionutils/normalization/VeryLenientDateTimeExtractor.kt
JetBrains
498,634,410
false
{"Kotlin": 129001}
package org.jetbrains.packagesearch.packageversionutils.normalization import kotlinx.datetime.Clock import kotlinx.datetime.LocalDateTime import kotlinx.datetime.TimeZone import kotlinx.datetime.toLocalDateTime public object VeryLenientDateTimeExtractor { /** * This list of patterns is sorted from longest to shortest. It's generated * by combining these base patterns: * * `yyyy/MM/dd_HH:mm:ss` * * `yyyy/MM/dd_HH:mm` * * `yyyy/MM_HH:mm:ss` * * `yyyy/MM_HH:mm` * * `yyyy/MM/dd` * * `yyyy/MM` * * With different dividers: * * Date dividers: `.`, `-`, `\[nothing]` * * Time dividers: `.`, `-`, `\[nothing]` * * Date/time separator: `.`, `-`, `'T'`,`\[nothing]` */ public val basePatterns: Sequence<String> = sequenceOf( "yyyy/MM/dd_HH:mm:ss", "yyyy/MM/dd_HH:mm", "yyyy/MM_HH:mm:ss", "yyyy/MM_HH:mm", "yyyy/MM/dd", "yyyy/MM", ) public val dateDividers: Sequence<String> = sequenceOf(".", "-", "") public val timeDividers: Sequence<String> = sequenceOf(".", "-", "") public val dateTimeSeparators: Sequence<String> = sequenceOf(".", "-", "'T'", "") public val datePatterns: Sequence<String> = basePatterns.flatMap { basePattern -> dateDividers.flatMap { dateDivider -> timeDividers.flatMap { timeDivider -> dateTimeSeparators.map { dateTimeSeparator -> basePattern .replace("/", dateDivider) .replace("_", dateTimeSeparator) .replace(":", timeDivider) } } } } public val formatters: List<DateTimeFormatter> by lazy { datePatterns.map { DateTimeFormatter(it) }.toList() } /** * The current year. Note that this value can, potentially, get out of date * if the JVM is started on year X and is still running when transitioning * to year Y. To ensure we don't have such bugs we should always add in a * certain "tolerance" when checking the year. We also assume the plugin will * not be left running for more than a few months (we release IDE versions * much more frequently than that), so having a 1-year tolerance should be * enough. We also expect the device clock is not more than 1-year off from * the real date, given one would have to go out of their way to make it so, * and plenty of things will break. * * ...yes, famous last words. */ private val currentYear get() = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()).year public fun extractTimestampLookingPrefixOrNull(versionName: String): String? = formatters .mapNotNull { it.parseOrNull(versionName) } .filter { it.year > currentYear + 1 } .map { versionName.substring(0 until it.toString().length) } .firstOrNull() } public expect fun DateTimeFormatter(pattern: String): DateTimeFormatter public expect class DateTimeFormatter { public fun parse(dateTimeString: String): LocalDateTime public fun parseOrNull(dateTimeString: String): LocalDateTime? }
0
Kotlin
4
5
aa00d67522436bf4ae38707b0d3fdcc04698ab7e
3,197
package-search-api-models
Apache License 2.0
src/main/kotlin/com/ginsberg/advent2022/Day18.kt
tginsberg
568,158,721
false
{"Kotlin": 113322}
/* * Copyright (c) 2022 by <NAME> */ /** * Advent of Code 2022, Day 18 - Boiling Boulders * Problem Description: http://adventofcode.com/2022/day/18 * Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2022/day18/ */ package com.ginsberg.advent2022 class Day18(input: List<String>) { private val points: Set<Point3D> = input.map { Point3D.of(it) }.toSet() fun solvePart1(): Int = points.sumOf { point -> 6 - point.cardinalNeighbors().count { neighbor -> neighbor in points } } fun solvePart2(): Int { val xRange = points.rangeOf { it.x } val yRange = points.rangeOf { it.y } val zRange = points.rangeOf { it.z } val queue = ArrayDeque<Point3D>().apply { add(Point3D(xRange.first, yRange.first, zRange.first)) } val seen = mutableSetOf<Point3D>() var sidesFound = 0 queue.forEach { lookNext -> if (lookNext !in seen) { lookNext.cardinalNeighbors() .filter { it.x in xRange && it.y in yRange && it.z in zRange } .forEach { neighbor -> seen += lookNext if (neighbor in points) sidesFound++ else queue.add(neighbor) } } } return sidesFound } private fun Set<Point3D>.rangeOf(function: (Point3D) -> Int): IntRange = this.minOf(function) - 1..this.maxOf(function) + 1 }
0
Kotlin
2
26
2cd87bdb95b431e2c358ffaac65b472ab756515e
1,501
advent-2022-kotlin
Apache License 2.0
src/Day19.kt
phoenixli
574,035,552
false
{"Kotlin": 29419}
fun main() { fun part1(input: List<String>): Int { val blueprints = mutableListOf<RobotFactory>() input.forEach { val robotFactory = RobotFactory() robotFactory.addBlueprint(it) blueprints.add(robotFactory) } val results = mutableListOf<Result>() blueprints.forEach { val result = Result(it) result.robots.add(Robot.OreRobot) println("=========================") println("Robots: " + result.robots) println("Resources: " + result.availableResources) println("=========================") repeat(24) { println("Minute " + (it+1)) result.manufacture() } results.add(result) } var sum = 0 for (i in results.indices) { val numGeode = results[i].availableResources[ResourceType.Geode] ?: 0 sum += numGeode * (i + 1) } return sum } fun part2(input: List<String>): Int { return input.size } // test if implementation meets criteria from the description, like: val testInput = readInput("Day19_test") println(part1(testInput)) // val input = readInput("Day19") // println(part1(input)) // println(part2(input)) } enum class ResourceType { Ore, Clay, Obsidian, Geode } enum class Robot(val resource: ResourceType) { OreRobot(ResourceType.Ore), ClayRobot(ResourceType.Clay), ObsidianRobot(ResourceType.Obsidian), GeodeRobot(ResourceType.Geode) } class RobotFactory { private val blueprint = mutableMapOf<Robot, Map<ResourceType, Int>>() fun addBlueprint(input: String) { var cost = mutableMapOf<ResourceType, Int>() var substring = input.substringAfter("ore robot costs ") cost[ResourceType.Ore] = substring.substring(0, substring.indexOf(" ")).toInt() blueprint[Robot.OreRobot] = cost cost = mutableMapOf() substring = input.substringAfter("clay robot costs ") cost[ResourceType.Ore] = substring.substring(0, substring.indexOf(" ")).toInt() blueprint.put(Robot.ClayRobot, cost) cost = mutableMapOf() substring = input.substringAfter("obsidian robot costs ") cost[ResourceType.Ore] = substring.substring(0, substring.indexOf(" ")).toInt() substring = substring.substringAfter("and ") cost[ResourceType.Clay] = substring.substring(0, substring.indexOf(" ")).toInt() blueprint.put(Robot.ObsidianRobot, cost) cost = mutableMapOf() substring = input.substringAfter("geode robot costs ") cost[ResourceType.Ore] = substring.substring(0, substring.indexOf(" ")).toInt() substring = substring.substringAfter("and ") cost[ResourceType.Obsidian] = substring.substring(0, substring.indexOf(" ")).toInt() blueprint.put(Robot.GeodeRobot, cost) println("Blueprint: " + blueprint) } fun makeRobot(robotType: Robot, availableResources: MutableMap<ResourceType, Int>): Robot? { var readyToMake = true blueprint[robotType]!!.forEach { (resourceType, count) -> if ((availableResources[resourceType] ?: 0) < count) { readyToMake = false } } if (readyToMake) { blueprint[robotType]!!.forEach { (resourceType, count) -> availableResources[resourceType] = availableResources[resourceType]!! - count } return robotType } return null } } class Result(private val robotFactory: RobotFactory) { val robots = mutableListOf<Robot>() val availableResources = mutableMapOf<ResourceType, Int>() fun manufacture() { val newRobots = buildRobots() robots.forEach { val resCount = availableResources[it.resource] ?: 0 availableResources[it.resource] = resCount + 1 } robots.addAll(newRobots) println("Robots: " + robots) println("Resources: " + availableResources) } private fun buildRobots(): List<Robot> { val newRobots = mutableListOf<Robot>() Robot.values().forEach { robotFactory.makeRobot(it, availableResources)?.let { robot -> newRobots.add(robot) } } return newRobots } }
0
Kotlin
0
0
5f993c7b3c3f518d4ea926a792767a1381349d75
4,367
Advent-of-Code-2022
Apache License 2.0
src/main/kotlin/io/github/aarjavp/aoc/day11/Day11.kt
AarjavP
433,672,017
false
{"Kotlin": 73104}
package io.github.aarjavp.aoc.day11 import io.github.aarjavp.aoc.readFromClasspath class Day11 { enum class Direction(val rowOffset: Int, val colOffset: Int) { UP(rowOffset = -1, colOffset = 0), UP_RIGHT(rowOffset = -1, colOffset = 1), RIGHT(rowOffset = 0, colOffset = 1), DOWN_RIGHT(rowOffset = 1, colOffset = 1), DOWN(rowOffset = 1, colOffset = 0), DOWN_LEFT(rowOffset = 1, colOffset = -1), LEFT(rowOffset = 0, colOffset = -1), UP_LEFT(rowOffset = -1, colOffset = -1), ; companion object { val values = values().toList() } } data class Location(val row: Int, val col: Int) { operator fun plus(direction: Direction): Location { return Location(row + direction.rowOffset, col + direction.colOffset) } } class Grid(val state: List<CharArray>) { val rows = state.size val columns = state.first().size init { for (row in state) { require(row.size == columns) { "Expected all rows to have same number of columns" } for (char in row) { check(char.isDigit()) { "Expected all cells to be a digit" } } } } fun Location.exists(): Boolean = row >= 0 && row < rows && col >= 0 && col < columns var flashesSoFar = 0 var stepsTaken = 0 fun step() { val flashes = ArrayDeque<Location>() for (row in 0 until rows) { for (col in 0 until columns) { val actual = state[row][col] if (actual == '9') { state[row][col] = '0' flashesSoFar++ flashes += Location(row, col) } else { state[row][col]++ } } } fun flash(location: Location) { for (direction in Direction.values) { val neighbor = location + direction if (!neighbor.exists()) continue when (state[neighbor.row][neighbor.col]) { '0' -> { // no-op } '9' -> { flashesSoFar++ flashes += neighbor state[neighbor.row][neighbor.col] = '0' } else -> state[neighbor.row][neighbor.col]++ } } } while (flashes.isNotEmpty()) { val flasher = flashes.removeFirst() flash(flasher) } stepsTaken++ } fun writeTo(dest: Appendable) { for (row in state) { dest.appendLine(String(row)) } } override fun toString(): String { return StringBuilder().also { writeTo(it) }.toString() } } fun parse(lines: Sequence<String>): Grid { return Grid(lines.map { it.toCharArray() }.toList()) } fun findSyncStep(grid: Grid): Int { //finds the next sync flashing step. Hopefully it's the first :) val targetFlashes = grid.rows * grid.columns while (true) { val startingFlashes = grid.flashesSoFar grid.step() val flashesThisStep = grid.flashesSoFar - startingFlashes if (flashesThisStep == targetFlashes) { return grid.stepsTaken } } } } fun main() { val solution = Day11() val grid = readFromClasspath("Day11.txt").useLines { lines -> solution.parse(lines) } repeat(100) { grid.step() } println("flashes after 100: ${grid.flashesSoFar}") val step = solution.findSyncStep(grid) println("sync step: $step") }
0
Kotlin
0
0
3f5908fa4991f9b21bb7e3428a359b218fad2a35
3,970
advent-of-code-2021
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/BalanceBST.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 /** * 1382. Balance a Binary Search Tree * @see <a href="https://leetcode.com/problems/balance-a-binary-search-tree/">Source</a> */ fun interface BalanceBST { operator fun invoke(root: TreeNode?): TreeNode? } class BalanceBSTInorder : BalanceBST { private val sortedArr: MutableList<TreeNode> = ArrayList() override operator fun invoke(root: TreeNode?): TreeNode? { inorderTraverse(root) return sortedArrayToBST(0, sortedArr.size - 1) } private fun inorderTraverse(root: TreeNode?) { if (root == null) return inorderTraverse(root.left) sortedArr.add(root) inorderTraverse(root.right) } private fun sortedArrayToBST(start: Int, end: Int): TreeNode? { if (start > end) return null val mid = (start + end) / 2 val root = sortedArr[mid] root.left = sortedArrayToBST(start, mid - 1) root.right = sortedArrayToBST(mid + 1, end) return root } } class BalanceBSTreeDSW : BalanceBST { override operator fun invoke(root: TreeNode?): TreeNode? { val pseudoRoot = TreeNode(0) pseudoRoot.right = root val nodeCount = flattenTreeWithRightRotations(pseudoRoot) val heightOfTree = (Math.log((nodeCount + 1).toDouble()) / Math.log(2.0)).toInt() val numOfNodesInTree = Math.pow(2.0, heightOfTree.toDouble()).toInt() - 1 createBalancedTreeWithLeftRotation(pseudoRoot, nodeCount - numOfNodesInTree) var numOfNodesInSubTree = numOfNodesInTree / 2 while (numOfNodesInSubTree > 0) { createBalancedTreeWithLeftRotation(pseudoRoot, numOfNodesInSubTree) numOfNodesInSubTree /= 2 } return pseudoRoot.right } private fun flattenTreeWithRightRotations(root: TreeNode): Int { var tree = root var nodeCount = 0 var pseudoRoot = tree.right while (pseudoRoot != null) { if (pseudoRoot.left != null) { val oldPseudoRoot: TreeNode = pseudoRoot pseudoRoot = pseudoRoot.left oldPseudoRoot.left = pseudoRoot?.right pseudoRoot?.right = oldPseudoRoot tree.right = pseudoRoot } else { ++nodeCount tree = pseudoRoot pseudoRoot = pseudoRoot.right } } return nodeCount } private fun createBalancedTreeWithLeftRotation(root: TreeNode?, numOfNodesInSubTree: Int) { var tree = root var num = numOfNodesInSubTree var pseudoRoot = tree?.right while (num-- > 0) { val oldPseudoRoot = pseudoRoot pseudoRoot = pseudoRoot?.right tree?.right = pseudoRoot oldPseudoRoot?.right = pseudoRoot?.left pseudoRoot?.left = oldPseudoRoot tree = pseudoRoot pseudoRoot = pseudoRoot?.right } } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,577
kotlab
Apache License 2.0
app/src/main/java/online/vapcom/codewars/algorithms/NodesLoop.kt
vapcomm
503,057,535
false
{"Kotlin": 142486}
package online.vapcom.codewars.algorithms class Node(val id: Int, var next: Node?) { companion object { fun createChain(chainSize: Int, loopSize: Int): Node { val loop: Array<Node> = if (loopSize == 1) { val n = Node(1, null) n.next = n val a = Array(1) { n } a[0] = n a } else { val loop = Array(loopSize) { Node(it + 1, null) } for (i in loop.lastIndex - 1 downTo 0) { loop[i].next = loop[i + 1] } loop[loop.lastIndex].next = loop[0] loop } if (chainSize <= 0) return loop[0] val chain = Array(chainSize) { Node(it + 1 + 1000000, null) } chain[chain.lastIndex].next = loop[0] for (i in chain.lastIndex - 1 downTo 0) { chain[i].next = chain[i + 1] } return chain[0] } } } /** * #27 Can you get the loop ? * https://www.codewars.com/kata/52a89c2ea8ddc5547a000863 */ fun loopSize(n: Node): Int { // find first node in loop fun firstNodeInLoop(n: Node): Node { val knownNodes = HashSet<Node>() var node: Node = n while (!knownNodes.contains(node)) { knownNodes.add(node) node = node.next as Node } return node } val firstInLoop = firstNodeInLoop(n) if (firstInLoop.next === firstInLoop) return 1 // count loop var nodes = 1 var node = firstInLoop.next while (node != firstInLoop) { node = node?.next nodes ++ } return nodes }
0
Kotlin
0
0
97b50e8e25211f43ccd49bcee2395c4bc942a37a
1,716
codewars
MIT License
2021/src/main/kotlin/day16_func.kt
madisp
434,510,913
false
{"Kotlin": 388138}
@file:OptIn(ExperimentalUnsignedTypes::class) import utils.Parser import utils.Solution fun main() { Day16Func.run() } object Day16Func : Solution<UByteArray>() { override val name = "day16" override val parser = Parser { input -> input.chunked(2).map { it.toUByte(16) }.toUByteArray() } sealed interface Packet { val version: Int val type: Int val size: Int } data class Literal( override val version: Int, override val type: Int, override val size: Int, val value: Long ) : Packet data class Operator( override val version: Int, override val type: Int, override val size: Int, val packets: List<Packet> ) : Packet private fun readBits(input: UByteArray, bitOff: Int, bitLen: Int): Int { val byte = input[bitOff / 8] val localBitOff = bitOff % 8 if (localBitOff + bitLen <= 8) { val mask = (1 shl bitLen) - 1 return mask and (byte.toInt() ushr (8 - bitLen - localBitOff)) } else { val len = 8 - localBitOff val mask = (1 shl len) - 1 return ((mask and byte.toInt()) shl (bitLen - len)) + readBits(input, bitOff + len, bitLen - len) } } private fun readPacket(input: UByteArray, bitOff: Int): Packet { val version = readBits(input, bitOff, 3) val type = readBits(input, bitOff + 3, 3) if (type == 4) { return readScalar(bitOff + 6, input, version, type) } else { return readOperator(input, bitOff, version, type) } } private fun readOperator( input: UByteArray, bitOff: Int, version: Int, type: Int ): Operator { // operator val lengthType = readBits(input, bitOff + 6, 1) if (lengthType == 0) { val end = readBits(input, bitOff + 6 + 1, 15) + bitOff + 6 + 1 + 15 val ps = generateSequence(bitOff + 6 + 1 + 15 to listOf(readPacket(input, bitOff + 6 + 1 + 15))) { (off, ps) -> val newOff = off + ps.last().size if (newOff >= end) null else newOff to ps + readPacket(input, newOff) } .map { it.second } .last() return Operator(version, type, 6 + 1 + 15 + ps.sumOf { it.size }, ps) } else { val totalPackets = readBits(input, bitOff + 6 + 1, 11) val ps = generateSequence(bitOff + 6 + 1 + 11 to listOf(readPacket(input, bitOff + 6 + 1 + 11))) { (off, ps) -> val newOff = off + ps.last().size newOff to ps + readPacket(input, newOff) } .map { it.second } .take(totalPackets) .last() return Operator(version, type, 6 + 1 + 11 + ps.sumOf { it.size }, ps) } } private fun readScalar( bitOff: Int, input: UByteArray, version: Int, type: Int ): Literal { val chunks = generateSequence(bitOff) { it + 5 } .map { off -> readBits(input, off, 5) } .takeWhile { it and 0b00010000 != 0 } .map { (it and 0b1111).toLong() } .toList() val value = (chunks + readBits(input, bitOff + 5 * chunks.size, 5).toLong()).reduce { acc, v -> (acc shl 4) + v } return Literal(version, type, 6 + ((chunks.size + 1) * 5), value) } private fun versionSum(packet: Packet): Int { return when (packet) { is Literal -> packet.version is Operator -> packet.version + packet.packets.sumOf { versionSum(it) } } } private fun calculate(packet: Packet): Long { return when (packet) { is Literal -> packet.value is Operator -> when (packet.type) { 0 -> packet.packets.sumOf { calculate(it) } 1 -> packet.packets.fold(1L) { acc, p -> acc * calculate(p) } 2 -> packet.packets.minOf { calculate(it) } 3 -> packet.packets.maxOf { calculate(it) } 5 -> if (calculate(packet.packets[0]) > calculate(packet.packets[1])) 1 else 0 6 -> if (calculate(packet.packets[0]) < calculate(packet.packets[1])) 1 else 0 7 -> if (calculate(packet.packets[0]) == calculate(packet.packets[1])) 1 else 0 else -> throw IllegalStateException("Unknown operator ${packet.type}") } } } override fun part1(input: UByteArray): Int { return versionSum(readPacket(input, 0)).also { if (it !in setOf(8, 965)) throw IllegalStateException("Borken answer $it") } } override fun part2(input: UByteArray): Long { return calculate(readPacket(input, 0)).also { if (it !in setOf(54L, 116672213160L)) throw IllegalStateException("Borken answer $it") } } }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
4,436
aoc_kotlin
MIT License
src/main/kotlin/org/jetbrains/bio/statistics/hypothesis/Testing.kt
karl-crl
208,228,814
true
{"Kotlin": 1021604}
package org.jetbrains.bio.statistics.hypothesis import org.jetbrains.bio.statistics.MoreMath import org.jetbrains.bio.viktor.F64Array import org.jetbrains.bio.viktor.argSort enum class Alternative { LESS, GREATER, TWO_SIDED } /** * Hypergeometric distribution describes the number of successes k * in n draws from a population of size N with a total of K successes. * * The corresponding test (also known as Fisher Exact Test) evaluates * a null hypothesis of independence. The one-sided P-value can be * calculated as follows: * * min(k, K) * P(X <= k) = sum C(K, i) C(N - K, n - i) / C(N, n) * max(0, n + K - N) * * The two-sided P-value is computed by summing up the probabilities * of all the tables with probability less than or equal to that of * the observed table. */ class FisherExactTest(private val N: Int, private val K: Int, private val n: Int, private val k: Int) { /** * Support of the Hypergeometric distribution with parameters * [N], [K] and [n]. */ private val support: IntRange get() = Math.max(0, n - (N - K))..Math.min(n, K) init { require(N >= 0) { "N must be >= 0 (N = $N)" } require(K >= 0 && k <= N) { "K must be from [0; $N] (K = $K)" } require(n in 0..N) { "n must be from [0; $N] (n = $n)" } require(k in support) { "k must be from [${support.first}; ${support.last}] (k = $k)" } } operator fun invoke(alternative: Alternative = Alternative.LESS): Double { return when (alternative) { Alternative.LESS -> { var acc = 0.0 for (x in support.start..Math.min(k, K)) { acc += hypergeometricProbability(N, K, n, x) } acc } Alternative.TWO_SIDED -> { val baseline = hypergeometricProbability(N, K, n, k) var acc = 0.0 for (x in support) { val current = hypergeometricProbability(N, K, n, x) // XXX the cutoff is chosen to be consistent with // 'fisher.test' in R. if (current <= baseline + 1e-6) { acc += current } } acc } else -> error(alternative.toString()) } } companion object { /** * Construct FET for a given contingency table. * * a | b * ----- * c | d */ @JvmStatic fun forTable(a: Int, b: Int, c: Int, d: Int): FisherExactTest { return FisherExactTest(N = a + b + c + d, K = a + b, n = a + c, k = a) } } } // This is up to 30x faster then calling // [HypergeometricDistribution#logProbability] because of the // tabulated factorial. private fun hypergeometricProbability(N: Int, K: Int, n: Int, k: Int): Double { return Math.exp(MoreMath.binomialCoefficientLog(K, k) + MoreMath.binomialCoefficientLog(N - K, n - k) - MoreMath.binomialCoefficientLog(N, n)) } object Multiple { /** * Applies Benjamini-Hochberg correction to the P-values. * * See https://en.wikipedia.org/wiki/False_discovery_rate. */ fun adjust(ps: F64Array): F64Array { val m = ps.size val sorted = ps.argSort(reverse = true) val original = IntArray(m) for (k in 0 until m) { original[sorted[k]] = k } val adjusted = F64Array(m) for (k in 0 until m) { adjusted[k] = Math.min(1.0, ps[sorted[k]] * m / (m - k)) } for (k in 1 until m) { adjusted[k] = Math.min(adjusted[k], adjusted[k - 1]) } adjusted.reorder(original) return adjusted } }
0
Kotlin
0
0
469bed933860cc34960a61ced4599862acbea9bd
3,953
bioinf-commons
MIT License
src/Day14.kt
tbilou
572,829,933
false
{"Kotlin": 40925}
fun main() { val day = "Day14" fun expand(p1: Pair<Int, Int>, p2: Pair<Int, Int>): MutableList<Pair<Int, Int>> { var result = mutableListOf<Pair<Int, Int>>() if (p1.first == p2.first) { // iterate over Y val l = listOf(p1.second, p2.second).sortedDescending() val steps = l.reduce(Int::minus) for (y in 0..steps) { result.add(p1.first to l.last() + y) } } else if (p1.second == p2.second) { // iterate over X val l = listOf(p1.first, p2.first).sortedDescending() val steps = l.reduce(Int::minus) for (x in 0..steps) { result.add(l.last() + x to p1.second) } } else error("check your input!") return result } fun parseInput(input: List<String>): List<Pair<Int, Int>> { return input.map { line -> line.split(" -> ") .map { it -> it.split(',') } .map { it.first().toInt() to it.last().toInt() } .also { println(it) } .windowed(2) { (a, b) -> expand(a, b) }.flatten() } .flatten() } fun canContinueToFall(grid: List<MutableList<String>>, p: Pair<Int, Int>): Boolean { return try { when (grid[p.second][p.first]) { "." -> true else -> false } } catch (exception: IndexOutOfBoundsException) { false } } fun step(grid: List<MutableList<String>>, sand: Pair<Int, Int>): Pair<Int, Int> { // Check if sand can fall down val down = sand.second + 1 return when (grid[down][sand.first]) { "." -> sand.first to down //Air "#", "o" -> { val left = canContinueToFall(grid, sand.first - 1 to down) val right = canContinueToFall(grid, sand.first + 1 to down) if (left) { sand.first - 1 to down } else if (right) { sand.first + 1 to down } else { sand } } else -> error("impossible condition. Check input!") } } fun buildGrid(list: List<Pair<Int, Int>>): List<MutableList<String>> { // Build grid val x = list.map { it.first }.max() * 2 val y = list.map { it.second }.max() var grid = List(y + 3) { mutableListOf("") } .map { list -> repeat(x) { list.add(".") } list } // Add walls list.forEach { p -> grid[p.second][p.first] = "#" } return grid } fun part1(input: List<String>): Int { val list = parseInput(input) // Cave Layout val grid = buildGrid(list) // Sand Simulation val start = 500 val abyss = grid.size - 1 var currentPos = -1 to -1 var nextPos = start to 0 var steps = 0 var dropSand = true // Simulate the drop of a grain of sand while (dropSand) { steps++ while (currentPos != nextPos) { // check if we are falling into the abyss if (nextPos.second >= abyss) { println("next on will go into the abyss. units:$steps") dropSand = false break } currentPos = nextPos nextPos = step(grid, nextPos) print("") } grid[nextPos.second][nextPos.first] = "o" currentPos = -1 to -1 nextPos = start to 0 } grid.print() return steps - 1 } fun part2(input: List<String>): Int { val list = parseInput(input) // Cave Layout val grid = buildGrid(list) repeat(grid[0].size) { grid[grid.size - 1][it] = "#" } grid.print() // Sand Simulation val start = 500 val goal = 500 to 0 var currentPos = -1 to -1 var nextPos = start to 0 var steps = 0 var dropSand = true // Simulate the drop of a grain of sand while (dropSand) { steps++ while (currentPos != nextPos) { currentPos = nextPos nextPos = step(grid, nextPos) // check if we're still at the top if (nextPos.first == goal.first && nextPos.second == goal.second) { println("We reached the goal. units:$steps") dropSand = false break } } grid[nextPos.second][nextPos.first] = "o" currentPos = -1 to -1 nextPos = start to 0 } grid.print() return steps } // test if implementation meets criteria from the description, like: val testInput = readInput("${day}_test") check(part1(testInput) == 24) check(part2(testInput) == 93) val input = readInput("$day") println(part1(input)) println(part2(input)) } private fun List<MutableList<String>>.print() { this.forEach { row -> row.forEach { s -> print(s) } println() } }
0
Kotlin
0
0
de480bb94785492a27f020a9e56f9ccf89f648b7
5,346
advent-of-code-2022
Apache License 2.0
leetcode-75-kotlin/src/main/kotlin/IncreasingTripletSubsequence.kt
Codextor
751,507,040
false
{"Kotlin": 49566}
/** * Given an integer array nums, * return true if there exists a triple of indices (i, j, k) such that i < j < k and nums[i] < nums[j] < nums[k]. * If no such indices exists, return false. * * * * Example 1: * * Input: nums = [1,2,3,4,5] * Output: true * Explanation: Any triplet where i < j < k is valid. * Example 2: * * Input: nums = [5,4,3,2,1] * Output: false * Explanation: No triplet exists. * Example 3: * * Input: nums = [2,1,5,0,4,6] * Output: true * Explanation: The triplet (3, 4, 5) is valid because nums[3] == 0 < nums[4] == 4 < nums[5] == 6. * * * Constraints: * * 1 <= nums.length <= 5 * 10^5 * -2^31 <= nums[i] <= 2^31 - 1 * * * Follow up: Could you implement a solution that runs in O(n) time complexity and O(1) space complexity? * @see <a href="https://leetcode.com/problems/increasing-triplet-subsequence/">LeetCode</a> */ fun increasingTriplet(nums: IntArray): Boolean { var first = Int.MAX_VALUE var second = Int.MAX_VALUE for (num in nums) { when { num <= first -> first = num num <= second -> second = num else -> return true } } return false }
0
Kotlin
0
0
0511a831aeee96e1bed3b18550be87a9110c36cb
1,178
leetcode-75
Apache License 2.0
src/AoC2.kt
Pi143
317,631,443
false
null
import java.io.File fun main() { println("Starting Day 2 A Test 1") calculateDay2PartA("Input/2020_Day2_A_Test1") println("Starting Day 2 A Real") calculateDay2PartA("Input/2020_Day2_A") println("Starting Day 2 B Test 1") calculateDay2PartB("Input/2020_Day2_A_Test1") println("Starting Day 2 B Real") calculateDay2PartB("Input/2020_Day2_A") } fun calculateDay2PartA(file: String){ val day2Data = readDay2Data(file) var validEntires = 0 day2Data.forEach { if(checkValidityPartA(it)){ validEntires++} } println("$validEntires are valid.") } fun calculateDay2PartB(file: String){ val day2Data = readDay2Data(file) var validEntires = 0 day2Data.forEach { if(checkValidityPartB(it)){ validEntires++} } println("$validEntires are valid.") } fun readDay2Data(input: String): MutableList<pwWithConfig> { val list = mutableListOf<pwWithConfig>() File(localdir + input).forEachLine { list.add(stringToPwWithConfig(it)) } return list } fun stringToPwWithConfig(string: String) : pwWithConfig{ val split1 = string.split(" ") val split1A = split1[0].split("-") val minAmount = split1A[0].toInt() val maxAmount = split1A[1].toInt() val split1B = split1[1].split(":") val char = split1B[0].toCharArray()[0] val password = split1[2] return pwWithConfig(minAmount, maxAmount,char,password) } fun checkValidityPartA(pwWithConfig: pwWithConfig): Boolean { val count = pwWithConfig.password.count { it == pwWithConfig.char } if(pwWithConfig.minAmount <= count && count <= pwWithConfig.maxAmount) { return true } return false } fun checkValidityPartB(pwWithConfig: pwWithConfig): Boolean { if(pwWithConfig.password[pwWithConfig.minAmount-1] == pwWithConfig.char && pwWithConfig.password[pwWithConfig.maxAmount-1] != pwWithConfig.char || pwWithConfig.password[pwWithConfig.minAmount-1] != pwWithConfig.char && pwWithConfig.password[pwWithConfig.maxAmount-1] == pwWithConfig.char) { return true } return false } class pwWithConfig( val minAmount : Int, val maxAmount: Int, val char : Char, val password: String )
0
Kotlin
0
1
fa21b7f0bd284319e60f964a48a60e1611ccd2c3
2,185
AdventOfCode2020
MIT License
src/com/github/frozengenis/day1/Puzzle.kt
FrozenSync
159,988,833
false
null
package com.github.frozengenis.day1 import java.io.File import java.util.* fun main() { val inputFile = File("""src\com\github\frozengenis\day1\input.txt""") val resultingFrequency = calculateResultingFrequency(inputFile) val duplicateResultingFrequency = findDuplicateResultingFrequency(inputFile) StringBuilder("Advent of Code 2018 - Day 1").appendln().appendln() .appendln("Resulting frequency: $resultingFrequency") .appendln("Duplicate resulting frequency: $duplicateResultingFrequency") .let(::print) } private fun calculateResultingFrequency(inputFile: File): Int { val scanner = Scanner(inputFile) var result = 0 while (scanner.hasNext()) { result += scanner.next().let(::parseFrequency) } return result } private fun findDuplicateResultingFrequency(inputFile: File): Int { var result: Int? = null var resultingFrequency = 0 val resultingFrequencies = mutableSetOf<Int>() while (result == null) { val searchResult = searchForDuplicate(inputFile, resultingFrequency, resultingFrequencies) if (searchResult.first == null) resultingFrequency = searchResult.second else result = searchResult.first } return result } private fun searchForDuplicate(inputFile: File, currentResultingFrequency: Int, resultingFrequencies: MutableSet<Int>): Pair<Int?, Int> { val scanner = Scanner(inputFile) var resultingFrequency = currentResultingFrequency while (scanner.hasNext()) { resultingFrequency += scanner.next().let(::parseFrequency) val isAdded = resultingFrequencies.add(resultingFrequency) if (!isAdded) return Pair(resultingFrequency, resultingFrequency) } return Pair(null, resultingFrequency) } private fun parseFrequency(input: String): Int { val scanner = input.trim().let(::Scanner) val token = scanner.useDelimiter("").next() val number = scanner.reset().nextInt() return if (token == "+") number else -number }
0
Kotlin
0
0
ec1e3472990a36b4d2a2270705253c679bee7618
2,000
advent-of-code-2018
The Unlicense
src/Day14.kt
weberchu
573,107,187
false
{"Kotlin": 91366}
private fun parseRocks(input: List<String>): Set<Pair<Int, Int>> { val rocks = mutableSetOf<Pair<Int, Int>>() for (line in input) { val rockCorners = line.split(" -> ") for (i in 0..rockCorners.size - 2) { val corner1 = rockCorners[i].split(",").map { it.toInt() } val corner2 = rockCorners[i + 1].split(",").map { it.toInt() } if (corner1[0] == corner2[0]) { val smallY = if (corner1[1] < corner2[1]) corner1[1] else corner2[1] val largeY = if (corner1[1] < corner2[1]) corner2[1] else corner1[1] for (y in smallY..largeY) { rocks.add(Pair(corner1[0], y)) } } else { val smallX = if (corner1[0] < corner2[0]) corner1[0] else corner2[0] val largeX = if (corner1[0] < corner2[0]) corner2[0] else corner1[0] for (x in smallX..largeX) { rocks.add(Pair(x, corner1[1])) } } } } return rocks } private fun part1(input: List<String>): Int { val rocks = parseRocks(input) val maxY = rocks.map { it.second }.reduce { rock1, rock2 -> if (rock1 < rock2) rock2 else rock1 } val sandsAndRocks = rocks.toMutableSet() var sandCount = 0 var isSandRest: Boolean do { var sand = Pair(500, 0) isSandRest = false do { if (!sandsAndRocks.contains(Pair(sand.first, sand.second + 1))) { sand = Pair(sand.first, sand.second + 1) } else if (!sandsAndRocks.contains(Pair(sand.first - 1, sand.second + 1))) { sand = Pair(sand.first - 1, sand.second + 1) } else if (!sandsAndRocks.contains(Pair(sand.first + 1, sand.second + 1))) { sand = Pair(sand.first + 1, sand.second + 1) } else { sandsAndRocks.add(sand) sandCount++ isSandRest = true } if (sand.second == maxY || sand == Pair(500, 0)) { isSandRest = false break } } while (!isSandRest) } while (isSandRest) return sandCount } private fun part2(input: List<String>): Int { val rocks = parseRocks(input) val maxY = rocks.map { it.second }.reduce { rock1, rock2 -> if (rock1 < rock2) rock2 else rock1 } val sandsAndRocks = rocks.toMutableSet() var sandCount = 0 var isSandRest: Boolean do { var sand = Pair(500, 0) isSandRest = false do { if (sand.second == maxY + 1) { sandsAndRocks.add(sand) sandCount++ isSandRest = true } else if (!sandsAndRocks.contains(Pair(sand.first, sand.second + 1))) { sand = Pair(sand.first, sand.second + 1) } else if (!sandsAndRocks.contains(Pair(sand.first - 1, sand.second + 1))) { sand = Pair(sand.first - 1, sand.second + 1) } else if (!sandsAndRocks.contains(Pair(sand.first + 1, sand.second + 1))) { sand = Pair(sand.first + 1, sand.second + 1) } else { sandsAndRocks.add(sand) sandCount++ isSandRest = true } if (sand == Pair(500, 0)) { isSandRest = false break } } while (!isSandRest) } while (isSandRest) return sandCount } fun main() { val input = readInput("Day14") // val input = readInput("Test") println("Part 1: " + part1(input)) println("Part 2: " + part2(input)) }
0
Kotlin
0
0
903ff33037e8dd6dd5504638a281cb4813763873
3,674
advent-of-code-2022
Apache License 2.0
2021/03/main.kt
chylex
433,239,393
false
null
import java.io.File fun main() { val lines = File("input.txt").readLines().filter(String::isNotEmpty) val input = Input(lines) part1(input) part2(input) } class Input(val lines: List<String>) { val totalRows = lines.size val totalColumns = lines[0].length } private fun part1(input: Input) = with(input) { val totalOnesPerColumn = Array(totalColumns) { column -> lines.count { it[column] == '1' } } val gammaRate = totalOnesPerColumn .map { if (it > totalRows - it) 1 else 0 } .foldIndexed(0) { index, total, bit -> total or (bit shl (totalColumns - index - 1)) } val epsilonRate = gammaRate xor ((1 shl totalColumns) - 1) println("Power consumption: ${gammaRate * epsilonRate}") } private fun part2(input: Input) = with(input) { fun findValueByCriteria(keepMostCommon: Boolean): Int { val keptLines = lines.toMutableList() for (column in 0 until totalColumns) { val ones = keptLines.count { it[column] == '1' } val zeros = keptLines.size - ones val keptValue = if (keepMostCommon) { if (ones >= zeros) '1' else '0' } else { if (zeros <= ones) '0' else '1' } keptLines.removeAll { it[column] != keptValue } if (keptLines.size == 1) { return keptLines.single().toInt(radix = 2) } } throw IllegalStateException() } val oxygenGeneratorRating = findValueByCriteria(keepMostCommon = true) val co2ScrubberRating = findValueByCriteria(keepMostCommon = false) println("Life support rating: ${oxygenGeneratorRating * co2ScrubberRating}") }
0
Rust
0
0
04e2c35138f59bee0a3edcb7acb31f66e8aa350f
1,534
Advent-of-Code
The Unlicense
src/Day03.kt
dominiquejb
572,656,769
false
{"Kotlin": 10603}
fun main() { fun Char.itemPriority(): Int { return when (val c = this.code) { in 97..122 -> c - 96 in 65..90 -> c - 38 else -> throw Error("Invalid item") } } fun getCommonItem(first: String, second: String): Char { for (c in first.toCharArray()) { if (second.toCharArray().contains(c)) { return c } } throw Error("No common item found") } fun getCommonItem(first: String, second: String, third: String): Char { for (c in first.toCharArray()) { if (second.toCharArray().contains(c) && third.toCharArray().contains(c)) { return c } } throw Error("No common item found") } fun part1(input: List<String>): Int { var prioritiesSum = 0 input.forEach { rucksack -> val pocketSize = rucksack.length/2 val first = rucksack.take(pocketSize) val second = rucksack.takeLast(pocketSize) val item = getCommonItem(first, second) prioritiesSum += item.itemPriority() } return prioritiesSum } fun part2(input: List<String>): Int { var prioritiesSum = 0 val it = input.iterator() while (it.hasNext()) { val first = it.next() val second = it.next() val third = it.next() val item = getCommonItem(first, second, third) prioritiesSum += item.itemPriority() } return prioritiesSum } val inputLines = readInputLines("input.03") println(part1(inputLines)) println(part2(inputLines)) }
0
Kotlin
0
0
f4f75f9fc0b5c6c81759357e9dcccb8759486f3a
1,701
advent-of-code-2022
Apache License 2.0
src/main/kotlin/days/Solution17.kt
Verulean
725,878,707
false
{"Kotlin": 62395}
package days import adventOfCode.InputHandler import adventOfCode.Solution import adventOfCode.util.* import java.util.* typealias IntGrid = List<List<Int>> typealias CrucibleState = Pair<Point2D, Point2D> object Solution17 : Solution<IntGrid>(AOC_YEAR, 17) { override fun getInput(handler: InputHandler) = handler.getInput("\n").map { it.map(Char::digitToInt) } private val directions = listOf(1 to 0, 0 to 1, -1 to 0, 0 to -1) private fun crucibleDijkstra(grid: IntGrid, minDist: Int, maxDist: Int): Int { val startState = (0 to 0) to (0 to 0) val end = grid.size - 1 to grid[0].size - 1 val gScores = mutableMapOf(startState to 0) val queue = PriorityQueue<Pair<Int, CrucibleState>> { p1, p2 -> p1.first - p2.first } queue.add(0 to startState) while (queue.isNotEmpty()) { val (cost, state) = queue.remove() val (pos, prevDir) = state if (pos == end) return cost directions.forEach directionLoop@{ dir -> if (dir == prevDir || -dir == prevDir) return@directionLoop var newCost = cost (1..maxDist).forEach lengthLoop@{ d -> val (ii, jj) = pos + d * dir if (ii !in grid.indices || jj !in grid[0].indices) return@lengthLoop newCost += grid[ii][jj] if (d < minDist) return@lengthLoop val newState = (ii to jj) to dir val best = gScores[newState] if (best == null || newCost < best) { gScores[newState] = newCost queue.add(newCost to newState) } } } } throw Exception("unreachable") } override fun solve(input: IntGrid): PairOf<Int> { return crucibleDijkstra(input, 1, 3) to crucibleDijkstra(input, 4, 10) } }
0
Kotlin
0
1
99d95ec6810f5a8574afd4df64eee8d6bfe7c78b
1,942
Advent-of-Code-2023
MIT License
src/main/kotlin/g2901_3000/s2902_count_of_sub_multisets_with_bounded_sum/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2901_3000.s2902_count_of_sub_multisets_with_bounded_sum // #Hard #Array #Hash_Table #Dynamic_Programming #Sliding_Window // #2024_01_03_Time_263_ms_(87.50%)_Space_41.5_MB_(37.50%) import kotlin.math.min @Suppress("NAME_SHADOWING") class Solution { private val mod = 1000000007 private val intMap = IntMap() fun countSubMultisets(nums: List<Int>, l: Int, r: Int): Int { intMap.clear() intMap.add(0) var total = 0 for (num in nums) { intMap.add(num) total += num } if (total < l) { return 0 } val r = min(r, total) val cnt = IntArray(r + 1) cnt[0] = intMap.map[0] var sum = 0 for (i in 1 until intMap.size) { val value = intMap.vals[i] val count = intMap.map[value] if (count > 0) { sum = min(r, sum + value * count) update(cnt, value, count, sum) } } var res = 0 for (i in l..r) { res = (res + cnt[i]) % mod } return res } private fun update(cnt: IntArray, n: Int, count: Int, sum: Int) { if (count == 1) { for (i in sum downTo n) { cnt[i] = (cnt[i] + cnt[i - n]) % mod } } else { for (i in n..sum) { cnt[i] = (cnt[i] + cnt[i - n]) % mod } val max = (count + 1) * n for (i in sum downTo max) { cnt[i] = (cnt[i] - cnt[i - max] + mod) % mod } } } private class IntMap { private val max = 20001 val map = IntArray(max) val vals = IntArray(max) var size = 0 fun add(v: Int) { if (map[v]++ == 0) { vals[size++] = v } } fun clear() { for (i in 0 until size) { map[vals[i]] = 0 } size = 0 } } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,012
LeetCode-in-Kotlin
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/NumWays.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import dev.shtanko.algorithms.ALPHABET_LETTERS_COUNT import dev.shtanko.algorithms.MOD /** * 1639. Number of Ways to Form a Target String Given a Dictionary * @see <a href="https://leetcode.com/problems/number-of-ways-to-form-a-target-string-given-a-dictionary"> * Source</a> */ fun interface NumWays { operator fun invoke(words: Array<String>, target: String): Int } class NumWaysDP : NumWays { override operator fun invoke(words: Array<String>, target: String): Int { val wLen: Int = words[0].length val tLen: Int = target.length val dp = Array(tLen) { LongArray(wLen) } val freq = Array(wLen) { IntArray(ALPHABET_LETTERS_COUNT) } for (w in words) { for (i in w.indices) { freq[i][w[i].code - 'a'.code]++ } } dp[0][0] = freq[0][target[0] - 'a'].toLong() for (j in 1 until wLen) { dp[0][j] = dp[0][j - 1] + freq[j][target[0] - 'a'] } for (i in 1 until tLen) { for (j in i until wLen) { val value = freq[j][target[i] - 'a'] dp[i][j] = (dp[i - 1][j - 1] * value + dp[i][j - 1]) % MOD } } return dp[tLen - 1][wLen - 1].toInt() } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,898
kotlab
Apache License 2.0
src/main/kotlin/com/dvdmunckhof/aoc/event2020/Day20.kt
dvdmunckhof
318,829,531
false
{"Kotlin": 195848, "PowerShell": 1266}
package com.dvdmunckhof.aoc.event2020 import com.dvdmunckhof.aoc.rotate import kotlin.math.sqrt class Day20(input: String) { private val tiles = input.split("\n\n").map { tile -> val id = tile.substring(5, 9).toLong() val grid = tile.split("\n").drop(1) val edgeLeft = grid.joinToString("") { it.first().toString() } val edgeRight = grid.joinToString("") { it.last().toString() } Tile(id, grid.first(), edgeRight, grid.last().reversed(), edgeLeft.reversed(), grid.map(String::toList)) } fun solvePart1(): Long { return corners().fold(1L) { acc, (tile, _) -> acc * tile.id } } fun solvePart2(): Int { val size = sqrt(tiles.size.toDouble()).toInt() val (corner, rotatedCorner) = getUpperLeftCorner() val remainingTiles = tiles.toMutableList() remainingTiles.remove(corner) val imageGrid = List(size) { mutableListOf<Tile>() } imageGrid[0] += rotatedCorner val orientationTop = 0 for ((rowPrev, row) in imageGrid.windowed(2)) { val targetEdge = rowPrev[0].edgeBottom.reversed() val tile = remainingTiles.first { it.edgeSet.contains(targetEdge) } val edge = tile.edgeMap.getValue(targetEdge) row += tile.transform(orientationTop - edge.orientation, edge.mirrored) remainingTiles.remove(tile) } val orientationLeft = 3 for (row in imageGrid) { for (i in 1 until size) { val targetEdge = row.last().edgeRight.reversed() val tile = remainingTiles.first { it.edgeSet.contains(targetEdge) } val edge = tile.edgeMap.getValue(targetEdge) val orientationOffset = if (edge.mirrored) 2 else 0 row += tile.transform(orientationLeft - edge.orientation + orientationOffset, edge.mirrored) remainingTiles.remove(tile) } } val stitchedImage = imageGrid.flatMap { row -> row.fold(List(row[0].grid.size - 2) { emptyList<Char>() }) { list, tile -> list.zip(tile.grid.drop(1).dropLast(1)) { a, b -> a + b.drop(1).dropLast(1) } } } val transformedImages = (1..7).runningFold(stitchedImage) { image, n -> if (n == 4) { image.rotate().map(List<Char>::asReversed) } else { image.rotate() } } val monsterInput = listOf(" # ", "# ## ## ###", " # # # # # # ") val monsterHeight = monsterInput.size val monsterWidth = monsterInput[0].length val monsterParts = monsterInput.flatMapIndexed { lineIndex: Int, line: String -> line.mapIndexedNotNull { charIndex, char -> if (char == '#') lineIndex to charIndex else null } } val monsterPixels = mutableSetOf<Pair<Int, Int>>() for (image in transformedImages) { for (row in 0..image.size - monsterHeight) { for (col in 0..image[row].size - monsterWidth) { val foundMonster = monsterParts.all { (r, c) -> image[row + r][col + c] == '#' } if (foundMonster) { monsterPixels += monsterParts.map { (r, c) -> row + r to col + c } } } } if (monsterPixels.isNotEmpty()) { break } } return stitchedImage.sumOf { row -> row.count { it == '#' } } - monsterPixels.size } private fun corners(): Sequence<Pair<Tile, List<String>>> { return tiles.asSequence().map { tile1 -> val otherTiles = tiles.minus(tile1) tile1 to tile1.edges.filter { edge -> otherTiles.any { other -> other.edgeSet.contains(edge) } } }.filter { it.second.size == 2 } } private fun getUpperLeftCorner(): Pair<Tile, Tile> { val corner = corners().first() var rotatedTile = corner.first val targetEdges = corner.second.toSet() while (!targetEdges.contains(rotatedTile.edgeRight) || !targetEdges.contains(rotatedTile.edgeBottom)) { rotatedTile = rotatedTile.rotate() } return corner.first to rotatedTile } private class Tile( val id: Long, val edgeTop: String, val edgeRight: String, val edgeBottom: String, val edgeLeft: String, val grid: List<List<Char>>, ) { val edges = listOf(edgeTop, edgeRight, edgeBottom, edgeLeft) val edgeMap = edges.foldIndexed(mapOf<String, Edge>()) { i, map, edge -> map + (edge to Edge(i, false)) + (edge.reversed() to Edge(i, true)) } val edgeSet get() = edgeMap.keys fun transform(rotate: Int, mirror: Boolean): Tile { return if (mirror) { mirror().rotate(4 - rotate) } else { rotate(rotate) } } private fun mirror(): Tile { val mirroredGrid = grid.map(List<Char>::asReversed) return Tile(id, edgeTop.reversed(), edgeLeft.reversed(), edgeBottom.reversed(), edgeRight.reversed(), mirroredGrid) } fun rotate(rotate: Int = 1): Tile { val n = Math.floorMod(rotate, 4) return (1..n).fold(this) { t, _ -> Tile(t.id, t.edgeLeft, t.edgeTop, t.edgeRight, t.edgeBottom, t.grid.rotate()) } } } private data class Edge(val orientation: Int, val mirrored: Boolean) }
0
Kotlin
0
0
025090211886c8520faa44b33460015b96578159
5,586
advent-of-code
Apache License 2.0
src/Day12.kt
SergeiMikhailovskii
573,781,461
false
{"Kotlin": 32574}
val queue = ArrayDeque<Point>() val matrixElementsWithDistanceToEnd = mutableMapOf<Point, Int>() var width: Int = 0 var height: Int = 0 var input: List<String> = listOf() fun main() { input = readInput("Day12_test") var end = Point(0, 0) input.forEachIndexed { i, line -> line.forEachIndexed { j, it -> if (it == 'E') { end = Point(i, j) } } } width = input[0].length height = input.size queue.add(end) matrixElementsWithDistanceToEnd[end] = 0 while (queue.isNotEmpty()) { val currentCell = queue.removeFirst() val distance = matrixElementsWithDistanceToEnd[currentCell]!! + 1 val itemValue = itemValue(input[currentCell.i][currentCell.j]) goNext(currentCell.i + 1, currentCell.j, distance, itemValue) goNext(currentCell.i - 1, currentCell.j, distance, itemValue) goNext(currentCell.i, currentCell.j + 1, distance, itemValue) goNext(currentCell.i, currentCell.j - 1, distance, itemValue) } var distance = Int.MAX_VALUE for (i in 0 until height) { for (j in 0 until width) { if (input[i][j] == 'a') { val distanceOfCell = matrixElementsWithDistanceToEnd[Point(i, j)] ?: Int.MAX_VALUE distance = minOf(distance, distanceOfCell) } } } println(distance) } fun goNext(i: Int, j: Int, d: Int, prevItemValue: Int) { if (i in 0 until height && j in 0 until width) { val point = Point(i, j) val newValue = itemValue(input[i][j]) if (newValue + 1 >= prevItemValue && !matrixElementsWithDistanceToEnd.containsKey(point)) { matrixElementsWithDistanceToEnd[point] = d queue.add(point) } } } fun itemValue(c: Char) = when (c) { 'S' -> 0 'E' -> 'z' - 'a' else -> c - 'a' } data class Point( val i: Int, val j: Int )
0
Kotlin
0
0
c7e16d65242d3be6d7e2c7eaf84f90f3f87c3f2d
1,930
advent-of-code-kotlin
Apache License 2.0
src/main/kotlin/year_2023/Day03.kt
krllus
572,617,904
false
{"Kotlin": 97314}
package year_2023 import Day import solve import utils.isStar class Day03 : Day(day = 3, year = 2023, "Gear Ratios") { override fun part1(): Int { val matrix = input.map { "$it.".toList() } var sum = 0 for (i in matrix.indices) { var numberStr = "" var numberStrAdjacent = "" for (j in 0..<matrix[i].size) { val char = matrix[i][j] if (char.isDigit()) { numberStr += char safeExecute { numberStrAdjacent += matrix[i - 1][j - 1] } safeExecute { numberStrAdjacent += matrix[i - 1][j] } safeExecute { numberStrAdjacent += matrix[i - 1][j + 1] } safeExecute { numberStrAdjacent += matrix[i][j - 1] } safeExecute { numberStrAdjacent += matrix[i][j + 1] } safeExecute { numberStrAdjacent += matrix[i + 1][j - 1] } safeExecute { numberStrAdjacent += matrix[i + 1][j] } safeExecute { numberStrAdjacent += matrix[i + 1][j + 1] } } else { if (numberStrAdjacent.any { c -> !(c.isDigit() || c == '.') }) { val number = numberStr.toInt() sum += number } numberStr = "" numberStrAdjacent = "" } } } return sum } override fun part2(): Int { val map = mutableMapOf<Point, ArrayList<Int>>() val matrix = input.map { "$it.".toList() } for (i in matrix.indices) { var numberStr = "" for (j in 0..<matrix[i].size) { val char = matrix[i][j] if (char.isDigit()) numberStr += char else { safeExecute { if (matrix[i - 1][j - 1].isStar()) { map.addElement(Point(i - 1, j - 1), numberStr.toInt()) } } safeExecute { if (matrix[i - 1][j].isStar()) { map.addElement(Point(i - 1, j), numberStr.toInt()) } } safeExecute { if (matrix[i - 1][j + 1].isStar()) { map.addElement(Point(i - 1, j + 1), numberStr.toInt()) } } safeExecute { if (matrix[i][j - 1].isStar()) { map.addElement(Point(i, j - 1), numberStr.toInt()) } } safeExecute { if (matrix[i][j].isStar()) { map.addElement(Point(i, j), numberStr.toInt()) } } safeExecute { if (matrix[i][j + 1].isStar()) { map.addElement(Point(i, j + 1), numberStr.toInt()) } } safeExecute { if (matrix[i + 1][j - 1].isStar()) { map.addElement(Point(i + 1, j - 1), numberStr.toInt()) } } safeExecute { if (matrix[i + 1][j].isStar()) { map.addElement(Point(i + 1, j), numberStr.toInt()) } } safeExecute { if (matrix[i + 1][j + 1].isStar()) { map.addElement(Point(i + 1, j + 1), numberStr.toInt()) } } numberStr = "" } } } val result = map.filter { it.value.size == 2 }.values return result.sumOf { list -> list[0] * list[1] } } } data class Point(val x: Int, val y: Int) fun safeExecute(block: () -> Unit) { try { block.invoke() } catch (_: Exception) { } } fun MutableMap<Point, ArrayList<Int>>.addElement(point: Point, element: Int) { val list = this[point] ?: arrayListOf() list.add(element) this[point] = list } fun main() { solve<Day03>(offerSubmit = true) { """ 467..114.. ...*...... ..35..633. ......#... 617*...... .....+.58. ..592..... ......755. ...$.*.... .664.598.. """.trimIndent()(part1 = 4361, part2 = 467835) } }
0
Kotlin
0
0
b5280f3592ba3a0fbe04da72d4b77fcc9754597e
4,595
advent-of-code
Apache License 2.0
src/main/kotlin/thesis/preprocess/types/extensions.kt
danilkolikov
123,672,959
false
null
package thesis.preprocess.types import thesis.preprocess.expressions.TypeName import thesis.preprocess.expressions.algebraic.term.AlgebraicEquation import thesis.preprocess.expressions.algebraic.term.AlgebraicTerm import thesis.preprocess.expressions.type.raw.RawType import thesis.utils.Edge import thesis.utils.UndirectedGraph import thesis.utils.solveSystem /** * Unifies two RawType-s to check that they have the same structure */ fun unifyTypes( first: RawType, second: RawType, definedTypes: Set<String> ): Map<TypeName, RawType> = listOf(first, second).unifyTypes(definedTypes) /** * Unifies list of RawType-s to check that they all have the same structure */ fun List<RawType>.unifyTypes(definedTypes: Set<String>): Map<TypeName, RawType> { if (size < 2) { return emptyMap() } val terms = map { it.toAlgebraicTerm() } val first = terms.first() val rest = terms.drop(1) return rest.map { AlgebraicEquation(first, it) } .inferTypes(definedTypes) .mapValues { (_, v) -> RawType.fromAlgebraicTerm(v) } } /** * Merges substitutions received from unification algorithm */ fun mergeSubstitutions( subs: List<Map<String, RawType>>, knownTypes: Set<TypeName> ): Map<String, RawType> { // Substitutions can intersect only by variables val intersection = mutableMapOf<String, MutableList<RawType>>() subs.forEach { substitution -> substitution.forEach { name, type -> intersection.putIfAbsent(name, mutableListOf()) intersection[name]?.add(type) } } val result = mutableMapOf<String, RawType>() val equations = intersection.map { (variable, list) -> result[variable] = list.first() val first = list.first().toAlgebraicTerm() listOf(AlgebraicEquation(AlgebraicTerm.Variable(variable), first)) + if (list.size == 1) { // Expression appears once - can add to result without unification emptyList() } else { // The same expression appears in many substitutions - have to unify list.drop(1).map { AlgebraicEquation(first, it.toAlgebraicTerm()) } } }.flatMap { it } val solution = equations.inferTypes(knownTypes).mapValues { (_, v) -> RawType.fromAlgebraicTerm(v) } return result.mapValues { (_, v) -> v.replaceLiterals(solution) } + solution } /** * Solves system of lambda equations and renames types according to the set of defined types */ fun List<AlgebraicEquation>.inferTypes(knownTypes: Set<TypeName>): Map<String, AlgebraicTerm> { val solution = solveSystem(this) return renameTypes(solution, knownTypes) } /** * Splits set of types to group of equal types and creates a new substitution, in which these types are * equal to previously defined ones */ private fun renameTypes( solution: Map<String, AlgebraicTerm>, knownTypes: Set<TypeName> ): Map<String, AlgebraicTerm> { // Types with equal names form undirected graph // Find connected components and set human-readable names to types in them val edges = mutableListOf<Edge<String>>() for ((left, right) in solution) { if (right is AlgebraicTerm.Variable) { edges.add(Edge(left, right.name)) } else { if (knownTypes.contains(left)) { // Type = Function type - definitely an error throw TypeInferenceErrorWithoutContext() } } } val graph = UndirectedGraph(edges) val components = graph.getConnectedComponents(knownTypes) val distinctTypes = knownTypes.map { components[it] }.toSet() if (distinctTypes.size != knownTypes.size) { // Some types were clashed during unification, that's definitely a type error throw TypeInferenceErrorWithoutContext() } val connectedComponents = components .filter { (name, value) -> name != value } .map { (name, value) -> name to AlgebraicTerm.Variable(value) } .toMap() return connectedComponents + solution .filterKeys { !connectedComponents.containsKey(it) && !knownTypes.contains(it) } .mapValues { (_, value) -> value.replace(connectedComponents) } }
0
Kotlin
0
2
0f5ad2d9fdd1f03d3bf62255da14b05e4e0289e1
4,312
fnn
MIT License
src/day10/Day10.kt
jorgensta
573,824,365
false
{"Kotlin": 31676}
class CPU() { val sprite = Sprite() var shift = 0 var cycles = 0 var X = 1 val values = mutableListOf<Int>() fun doTick() { cycles++ checkForMod20() sprite.draw(cycles, X+shift) } private fun checkForMod20() { if(cycles.mod(40) == 20) { values.add(X * cycles) } if(cycles.mod(40) == 0){ shift+=40 } } fun addx(x: Int) { X += x } fun doInstruction(instruction: String) { if(instruction.contains("addx")) { // After two cycles, addX doTick() doTick() addx(instruction.split(" ").last().toInt()) return } if (instruction == "noop") { // Takes one cycle to complete doTick() } } fun result(): Int = values.sum() } class Sprite() { val CRT = (0..6*40 - 1).map { "." }.toMutableList() fun draw(cycle: Int, X: Int) { val sprite = getSprite(X) val cyclePosition = cycle - 1 val override = sprite.find { it == cyclePosition } if( override != null) { CRT[override] = "#" } } // The sprite is 3 pixels wide fun getSprite(X: Int): List<Int> { return listOf(X - 1, X, X + 1) } public override fun toString(): String { return CRT.joinToString("").windowed(40, 40).joinToString("\n") { it } } } fun main() { val day = "day10" val filename = "Day10" fun part1(input: List<String>): Int { val cpu = CPU() input.forEach {cpu.doInstruction(it)} return cpu.result() } fun part2(input: List<String>) { val cpu = CPU() input.forEach { cpu.doInstruction(it) } println(cpu.sprite) } // test if implementation meets criteria from the description, like: val testInput = readInput("/$day/${filename}_test") val input = readInput("/$day/$filename") val partOneTest = part1(testInput) check(partOneTest == 13140) println("Part one: ${part1(input)}") val partTwoTest = part2(testInput) println("Part two: ${part2(input)}") }
0
Kotlin
0
0
7243e32351a926c3a269f1e37c1689dfaf9484de
2,179
AoC2022
Apache License 2.0
src/main/kotlin/com/hj/leetcode/kotlin/problem433/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem433 /** * LeetCode page: [433. Minimum Genetic Mutation](https://leetcode.com/problems/minimum-genetic-mutation/); */ class Solution { /* Complexity: * Time O(N^2) and Space O(N) where N is the size of bank; */ fun minMutation(start: String, end: String, bank: Array<String>): Int { val noMutationRequired = start == end if (noMutationRequired) return 0 val validGenes = bank.toHashSet().apply { remove(start) } val isInvalidEndGene = end !in validGenes if (isInvalidEndGene) return -1 return findMinNonZeroStepsToEndGene(0, listOf(start), validGenes, end) } private tailrec fun findMinNonZeroStepsToEndGene( currStep: Int, genesAtCurrStep: List<String>, validGenes: MutableSet<String>, endGene: String ): Int { val genesAtNextStep = mutableListOf<String>() for (gene in genesAtCurrStep) { val validGenesIterator = validGenes.iterator() while (validGenesIterator.hasNext()) { val validGene = validGenesIterator.next() val inOneMutation = inOneMutation(gene, validGene) if (inOneMutation) { if (validGene == endGene) return currStep + 1 genesAtNextStep.add(validGene) validGenesIterator.remove() } } } return if (genesAtNextStep.isEmpty()) { -1 } else { findMinNonZeroStepsToEndGene(currStep + 1, genesAtNextStep, validGenes, endGene) } } private fun inOneMutation(gene: String, target: String): Boolean { require(gene.length == target.length) var numDiff = 0 for (index in gene.indices) { if (gene[index] != target[index]) { if (numDiff == 0) numDiff++ else return false } } return true } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
1,976
hj-leetcode-kotlin
Apache License 2.0
src/main/kotlin/aoc2015/AntSue.kt
komu
113,825,414
false
{"Kotlin": 395919}
package komu.adventofcode.aoc2015 import komu.adventofcode.utils.nonEmptyLines fun antSue1(input: String): Int = Sue.parseAll(input).find { it.matchesKnown() }?.number ?: error("no match") fun antSue2(input: String): Int = Sue.parseAll(input).find { it.matchesKnown2() }?.number ?: error("no match") private class Sue(val number: Int, val things: Map<String, Int>) { fun matchesKnown() = isEqual("children", 3) && isEqual("cats", 7) && isEqual("samoyeds", 2) && isEqual("pomeranians", 3) && isEqual("akitas", 0) && isEqual("vizslas", 0) && isEqual("goldfish", 5) && isEqual("trees", 3) && isEqual("cars", 2) && isEqual("perfumes", 1) fun matchesKnown2() = isEqual("children", 3) && isEqual("samoyeds", 2) && isEqual("akitas", 0) && isEqual("vizslas", 0) && isEqual("cars", 2) && isEqual("perfumes", 1) && isGreater("cats", 7) && isGreater("trees", 3) && isLess("pomeranians", 3) && isLess("goldfish", 5) private fun isEqual(key: String, expected: Int) = (things[key] ?: expected) == expected private fun isGreater(key: String, expected: Int) = (things[key] ?: (expected + 1)) > expected private fun isLess(key: String, expected: Int) = (things[key] ?: (expected - 1)) < expected companion object { private val regex = Regex("""Sue (\d+): (.+)""") fun parseAll(input: String) = input.nonEmptyLines().map { parse(it) } private fun parse(input: String): Sue { val (num, things) = regex.matchEntire(input)?.destructured ?: error("invalid Sue '$input'") return Sue(num.toInt(), things = things.split(", ").associate { val (thing, count) = it.split(": ") thing to count.toInt() }) } } }
0
Kotlin
0
0
8e135f80d65d15dbbee5d2749cccbe098a1bc5d8
2,026
advent-of-code
MIT License
src/main/kotlin/g1501_1600/s1569_number_of_ways_to_reorder_array_to_get_same_bst/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1501_1600.s1569_number_of_ways_to_reorder_array_to_get_same_bst // #Hard #Array #Dynamic_Programming #Math #Tree #Binary_Tree #Union_Find #Binary_Search_Tree // #Divide_and_Conquer #Memoization #Combinatorics // #2023_06_14_Time_256_ms_(100.00%)_Space_38.1_MB_(100.00%) class Solution { fun numOfWays(nums: IntArray): Int { val mod: Long = 1000000007 val fact = LongArray(1001) fact[0] = 1 for (i in 1..1000) { fact[i] = fact[i - 1] * i % mod } val root = TreeNode(nums[0]) for (i in 1 until nums.size) { addInTree(nums[i], root) } return ((calcPerms(root, fact).perm - 1) % mod).toInt() } class Inverse(var x: Long, var y: Long) class TreeInfo(var numOfNodes: Long, var perm: Long) class TreeNode(var `val`: Int) { var left: TreeNode? = null var right: TreeNode? = null } private fun calcPerms(root: TreeNode?, fact: LongArray): TreeInfo { val left: TreeInfo val right: TreeInfo left = if (root!!.left != null) { calcPerms( root.left, fact ) } else { TreeInfo(0, 1) } right = if (root.right != null) { calcPerms( root.right, fact ) } else { TreeInfo(0, 1) } val mod: Long = 1000000007 val totNodes = left.numOfNodes + right.numOfNodes + 1 val modDiv = getModDivision( fact[totNodes.toInt() - 1], fact[left.numOfNodes.toInt()], fact[right.numOfNodes.toInt()], mod ) val perms = if (totNodes == 1L) 1 else left.perm * right.perm % mod * modDiv % mod left.numOfNodes = totNodes left.perm = perms return left } private fun getModDivision(a: Long, b1: Long, b2: Long, m: Long): Long { val b = b1 * b2 val inv = getInverse(b, m) return inv * a % m } private fun getInverse(b: Long, m: Long): Long { val inv = getInverseExtended(b, m) return (inv.x % m + m) % m } private fun getInverseExtended(a: Long, b: Long): Inverse { if (a == 0L) { return Inverse(0, 1) } val inv = getInverseExtended(b % a, a) val x1 = inv.y - b / a * inv.x val y1 = inv.x inv.x = x1 inv.y = y1 return inv } private fun addInTree(x: Int, root: TreeNode?) { if (root!!.`val` > x) { if (root.left != null) { addInTree(x, root.left) } else { root.left = TreeNode(x) } } if (root.`val` < x) { if (root.right != null) { addInTree(x, root.right) } else { root.right = TreeNode(x) } } } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,907
LeetCode-in-Kotlin
MIT License
src/Day20.kt
jvmusin
572,685,421
false
{"Kotlin": 86453}
import java.util.* import kotlin.math.abs import kotlin.math.sign import kotlin.random.Random import kotlin.random.nextInt fun main() { fun part1(input: List<String>): Int { val list = input.mapIndexed { index, s -> s.toInt() to index }.toMutableList() for (i in list.indices) { var pos = list.indexOfFirst { it.second == i } val x = list[pos] val delta = x.first.sign repeat(abs(x.first)) { Collections.swap(list, pos, (pos + delta + list.size) % list.size) pos += delta pos += list.size pos %= list.size } } val pos0 = list.indexOfFirst { it.first == 0 } val res = listOf(1000, 2000, 3000).map { list[(pos0 + it) % list.size] } return res.sumOf { it.first } } fun MutableList<Pair<Long, Int>>.normalize(): MutableList<Pair<Long, Int>> { while (first().second != 0) add(removeFirst()) return this } fun MutableList<Pair<Long, Int>>.putFirstIndex(i: Int) { while (first().second != i) add(removeFirst()) } fun MutableList<Pair<Long, Int>>.applyShift(i: Int) { putFirstIndex(i) val x = first().first val singleShifts = abs(x) / (size - 1) repeat((singleShifts % size).toInt()) { if (x > 0) add(removeFirst()) else add(0, removeLast()) } val rem = abs(x) % (size - 1) putFirstIndex(i) var pos = 0 val direction = x.sign repeat(rem.toInt()) { val next = (pos + direction + size) % size Collections.swap(this, pos, next) pos = next } } fun test(a: List<Pair<Long, Int>>) { fun naive(): MutableList<Pair<Long, Int>> { val list = a.toMutableList() for (i in list.indices) { var pos = list.indexOfFirst { it.second == i } val x = list[pos].first val direction = x.sign repeat(abs(x).toInt()) { val next = (pos + direction + list.size) % list.size Collections.swap(list, pos, next) pos = next } } return list } fun faster(): MutableList<Pair<Long, Int>> { val list = a.toMutableList() for (i in list.indices) { list.applyShift(i) } return list } val naive = naive().normalize() val faster = faster().normalize() println(a) println(naive) println(faster) println(naive == faster) require(naive == faster) } /* 12345 21345 23145 23415 23451 13452 12345 52341 52314 52134 51234 15234 */ fun part2(input: List<String>): Long { val rnd = Random(239) while (false) { test(List(10) { rnd.nextInt(-5000000..5000000).toLong() to it }) } val list = input.mapIndexedTo(mutableListOf()) { index, s -> s.toLong() * 811589153L to index } val size = list.size repeat(10) { for (i in list.indices) { list.applyShift(i) } println(list.map { it.first }) } val pos0 = list.indexOfFirst { it.first == 0L } val res = arrayOf(1000, 2000, 3000).map { list[(pos0 + it) % size] } return res.sumOf { it.first } } @Suppress("DuplicatedCode") run { val day = String.format("%02d", 20) val testInput = readInput("Day${day}_test") val input = readInput("Day$day") println("Part 1 test - " + part1(testInput)) println("Part 1 real - " + part1(input)) println("---") println("Part 2 test - " + part2(testInput)) println("Part 2 real - " + part2(input)) } }
1
Kotlin
0
0
4dd83724103617aa0e77eb145744bc3e8c988959
3,941
advent-of-code-2022
Apache License 2.0
src/Day05_1.kt
ozzush
579,610,908
false
{"Kotlin": 5111}
// [P] [Q] [T] // [F] [N] [P] [L] [M] // [H] [T] [H] [M] [H] [Z] // [M] [C] [P] [Q] [R] [C] [J] // [T] [J] [M] [F] [L] [G] [R] [Q] // [V] [G] [D] [V] [G] [D] [N] [W] [L] // [L] [Q] [S] [B] [H] [B] [M] [L] [D] // [D] [H] [R] [L] [N] [W] [G] [C] [R] // 1 2 3 4 5 6 7 8 9 val state = listOf("FHMTVLD", "PNTCJGQH", "HPMDSR", "FVBL", "QLGHN", "PMRGDBW", "QLHCRNMG", "WLC", "TMZJQLDR") .map { it.toList() }.toMutableList() val testState = listOf("NZ", "DCM", "P") .map { it.toList() }.toMutableList() fun main() { fun solve(input: String, init: MutableList<List<Char>>) = readInput(input).fold(init) { acc, elm -> val numbers = Regex("[0-9]+").findAll(elm) .map(MatchResult::value) .toList() .map { it.toInt() } acc[numbers[2] - 1] = (acc[numbers[1] - 1].take(numbers[0]) + acc[numbers[2] - 1]) acc[numbers[1] - 1] = acc[numbers[1] - 1].takeLast(acc[numbers[1] - 1].size - numbers[0]) // println(acc) acc }.map { it[0] }.joinToString("") val test = solve("day05_test", testState) check(test == "MCD") solve("day05", state).println() }
0
Kotlin
0
0
9b29a13833659f86d3791b5c07f9decb0dcee475
1,218
AdventOfCode2022
Apache License 2.0
Retos/Reto #2 - EL PARTIDO DE TENIS [Media]/kotlin/masdos.kt
mouredev
581,049,695
false
{"Python": 3866914, "JavaScript": 1514237, "Java": 1272062, "C#": 770734, "Kotlin": 533094, "TypeScript": 457043, "Rust": 356917, "PHP": 281430, "Go": 243918, "Jupyter Notebook": 221090, "Swift": 216751, "C": 210761, "C++": 164758, "Dart": 159755, "Ruby": 70259, "Perl": 52923, "VBScript": 49663, "HTML": 45912, "Raku": 44139, "Scala": 30892, "Shell": 27625, "R": 19771, "Lua": 16625, "COBOL": 15467, "PowerShell": 14611, "Common Lisp": 12715, "F#": 12710, "Pascal": 12673, "Haskell": 11051, "Assembly": 10368, "Elixir": 9033, "Visual Basic .NET": 7350, "Groovy": 7331, "PLpgSQL": 6742, "Clojure": 6227, "TSQL": 5744, "Zig": 5594, "Objective-C": 5413, "Apex": 4662, "ActionScript": 3778, "Batchfile": 3608, "OCaml": 3407, "Ada": 3349, "ABAP": 2631, "Erlang": 2460, "BASIC": 2340, "D": 2243, "Awk": 2203, "CoffeeScript": 2199, "Vim Script": 2158, "Brainfuck": 1550, "Prolog": 1342, "Crystal": 783, "Fortran": 778, "Solidity": 560, "Standard ML": 525, "Scheme": 457, "Vala": 454, "Limbo": 356, "xBase": 346, "Jasmin": 285, "Eiffel": 256, "GDScript": 252, "Witcher Script": 228, "Julia": 224, "MATLAB": 193, "Forth": 177, "Mercury": 175, "Befunge": 173, "Ballerina": 160, "Smalltalk": 130, "Modula-2": 129, "Rebol": 127, "NewLisp": 124, "Haxe": 112, "HolyC": 110, "GLSL": 106, "CWeb": 105, "AL": 102, "Fantom": 97, "Alloy": 93, "Cool": 93, "AppleScript": 85, "Ceylon": 81, "Idris": 80, "Dylan": 70, "Agda": 69, "Pony": 69, "Pawn": 65, "Elm": 61, "Red": 61, "Grace": 59, "Mathematica": 58, "Lasso": 57, "Genie": 42, "LOLCODE": 40, "Nim": 38, "V": 38, "Chapel": 34, "Ioke": 32, "Racket": 28, "LiveScript": 25, "Self": 24, "Hy": 22, "Arc": 21, "Nit": 21, "Boo": 19, "Tcl": 17, "Turing": 17}
import kotlin.math.abs fun main() { /* * Escribe un programa que muestre cómo transcurre un juego de tenis y quién lo ha ganado. * El programa recibirá una secuencia formada por "P1" (Player 1) o "P2" (Player 2), según quien * gane cada punto del juego. * * - Las puntuaciones de un juego son "Love" (cero), 15, 30, 40, "Deuce" (empate), ventaja. * - Ante la secuencia [P1, P1, P2, P2, P1, P2, P1, P1], el programa mostraría lo siguiente: * 15 - Love * 30 - Love * 30 - 15 * 30 - 30 * 40 - 30 * Deuce * Ventaja P1 * Ha ganado el P1 * - Si quieres, puedes controlar errores en la entrada de datos. * - Consulta las reglas del juego si tienes dudas sobre el sistema de puntos. */ val matchResult: MutableList<String> = mutableListOf() println("PARTIDO DE TENIS") var finish = false while (!finish) { println( "Introduce quien ha ganado el punto. P1 (Player 1), P2 (Player 2) o X (Fin del partido):" ) when (val point = readln()) { "P1", "P2" -> matchResult.add(point) "X" -> finish = true else -> println("El parámetro '$point' no es correcto. Aceptados: P1, P2 o X") } } calculateScoreGame(matchResult).forEach { println(it) } } private fun calculateScoreGame(matchResult: MutableList<String>): List<String> { val pointSystem = mapOf(0 to "Love", 1 to "15", 2 to "30", 3 to "40") var scoreP1 = 0 var scoreP2 = 0 return matchResult.map { if (it == "P1") scoreP1++ else scoreP2++ when { isDeuce(scoreP1, scoreP2) -> "Deuce" isAdvantage(scoreP1, scoreP2) -> "Ventaja $it" isWin(scoreP1, scoreP2) -> "Ha ganado el $it" else -> "${pointSystem[scoreP1]} - ${pointSystem[scoreP2]}" } } } private fun isWin(scoreP1: Int, scoreP2: Int) = (scoreP1 >= 4 || scoreP2 >= 4) && abs(scoreP1 - scoreP2) >= 2 private fun isAdvantage(scoreP1: Int, scoreP2: Int) = (scoreP1 > 3 || scoreP2 > 3) && abs(scoreP1 - scoreP2) == 1 private fun isDeuce(scoreP1: Int, scoreP2: Int) = scoreP1 >= 3 && scoreP2 >= 3 && scoreP1 == scoreP2
4
Python
2,929
4,661
adcec568ef7944fae3dcbb40c79dbfb8ef1f633c
2,097
retos-programacion-2023
Apache License 2.0
foreach/src/main0.kt
XinyueZ
96,028,554
false
null
import java.util.stream.Collectors import java.util.stream.IntStream import java.util.stream.Stream fun main(args: Array<String>) { println("Examples foreach, list, array, collection ....") println() val list1 = listOf("one", "two", "three") foreachList(list1) val list2 = list1 + listOf("four", "five", "six") streamForeachList(list2) translateNumbers(list2) sum(list2) sumParallel(list2) sumAdvanced(list2) evenOdd(list2) simulateForeach(list2) { println(it) } } fun foreachList(vals: List<String>) { println("[foreach] on list") vals.forEach { println(it) } } fun streamForeachList(vals: List<String>) { println("[stream.foreach] on list") vals.stream().forEach { println(it) } } fun simulateForeach(vals: List<String>, body: (String) -> Unit) { println("Foreach simulated by inline fun") for (s in vals) { body(s) } } fun translateNumbers(vals: List<String>) { println("[stream.mapToInt.foreach] on list") vals.stream().mapToInt { when (it) { "one" -> 1 "two" -> 2 "three" -> 3 "four" -> 4 "five" -> 5 "six" -> 6 else -> -1 } }.forEach { println(it) } } fun sum(vals: List<String>) { println("[stream.mapToInt.sum] on list") vals.stream().filter({ if (vals.indexOf(it) == vals.size - 1) print(it + " = ") else print(it + " + ") true }).mapToInt { when (it) { "one" -> 1 "two" -> 2 "three" -> 3 "four" -> 4 "five" -> 5 "six" -> 6 else -> -1 } }.sum().let { println(it) } } fun sumParallel(vals: List<String>) { println("[stream.mapToInt.parallel.sum] on list") vals.stream().parallel().filter({ if (vals.indexOf(it) == vals.size - 1) print(it + " = ") else print(it + " + ") true }).mapToInt { when (it) { "one" -> 1 "two" -> 2 "three" -> 3 "four" -> 4 "five" -> 5 "six" -> 6 else -> -1 } }.sum().let { println(it) } } fun sumAdvanced(vals: List<String>) { println("[stream + stream] on list") vals.stream().flatMapToInt { Stream.of( when (it) { "one" -> Pair(1, 1)//index or position, value "two" -> Pair(2, 2) "three" -> Pair(3, 3) "four" -> Pair(4, 4) "five" -> Pair(5, 5) "six" -> Pair(6, 7) else -> null } ).filter { if (it!!.first == vals.size) print(it.first.toString() + " = ") else print(it.first.toString() + " + ") true }.flatMapToInt { IntStream.of(it!!.second) } }.sum().let { println(it) } } fun evenOdd(vals: List<String>) { println("[stream + collect + partitioningBy] on list") val collect = vals.stream().collect(Collectors.partitioningBy({ val num = when (it) { "one" -> 1 "two" -> 2 "three" -> 3 "four" -> 4 "five" -> 5 "six" -> 6 else -> -1 } num.rem(2) == 0 })) println("even:") println(collect[true]) println("odd:") println(collect[false]) }
0
Kotlin
0
0
3ec03f258621f32a5d134f04075e00ec95151576
3,384
lambda-world
MIT License
src/Day04.kt
holukent
573,489,120
false
{"Kotlin": 5111}
import java.io.File fun main() { fun part1(input: String): Int { val data = input.split("\r\n") var result = 0 for (d in data) { val temp = d.split(",").map { it.split("-") } val first = temp[0] val second = temp[1] if ( (first[0].toInt() <= second[0].toInt() && first[1].toInt() >= second[1].toInt()) || (first[0].toInt() >= second[0].toInt() && first[1].toInt() <= second[1].toInt()) ) { result++ } } return result } fun part2(input: String): Int { val data = input.split("\r\n") var result = 0 for (d in data) { val temp = d.split(",").map { it.split("-") } val first = temp[0].map { it.toInt() } val second = temp[1].map { it.toInt() } if ( (first[0] in second[0]..second[1]) || (first[1] in second[0]..second[1]) || (second[0] in first[0]..first[1]) || (second[0] in first[0]..first[1]) ) { result++ } } return result } val testInput = File("src/Day04_test.txt").readText() check(part2(testInput) == 4) val input = File("src/Day04.txt").readText() println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
6993a6f0f20c226772a16f3b60217f1f0f025ddf
1,411
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/advent2019/day6/day6.kt
davidpricedev
225,621,794
false
null
package advent2019.day6 import advent2019.util.memoize fun main() { val inputAsMap = inputToMap(getInput()) runPart1(inputAsMap) runPart2(inputAsMap) } fun runPart1(inputAsMap: Map<String, String>) { println(countAllAncestors(inputAsMap)) } fun runPart2(inputAsMap: Map<String, String>) { println(calculateShortestPath(inputAsMap, "YOU", "SAN")) } fun countAllAncestors(map: Map<String, String>) = map.keys.map { buildAncestorList(it, map, listOf()).count() }.sum() /** * Part 2 * Calculate the shortest orbit jump path between one orbiting body (start) and another (dest) */ fun calculateShortestPath(map: Map<String, String>, start: String, dest: String): Int { // Build the raw data we need val ancestorMap = map.mapValues { buildAncestorList(it.key, map, listOf()) } // Now find the nearest common ancestor val startAncestors = ancestorMap[start] ?: listOf() val destAncestors = ancestorMap[dest] ?: listOf() val intersects = startAncestors.intersect(destAncestors) val nearestCommonAncestor = intersects.first() return startAncestors.indexOf(nearestCommonAncestor) + destAncestors.indexOf(nearestCommonAncestor) } val buildAncestorList = ::buildAncestorListRaw.memoize() fun buildAncestorListRaw(key: String, map: Map<String, String>, ancestorList: List<String> = listOf()): List<String> = if (!map.containsKey(key)) { ancestorList } else { val nextKey = map[key] ?: "(╯°□°)╯︵ ┻━┻" buildAncestorList(nextKey, map, ancestorList.plus(nextKey)) } fun inputToMap(input: List<String>) = input.map { stringToPair(it) }.toMap() fun stringToPair(orbitStr: String): Pair<String, String> { val parts = orbitStr.split(")") return Pair(parts[1], parts[0]) } fun getInput() = """ FGY)61Z 2BN)LM7 QXY)TVB 5M5)Y6C 2L2)64M 6TT)183 H6P)6TT LPL)WP5 TDW)SDV 4N3)LHM MJ7)STL V17)4QM 2XW)R2P CMK)P3C KN5)XBH 4GV)Z17 VQW)KD6 N6Q)GBK LZC)5R2 3Z1)L7Y 1LV)QCF NQ5)6K4 3XX)D1H YT6)DXZ JFB)CMF NFC)DYG VG6)W38 31Z)TCV 597)H8Q GK1)MSN 69N)W4Y 3NY)1FX W81)3XX LP1)KBR 3KD)X65 YSD)HLF WKN)NXN C9S)NYS 9DX)Y3V VY4)YSL 2V4)79M X68)1RB 53T)H97 TKM)2J1 K8M)N95 HZ2)J3B R6Z)KQ1 96F)5WS W68)KQ5 H4G)NCN WXV)BH6 8Z1)KVB WGQ)18Y 4M1)9D8 2NH)RLJ KVB)1Y5 3SG)RFG GBD)HZJ 1W4)JZ4 4W5)R1J 6KP)GJB 1QS)4D5 1Q4)FDD DZX)Q8F 7MB)1RF RFG)TKV LK4)QTF YKS)LLV 4Z9)2BL VNR)WJ4 81Z)KNH 2V7)9LV MCW)LRD SGB)HTX NKK)DGX MHG)C7W 2T7)6VV X9J)2CL 8CF)RPP LVZ)GY6 NDK)D1V JYG)LTF ZL3)JP5 RZP)NGS 6LW)212 4QM)6B2 351)ZCK 8FJ)JF9 TH4)XZV 3HK)1W4 DCX)TKM 8JW)CCB Z5Y)4N7 L73)1XV 4QJ)6VW F4H)8C7 RKS)BQ9 HHB)RWF 2T7)X5H XQF)HXM QKM)CMJ GC3)RZR BBL)D5Q LC7)JBF 8RJ)MZ1 PD9)TYR MWX)B17 DR1)L88 KBR)B16 CM2)Q2J J5Q)3WP 3Z1)2XW YCF)VY4 76M)2V4 CCM)L2Z 7XM)YNQ 7HW)GTK ZSM)6LC H9P)G1N 4ZD)B3C DXZ)39Y 18Y)V17 747)QXY W26)ZTN RLJ)J5Q PHC)96F ZQD)PMY BWK)8RJ 8C4)DRX YL1)NDK W19)PFH T6V)X8G LPR)TRR JRV)NF8 248)XVV KQ1)H3P 747)BSB 8PH)C4N 7ZT)9M8 FPQ)QKH LXZ)CYZ VZX)681 PRZ)6J4 XZ6)91R G77)QG1 QCF)G3S NXN)XT1 K95)DY2 1JF)NNH 4N7)7W3 5RQ)PBN JRS)8D1 G7C)8SK H3P)H16 346)Q8Q HH7)5LZ HZJ)WFK FRH)81J DQM)K3X HTX)9RN VV9)4Z9 X6T)T37 JC7)K7H P98)9SF 9SD)XFM V9P)B98 BG7)8NQ YPZ)PMJ 5VN)NFR T9Z)LK4 J5G)N4K X5R)GFG TZP)MK5 2B4)5MV FNG)RTR WFK)HXC BJ7)R2J HCZ)HVV 1CM)HYW 9FL)DPR JPQ)FFS P5P)6VT D1V)MJK RZB)Q92 M72)QP1 8ZZ)L16 7FB)XZN X6C)TSV MK5)SC7 9B4)7ZX JZ4)6C5 5H2)33S WY2)487 PFH)1J9 6RF)G42 VH4)T75 JF9)9H3 HL8)DMB WSR)98S W6W)NNX Y6C)LC7 G9P)VLT 6B2)D5V HXC)GX8 T3V)4B7 9KC)46N SDV)5T7 8D1)8QG TZJ)5QJ MBT)TBD F1D)M29 19K)C7H TBN)6KQ TKC)76M 38H)6L2 ZBK)PVD DXR)CTS KCS)XDX QWW)849 7W3)NMG BX6)397 Q61)38H C7H)JFB K1Y)2ZR 39Y)CMK 3FL)QTP S7Y)6DR 2YN)J4C Q8F)PG7 J5W)72Z CN9)L7M R1J)53D YFG)CRC 779)4RY DGZ)M17 5LZ)BZ3 B5S)FX6 5VV)5P5 8M9)2P8 GT6)J29 WFK)759 8NV)FSB YWS)Q8X ZV4)ZLV 6C5)NF5 CP9)XC7 61Z)YH9 VZ8)W81 FGN)JMN ZSW)72R JSN)P6K Y3Z)Q7M LT7)ZZM 1WZ)319 CGG)D7H NT4)HG8 RLB)QQR S4B)3SG H3Z)BDJ RZR)GH3 QP1)PND FSB)PK7 B3C)KGS 4P5)W26 TSV)1LV 37K)1Q4 L5B)J9C P6K)G14 XZN)CGQ N95)6LW W8S)2NH HXM)GX7 6KQ)ZQY Y2L)C57 DPR)318 7S8)Y82 Q8J)YJQ 2YC)SX6 DK2)N41 C1N)PRZ LW3)1P2 GGX)4R2 9FZ)8PH 4WD)3J1 J9C)G9P J81)XJS WCJ)2B4 M3V)1QC QQP)1F7 9HM)979 NGS)72D CMF)D5N M2S)VDJ QW7)LQ8 PFF)4LD 1YN)MHG FR3)W19 CKS)ST1 1S4)VZX 7S8)M83 L16)7VX CTS)YFG WJ4)SGB 4S5)6V7 MF4)7GN QTP)M5Q 6TD)HXG QXY)MFG 6K5)JRS XN6)113 TPY)2YC XL2)PMC VSK)THY L88)8CF NFR)PCV MDX)LPZ D3K)4FG 8YP)L2L PMY)QJM GH3)TG5 6KZ)F1H Y85)X68 CMJ)VMQ GFG)8Z8 1L1)VH4 BTN)Q91 T7W)TVF 6LC)LPL BW5)RXF 6VW)X6C 5P5)BK8 24B)VV9 HCT)9KC Q2J)96V 5D3)97R BJL)PFS RTR)J8P VCJ)8GM 6KF)LNJ KLB)31Z VQW)2V7 8CJ)5QS V2S)QWW 6DR)3KD D5N)5B5 DK1)Z16 YVB)P7K WSY)X5R P13)T4G VGZ)SYR LVB)ZWS RPG)CQP 81J)573 F9B)CKC M3R)8JW HL8)G1B WDN)WYX ZZ3)F17 7XM)MK1 HKF)VNR BSB)H4G JS4)MS6 SXQ)G7N G1F)5VN NH5)V2Y 2WF)LS2 K51)SVQ MM2)MDX JSN)LR3 FTV)28F R66)8DH 5JM)Y2L Q92)GRR 55L)3Z1 2BG)VLB 7GN)P6R 8K3)YCL KDN)R6Z GX8)KCS TCV)H9P 6J4)JS4 Q7M)JRV NXF)5B3 573)HZC HZC)F4H MSN)W3D TBD)2YQ YQN)12D RQX)94S GTK)RYG GVG)9WV CM5)V9P QP9)JNR JYG)NN1 2P8)9BZ FF6)PSW WB6)NKK CZJ)H7C YYH)62H YSL)LP1 SJJ)YC6 9GB)GSF P6X)8Z1 P8C)CTR 979)83S NF5)TBK TQP)8NV PC3)YMB QST)M2S X56)19Y Y7G)H3Z 2RN)BDK TYR)JXJ NF2)WB6 P7K)DXN RKH)WZ7 17T)XNK NL1)QHY Y82)WJS L7M)BC5 KJB)ZSW DXN)KVH VLW)JPQ S2D)DGZ FX6)NYD FWT)TKC 2JN)VQW V2Y)X86 H97)XL2 BLC)DCK 6N7)868 FPF)F3R F1H)WHH XFM)R2N PNH)KYQ J4C)6VX TVB)G1F NNX)B66 BZ3)V9W GMR)QST RBB)Y34 577)755 SX6)3V2 1L1)DK1 X5V)RZ8 M3F)QF7 8YR)677 M83)FPF J28)M8L M83)FRY T8Y)X6T MMJ)YL1 487)T2N TRR)KJB FFS)QNC WP5)3L6 6V7)1Z7 9FL)X5Q W38)2RS 1J9)X92 N9X)9KT 12D)F9B 6QR)DCX 7ZT)MM2 P8K)K51 WKR)M3F CCB)B29 RSN)VCJ L7S)37K 5QS)HQR 6RF)NPC Y1T)2T7 FGB)YT6 MGY)K95 DGX)LWC TH4)X26 MFG)FPQ Y7Y)L67 DM6)9NJ THY)2JN SMJ)PC3 SZC)S7Y JPQ)VHY SKG)11M YNJ)3HK 2V4)VX3 QP9)711 681)BBL 2G8)8K1 QW9)7HW 9J6)MYL 93R)6TD J9W)2YN CRC)VBT XDD)G9R 97R)9HM ZCK)TZJ 5WS)9L3 BCW)7PY XLV)47R CK9)1L1 GHN)5DM 759)MMJ WYX)RSC VLT)1WZ 7T6)PRP 62G)PHC XBH)4WD 4FG)LVB 1X7)CP9 X5R)8C4 GK1)DQM 3WP)YKS G42)672 BDJ)7XM 9BZ)W4G PJJ)YZ4 SQZ)5VV VK9)45G R2P)MWX NHX)YYH 9RW)JC7 94S)VX4 G3Q)R21 6K4)6N7 3L6)4W3 3C3)Y7Y 9M8)NQ5 SJM)68L P6K)G72 K3X)CZJ CY6)L5B LWK)MZG 43Y)QKM 6DR)HH7 HT1)54V 2BL)PX9 5B3)LVZ Z6H)JYB 5MG)Y8Q VKJ)VK5 LR3)P6X F1F)7YW VY4)W52 VG6)YLW T1Q)LWG KYQ)BY7 672)WDN SR5)SQZ NKK)DK2 YJQ)XN6 6XD)Y1S Z5M)QHT Z6S)BJK COM)ML7 WB1)DFR X5H)2L2 C7Q)MJC BJK)SKV LC7)7SS V9W)VZ8 PHF)1YT G72)QW7 ZJV)346 W3D)8S7 R2N)8CJ TDL)W6W DLT)6QR X92)1M4 WC6)LXZ BXW)1YY CN9)VFJ 6KQ)YOU XNK)NHX DQ4)X34 MJK)Y55 T75)5YF PCV)N9X JBF)SZC ZLV)VS8 2YC)DLT RFL)KPR 8N7)FDY PND)GMR DRX)69N 45G)P3N NYS)9B4 YDY)NWQ 6GC)DZX NMG)TJ2 PFS)JYG KNT)5FZ ZYN)ZQ2 K9P)RQX ML8)B9J PRP)9GB 67N)JSN 3HG)GHN PYN)KJN GVG)WY9 S8N)YT5 VFJ)2RN 6VX)6LB FHY)7DC D65)4N3 BH6)MF4 DKW)M3J DYG)3FP YC8)HZ2 G8R)M3R HXG)HWS CQP)LW3 GCH)9SD 4HR)LX9 KQ5)YV4 2V2)C9S 3J1)TP4 XPL)QVR TG5)GQB KVH)VQ7 JMN)BX6 QX9)72M 4RY)Z6H HGN)SAN NF8)577 72D)BLC QG1)125 SYR)XZ3 WW5)LZC 5YF)X56 N9R)ZZ3 6VT)YPR 8S7)XDD 65Y)P5P 9SF)R6Y GJB)LWK 9RN)QYV THY)Y85 1YT)1JF TKC)ZQD PD9)YNJ 3FP)DKW XDX)D91 G9R)BCV RXF)BXW 44W)FGB GY6)1ZW TTT)PZ7 LTF)4GZ 9NJ)RMB CYJ)7XL 183)PQF 319)WC6 DY9)8ZZ P7W)VSK G1F)F4Y MZ1)1YN JRF)M9R 3V2)QXF STL)C7Q 6VV)CN9 QF7)G93 PSW)FRD T2N)8N7 Z17)4ZD P5X)M8C GX7)YLK PMJ)N2Y HG8)W8S WH4)ZBK 6RT)FGN 9WV)K1T B98)YVB H7C)WXV YH9)MGY NNH)65Y VQ7)3NY RGV)V9J B2H)NF2 HQR)L4D LM7)S4B JBS)GK1 DRX)YDY JNR)8YP 1F7)DXR FRD)ML8 RQ6)9SW TP4)BW5 MYL)HL8 VS8)J81 Y9Z)CNZ Y1S)DC6 4GZ)N9R M5M)MJ7 2BN)DR1 53D)G7C G14)QX9 Y9L)2P6 XSQ)GYL MJD)Y9L P3C)2P7 Q3P)MSM QVR)WB1 X9R)RKS CGG)38V 5VN)QQP 96V)F1D ZQY)Y8L M29)P8K CKC)JC3 TDW)VW5 Q91)FNR X5Q)YCT PZ7)4FZ ZL3)114 K1T)J6S B17)779 PQF)NXF NCN)3FL W4G)NTH 7PY)74M VDJ)JW4 V1F)GDQ QQR)YQN 2S5)RBB 7FF)597 MS6)V4N QW9)4P5 BLC)C31 QTF)ZVX YNJ)RHQ G93)6KZ P3N)P8C G9P)ZSM 91R)LPG PG7)VRY DCK)D65 CCB)BTN D7H)D3K XT1)W5Q 7DC)M72 PK7)H6P 6VW)1FS KGS)HHN WZ7)J4Q RSW)RQ6 M4B)7T6 LLV)YSD WDN)7FF DTY)WGQ P5P)3HG H6P)5RQ 64M)4TV 8GM)LCC 1YY)G8R XVV)DM6 WY9)XKN QHY)G43 7SS)T6V PX9)SR5 VK5)81Z YG3)V1F YT5)CKS F17)SH3 2JP)2G8 6LC)RZB XS1)RGV R2J)2V2 QKH)L5N ZZB)YG3 Y8L)6C2 YPR)3ZK 7YW)1RM 9DP)9DX V9P)248 N2Y)D8V TVB)KLB 5YF)RFL SM3)595 DXR)8FJ PBN)G77 QDC)MBT 595)PNH 5B5)DTY CNZ)L7X VW5)CK9 HLF)K7N VRY)PGG GRR)C1N L4D)PQ7 YLW)1QS YLK)X5V H8Q)Z1Q FRY)VLW LWC)ZJV KGL)DP8 XC7)48H ML7)V6Q YLW)Q3P CGQ)PFF X5Q)61X 46N)S2D QHT)8K3 JNY)F9R 2LS)QS5 XZV)4S5 CYZ)KN5 NYD)T3V 1FX)Z6S 2WD)VKJ 9H3)PYN JC3)VR5 DXZ)FNG D1H)TTT XJM)PHF B16)WSR HYW)24B RRM)L3N 1P2)1S4 7ZX)2BN 8DH)JRF SC7)DY9 L2L)9FZ 1FS)DQ4 VK9)ZZB TKV)BPX F1D)J71 83S)TH4 J3B)VGZ 771)WY2 5PJ)W68 1RB)YPZ YT5)CGG HWS)P13 9J6)CY6 LRD)JNY LPD)5MG 1M4)SJM FLZ)TZP LPG)XPL Z1Q)QCV B2B)TDW F3R)GC3 DMB)FTV 1RF)V2S YC8)XS1 1X4)QP9 NN1)1X7 9VC)LFC GSF)PD9 KD8)RKH JW4)2WD 53D)MCW RWF)HGN QCV)2JP G3S)HCZ 4LD)4GV 2RS)T8Y 6JT)BR1 7XL)GCH FNR)WS8 HSV)LPD GRT)S8N V6Q)TPY RHS)GBD MK1)T7W GDQ)BCW J71)B2H FTV)67N 8NM)D43 Y8Q)H2X SVQ)MJD 8QG)55L 5FZ)M5M VX4)9FL M5Q)4M1 SM3)ZL3 Z16)FF6 M3J)9DP 125)Q61 FDD)6KP CMF)1G1 BZD)XQF RSC)6DT X8G)YLS X26)KNT P98)Y3Z F5V)4QJ 4B7)NFC 5T7)Z5Y BDK)3C3 J29)K9P 114)9VC 5MV)J5W C2Q)LDB D5V)CJ1 8Z8)SXQ Y55)X9J XZ3)X5T R6Y)XJM G43)17T JXJ)7S8 6LB)T9Z BPX)TBN RYG)X9R YC6)6K5 212)6GC 19R)62G 1Z7)HT1 X68)ZV4 RZ8)FGY 72R)Y1T MJC)52Z 1G1)TDL T75)SJJ Y3V)L73 J4Q)FR3 LFC)JKP HHN)WH4 262)J28 QNC)B2B 4W3)GYK JP5)GVG DC6)4W5 KNH)NT4 X65)RPG Q92)5DK CQP)5PJ QYM)LDX DY2)CM5 T7V)7C5 K7N)LPR M8L)W33 1XV)19K W4Y)YCF FDY)GT6 WS8)6KF BC5)VXF BY7)8M9 9L3)SM3 JKP)M15 YMB)484 YCL)KGL 3FP)BVD Y34)VG6 VHY)BG7 BC5)CYJ ZVX)FHY W33)7MB VQ7)747 WSY)5M5 711)QYM 5R2)2LS X34)WSY GYL)HMG 318)M4B 5QJ)HHB B29)8R7 HMG)53T CTR)771 1N9)HSV 1ZW)WKN M8C)6XD 61X)JN5 R21)F5V RPP)7ZT 68L)BJ7 NJB)VK9 8HV)ZBW 49Z)CCM LHM)RB8 LVZ)P98 QXF)J9W 677)G3Q V9J)P5X PZ7)BWK L5N)K1Y PVD)6RF VKX)C2Q 9SD)FRH 8R7)7FB 38V)T1Q 4D5)1N9 9LV)RSN 9WV)HCT BVD)Z5M 2J1)K8M 19Y)2BG G7N)RZP J6S)HKF 1QC)QDC C57)GRT 397)5H2 F4Y)WKR LFC)43Y HCZ)1X4 K7H)5J7 Q8X)SMJ J8P)J5G 5DK)FLZ QYV)RLB M9R)NJB W52)262 GFH)N6Q KJN)PJJ VX3)49Z LS2)Q4D NPC)TQP B2H)HMK 5DM)2WF TJ2)WKB NWQ)NN3 62H)5D3 LQ8)5JM F9R)R66 6L2)WW5 RMB)VKX VXF)19R VMQ)WZ1 6C2)Y9Z YCT)6RT YNQ)QW9 LWG)4HR 7C5)351 BK8)B5S 79M)2S5 BCV)6TZ KPR)WCJ 6TZ)Q8J XLV)1CM 2YQ)W1M M17)9J6 H4G)M3V 8SK)CM2 V4N)FWT 4TV)93R ZZM)9RW VLB)6S1 G1B)KDN 6XD)P7W GBK)8HV KGL)44W ZBW)ZYN 28F)8NM Q4D)JBS RB8)GGX XKN)LT7 Q29)BZD 47R)L7S JN5)KD8 G7N)YC8 VR5)NH5 JNR)BJL PQ7)XLV WJS)6JT RHQ)XZ6 113)Q29 VCJ)XSQ 52Z)T7V L7X)SKG S8N)Y7G CJ1)NL1 QS5)RRM C4N)RHS 484)8YR SKV)YWS 72M)F1F 3ZK)RSW 1LV)GFH""".trimIndent().trim().split("\n")
0
Kotlin
0
0
2283647e5b4ed15ced27dcf2a5cf552c7bd49ae9
14,665
adventOfCode2019
Apache License 2.0
src/main/kotlin/com/github/davio/aoc/y2023/Day1.kt
Davio
317,510,947
false
{"Kotlin": 405939}
package com.github.davio.aoc.y2023 import com.github.davio.aoc.general.Day import com.github.davio.aoc.general.getInputAsList /** * See [Advent of Code 2023 Day 1](https://adventofcode.com/2023/day/1#part2]) */ class Day1(exampleNumber: Int? = null) : Day(exampleNumber) { override fun part1() = getInputAsList().sumOf { line -> line.filter { c -> c.isDigit() }.let { 10 * it.first().digitToInt() + it.last().digitToInt() } } override fun part2() = getInputAsList().sumOf { line -> 10 * getFirstDigit(line) + getLastDigit(line) } private val digitWords = listOf( "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" ) private val digitWordsReversed = digitWords.map { it.reversed() } private fun getFirstDigit(line: String): Int = getDigit(line, digitWords) private fun getLastDigit(line: String): Int = getDigit(line.reversed(), digitWordsReversed) private fun getDigit(line: String, words: List<String>): Int { var buffer = "" var expectedChars = words.map { it.first() }.toSet() line.forEach { c -> if (c.isDigit()) return c.digitToInt() if (!expectedChars.contains(c)) { buffer = "" return@forEach } buffer += c expectedChars = words.filter { it.startsWith(buffer) }.mapNotNull { it.drop(buffer.length).firstOrNull() }.toSet() if (expectedChars.isEmpty()) { return words.indexOf(buffer) + 1 } } return -1 } }
1
Kotlin
0
0
4fafd2b0a88f2f54aa478570301ed55f9649d8f3
1,604
advent-of-code
MIT License
src/test/kotlin/com/igorwojda/list/medianoftwosorted/Solution.kt
igorwojda
159,511,104
false
{"Kotlin": 254856}
package com.igorwojda.list.medianoftwosorted // Time complexity: O(log (m+n)) private object Solution1 { fun medianOfSortedLists(list1: List<Int>, list2: List<Int>): Double { val totalSize = list1.size + list2.size val lastIndex = (totalSize / 2) var prevValue: Int? = null var pointer1Index = 0 var pointer2Index = 0 (0..lastIndex).forEach { val value1 = list1.getOrNull(pointer1Index) val value2 = list2.getOrNull(pointer2Index) val minValue = when { value1 != null && value2 == null -> { pointer1Index++ value1 } value2 != null && value1 == null -> { pointer2Index++ value2 } value1!! < value2!! -> { pointer1Index++ value1 } else -> { pointer2Index++ value2 } } if (it == lastIndex) { val totalSizeIsOdd = totalSize % 2 != 0 return if (totalSizeIsOdd) { return minValue.toDouble() } else { val localPrevValue = prevValue if (localPrevValue == null) { minValue.toDouble() } else { (localPrevValue + minValue) / 2.0 } } } prevValue = minValue println("-----------") } return 0.0 } } // Time complexity: O(n) // Space complexity O(n) private object Solution2 { fun medianOfSortedLists(list1: List<Int>, list2: List<Int>): Double { val mergedList = list1 .plus(list2) .sorted() val median = if (mergedList.size % 2 != 0) { mergedList[mergedList.size / 2].toDouble() } else { (mergedList[mergedList.size / 2].toDouble() + mergedList[mergedList.size / 2 - 1].toDouble()) / 2 } return median } }
9
Kotlin
225
895
b09b738846e9f30ad2e9716e4e1401e2724aeaec
2,170
kotlin-coding-challenges
MIT License
src/day10/Day10.kt
idle-code
572,642,410
false
{"Kotlin": 79612}
package day10 import logEnabled import logln import readInput private const val DAY_NUMBER = 10 private const val SCREEN_WIDTH = 40 data class Operation(val opcode: String, val cost: Int, val arg: Int? = null) class Simulator { private var registerX = 1 private var currentCycle = 0 val watchValues = ArrayList<Pair<Int, Int>>() private val watchPoints = HashSet<Int>() private val screen = Array(SCREEN_WIDTH * 6) { false } private val spriteRange: IntRange get() = IntRange(registerX - 1, registerX + 1) fun addWatch(cycle: Int) { watchPoints.add(cycle) } fun execute(operations: List<Operation>) { for (operation in operations) { execute(operation) } } private fun execute(operation: Operation) { updateScreen(operation.cost) updateWatch(operation.cost) currentCycle += operation.cost when (operation.opcode) { "noop" -> Unit "addx" -> registerX += operation.arg!! else -> throw IllegalArgumentException("Unknown opcode: ${operation.opcode}") } } private fun updateWatch(currentInstructionCycleCost: Int) { for (cycle in currentCycle+1 ..currentCycle + currentInstructionCycleCost) { if (cycle in watchPoints) watchValues.add(cycle to registerX) } } private fun updateScreen(currentInstructionCycleCost: Int) { for (offset in 0 until currentInstructionCycleCost) { if ((currentCycle + offset) % SCREEN_WIDTH in spriteRange) screen[currentCycle + offset] = true } } fun printScreen() { for (y in 0..5) { for (x in 0 until SCREEN_WIDTH) print(if (screen[y* SCREEN_WIDTH + x]) '#' else '.') println() } println() } } fun main() { fun parseProgram(rawInput: List<String>): List<Operation> { val program = ArrayList<Operation>() for (line in rawInput) { if (line.startsWith("noop")) program.add(Operation("noop", 1)) else { val arg = line.substringAfter(' ') program.add(Operation("addx", 2, arg.toInt())) } } return program } fun part1(rawInput: List<String>): Int { val program = parseProgram(rawInput) val checkpoints = listOf(20, 60, 100, 140, 180, 220) val simulator = Simulator() for (point in checkpoints) simulator.addWatch(point) simulator.execute(program) for (cycleToValue in simulator.watchValues) { logln("Cycle ${cycleToValue.first}*${cycleToValue.second} = ${cycleToValue.first * cycleToValue.second}") } val signalStrength = simulator.watchValues.sumOf { it.first * it.second } return signalStrength } fun part2(rawInput: List<String>): Int { val program = parseProgram(rawInput) val simulator = Simulator() simulator.execute(program) simulator.printScreen() return 0 } val sampleInput = readInput("sample_data", DAY_NUMBER) val mainInput = readInput("main_data", DAY_NUMBER) logEnabled = false val part1SampleResult = part1(sampleInput) println(part1SampleResult) check(part1SampleResult == 13140) val part1MainResult = part1(mainInput) println(part1MainResult) check(part1MainResult == 14320) val part2SampleResult = part2(sampleInput) // println(part2SampleResult) // check(part2SampleResult == 0) val part2MainResult = part2(mainInput) // println(part2MainResult) // check(part2MainResult == 0) }
0
Kotlin
0
0
1b261c399a0a84c333cf16f1031b4b1f18b651c7
3,717
advent-of-code-2022
Apache License 2.0
solutions/src/FourSum.kt
JustAnotherSoftwareDeveloper
139,743,481
false
{"Kotlin": 305071, "Java": 14982}
class FourSum { fun fourSum(nums: IntArray, target: Int): List<List<Int>> { return NSum(nums,target,4).map { it.sorted() }.distinct() } private fun NSum(nums: IntArray, target: Int, N: Int): List<List<Int>> { if (N == 2) { return twoSum(nums, target) } else { val sums = mutableListOf<List<Int>>() nums.forEachIndexed { index, i -> val withoutIt = when (index) { 0 -> nums.slice(1..nums.lastIndex) nums.lastIndex -> nums.slice(0 until nums.lastIndex) else -> nums.slice(0 until index)+nums.slice(index+1 until nums.size) }.toIntArray() val remaining = target - i sums.addAll(NSum(withoutIt,remaining,N-1).map { it+i }) } return sums } } private fun twoSum(nums: IntArray, target: Int) : List<List<Int>> { val compliments = mutableMapOf<Int,Int>() val sums = mutableListOf<List<Int>>() nums.forEach { if (compliments[it]!= null) { sums.add(listOf(it,compliments[it]!!)) } else { compliments[target-it] = it } } return sums.map { it.toList() }.toList() } }
0
Kotlin
0
0
fa4a9089be4af420a4ad51938a276657b2e4301f
1,310
leetcode-solutions
MIT License
advent/src/test/kotlin/org/elwaxoro/advent/y2021/Dec24.kt
elwaxoro
328,044,882
false
{"Kotlin": 376774}
package org.elwaxoro.advent.y2021 import org.elwaxoro.advent.PuzzleDayTester /** * Arithmetic Logic Unit */ class Dec24 : PuzzleDayTester(24, 2021) { override fun part1(): Any = monaderator(isMax = true) override fun part2(): Any = monaderator(isMax = false) /** * Can treat this whole program as a set of smaller sub-programs each marked at the start by "inp w" * There are 14 sub-programs and 14 numbers in the monad. Coincidence? I think not! * Most of the program is useless, just need to know if the sub-program is a "push" or a "pop" action * Pair each push to a pop, pushes always come with a positive number and pops with a negative number */ private fun monaderator(isMax: Boolean): String = parse().foldIndexed(mutableMapOf<Int, Int>() to mutableListOf<Pair<Int, Int>>()) { idx, acc, subProgram -> acc.also { (monad, stack) -> // cmd 5 is always something like "add x -8", if it's positive this is a "push" sub-program, else it's a "pop" val mod = subProgram[5][2].toInt() // cmd 15 is the only other line that matters, always something like "add y 5" // push or pop the stack and compare it to the saved digitMod for this sub-program: // this gives both min and max values for the popped idx as well as the current idx if (mod > 0) { // push the currently tracked digit in "add y <int>" // this will be paired with the pop action later to decide what high/low values belong to the pair of push/pop digits stack.add(idx to subProgram[15][2].toInt()) } else { val (popIdx, popMod) = stack.removeLast() val diff = popMod + mod //popMod is always positive, digitMod is always negative if (diff < 0) { if (isMax) { monad[popIdx] = 9 monad[idx] = 9 + diff } else { monad[popIdx] = -1 * diff + 1 monad[idx] = 1 } } else { if (isMax) { monad[popIdx] = 9 - diff monad[idx] = 9 } else { monad[popIdx] = 1 monad[idx] = 1 + diff } } } } }.let { (monad, _) -> monad.keys.sorted().joinToString("") { d -> "${monad[d]}" } } /** * Ham-jammed the input file to split each sub-program with an extra newline * returns a list of subprograms, each subprogram is a list of strings to split "add x -8" into ["add", "x", "-8"] */ private fun parse(): List<List<List<String>>> = load(delimiter = "\n\n").map { it.split("\n").map { it.split(" ") } } }
0
Kotlin
4
0
1718f2d675f637b97c54631cb869165167bc713c
3,052
advent-of-code
MIT License
05.kts
pin2t
725,922,444
false
{"Kotlin": 48856, "Go": 48364, "Shell": 54}
import java.util.* val scanner = Scanner(System.`in`) val mappings = ArrayList<List<Pair<LongRange, Long>>>() val seeds = ArrayList<Long>() val number = Regex("\\d+") while (scanner.hasNext()) { val line = scanner.nextLine() if (line.startsWith("seeds:")) { seeds.addAll(number.findAll(line).map { it.value.toLong() }) } else if (line.endsWith("map:")) { val m = ArrayList<Pair<LongRange, Long>>() while (scanner.hasNext()) { val l = scanner.nextLine() if (l == "") break val mm = number.findAll(l).map { it.value.toLong() }.toList() m.add(Pair((mm[1]..<(mm[1] + mm[2])), mm[0])) } mappings.add(m) } } var minLocation = Long.MAX_VALUE for (seed in seeds) { var mapped = seed for (mapping in mappings) { for (r in mapping) { if (r.first.contains(mapped)) { mapped = r.second + (mapped - r.first.first) break } } } minLocation = minOf(minLocation, mapped) } var ranges = ArrayList<LongRange>() for (i in 0..<seeds.size step 2) { ranges.add((seeds[i]..<seeds[i] + seeds[i + 1])) } for (mapping in mappings) { val mapped = ArrayList<LongRange>() fun map(rr: LongRange) { var mr: Optional<LongRange> = Optional.empty() for (r in mapping) { val offset = r.second - r.first.first if (r.first.contains(rr.first) && r.first.contains(rr.last)) { mr = Optional.of(((rr.first + offset)..(rr.last + offset))) } else if (r.first.contains(rr.first)) { mr = Optional.of(((rr.first + offset)..(r.first.last + offset))) map(((r.first.last + 1)..rr.last)) } else if (r.first.contains(rr.last)) { mr = Optional.of(((r.first.first + offset)..(rr.last + offset))) map((rr.first..(r.first.first - 1))) } else if (rr.contains(r.first.first) && rr.contains(r.first.last)) { map((rr.first..(r.first.first - 1))) map(((r.first.last + 1)..rr.last)) mr = Optional.of(((r.first.first + offset)..(r.first.last + offset))) } if (mr.isPresent) break } mapped.add(if (mr.isPresent) mr.get() else rr) } for (r in ranges) map(r) ranges = mapped } println(listOf(minLocation, ranges.minOf { it.first }))
0
Kotlin
1
0
7575ab03cdadcd581acabd0b603a6f999119bbb6
2,428
aoc2023
MIT License
2021/src/test/kotlin/Day17.kt
jp7677
318,523,414
false
{"Kotlin": 171284, "C++": 87930, "Rust": 59366, "C#": 1731, "Shell": 354, "CMake": 338}
import kotlin.math.abs import kotlin.test.Test import kotlin.test.assertEquals class Day17 { data class Coord(val x: Int, val y: Int) data class Step(val position: Coord, val velocity: Coord) @Test fun `run part 01`() { val area = getArea() val maxY = (area.getMinInitialVelocityX()..area.getMaxInitialVelocityX()).flatMap { velocityX -> (area.minY()..abs(area.minY())).mapNotNull { velocityY -> area.fireProbe(Coord(velocityX, velocityY)).let { (hit, steps) -> if (hit) steps.maxOf { step -> step.position.y } else null } } } .maxOrNull() assertEquals(6555, maxY) } @Test fun `run part 02`() { val area = getArea() val maxY = (area.getMinInitialVelocityX()..area.maxX()).flatMap { x -> (area.minY()..abs(area.minY())).mapNotNull { y -> area.fireProbe(Coord(x, y)).let { (hit, _) -> hit } } } .count { it } assertEquals(4973, maxY) } private fun Set<Coord>.getMinInitialVelocityX() = generateSequence(1 to 1) { (index, it) -> if (index + it < this.minX()) index.inc() to index + it else null } .count() private fun Set<Coord>.getMaxInitialVelocityX() = generateSequence(1 to 1) { (index, it) -> if (index + it < this.maxX()) index.inc() to index + it else null } .count() private fun Set<Coord>.fireProbe(initialVelocity: Coord): Pair<Boolean, Set<Step>> { val areaMaxX = maxX() val areaMinY = minY() val steps = generateSequence(Step(Coord(0, 0), initialVelocity)) { if (it.position.x <= areaMaxX && it.position.y >= areaMinY) Step( Coord(it.position.x + it.velocity.x, it.position.y + it.velocity.y), Coord(if (it.velocity.x == 0) 0 else it.velocity.x.dec(), it.velocity.y.dec()) ) else null } .toSet() return (steps.map { it.position } intersect this).any() to steps } private fun Set<Coord>.minX() = minOf { it.x } private fun Set<Coord>.maxX() = maxOf { it.x } private fun Set<Coord>.minY() = minOf { it.y } private fun getArea() = Util.getInputAsString("day17-input.txt") .split("=", ".", ",") .mapNotNull { it.toIntOrNull() } .let { Coord(it[0], it[3]) to Coord(it[1], it[2]) } .let { (topLeft, bottomRight) -> (topLeft.x..bottomRight.x).flatMap { x -> (bottomRight.y..topLeft.y).map { y -> Coord(x, y) } } } .toSet() }
0
Kotlin
1
2
8bc5e92ce961440e011688319e07ca9a4a86d9c9
2,736
adventofcode
MIT License
src/Day03.kt
casslabath
573,177,204
false
{"Kotlin": 27085}
import java.util.* fun main() { fun initPriorityMap(): Map<Char, Int> { val lower = "abcdefghijklmnopqrstuvwxyz" val upper = lower.uppercase(Locale.getDefault()) val map: MutableMap<Char, Int> = mutableMapOf() var count = 1 for(letter in lower.toCharArray()) { map[letter] = count count++ } for(letter in upper.toCharArray()) { map[letter] = count count++ } return map } fun part1(input: List<String>): Int { val priorityMap = initPriorityMap() var total = 0 for(sack in input) { val componentOne = sack.substring(0, sack.length / 2).toCharArray().toSet() val componentTwo = sack.substring(sack.length / 2).toCharArray().toSet() for(letter in componentOne) { if(componentTwo.contains(letter)) { total += priorityMap[letter]!! break } } } return total } fun part2(input: List<String>): Int { val priorityMap = initPriorityMap() var total = 0 for(i in input.indices step 3) { val sackOne: Set<Char> = input[i].toCharArray().toSet() val sackTwo = input[i+1].toCharArray().toSet() val sackThree = input[i+2].toCharArray().toSet() for(letter in sackOne) { if(sackTwo.contains(letter) && sackThree.contains(letter)) { total += priorityMap[letter]!! break } } } return total } val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
5f7305e45f41a6893b6e12c8d92db7607723425e
1,746
KotlinAdvent2022
Apache License 2.0