path
stringlengths
5
169
owner
stringlengths
2
34
repo_id
int64
1.49M
755M
is_fork
bool
2 classes
languages_distribution
stringlengths
16
1.68k
content
stringlengths
446
72k
issues
float64
0
1.84k
main_language
stringclasses
37 values
forks
int64
0
5.77k
stars
int64
0
46.8k
commit_sha
stringlengths
40
40
size
int64
446
72.6k
name
stringlengths
2
64
license
stringclasses
15 values
src/Day05.kt
thomasreader
573,047,664
false
{"Kotlin": 59975}
import java.io.Reader import java.util.* fun main() { val testInput = """ [D] [N] [C] [Z] [M] [P] 1 2 3 move 1 from 2 to 1 move 3 from 1 to 3 move 2 from 2 to 1 move 1 from 1 to 2 """.trimIndent() val testResultStacks = partOne(testInput.reader()) check(testResultStacks.getTops() == "CMZ") val input = file("Day05.txt") println( partOne(input.bufferedReader()).getTops() ) check( partTwo(testInput.reader()).getTops() == "MCD" ) println( partTwo(input.bufferedReader()).getTops() ) } private fun List<Stack<Char>>.getTops(): String = buildString(this.size) { [email protected] { stack -> stack.peek()?.let { append(it) } } } private fun List<Stack<Char>>.applyCraneOperation(fromStackIx: Int, toStackIx: Int, amount: Int, isModel9001: Boolean) { val fromStack = this[fromStackIx] val toStack = this[toStackIx] if (fromStack.isNotEmpty()) { val moving = mutableListOf<Char>() for (i in (0 until amount)) { moving.add(fromStack.pop()) } val movingChecked = if (isModel9001) moving.reversed() else moving movingChecked.forEach { toStack.push(it) } } } private fun getStacks(source: Reader, isModel9001: Boolean): List<Stack<Char>> { val startingValues = mutableListOf<String>() val stacks = mutableListOf<Stack<Char>>() var isStackInit = false fun MutableList<Stack<Char>>.init(startingValues: List<String>): MutableList<Stack<Char>> { val rowNumbersIx: Int = startingValues.indexOfLast { row -> row.isNotBlank() || row.replace(" ", "").toBigIntegerOrNull() != null } val colIxs = startingValues[rowNumbersIx] .toCharArray() .mapIndexed { index, c -> if (c.digitToIntOrNull() != null) index else null } .filterNotNull() val numCols = colIxs.size//startingValues[rowNumbersIx].findLast { it.isDigit() }!!.digitToInt() for (i in 0 until numCols) { this.add(Stack()) } val values = startingValues.subList(0, rowNumbersIx).reversed() values.forEachIndexed { rowIx, row -> colIxs.forEachIndexed { index, columnIx -> if (columnIx < row.length) { val v = row[columnIx] if (v.isLetter()) { this[index].push(row[columnIx]) } } } } // val values = startingValues.subList(0, rowNumbersIx).map { s -> // s // .replace(Regex(""" {3}|\] \["""), ",") // .replace(Regex("""\[|\]| +"""), "") // .split(",") // .map { if (it.isBlank()) null else it[0] } // } // // values.reversed().forEach { row -> // row.forEachIndexed { index, c -> // if (c != null) { // this[index].push(c) // } // } // } return this } source.forEachLine { line -> if (line.startsWith("move")) { if (!isStackInit) { stacks.init(startingValues) isStackInit = true } line.split(' ').also { stringList -> stacks.applyCraneOperation( fromStackIx = stringList[3].toInt() - 1, toStackIx = stringList[5].toInt() - 1, amount = stringList[1].toInt(), isModel9001 = isModel9001 ) } } else { startingValues.add(line) } } return stacks } private fun partOne(source: Reader) = getStacks(source, false) private fun partTwo(source: Reader) = getStacks(source, true)
0
Kotlin
0
0
eff121af4aa65f33e05eb5e65c97d2ee464d18a6
3,916
advent-of-code-2022-kotlin
Apache License 2.0
src/main/kotlin/year2022/day-04.kt
ppichler94
653,105,004
false
{"Kotlin": 182859}
package year2022 import lib.aoc.Day import lib.aoc.Part fun main() { Day(4, 2022, PartA4(), PartB4()).run() } open class PartA4 : Part() { data class Section(val start1: Int, val end1: Int, val start2: Int, val end2: Int) internal lateinit var sections: List<Section> override fun parse(text: String) { val regex = """\d+""".toRegex() sections = text.split("\n").map { val result = regex.findAll(it) val (start1, end1, start2, end2) = result.toList().map { it.value.toInt() } Section(start1, end1, start2, end2) } } override fun compute(): String { return sections.count(this::fullyContains).toString() } private fun fullyContains(section: Section): Boolean { return (((section.start1 <= section.start2) and (section.end1 >= section.end2)) or ((section.start2 <= section.start1) and (section.end2 >= section.end1))) } override val exampleAnswer: String get() = "2" } class PartB4 : PartA4() { override fun compute(): String { return sections.count(this::overlaps).toString() } private fun overlaps(section: Section): Boolean { if (section.start1 in section.start2..section.end2) { return true } if (section.end1 in section.start2..section.end2) { return true } if (section.start2 in section.start1..section.end1) { return true } return section.end2 in section.start1..section.end1 } override val exampleAnswer: String get() = "4" }
0
Kotlin
0
0
49dc6eb7aa2a68c45c716587427353567d7ea313
1,668
Advent-Of-Code-Kotlin
MIT License
src/array/LeetCode350.kt
Alex-Linrk
180,918,573
false
null
package array import java.util.* /** * 350. 两个数组的交集 II * 给定两个数组,编写一个函数来计算它们的交集。 示例 1: 输入: nums1 = [1,2,2,1], nums2 = [2,2] 输出: [2,2] 示例 2: 输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4] 输出: [4,9] 说明: 输出结果中每个元素出现的次数,应与元素在两个数组中出现的次数一致。 我们可以不考虑输出结果的顺序。 进阶: 如果给定的数组已经排好序呢?你将如何优化你的算法? 如果 nums1 的大小比 nums2 小很多,哪种方法更优? 如果 nums2 的元素存储在磁盘上,磁盘内存是有限的,并且你不能一次加载所有的元素到内存中,你该怎么办? */ class LeetCode350 { fun intersect(nums1: IntArray, nums2: IntArray): IntArray { if (nums1.isEmpty() || nums2.isEmpty()) return IntArray(0) Arrays.sort(nums1) Arrays.sort(nums2) if (nums1.last() < nums2.first() || nums1.first() > nums2.last()) return IntArray(0) val result = IntArray(Math.min(nums1.size, nums2.size)) var x = 0 var y = 0 var count = 0 var max = nums1 var min = nums2 if (nums1.size < nums2.size) { max = nums2 min = nums1 } while (x < min.size && y < max.size) { when { min[x] > max[y] -> y++ min[x] < max[y] -> x++ else -> { result[count++] = min[x] x++ y++ } } } return result.copyOfRange(0,count) } } fun main() { println( LeetCode350().intersect( intArrayOf(1, 2, 2, 1), intArrayOf(2, 2) ).asList() ) println( LeetCode350().intersect( intArrayOf(4,9,5), intArrayOf(9,4,9,8,4) ).asList() ) }
0
Kotlin
0
0
59f4ab02819b7782a6af19bc73307b93fdc5bf37
1,976
LeetCode
Apache License 2.0
src/Day07.kt
erwinw
572,913,172
false
{"Kotlin": 87621}
@file:Suppress("MagicNumber") private const val DAY = "07" private const val PART1_CHECK = 95437 private const val PART2_CHECK = 24933642 abstract class FsEntry( open val name: String, val parent: Directory?, ) { abstract fun print(depth: Int = 0) abstract val size: Int open fun printLnIndented(depth: Int, message: String) { println("${" ".repeat(depth)}$message") } fun path(): String = listOfNotNull(parent?.path(), name).joinToString("/") } class Directory( name: String, parent: Directory?, ) : FsEntry( name, parent, ) { var entries: MutableList<FsEntry> = mutableListOf() override fun print(depth: Int) { printLnIndented(depth, "- $name (dir, size=$size)") entries.forEach { it.print(depth + 1) } } override val size: Int get() = entries.sumOf { it.size } } class File( name: String, parent: Directory?, override val size: Int, ) : FsEntry( name, parent, ) { override fun print(depth: Int) { printLnIndented(depth, "- $name (file, size=$size)") } } private fun parseFs(input: List<String>): Pair<Directory, List<Directory>> { val root = Directory("/", null) var currentDirectory = root val allDirectories = mutableListOf(root) val inputStack = input.toMutableList() while (inputStack.isNotEmpty()) { val line = inputStack.removeFirst() when (line.take(5)) { "$ cd " -> { val targetDirectoryName = line.drop(5) currentDirectory = when (targetDirectoryName) { "/" -> root ".." -> currentDirectory.parent ?: throw IllegalArgumentException("Cannot move up from root") else -> { currentDirectory.entries .filterIsInstance<Directory>() .firstOrNull { it.name == targetDirectoryName } ?: throw IllegalAccessException("Target directory '$targetDirectoryName' not found") } } } "$ ls" -> { while (inputStack.isNotEmpty() && inputStack.first()[0] != '$') { // ls output val (sizeType, entryName) = inputStack.removeFirst().split(' ') val newEntry = if (sizeType == "dir") { Directory(entryName, currentDirectory).also { allDirectories.add(it) } } else { File(entryName, currentDirectory, sizeType.toInt()) } currentDirectory.entries.add(newEntry) } } } } return root to allDirectories } fun main() { fun part1(input: List<String>): Int { val (root, allDirectories) = parseFs(input) root.print() return allDirectories.filter { it.size <= 100_000 }.sumOf { it.size } } fun part2(input: List<String>): Int { val (root, allDirectories) = parseFs(input) val totalSpace = 70_000_000 val requiredSpace = 30_000_000 val freeSpace = totalSpace - root.size val missingSpace = requiredSpace - freeSpace println("Missing space: $missingSpace") val toDelete = allDirectories .filter { it.size >= missingSpace } .minByOrNull { it.size } println("To delete: ${toDelete?.size} (${toDelete?.path()})") return toDelete?.size ?: 0 } println("Day $DAY") // test if implementation meets criteria from the description, like: val testInput = readInput("Day${DAY}_test") check(part1(testInput).also { println("Part1 output: $it") } == PART1_CHECK) check(part2(testInput).also { println("Part2 output: $it") } == PART2_CHECK) val input = readInput("Day$DAY") println("Part1 final output: ${part1(input)}") println("Part2 final output: ${part2(input)}") }
0
Kotlin
0
0
57cba37265a3c63dea741c187095eff24d0b5381
4,165
adventofcode2022
Apache License 2.0
src/main/kotlin/com/github/javadev/sort/MergeSort.kt
javadev
156,964,261
false
null
package com.github.javadev.sort import java.util.Arrays /* public class MergeSort { public void mergeSort(int[] array) { mergeSort(array, 0, array.length - 1); } void mergeSort(int[] array, int low, int high) { if (high - low < 2) { return; } if (low < high) { int mid = low + (high - low) / 2; mergeSort(array, low, mid); mergeSort(array, mid + 1, high); merge(array, low, mid, high); } } void merge(int[] array, int low, int mid, int high) { int[] b = Arrays.copyOfRange(array, low, mid); for (int i = low, j = mid, k = 0; k < b.length; i++) { if (j == high || b[k] < array[j]) { array[i] = b[k++]; } else { array[i] = array[j++]; } } } int[] merge(int[] a, int[] b) { int[] answer = new int[a.length + b.length]; int i = 0, j = 0, k = 0; while (i < a.length && j < b.length) { if (a[i] < b[j]) { answer[k++] = a[i++]; } else { answer[k++] = b[j++]; } } while (i < a.length) { answer[k++] = a[i++]; } while (j < b.length) { answer[k++] = b[j++]; } return answer; } } */ class MergeSort { fun mergeSort(array:IntArray) { mergeSort(array, 0, array.size - 1) } internal fun mergeSort(array:IntArray, low:Int, high:Int) { if (high - low < 2) { return } if (low < high) { val mid = low + (high - low) / 2 mergeSort(array, low, mid) mergeSort(array, mid + 1, high) merge(array, low, mid, high) } } internal fun merge(array:IntArray, low:Int, mid:Int, high:Int) { val b = Arrays.copyOfRange(array, low, mid) var i = low var j = mid var k = 0 while (k < b.size) { if (j == high || b[k] < array[j]) { array[i] = b[k++] } else { array[i] = array[j++] } i++ } } internal fun merge(a:IntArray, b:IntArray):IntArray { val answer = IntArray(a.size + b.size) var i = 0 var j = 0 var k = 0 while (i < a.size && j < b.size) { if (a[i] < b[j]) { answer[k++] = a[i++] } else { answer[k++] = b[j++] } } while (i < a.size) { answer[k++] = a[i++] } while (j < b.size) { answer[k++] = b[j++] } return answer } }
0
Kotlin
0
5
3f71122f1d88ee1d83acc049f9f5d44179c34147
2,379
classic-cherries-kotlin
Apache License 2.0
src/leetcodeProblem/leetcode/editor/en/SwapNodesInPairs.kt
faniabdullah
382,893,751
false
null
//Given a linked list, swap every two adjacent nodes and return its head. You //must solve the problem without modifying the values in the list's nodes (i.e., //only nodes themselves may be changed.) // // // Example 1: // // //Input: head = [1,2,3,4] //Output: [2,1,4,3] // // // Example 2: // // //Input: head = [] //Output: [] // // // Example 3: // // //Input: head = [1] //Output: [1] // // // // Constraints: // // // The number of nodes in the list is in the range [0, 100]. // 0 <= Node.val <= 100 // // Related Topics Linked List Recursion 👍 4687 👎 248 package leetcodeProblem.leetcode.editor.en import leetcode_study_badge.data_structure.ListNode class SwapNodesInPairs { fun solution() { } //below code is used to auto submit to leetcode.com (using ide plugin) //leetcode submit region begin(Prohibit modification and deletion) /** * Example: * var li = ListNode(5) * var v = li.`val` * Definition for singly-linked list. * class ListNode(var `val`: Int) { * var next: ListNode? = null * } */ class Solution { fun swapPairs(head: ListNode?): ListNode? { return helpSwap(head, head?.next) } private fun helpSwap(head: ListNode?, next: ListNode?): ListNode? { if (head == null) return null if (next == null) return head val nextPair = next.next next.next = head head.next = helpSwap(nextPair, nextPair?.next) return next } } //leetcode submit region end(Prohibit modification and deletion) } fun main() {}
0
Kotlin
0
6
ecf14fe132824e944818fda1123f1c7796c30532
1,638
dsa-kotlin
MIT License
kotlin/src/katas/kotlin/leetcode/generate_parens/GenerateParensTests.kt
dkandalov
2,517,870
false
{"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221}
package katas.kotlin.leetcode.generate_parens import katas.kotlin.softFail import org.junit.jupiter.api.Test abstract class GenerateParensTests(val generate: (Int) -> List<String>) { @Test fun `it works`() = softFail { generate(1) shouldEqual listOf("()") generate(2) shouldEqual listOf("()()", "(())") generate(3) shouldEqual listOf( "()()()", "(()())", "()(())", "(())()", "((()))" ) generate(4) shouldEqual listOf( "()()()()", "(()()())", "()(()())", "(()())()", "((()()))", "()()(())", "()(())()", "(()(()))", "()(())()", "(())()()", "((())())", "()((()))", "((()))()", "(((())))" ) } } class RecursiveParensTests : GenerateParensTests(::parensRecur) private fun parensRecur(n: Int): List<String> { return when (n) { 0 -> listOf("") 1 -> listOf("()") else -> parensRecur(n - 1).flatMap { listOf("()$it", "$it()", "($it)").distinct() } } } class IterativeParensTests : GenerateParensTests(::parens) private fun parens(n: Int): List<String> { var counter = n var result = listOf("") while (counter > 0) { result = result.flatMap { listOf("()$it", "$it()", "($it)").distinct() } counter-- } return result }
7
Roff
3
5
0f169804fae2984b1a78fc25da2d7157a8c7a7be
1,492
katas
The Unlicense
src/main/kotlin/github/walkmansit/aoc2020/Day18.kt
walkmansit
317,479,715
false
null
package github.walkmansit.aoc2020 import java.util.* class Day18(val input: List<String>) : DayAoc<Long, Long> { class Calculator private constructor(private val expressions: Array<String>) { private val operations = setOf('+', '*') fun calsEvalSums(): Long { var sum = 0L for (v in expressions.map { evaluate(0, it, it[0] == '(') }) sum += v.first return sum } private fun evaluate(startIdx: Int, expr: String, findClose: Boolean): Pair<Long, Int> { var acc = 0L var value = 0L var idx = startIdx when (expr[idx]) { in arrayOf(')', '*', '+') -> throw IllegalArgumentException("first operand cant be in [')','*','+']") '(' -> { val (s, i) = evaluate(idx + 1, expr, true) acc = s idx = i } else -> { acc = expr[idx].toString().toLong() idx++ } } while (idx != expr.length && (!findClose || findClose && expr[idx] != ')')) { val isSum = when (expr[idx]) { '+' -> true '*' -> false else -> throw IllegalArgumentException("invalid operator character") } idx++ when (expr[idx]) { in arrayOf(')', '*', '+') -> throw IllegalArgumentException("second operand cant be in ['(',')','*','+']") '(' -> { val (s, i) = evaluate(idx + 1, expr, true) value = s idx = i } else -> { value = expr[idx].toString().toLong() idx++ } } acc = if (isSum) acc + value else acc * value } return acc to ++idx } fun calculateWithSumPriority(): Long { return expressions.asSequence().map { it.toRPR().calculateRPR() }.sum() } // преобразование выражения в обратную польскую запись private fun String.toRPR(): String { val sb = StringBuilder() val stack = Stack<Char>() for (ch in this) { if (ch != ' ') when (ch) { '(' -> stack.push(ch) ')' -> { while (stack.last() != '(') { sb.append(stack.pop()) } stack.pop() } in operations -> { while (stack.isNotEmpty() && higherOrSamePriority(ch, stack.last())) { sb.append(stack.pop()) } stack.push(ch) } else -> sb.append(ch) } } while (stack.isNotEmpty()) sb.append(stack.pop()) return sb.toString() } private fun String.calculateRPR(): Long { val stack = Stack<Long>() for (ch in this) { if (ch !in operations) { stack.push(ch.toString().toLong()) } else { val a = stack.pop() val b = stack.pop() stack.push(if (ch == '+') a + b else a * b) } } return stack.pop() } private fun higherOrSamePriority(curr: Char, other: Char): Boolean { if (other == '(') return false return other != '*' || curr != '+' } companion object { private fun String.removeWhitespaces(): String { val sb = StringBuilder() for (ch in this) { if (ch != ' ') sb.append(ch) } return sb.toString() } fun fromInput(inp: List<String>): Calculator { return Calculator(inp.map { it.removeWhitespaces() }.toTypedArray()) } } } override fun getResultPartOne(): Long { return Calculator.fromInput(input).calsEvalSums() } override fun getResultPartTwo(): Long { return Calculator.fromInput(input).calculateWithSumPriority() } }
0
Kotlin
0
0
9c005ac4513119ebb6527c01b8f56ec8fd01c9ae
4,700
AdventOfCode2020
MIT License
src/main/java/com/barneyb/aoc/aoc2016/day18/LikeARogue.kt
barneyb
553,291,150
false
{"Kotlin": 184395, "Java": 104225, "HTML": 6307, "JavaScript": 5601, "Shell": 3219, "CSS": 1020}
package com.barneyb.aoc.aoc2016.day18 import com.barneyb.aoc.util.Solver fun main() { Solver.execute( ::parse, { safeTileCount(it, 40) }, { safeTileCount(it, 400000) }, ) } internal fun parse(input: String) = input.trim().let { val arr = BooleanArray(it.length) for (i in it.indices) { if (input[i] == '^') arr[i] = true } arr } internal fun safeTileCount(start: String, rows: Int) = safeTileCount(parse(start), rows) internal fun safeTileCount(start: BooleanArray, rows: Int): Int { var count = 0 var curr = start var next: BooleanArray var left: Boolean var center: Boolean var right: Boolean for (r in 1..rows) { next = BooleanArray(curr.size) for (i in curr.indices) { center = curr[i] if (!center) count++ left = i > 0 && curr[i - 1] right = i < curr.size - 1 && curr[i + 1] if (left && center && !right) next[i] = true else if (!left && center && right) next[i] = true else if (left && !center && !right) next[i] = true else if (!left && !center && right) next[i] = true } curr = next } return count }
0
Kotlin
0
0
8b5956164ff0be79a27f68ef09a9e7171cc91995
1,329
aoc-2022
MIT License
src/main/kotlin/Day1/Day01.kt
fisherthewol
433,544,714
false
{"Kotlin": 8877}
package Day1 import readInput fun part1(lines: List<Int>): Int { var depthIncrease = 0 var prevMeasure: Int var currentMeasure = Int.MAX_VALUE for (line in lines) { prevMeasure = currentMeasure // Move along one. currentMeasure = line if (currentMeasure > prevMeasure) depthIncrease++ } return depthIncrease } fun part2(lines: List<Int>): Int { var a: Int; var b = lines[0]; var c = lines[1] var prevSum: Int var currentSum = Int.MAX_VALUE var index = 2 var sumIncrease = 0 while (index < lines.size) { a = b b = c c = lines[index] prevSum = currentSum currentSum = a + b + c if (currentSum > prevSum) sumIncrease++ index++ } return sumIncrease } fun main() { val lines = readInput("Day1","Day01input").map { it.toInt() } println("Measurements greater than previous: ${part1(lines)}.") println("Sums greater than previous window: ${part2(lines)}.") }
0
Kotlin
0
0
d078aa647c666adf3d562fb1c67de6bef9956bcf
1,002
AoC2021
MIT License
app/src/main/java/com/cornellappdev/uplift/models/FacilityInfoModels.kt
cuappdev
596,747,757
false
{"Kotlin": 273937}
package com.cornellappdev.uplift.models /** * A facility representing one court at a fitness center. */ data class CourtFacility( /** The court's name (e.g. "Court 1") */ val name: String, /** Exactly 7 lists of [CourtTime] objects: Monday, Tuesday, etc. for this court. */ val hours: List<List<CourtTime>?> ) /** A court time interval which can be designated to a sport. */ data class CourtTime( val time: TimeInterval, val type: String ) /** Swimming information for one day. */ data class SwimmingInfo( val swimmingTimes: List<SwimmingTime> ) { /** * Returns [swimmingTimes] as a list of [TimeInterval]s. */ fun hours(): List<TimeInterval> { return swimmingTimes.map { swimTime -> swimTime.time } } } /** One time interval of swimming time which can be designated as women only. */ data class SwimmingTime( val time: TimeInterval, val womenOnly: Boolean ) /** Bowling information for one day. */ data class BowlingInfo( val hours: List<TimeInterval>, val pricePerGame: String, val shoeRental: String ) /** An [EquipmentGrouping] is a grouping of one or more pieces of gym equipment under a particular * category. [UpliftGym] objects may have multiple [EquipmentGrouping]s to specify all the equipment * they carry. */ data class EquipmentGrouping( /** The title of this equipment grouping. (e.g. "Cardio Machines") */ val name: String, /** A list of equipment that this grouping offers. * * Example: The list (("Treadmills", 5), ("Rowing Machines", 3)) indicates that this grouping has * 5 treadmills and 3 rowing machines. * */ val equipmentList: List<Pair<String, Int>> )
1
Kotlin
0
1
c5bc20ab8a0364c6620ff7adf48cfbaa7295100c
1,701
uplift-android
MIT License
src/main/kotlin/_0054_SpiralMatrix.kt
ryandyoon
664,493,186
false
null
// https://leetcode.com/problems/spiral-matrix fun spiralOrder(matrix: Array<IntArray>): List<Int> { val numIndices = matrix.size * matrix.first().size val spiral = mutableListOf<Int>() val viewed = Array(matrix.size) { BooleanArray(matrix.first().size) } var row = 0 var col = 0 var rowOffset = 0 var colOffset = 1 while (spiral.size < numIndices) { spiral.add(matrix[row][col]) viewed[row][col] = true val isNextIndexValid = validIndex( row = row + rowOffset, col = col + colOffset, lastRow = matrix.lastIndex, lastCol = matrix.first().lastIndex ) if (!isNextIndexValid || viewed[row + rowOffset][col + colOffset]) { when { colOffset == 1 -> { rowOffset = 1 colOffset = 0 } rowOffset == 1 -> { rowOffset = 0 colOffset = -1 } colOffset == -1 -> { rowOffset = -1 colOffset = 0 } else -> { rowOffset = 0 colOffset = 1 } } } row += rowOffset col += colOffset } return spiral } private fun validIndex(row: Int, col: Int, lastRow: Int, lastCol: Int): Boolean { return row in 0..lastRow && col in 0..lastCol }
0
Kotlin
0
0
7f75078ddeb22983b2521d8ac80f5973f58fd123
1,474
leetcode-kotlin
MIT License
src/main/kotlin/Matrix.kt
snikiforov4
485,917,499
false
{"Kotlin": 9895}
package processor import kotlin.math.pow class Matrix(private val matrix: Array<Array<Double>>) { companion object { fun empty(n: Int, m: Int = n): Matrix { require(n > 0) require(m > 0) return Matrix(Array(n) { Array(m) { 0.0 } }) } } val sizesOfDimensions: IntArray get() { val n = matrix.size val m = matrix.firstOrNull()?.size ?: 0 return intArrayOf(n, m) } operator fun get(n: Int, m: Int): Double = matrix[n][m] operator fun set(n: Int, m: Int, value: Double) { matrix[n][m] = value } fun swap(x1: Int, y1: Int, x2: Int, y2: Int) { val temp = this[x1, y1] this[x1, y1] = this[x2, y2] this[x2, y2] = temp } fun isSquare(): Boolean { val (x, y) = this.sizesOfDimensions return x == y } fun determinant(): Double { require(this.isSquare()) val (n) = this.sizesOfDimensions return when { n == 1 -> this[0, 0] n == 2 -> (this[0, 0] * this[1, 1]) - (this[0, 1] * this[1, 0]) n >= 3 -> { var res = 0.0 repeat(n) { res += this[0, it] * cofactor(0, it) } res } else -> 0.0 } } private fun cofactor(x: Int, y: Int): Double { return (-1.0).pow(x + y) * subMatrixExcluding(x, y).determinant() } private fun subMatrixExcluding(xExclude: Int, yExclude: Int): Matrix { val (n, m) = this.sizesOfDimensions require(xExclude in 0 until n) { "Index out of range: $xExclude" } require(yExclude in 0 until m) { "Index out of range: $yExclude" } val result = empty(n - 1, m - 1) var i = 0 for (x in 0 until n) { if (x == xExclude) { continue } var j = 0 for (y in 0 until m) { if (y == yExclude) { continue } result[i, j] = this[x, y] j++ } i++ } return result } fun toCofactorMatrix(): Matrix { require(isSquare()) val (n) = sizesOfDimensions val result = empty(n) for (x in 0 until n) { for (y in 0 until n) { result[x, y] = cofactor(x, y) } } return result } } interface TransposeStrategy { companion object { fun byNumber(number: Int): TransposeStrategy = when (number) { 1 -> MainDiagonalTransposeStrategy 2 -> SideDiagonalTransposeStrategy 3 -> VerticalLineTransposeStrategy 4 -> HorizontalLineTransposeStrategy else -> NullTransposeStrategy } } fun transpose(matrix: Matrix) } object MainDiagonalTransposeStrategy : TransposeStrategy { override fun transpose(matrix: Matrix) { val (n, m) = matrix.sizesOfDimensions check(n == m) for (x in 0 until n) { for (y in 0 until x) { matrix.swap(x, y, y, x) } } } } object SideDiagonalTransposeStrategy : TransposeStrategy { override fun transpose(matrix: Matrix) { val (n, m) = matrix.sizesOfDimensions check(n == m) for (x in 0 until n) { for (y in (0 until m - x - 1)) { matrix.swap(x, y, n - 1 - y, m - 1 - x) } } } } object VerticalLineTransposeStrategy : TransposeStrategy { override fun transpose(matrix: Matrix) { val (n, m) = matrix.sizesOfDimensions check(n == m) for (x in 0 until n) { for (y in 0 until m / 2) { matrix.swap(x, y, x, m - 1 - y) } } } } object HorizontalLineTransposeStrategy : TransposeStrategy { override fun transpose(matrix: Matrix) { val (n, m) = matrix.sizesOfDimensions check(n == m) for (x in 0 until n / 2) { for (y in 0 until m) { matrix.swap(x, y, n - 1 - x, y) } } } } object NullTransposeStrategy : TransposeStrategy { override fun transpose(matrix: Matrix) { } }
0
Kotlin
0
0
ace36ad30c0a2024966744792a45e98b3358e10d
4,302
numeric-matrix-processor
Apache License 2.0
src/main/kotlin/com/hj/leetcode/kotlin/problem1027/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem1027 /** * LeetCode page: [1027. Longest Arithmetic Subsequence](https://leetcode.com/problems/longest-arithmetic-subsequence/); */ class Solution { /* Complexity: * Time O(N^2) and Space O(N^2) where N is the size of nums; */ fun longestArithSeqLength(nums: IntArray): Int { /* dp[endValue][commonDifference] ::= the longest length of arithmetic subsequence * having endValue and commonDifference; */ val dp = mutableMapOf<Int, MutableMap<Int, Int>>() var result = 0 for (endValue in nums) { val subsequences = hashMapOf<Int, Int>() // entry = (commonDifference, length) for (existingEndValue in dp.keys) { /* Form/extend an arithmetic subsequence using existingEndValue as the * second-to-last value; */ val commonDifference = endValue - existingEndValue val length = 1 + (dp[existingEndValue]?.get(commonDifference) ?: 1) subsequences[commonDifference] = length result = maxOf(result, length) } dp[endValue] = subsequences } return result } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
1,238
hj-leetcode-kotlin
Apache License 2.0
Retos/Reto #39 - TRIPLES PITAGÓRICOS [Media]/kotlin/pisanowp.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}
fun main() { /* * Reto #39 02/10/2023 TRIPLES PITAGÓRICOS * * Crea una función que encuentre todos los triples pitagóricos * (ternas) menores o iguales a un número dado. * - Debes buscar información sobre qué es un triple pitagórico. * - La función únicamente recibe el número máximo que puede * aparecer en el triple. * - Ejemplo: Los triples menores o iguales a 10 están * formados por (3, 4, 5) y (6, 8, 10). */ // Tres números enteros a , b , c que satisfacen la ecuación del teorema de Pitágoras // ( a 2 + b 2 = c 2 ) son llamados triples Pitagóricos . val numMaximo = 10 println("Los triples pitagoricos menores o iguales a $numMaximo son ${findTriplesPitagoricos(numMaximo)}") } fun findTriplesPitagoricos(numMaximo: Int): List<List<Int>> { var triplesPitagoricos = mutableListOf<List<Int>>() (1..numMaximo).forEach { a -> (a..numMaximo).forEach { b -> (b..numMaximo).forEach { c -> if ((a !== b) && (b !== c) && (a !== c)) { if ((a * a + b * b) == (c * c)) { triplesPitagoricos.add(listOf(a, b, c)) } } } // c } // b } // a return triplesPitagoricos }
4
Python
2,929
4,661
adcec568ef7944fae3dcbb40c79dbfb8ef1f633c
1,312
retos-programacion-2023
Apache License 2.0
src/main/kotlin/nl/jackploeg/aoc/_2022/calendar/day02/Day02.kt
jackploeg
736,755,380
false
{"Kotlin": 318734}
package nl.jackploeg.aoc._2022.calendar.day02 import javax.inject.Inject import nl.jackploeg.aoc.generators.InputGenerator.InputGeneratorFactory import nl.jackploeg.aoc.utilities.readStringFile class Day02 @Inject constructor( private val generatorFactory: InputGeneratorFactory, ) { fun partOne(fileName: String): Int { val moves = readStrategy(fileName) return moves.map { calculateScore1(it) } .reduce { sum, score -> sum + score} } fun partTwo(fileName: String): Int { val moves = readStrategy(fileName) return moves.map { calculateScore2(it) } .reduce { sum, score -> sum + score} } fun readStrategy(fileName: String): List<Pair<Char, Char>> { val moves: MutableList<Pair<Char, Char>> = mutableListOf() val pairs = readStringFile(fileName) for (pair in pairs) { moves.add(Pair(pair[0], pair[2])) } return moves } fun calculateScore1(move: Pair<Char, Char>): Int { val (a, b) = move var score = when (a) { 'A' -> when (b) { 'X' -> 3 'Y' -> 6 'Z' -> 0 else -> -1 } 'B' -> when (b) { 'X' -> 0 'Y' -> 3 'Z' -> 6 else -> -1 } 'C' -> when (b) { 'X' -> 6 'Y' -> 0 'Z' -> 3 else -> -1 } else -> -1 } score += when (b) { 'X' -> 1 'Y' -> 2 'Z' -> 3 else -> -1 } return score } fun calculateScore2(move: Pair<Char, Char>): Int { val (a, b) = move // a = rock, b = paper, c = scissors // x = lose, y = draw, z = win // 1 = rock, 2 = paper, 3 = scissors val myMove = when (a) { 'A' -> when (b) { 'X' -> 3 'Y' -> 1 'Z' -> 2 else -> -1 } 'B' -> when (b) { 'X' -> 1 'Y' -> 2 'Z' -> 3 else -> -1 } 'C' -> when (b) { 'X' -> 2 'Y' -> 3 'Z' -> 1 else -> -1 } else -> -1 } val score = myMove + when (b) { 'X' -> 0 'Y' -> 3 'Z' -> 6 else -> -1 } return score } }
0
Kotlin
0
0
f2b873b6cf24bf95a4ba3d0e4f6e007b96423b76
2,790
advent-of-code
MIT License
src/main/kotlin/days/Day4.kt
hughjdavey
225,440,374
false
null
package days class Day4 : Day(4) { private val range = inputString.split('-').map { it.trim().toInt() } override fun partOne(): Any { return (range[0]..range[1]).count { meetsPasswordCriteria(it.toString()) } } override fun partTwo(): Any { return (range[0]..range[1]).count { meetsExtendedPasswordCriteria(it.toString()) } } fun meetsPasswordCriteria(password: String): Boolean { return password.length == 6 && password.all { it.isDigit() } && password.toSet().size < 6 && password.map { it.toInt() }.windowed(2, 1).all { it[1] >= it[0] } } fun meetsExtendedPasswordCriteria(password: String): Boolean { return meetsPasswordCriteria(password) && "<PASSWORD>".windowed(4, 1).find { it[1] == it[2] && it[0] != it[1] && it[3] != it[1] } != null } }
0
Kotlin
0
1
84db818b023668c2bf701cebe7c07f30bc08def0
859
aoc-2019
Creative Commons Zero v1.0 Universal
src/main/kotlin/Day12.kt
pavittr
317,532,861
false
null
import java.io.File import java.nio.charset.Charset import kotlin.math.absoluteValue import kotlin.streams.toList fun main() { val testDocs = File("test/day12").readLines(Charset.defaultCharset()) val puzzles = File("puzzles/day12").readLines(Charset.defaultCharset()) var initBoat = Triple(0, 0, "E") fun compass(facing: String, turn: String, magnitude: Int): String { val compassPoints = listOf("N", "E", "S", "W") val numberTurns = magnitude / 90 // if L then negative scroll val startIndex = compassPoints.mapIndexed { index, point -> if (point == facing) { index } else { -1 } }.filter { it >= 0 }.first() println("Turning from $facing through $turn $magnitude $numberTurns $startIndex") if (numberTurns == 2) { return compassPoints[(startIndex + 2) % 4] } else if ((turn == "L" && numberTurns == 1) || (turn == "R" && numberTurns == 3)) { return compassPoints[(startIndex + 3) % 4] } else if ((turn == "L" && numberTurns == 3) || (turn == "R" && numberTurns == 1)) { return compassPoints[(startIndex + 1) % 4] } return facing } fun move(boat: Triple<Int, Int, String>, direction: String, magnitude: Int): Triple<Int, Int, String> { when (direction) { "N" -> return Triple(boat.first, boat.second + magnitude, boat.third) "S" -> return Triple(boat.first, boat.second - magnitude, boat.third) "E" -> return Triple(boat.first + magnitude, boat.second, boat.third) "W" -> return Triple(boat.first - magnitude, boat.second, boat.third) } return boat } fun directBoat(boat: Triple<Int, Int, String>, instruction: String): Triple<Int, Int, String> { val order = instruction.take(1) val magnitude = instruction.drop(1).toInt() return if (order in listOf("L", "R")) { Triple(boat.first, boat.second, compass(boat.third, order, magnitude)) } else { val direction = if (order == "F") { boat.third } else { order } move(boat, direction, magnitude) } } testDocs.forEach { println(initBoat); initBoat = directBoat(initBoat, it) } println(initBoat) println(initBoat.first.absoluteValue + initBoat.second.absoluteValue) initBoat = Triple(0, 0, "E") puzzles.forEach { println(initBoat); initBoat = directBoat(initBoat, it) } println(initBoat) println(initBoat.first.absoluteValue + initBoat.second.absoluteValue) // Part 2 fun part2(instructions: List<String>) : Pair<Int, Int> { var waypoint = Pair(10, 1) var boatPos = Pair(0, 0) instructions.forEach { println("Entering with $boatPos and $waypoint using $it") val instruction = it.take(1) val magnitude = it.drop(1).toInt() if (instruction in listOf("L", "R")) { when (it) { "L90" -> waypoint = Pair(waypoint.second * -1, waypoint.first) "L180" -> waypoint = Pair(waypoint.first * -1, waypoint.second * -1) "L270" -> waypoint = Pair(waypoint.second, waypoint.first * -1) "R90" -> waypoint = Pair(waypoint.second, waypoint.first * -1) "R180" -> waypoint = Pair(waypoint.first * -1, waypoint.second * -1) "R270" -> waypoint = Pair(waypoint.second * -1, waypoint.first) } } else { when (instruction) { "N" -> waypoint = Pair(waypoint.first, waypoint.second + magnitude) "E" -> waypoint = Pair(waypoint.first + magnitude, waypoint.second) "S" -> waypoint = Pair(waypoint.first, waypoint.second - magnitude) "W" -> waypoint = Pair(waypoint.first - magnitude, waypoint.second) "F" -> boatPos = Pair( boatPos.first + (waypoint.first * magnitude), boatPos.second + (waypoint.second * magnitude) ) } } println("Exiting with $boatPos and $waypoint using $it") } return boatPos } println(part2(testDocs).let{it.second.absoluteValue + it.first.absoluteValue}) println(part2(puzzles).let{it.second.absoluteValue + it.first.absoluteValue}) }
0
Kotlin
0
0
3d8c83a7fa8f5a8d0f129c20038e80a829ed7d04
4,585
aoc2020
Apache License 2.0
src/main/kotlin/Rucksack.kt
alebedev
573,733,821
false
{"Kotlin": 82424}
import java.lang.RuntimeException fun main() { var result = 0 for (group in readRucksack()) { result += charScore(findGroupBadge(group)) } println("Total score: $result") } private typealias Group = MutableList<String> private fun readRucksack(): Iterable<Group> { val result = mutableListOf<Group>() var group: Group generateSequence(::readLine).forEachIndexed { i, line -> if (i % 3 == 0) { group = mutableListOf() result.add(group) } else { group = result.last() } group.add(line) } return result.toList() } private fun findGroupBadge(group: Group): Char { val sets = group.map { it.toSet() } val commonChars = sets.reduce {chars, lineChars -> chars.intersect(lineChars)} if (commonChars.size != 1) { throw Error("Expected to find exactly one unique char") } return commonChars.first() } private fun charScore(char: Char) = when (char) { in 'a'..'z' -> { char.code - 'a'.code + 1 } in 'A'..'Z' -> { char.code - 'A'.code + 27 } else -> throw RuntimeException("Unexpected char $char") }
0
Kotlin
0
0
d6ba46bc414c6a55a1093f46a6f97510df399cd1
1,183
aoc2022
MIT License
Kotlin/problems/0032_verify_preorder_serialization_binary_tree.kt
oxone-999
243,366,951
true
{"C++": 961697, "Kotlin": 99948, "Java": 17927, "Python": 9476, "Shell": 999, "Makefile": 187}
// Problem Statement // One way to serialize a binary tree is to use pre-order traversal. // When we encounter a non-null node, we record the node's value. // If it is a null node, we record using a sentinel value such as #. // // _9_ // / \ // 3 2 // / \ / \ // 4 1 # 6 // / \ / \ / \ // # # # # # # // For example, the above binary tree can be serialized to the string // "9,3,4,#,#,1,#,#,2,#,6,#,#", where # represents a null node. // // Given a string of comma separated values, verify whether it is a correct // preorder traversal serialization of a binary tree. // Find an algorithm without reconstructing the tree. // // Each comma separated value in the string must be either an integer or a // character '#' representing null pointer. // // You may assume that the input format is always valid, for example it could // never contain two consecutive commas such as "1,,3". // // Input: "9,3,4,#,#,1,#,#,2,#,6,#,#" // Output: true import java.util.Stack class Solution { fun isValidSerialization(preorder: String): Boolean { val helper = Stack<Pair<String,Int>>() val splited = preorder.split(',') var index = 0 while(index<splited.size){ if(splited[index]=="#"){ if(helper.isEmpty()){ if(index==0 && splited.size==1) return true else return false } helper.incrementLast() while(!helper.isEmpty() && helper.peek().second==2){ helper.pop(); if(!helper.isEmpty()){ helper.incrementLast() } } }else{ helper.push(Pair(splited[index],0)) } index+=1 if(helper.empty()){ break; } } return helper.isEmpty() && index == splited.size } private fun Stack<Pair<String,Int>>.incrementLast(){ val last = this.pop() this.push(Pair<String,Int>(last.first,last.second+1)) } } fun main(args: Array<String>) { val preorder = "9,3,4,#,#,1,#,#,2,#,6,#,#" val sol = Solution() println(sol.isValidSerialization(preorder)) }
0
null
0
0
52dc527111e7422923a0e25684d8f4837e81a09b
2,364
algorithms
MIT License
src/main/kotlin/arraysandstrings/MinimumCostToHireKWorkers.kt
e-freiman
471,473,372
false
{"Kotlin": 78010}
package arraysandstrings import java.util.PriorityQueue fun mincostToHireWorkers(quality: IntArray, wage: IntArray, k: Int): Double { val x = wage.indices.sortedWith {a, b -> val ra = wage[a].toDouble() / quality[a].toDouble() val rb = wage[b].toDouble() / quality[b].toDouble() if (ra < rb) -1 else 1 } val pq = PriorityQueue<Int>(k) {a, b -> b - a} var minGroupPay = Double.MAX_VALUE var sum = 0 for (i in x.indices) { val cost = wage[x[i]].toDouble() / quality[x[i]].toDouble() pq.add(quality[x[i]]) sum += quality[x[i]] if (pq.size > k) { sum -= pq.poll() } if (pq.size == k) { minGroupPay = minOf(sum.toDouble() * cost, minGroupPay) } } return minGroupPay } fun main() { println(mincostToHireWorkers(intArrayOf(10,20,5), intArrayOf(70,50,30), 2)) }
0
Kotlin
0
0
fab7f275fbbafeeb79c520622995216f6c7d8642
916
LeetcodeGoogleInterview
Apache License 2.0
lib_algorithms_sort_kotlin/src/main/java/net/chris/lib/algorithms/sort/kotlin/KTHeapSorter.kt
chrisfang6
105,401,243
false
{"Java": 68669, "Kotlin": 26275, "C++": 12503, "CMake": 2182, "C": 1403}
package net.chris.lib.algorithms.sort.kotlin /** * Heap sort. * * @param <T> </T> */ abstract class KTHeapSorter : KTSorter() { override fun subSort(array: IntArray) { if (array == null) { return } var heapsize = array.size buildheap(array) for (i in 0 until array.size - 1) { // swap the first and the last val temp: Int temp = array[0] array[0] = array[heapsize - 1] array[heapsize - 1] = temp // heapify the array heapsize -= 1 heapify(array, 0, heapsize) } } fun buildheap(array: IntArray) { val length = array.size val nonleaf = length / 2 - 1 for (i in nonleaf downTo 0) { heapify(array, i, length) } } fun heapify(array: IntArray, i: Int, heapsize: Int) { var smallest = i val left = 2 * i + 1 val right = 2 * i + 2 if (left < heapsize) { if (compareTo(array[i], array[left]) > 0) { smallest = left } else smallest = i } if (right < heapsize) { if (compareTo(array[smallest], array[right]) > 0) { smallest = right } } if (smallest != i) { val temp: Int temp = array[i] array[i] = array[smallest] array[smallest] = temp doUpdate(array) heapify(array, smallest, heapsize) } } }
0
Java
0
0
1f1c2206d5d9f0a3d6c070a7f6112f60c2714ec0
1,555
sort
Apache License 2.0
src/main/kotlin/com/github/amolkov/kotlin/algorithms/sorting/QuickSort.kt
amolkov
122,844,991
false
null
package com.github.amolkov.kotlin.algorithms.sorting import com.github.amolkov.kotlin.algorithms.extensions.swap class QuickSort { companion object { /** * Sorts the specified array into ascending order, according to the natural ordering of its elements, * using the quick sort algorithm. * * @param arr the array to be sorted */ fun <T : Comparable<T>> sort(arr: Array<T>) = sort(arr, 0, arr.size - 1) private fun <T : Comparable<T>> sort(arr: Array<T>, lo: Int, hi: Int) { if (lo >= hi) { return } val p = partition(arr, lo, hi) sort(arr, lo, p - 1) sort(arr, p, hi) } private fun <T : Comparable<T>> partition(arr: Array<T>, lo: Int, hi: Int): Int { val pivot = arr[hi] var left = lo var right = hi while (left < right) { while (arr[left] < pivot) left++ while (arr[right] > pivot) right-- if (left <= right) { arr.swap(left, right) } } return left } } }
0
Kotlin
0
0
acb6bc2e397087fec8432b3307d0c0ea0c6ba75b
1,205
kotlin-algorithms
Apache License 2.0
Kotlin101/11-flow-control/03_For.kt
ge47jaz
695,323,673
false
{"Kotlin": 77958}
import kotlin.text.toInt // different vaiations of for loops // ranges fun printOneToTen() { for (i in 1..10) { println(i) } } fun printTenToOne() { for (i in 10 downTo 1) { println(i) } } fun printOddsOneToTen() { for (i in 1..10 step 2) { println(i) } } fun printOddsTenToOne() { for (i in 10 downTo 1 step 2) { println(i) } } fun printEvensOneToTen() { for (i in 1 until 10 step 2) { println(i) } } fun printEvensTenToOne() { for (i in 10 downTo 1 step 2) { println(i) } } // iterating over collections fun printList() { val list = listOf("a", "b", "c") for (item: String in list) { println(item) } } // some examples // add all numbers from 1 to given int fun addAllNumbersUpTo(int: Int) { var res: Int = 0 for (i in 1..int) res += i println("the sum is $res") } // hashmap given. for each person print out corresponding number fun printCorrespondingNumber() { val customers = hashMapOf("Peter" to 3, "Anne" to 2, "Chris" to 39) // loop through keys and get corresponding value for (customerName in customers.keys) { // get corresponding value val number = customers[customerName] println("$customerName has the number $number") } } /** * ask user to input a year, for each month of that year print out how many days there are consider * leap years (divisible by 4) */ fun daysInMonth() { println("enter year") val input = readLine() ?: "2020" val year = input.toInt() for (i in 1..12) { val message = when (i) { 1 -> "January: 31 days" 2 -> if (year % 4 == 0) "Febuary: 29 days" else "Febuary: 28 days" 3 -> "March: 31 days" 4 -> "April: 30 days" 5 -> "May: 31 days" 6 -> "June: 30 days" 7 -> "July: 31 days" 8 -> "August: 31 days" 9 -> "September: 30 days" 10 -> "October: 31 days" 11 -> "November: 30 days" 12 -> "December: 31 days" else -> "" } println(message) } } // race countdown fun countdown() { for (i in 10 downTo 0) { when (i) { 9 -> println(i.toString() + ": start your engines") 6 -> println(i.toString() + ": on your marks") 3 -> println(i.toString() + ": get set") 0 -> println(i.toString() + ": go") else -> println(i) } } } // print all even numbers form 10 to 1 with "step" fun printEven() { for (i in 10 downTo 1 step 2) println(i) } // nested for loops - print out matrix of a certain size fun nestedFor(size: Int) { for (i in 0..size) { for (j in 0..size) { // "/t" it tab print("$i,$j \t") } println() } } // ask user to input a number, print out every number smaller that this number that is divisible by // 7 in descending order fun multiplesOfSeven() { println("input a number") val input = readLine() ?: "0" val number = input.toInt() for (i in number downTo 0) { if (i % 7 == 0) print(i.toString() + "\t") } } // print lower triangle of a rectangle with "width" and "hight" fun lowerTriangle(width: Int, hight: Int) { var lineWidth: Int = 1 for (i in 1..hight) { for (j in 1..lineWidth) { if (lineWidth <= width) { print("X") } else { return } } lineWidth++ println() } } fun main(args: Array<String>) { // printCorrespondingNumber() // addAllNumbersUpTo(5) // daysInMonth() // countdown() // printEven() // nestedFor(5) // multiplesOfSeven() // lowerTriangle(5, 6) }
0
Kotlin
0
0
87dba8f8137c32d0ef6912efd5999675a2620ab4
3,936
kotlin-progress
MIT License
src/questions/ReverseWordsInStringIII.kt
realpacific
234,499,820
false
null
package questions import _utils.UseCommentAsDocumentation import utils.shouldBe import java.lang.StringBuilder /** * Given a string s, reverse the order of characters in each word within a sentence * while still preserving whitespace and initial word order. * * [Source](https://leetcode.com/problems/reverse-words-in-a-string-iii/) */ @UseCommentAsDocumentation private fun reverseWords(s: String): String { if (s.length == 1) { return s } val sb = StringBuilder(s) var wordBegin = 0 var wordEnd = wordBegin // To consider for single letter words, start from same position as [wordBegin] while (wordEnd < sb.length && wordBegin < sb.length) { var wordEndChar: Char? = sb.getOrNull(wordEnd) ?: break while (wordEndChar != ' ') { // until you find a white space, move right wordEnd++ wordEndChar = sb.getOrNull(wordEnd) if (wordEndChar == null || wordEndChar == ' ') { // end of the string reached || found a white space wordEnd-- break } } // [wordBeing, wordEnd] contains a word swap(sb, begin = wordBegin, end = wordEnd) // swap in current word wordBegin = wordEnd + 2 // move ahead of white space wordEnd = wordBegin } return sb.toString() } private fun swap(sb: StringBuilder, begin: Int, end: Int) { var startFrom = begin var endAt = end while (startFrom < endAt) { val temp = sb[startFrom] sb[startFrom] = sb[endAt] sb[endAt] = temp startFrom++ endAt-- } } fun main() { reverseWords(s = "a b d ee$#% aef\$ea eaef eaj ae##ea'fe") shouldBe "a b d %#\$ee ae\$fea feae jae ef'ae##ea" reverseWords(s = "I love u") shouldBe "I evol u" reverseWords(s = "God Ding") shouldBe "doG gniD" reverseWords(s = "Let's take LeetCode contest") shouldBe "s'teL ekat edoCteeL tsetnoc" }
4
Kotlin
5
93
22eef528ef1bea9b9831178b64ff2f5b1f61a51f
1,930
algorithms
MIT License
shared/src/commonMain/kotlin/com/aglushkov/wordteacher/shared/repository/dict/Trie.kt
soniccat
302,971,014
false
{"Kotlin": 1008121, "Go": 137919, "Swift": 38695, "TypeScript": 29600, "Dockerfile": 5486, "Makefile": 3673, "JavaScript": 3131, "Ruby": 1740, "HTML": 897, "Java": 872, "SCSS": 544, "C": 59, "Shell": 58}
package com.aglushkov.wordteacher.shared.repository.dict import com.aglushkov.wordteacher.shared.general.extensions.addElements abstract class Trie<T, D>: Iterable<T> { private val root = TrieNode<T>("", null) abstract fun createEntry(node: TrieNode<T>, data: D): T abstract fun setNodeForEntry(entry: T, node: TrieNode<T>) // TODO: try to move node in Entry type fun put(word: String, data: D): T { val node = putWord(word, data) val entry = createEntry(node, data) node.dictIndexEntries.add( entry ) return entry } private fun putWord(word: String, data: D): TrieNode<T> { var node = root var innerNodeIndex = 0 word.onEach { ch -> // match with prefix -> go along the prefix if (innerNodeIndex < node.prefix.length && node.prefix[innerNodeIndex] == ch) { innerNodeIndex += 1 // reached the end of prefix and there aren't any children aren't any entries -> extend prefix // skip if node is root } else if (node != root && node.prefix.length == innerNodeIndex && node.children.isEmpty() && node.dictIndexEntries.isEmpty()) { node.prefix = node.prefix + ch innerNodeIndex += 1 // reached the end of prefix and there're children or entries -> try to find a child with the same prefix or add a new child } else if (node.prefix.length == innerNodeIndex && (node.children.isNotEmpty() || node.dictIndexEntries.isNotEmpty() || node == root)) { val childNode = node.children.firstOrNull { it.prefix.first() == ch } if (childNode != null) { node = childNode } else { val newNode = TrieNode<T>(ch.toString(), node) node.children.add(newNode) node = newNode } innerNodeIndex = 1 // in the middle of prefix got that the next character is different -> split the node } else if (innerNodeIndex < node.prefix.length && node.prefix[innerNodeIndex] != ch) { val newNode1 = TrieNode<T>( node.prefix.substring(innerNodeIndex, node.prefix.length), node, node.dictIndexEntries.toMutableList(), node.children.toMutableList() ) newNode1.dictIndexEntries.map { setNodeForEntry(it, newNode1) } newNode1.children.onEach { it.parent = newNode1 } val newNode2 = TrieNode( ch.toString(), node ) node.prefix = node.prefix.substring(0, innerNodeIndex) node.dictIndexEntries.clear() node.children.clear() node.children.addElements(newNode1, newNode2) node = newNode2 innerNodeIndex = 1 } else { throw RuntimeException("TrieNode.putWordInternal: impossible condition") } } // found a node but it for a longer word with the same beginning, split the node if (innerNodeIndex != node.prefix.length) { // here innerNodeIndex is already incremented // a node with the right part of text val rightNode = TrieNode<T>( node.prefix.substring(innerNodeIndex, node.prefix.length), node, node.dictIndexEntries.toMutableList(), node.children.toMutableList() ) rightNode.dictIndexEntries.map { setNodeForEntry(it, rightNode) } rightNode.children.onEach { it.parent = rightNode } // transform the node to the node with the left part of text node.prefix = node.prefix.substring(0, innerNodeIndex) node.dictIndexEntries.clear() node.children.clear() node.children.addElements(rightNode) } return node } fun wordsStartWith(prefix: String, limit: Int): List<T> { var node: TrieNode<T>? = root prefix.onEach { ch -> node = node?.findChild(ch) } return node?.let { words(it, limit) } ?: emptyList() } private fun words(node: TrieNode<T>, limit: Int): List<T> { val entries = mutableListOf<T>() runVisitor(node) { entries.add(it) entries.size < limit } return entries } fun word(word: String): List<T> { var node: TrieNode<T>? = root word.onEach { ch -> node = node?.findChild(ch) } return node?.dictIndexEntries.orEmpty() } fun asSequence(): Sequence<T> { return sequence { yieldAll(iterator()) } } fun isEmpty() = root.children.isEmpty() && root.dictIndexEntries.isEmpty() private fun runVisitor( node: TrieNode<T>, visitor: (entry: T) -> Boolean ): Boolean { node.dictIndexEntries.onEach { if (!visitor.invoke(it)) return false } node.children.onEach { if (!runVisitor(it, visitor)) return false } return true } // TODO: refactor, simplify logic // we can request all the word forms at once (lemma, term) and remove that misleading "needAnotherOne: Boolean" fun entry( word: String, nextWord: (needAnotherOne: Boolean) -> String?, onFound: (node: MutableList<T>) -> Unit ) { var node: TrieNode<T>? = root word.onEach { ch -> node = node?.findChild(ch) if (node == null) return } var initialWordNode: TrieNode<T>? = null val spaceNode = node?.findChild(' ') if (spaceNode != null) { node = spaceNode } else if (node?.isEnd == true) { initialWordNode = node node?.let { safeNode -> onFound(safeNode.dictIndexEntries) } } else { return } // set to false when we ask for the next word in the sentence // set to true when we ask for another similar word at the current position i.e. a token instead of a lemma var needAnotherOne = false var nw = nextWord(needAnotherOne) while (nw != null) { val nextNode = wordNode(nw, node) if (nextNode == null) { needAnotherOne = true } else { needAnotherOne = false if (nextNode.isEnd) { onFound(nextNode.dictIndexEntries) } val spaceNode2 = nextNode.findChild(' ') if (spaceNode2 != null) { node = spaceNode2 } else if ( nextNode.isEnd && nextNode.dictIndexEntries.isEmpty() || !nextNode.isEnd && nextNode.dictIndexEntries.isNotEmpty() // added for cases like "out of sorts" as lemma "sort" doesn't fit and we're in the middle of a metanode ) { needAnotherOne = true } else { node = nextNode break } } nw = nextWord(needAnotherOne) } if (initialWordNode != node) { node?.let { safeNode -> if (safeNode.isEnd) { onFound(safeNode.dictIndexEntries) } } } } private fun wordNode(word: String, startNode: TrieNode<T>?): TrieNode<T>? { var node: TrieNode<T>? = startNode word.onEach { ch -> node = node?.findChild(ch) if (node == null) return null } return node } override fun iterator(): Iterator<T> { return TrieIterator(root) } private class TrieIterator<T>( rootNode: TrieNode<T> ): Iterator<T> { private var nodeStack = ArrayDeque<TrieIteratorNode<T>>() init { if (rootNode.children.isNotEmpty() || rootNode.dictIndexEntries.isNotEmpty()) { walkDownUntilEntries(rootNode) } } private fun walkDownUntilEntries(aNode: TrieNode<T>): TrieIteratorNode<T> { var node = aNode do { val iteratorNode = TrieIteratorNode(node) nodeStack.addLast(iteratorNode) if (iteratorNode.entryIterator.hasNext()) { return iteratorNode } else if (iteratorNode.childIterator.hasNext()) { node = iteratorNode.childIterator.next() } else { break } } while (true) throw RuntimeException("TrieIterator.walkDownUntilEntries returns null") } override fun hasNext(): Boolean = nodeStack.lastOrNull() != null && (nodeStack.last().entryIterator.hasNext() || nodeStack.last().childIterator.hasNext()) override fun next(): T { var result: T? = null val entry = nodeStack.last() if (entry.entryIterator.hasNext()) { result = entry.entryIterator.next() } else if (entry.childIterator.hasNext()) { val nextLastNode = walkDownUntilEntries(entry.childIterator.next()) result = nextLastNode.entryIterator.next() } while (nodeStack.isNotEmpty() && !nodeStack.last().entryIterator.hasNext() && !nodeStack.last().childIterator.hasNext()) { nodeStack.removeLast() } if (result != null) { return result } throw RuntimeException("TrieIterator.next returns null") } private data class TrieIteratorNode<T>( val node: TrieNode<T>, var entryIterator: Iterator<T> = node.dictIndexEntries.iterator(), var childIterator: Iterator<TrieNode<T>> = node.children.iterator() ) } } open class TrieNode<T>( var prefix: String, var parent: TrieNode<T>?, val dictIndexEntries: MutableList<T> = mutableListOf(), val children: MutableList<TrieNode<T>> = mutableListOf() // TODO: add alphabetical sorting ) { open val isEnd: Boolean get() { return prefix.length == 1 && dictIndexEntries.isNotEmpty() } // To be able to work with nodes in this way: // // var node: TrieNode? = n // prefix.onEach { ch -> // node = node?.findChild(ch) // } // open fun findChild(ch: Char): TrieNode<T>? { if (prefix.length > 1 && prefix[1] == ch) { return MetaTrieNode(this, 1) } return children.firstOrNull { it.prefix.first() == ch } } fun calcWord(): String { return buildString { var node: TrieNode<T> = this@TrieNode while (true) { insert(0, node.prefix) val p = node.parent if (p != null) { node = p } else { break; } } } } } private data class MetaTrieNode<T>( val ref: TrieNode<T>, val offset: Int ): TrieNode<T>(ref.prefix, ref, ref.dictIndexEntries, ref.children) { override val isEnd: Boolean get() = offset + 1 == ref.prefix.length && ref.dictIndexEntries.isNotEmpty() override fun findChild(ch: Char): TrieNode<T>? { if (offset + 1 < prefix.length && prefix[offset + 1] == ch) { return MetaTrieNode(this, offset + 1) } return children.firstOrNull { it.prefix.first() == ch } } }
0
Kotlin
1
10
b904cbee5072a15a4be51f2346d460aa662c1ea4
12,033
WordTeacher
MIT License
Hyperskill/Numeric-Matrix-Processor/Main.kt
Alphabeater
435,048,407
false
{"Kotlin": 69566, "Python": 5974}
package processor import java.util.* val s = Scanner(System.`in`) fun main() { loop@ do { print(""" 1. Add matrices 2. Multiply matrix by a constant 3. Multiply matrices 4. Transpose matrix 5. Calculate a determinant 6. Inverse matrix 0. Exit Your choice: """.trimIndent()) val option = s.nextInt() try { when (option) { 0 -> break@loop 1 -> printMatrix(sumMatrix( readMatrix("first "), readMatrix("second "))) 2 -> printMatrix(multiplyMatrixConst( readMatrix(""), readConst())) 3 -> printMatrix(multiplyMatrix( readMatrix("first "), readMatrix("second ") )) 4 -> printMatrix(transposeMatrix()) 5 -> println(calculateDeterminant(readMatrix(""))) 6 -> readMatrix("").let { printMatrix(inverseMatrix( it, recursiveDeterminant(it))) } else -> throw Exception("Invalid option.") } } catch (e: Exception) { println(e.message) continue@loop } } while (true) } fun sumMatrix(a: Array<Array<Double>>, b: Array<Array<Double>>): Array<Array<Double>> { if (a.size == b.size && a[0].size == b[0].size) { val c = Array(a.size) { Array(a[0].size) { 0.0 } } for (i in a.indices) { for (j in a[0].indices) { c[i][j] = a[i][j] + b[i][j] } } return c } else throw Exception("The operation cannot be performed.") } fun multiplyMatrixConst(m: Array<Array<Double>>, const: Double): Array<Array<Double>> { val c = Array(m.size) { Array(m[0].size) { 0.0 } } for (i in m.indices) { for (j in m[0].indices) { c[i][j] = m[i][j] * const } } return c } fun multiplyMatrix(a: Array<Array<Double>>, b: Array<Array<Double>>): Array<Array<Double>> { if (a[0].size == b.size) { val c = Array(a.size) { Array(b[0].size) { 0.0 } } for (i in c.indices) { for (j in c[0].indices) { var r = 0.0 for (k in a[0].indices){ r += a[i][k] * b[k][j] } c[i][j] = r } } return c } else throw Exception("The operation cannot be performed.") } fun transposeMatrix(): Array<Array<Double>> { print(""" 1. Main diagonal 2. Side diagonal 3. Vertical line 4. Horizontal line Your choice: """.trimIndent()) val option = s.nextInt() val m = readMatrix("") return when (option) { 1 -> tMainDiagonal(m) 2 -> tSideDiagonal(m) 3 -> tVerticalLine(m) 4 -> tHorizontalLine(m) else -> throw Exception("Invalid option.") } } fun tMainDiagonal(m: Array<Array<Double>>): Array<Array<Double>> { val r = Array(m[0].size) { Array(m.size) { 0.0 } } for (i in m.indices) { for (j in m[0].indices) { r[j][i] = m[i][j] } } return r } fun tSideDiagonal(m: Array<Array<Double>>): Array<Array<Double>> { val r = Array(m[0].size) { Array(m.size) { 0.0 } } for (i in m.size - 1 downTo 0) { for (j in m[0].size - 1 downTo 0) { r[i][j] = m[m[0].size - 1 - j][m.size - 1 - i] } } return r } fun tVerticalLine(m: Array<Array<Double>>): Array<Array<Double>> { val r = Array(m[0].size) { Array(m.size) { 0.0 } } for (i in m.indices) { for (j in m[0].indices) { r[i][j] = m[i][m[0].size - 1 - j] } } return r } fun tHorizontalLine(m: Array<Array<Double>>): Array<Array<Double>> { val r = Array(m[0].size) { Array(m.size) { 0.0 } } for (i in m.indices) { for (j in m[0].indices) { r[i][j] = m[m.size - 1 - i][j] } } return r } fun calculateDeterminant(m: Array<Array<Double>>): Double { if (m.size == m[0].size) { return recursiveDeterminant(m) } else throw Exception("The operation cannot be performed.") } fun recursiveDeterminant(m: Array<Array<Double>>): Double { return if (m.size == 2) { m[0][0] * m[1][1] - m[0][1] * m[1][0] } else { var res = 0.0 for (j in m[0].indices) { val n = getMinor(m, j) val sign = if ( j % 2 == 0) 1.0 else -1.0 res += sign * m[0][j] * recursiveDeterminant(n) } res } } fun getMinor(m: Array<Array<Double>>, x: Int): Array<Array<Double>> { val r = Array(m[0].size - 1) { Array(m.size - 1) { 0.0 } } var k = 0 for (i in 1 until m.size) { for (j in m[0].indices) { if (x != j) { r[i - 1][k++] = m[i][j] } } k = 0 } return r } fun getAdjointMatrix(m: Array<Array<Double>>): Array<Array<Double>> { val r = Array(m[0].size) { Array(m.size) { 0.0 } } for (i in m.indices) { for (j in m[i].indices) { var t = Array(m[0].size) { Array(m[0].size) { 0.0 } } for (k in m.indices) { t[k] = m[k].filterIndexed { id, _ -> id != j }.toTypedArray() } t = t.filterIndexed { id, _ -> id != i }.toTypedArray() val sign = if ( (i + j) % 2 == 0) 1.0 else -1.0 r[i][j] = sign * recursiveDeterminant(t) } } return tMainDiagonal(r) } fun inverseMatrix(m: Array<Array<Double>>, det: Double): Array<Array<Double>> { if (det != 0.0) { return multiplyMatrixConst(getAdjointMatrix(m), 1.0 / det) } else throw Exception("This matrix doesn't have an inverse.") } fun readMatrix(str: String): Array<Array<Double>> { print("Enter size of ${str}matrix: ") val (row, col) = Array(2) { s.nextInt() } print("Enter ${str}matrix:\n") return Array(row) { Array(col) { s.nextDouble() } } } fun printMatrix(c: Array<Array<Double>>) { println("The result is:") for (i in c.indices) { for (j in c[0].indices) { print("${c[i][j]} ") } println() } } fun readConst(): Double{ print("Enter constant: ") return s.nextDouble() }
0
Kotlin
0
0
05c8d4614e025ed2f26fef2e5b1581630201adf0
6,344
Archive
MIT License
2023/src/main/kotlin/Day10.kt
dlew
498,498,097
false
{"Kotlin": 331659, "TypeScript": 60083, "JavaScript": 262}
private typealias Grid = List<String> object Day10 { private data class Pos(val x: Int, val y: Int) fun part1(input: String) = findLoop(input.splitNewlines()).size / 2 fun part2(input: String): Int { val grid = input.splitNewlines() val loop = findLoop(grid).toSet() // Every time we hit a wall, switch parity, only count those inside // Kind of tricksy because we can't count all corners for parity checking var total = 0 var parity = false grid.forEachIndexed { y, row -> row.forEachIndexed { x, c -> if (Pos(x, y) in loop) { if (c == '|' || c == 'L' || c == 'J') { parity = !parity } } else if (parity) { total++ } } } return total } private fun findLoop(grid: Grid): List<Pos> { val start = findStart(grid) val loop = mutableListOf<Pos>() val marked = mutableSetOf<Pos>() // Not necessary, but much faster using a Set here var curr: Pos? = start while (curr != null) { loop.add(curr) marked.add(curr) curr = directions .mapNotNull { it(grid, curr!!) } .firstOrNull { it !in marked } } return loop } private fun findStart(grid: Grid): Pos { grid.forEachIndexed { y, row -> val x = row.indexOf('S') if (x != -1) { return Pos(x, y) } } throw IllegalArgumentException("No starting position!") } private val directions = listOf(this::north, this::east, this::south, this::west) private val canGoNorth = setOf('S', '|', 'L', 'J') private val canGoEast = setOf('S', '-', 'L', 'F') private val canGoSouth = setOf('S', '|', '7', 'F') private val canGoWest = setOf('S', '-', 'J', '7') private fun north(grid: Grid, pos: Pos): Pos? { if (pos.y == 0) return null return testDirection(grid, pos, pos.copy(y = pos.y - 1), canGoNorth, canGoSouth) } private fun east(grid: Grid, pos: Pos): Pos? { if (pos.x == grid[0].length - 1) return null return testDirection(grid, pos, pos.copy(x = pos.x + 1), canGoEast, canGoWest) } private fun south(grid: Grid, pos: Pos): Pos? { if (pos.y == grid.size - 1) return null return testDirection(grid, pos, pos.copy(y = pos.y + 1), canGoSouth, canGoNorth) } private fun west(grid: Grid, pos: Pos): Pos? { if (pos.x == 0) return null return testDirection(grid, pos, pos.copy(x = pos.x - 1), canGoWest, canGoEast) } private fun testDirection(grid: Grid, pos: Pos, testPos: Pos, currAllowed: Set<Char>, testAllowed: Set<Char>): Pos? { val curr = grid[pos.y][pos.x] val test = grid[testPos.y][testPos.x] return if (curr in currAllowed && test in testAllowed) testPos else null } }
0
Kotlin
0
0
6972f6e3addae03ec1090b64fa1dcecac3bc275c
2,726
advent-of-code
MIT License
src/iii_conventions/MyDate.kt
pwojnowski
123,978,024
true
{"Kotlin": 73188, "Java": 4952}
package iii_conventions data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int) : Comparable<MyDate> { override fun compareTo(other: MyDate): Int { if (year != other.year) return year.compareTo(other.year) if (month != other.month) return month.compareTo(other.month) return dayOfMonth.compareTo(other.dayOfMonth) } } operator fun MyDate.rangeTo(other: MyDate): DateRange = DateRange(this, other) operator fun MyDate.plus(interval: TimeInterval): MyDate { return addTimeIntervals(interval, 1) } operator fun MyDate.plus(repeatedInterval: RepeatedTimeInterval): MyDate { var date = this for (i in 1..(repeatedInterval.times)) { date += repeatedInterval.interval } return date } class RepeatedTimeInterval(val interval: TimeInterval, val times: Int) enum class TimeInterval { DAY, WEEK, YEAR; operator fun times(times: Int): RepeatedTimeInterval = RepeatedTimeInterval(this, times) } // 1st solution: implement ClosedRange interface class DateRange(override val start: MyDate, override val endInclusive: MyDate) : ClosedRange<MyDate>, Iterator<MyDate> { private var currentDate = start override fun hasNext(): Boolean = currentDate <= endInclusive override fun next(): MyDate { // what in case of no further elements? val result = currentDate if (hasNext()) currentDate = currentDate.nextDay() return result } // 2nd solution: implement "contains" method to allow "in" operator // operator fun contains(date: MyDate): Boolean { // return start <= date && date <= endInclusive // } }
0
Kotlin
0
0
1e973bd2b787321a04e97dda0f077bbac7211911
1,648
kotlin-koans
MIT License
kotlin/13_sorts/BucketSort.kt
willpyshan13
225,825,279
true
{"Python": 148296, "C": 144551, "C++": 131943, "Java": 101378, "Scala": 97442, "Rust": 77415, "Go": 73304, "PHP": 69589, "JavaScript": 62356, "Kotlin": 56424, "C#": 41255, "TypeScript": 38704, "Objective-C": 27661, "Swift": 23431, "HTML": 1582, "Shell": 35}
/** * @Description:桶排序算法 * @Author: Hoda * @Date: Create in 2019-06-01 * @Modified By: * @Modified Date: */ object BucketSort { /** * 桶排序 * * @param arr 数组 * @param bucketSize 桶容量 */ fun bucketSort(arr: IntArray, bucketSize: Int) { if (arr.size < 2) { return } // 数组最小值 var minValue = arr[0] // 数组最大值 var maxValue = arr[1] for (i in arr.indices) { if (arr[i] < minValue) { minValue = arr[i] } else if (arr[i] > maxValue) { maxValue = arr[i] } } // 桶数量 val bucketCount = (maxValue - minValue) / bucketSize + 1 val buckets = Array(bucketCount) { IntArray(bucketSize) } val indexArr = IntArray(bucketCount) // 将数组中值分配到各个桶里 for (i in arr.indices) { val bucketIndex = (arr[i] - minValue) / bucketSize if (indexArr[bucketIndex] == buckets[bucketIndex].length) { ensureCapacity(buckets, bucketIndex) } buckets[bucketIndex][indexArr[bucketIndex]++] = arr[i] } // 对每个桶进行排序,这里使用了快速排序 var k = 0 for (i in buckets.indices) { if (indexArr[i] == 0) { continue } quickSortC(buckets[i], 0, indexArr[i] - 1) for (j in 0 until indexArr[i]) { arr[k++] = buckets[i][j] } } } /** * 数组扩容 * * @param buckets * @param bucketIndex */ private fun ensureCapacity( buckets: Array<IntArray>, bucketIndex: Int ) { val tempArr = buckets[bucketIndex] val newArr = IntArray(tempArr.size * 2) for (j in tempArr.indices) { newArr[j] = tempArr[j] } buckets[bucketIndex] = newArr } /** * 快速排序递归函数 * * @param arr * @param p * @param r */ private fun quickSortC(arr: IntArray, p: Int, r: Int) { if (p >= r) { return } val q = partition(arr, p, r) quickSortC(arr, p, q - 1) quickSortC(arr, q + 1, r) } /** * 分区函数 * * @param arr * @param p * @param r * @return 分区点位置 */ private fun partition(arr: IntArray, p: Int, r: Int): Int { val pivot = arr[r] var i = p for (j in p until r) { if (arr[j] <= pivot) { swap(arr, i, j) i++ } } swap(arr, i, r) return i } /** * 交换 * * @param arr * @param i * @param j */ private fun swap(arr: IntArray, i: Int, j: Int) { if (i == j) { return } val tmp = arr[i] arr[i] = arr[j] arr[j] = tmp } }
0
Python
0
1
40dd1d3c828ac8f8486beacd1777da88deaabb50
3,039
algo
Apache License 2.0
src/main/kotlin/adventOfCode2023/Day12.kt
TetraTsunami
726,140,343
false
{"Kotlin": 80024}
package adventOfCode2023 import util.* @Suppress("unused") class Day12(input: String, context: RunContext = RunContext.PROD) : Day(input, context) { val variationsMemo = mutableMapOf<Triple<List<Char>, List<Int>, Boolean>, Long>() override fun solve() { var s1 = 0L for (line in lines) { val (springs, inter) = line.split(" ") val nums = inter.split(",").map { it.toInt() } val vars = numVariations(springs.toList(), nums, false) s1 += vars } a(s1) var s2 = 0L for (line in lines) { var (springs, inter) = line.split(" ") springs = (0..4).map { springs }.joinToString("?") val inter2 = inter.split(",").map { it.toInt() } val nums = (0..4).map { inter2 }.flatten() val vars = numVariations(springs.toList(), nums, false) s2 += vars } a(s2) } fun numVariations(s: List<Char>, badSprings: List<Int>, decreasing: Boolean): Long { // base case: no bad springs, no more string if (s.isEmpty()) { return if (badSprings.isEmpty() || (badSprings[0] == 0 && badSprings.size == 1)) 1L else 0L } if (badSprings.isEmpty()) { return if (s.none { it == '#' }) 1L else 0L } if (badSprings[0] < 0) return 0 // ???.### 1,1,3 // -> .??.### 1,1,3 // -> #??.### 0,1,3 val firstChar = s.first() return variationsMemo.getOrPut(Triple(s, badSprings, decreasing)) { when (firstChar) { '#' -> hash(s, badSprings) '.' -> dot(s, badSprings, decreasing) '?' -> hash(s, badSprings) + dot(s, badSprings, decreasing) else -> 0 } } } fun hash(s: List<Char>, b: List<Int>): Long { // remove first char // decrement first bad spring return numVariations(s.drop(1), b.toMutableList().let { it[0]-- ; it }, true) } fun dot(s: List<Char>, b: List<Int>, decreasing: Boolean): Long { // remove first char, respect spacing if (b[0] == 0) { return numVariations(s.drop(1), b.drop(1), false) } if (decreasing) return 0 return numVariations(s.drop(1), b, false) } }
0
Kotlin
0
0
78d1b5d1c17122fed4f4e0a25fdacf1e62c17bfd
2,344
AdventOfCode2023
Apache License 2.0
src/main/kotlin/com/nibado/projects/advent/y2016/Day13.kt
nielsutrecht
47,550,570
false
null
package com.nibado.projects.advent.y2016 import com.nibado.projects.advent.Day import com.nibado.projects.advent.Point import com.nibado.projects.advent.collect.Maze import com.nibado.projects.advent.search.BreadthFirst object Day13 : Day { private val input = 1362 private val solution : Map<Point, Int> by lazy { solve(40,40) } private fun solve(width: Int, height: Int) : Map<Point, Int> { val maze = Maze(width, height) for(y in 0 until height) { for(x in 0 until width) { val hash = x * x + 3 * x + 2 * x * y + y + y * y + input val wall = hash.toString(2).toCharArray().count { it == '1' } % 2 == 1 maze.set(x, y, wall) } } return (0 .. 39).flatMap { x -> ( 0 .. 39).map { y -> Point(x, y) } } .filter { maze.inBound(it) } .filterNot { maze.isWall(it) } .map { it to BreadthFirst.search(maze, Point(1, 1), it).toSet().size - 1 } .filter { it.second >= 0 }.toMap() } override fun part1() = solution[Point(31,39)]!!.toString() override fun part2() = solution.values.filter { it <= 50 }.count().toString() }
1
Kotlin
0
15
b4221cdd75e07b2860abf6cdc27c165b979aa1c7
1,209
adventofcode
MIT License
2023/day04-25/src/main/kotlin/Day11.kt
CakeOrRiot
317,423,901
false
{"Kotlin": 62169, "Python": 56994, "C#": 20675, "Rust": 10417}
import java.io.File import java.math.BigInteger import java.util.* import kotlin.math.abs import kotlin.math.max import kotlin.math.min class Day11 { fun solve1() { val grid = File("inputs/11.txt").inputStream().bufferedReader().lineSequence().map { it.toMutableList() } .toMutableList() val rowsWithGalaxy = (0..<grid.count()).toSortedSet() val colsWithGalaxy = (0..<grid.count()).toSortedSet() val galaxies = emptySet<Point>().toMutableSet() for (i in 0..<grid.count()) { for (j in 0..<grid.count()) { if (grid[i][j] == '#') { rowsWithGalaxy.remove(i) colsWithGalaxy.remove(j) galaxies.add(Point(i, j)) } } } var res = 0L for (g1 in galaxies) for (g2 in galaxies) { var dist = abs(g1.x - g2.x) + abs(g1.y - g2.y) val minX = min(g1.x, g2.x) val maxX = max(g1.x, g2.x) val minY = min(g1.y, g2.y) val maxY = max(g1.y, g2.y) dist += rowsWithGalaxy.subSet(minX, maxX).count() dist += colsWithGalaxy.subSet(minY, maxY).count() res += dist } println(res / 2) } fun solve2() { val grid = File("inputs/11.txt").inputStream().bufferedReader().lineSequence().map { it.toMutableList() } .toMutableList() val rowsWithGalaxy = (0..<grid.count()).toSortedSet() val colsWithGalaxy = (0..<grid.count()).toSortedSet() val galaxies = emptySet<Point>().toMutableSet() for (i in 0..<grid.count()) { for (j in 0..<grid.count()) { if (grid[i][j] == '#') { rowsWithGalaxy.remove(i) colsWithGalaxy.remove(j) galaxies.add(Point(i, j)) } } } var res = BigInteger.ZERO val resizeConst = 1000000.toBigInteger() for (g1 in galaxies) for (g2 in galaxies) { val minX = min(g1.x, g2.x) val maxX = max(g1.x, g2.x) val minY = min(g1.y, g2.y) val maxY = max(g1.y, g2.y) val rowsCnt = rowsWithGalaxy.subSet(minX, maxX).count().toBigInteger() val colsCnt = colsWithGalaxy.subSet(minY, maxY).count().toBigInteger() var dist = ((abs(g1.x - g2.x) + abs(g1.y - g2.y)).toBigInteger() - rowsCnt - colsCnt) dist += BigInteger.ZERO.max((rowsCnt * resizeConst)) dist += BigInteger.ZERO.max((colsCnt * resizeConst)) res += dist } println(res / 2.toBigInteger()) } data class Point(val x: Int, val y: Int) }
0
Kotlin
0
0
8fda713192b6278b69816cd413de062bb2d0e400
2,728
AdventOfCode
MIT License
dcp_kotlin/src/main/kotlin/dcp/day317/day317.kt
sraaphorst
182,330,159
false
{"C++": 577416, "Kotlin": 231559, "Python": 132573, "Scala": 50468, "Java": 34742, "CMake": 2332, "C": 315}
package dcp.day317 // day317.kt // By <NAME>, 2020. /** * Brute force approach: O(N) time. */ fun andIntBF(x: Int, y: Int): Int { require(x <= y) tailrec fun aux(result: Int = x, i: Int = x + 1): Int = when (i) { y + 1 -> result else -> aux(result and i, i + 1) } return aux() } fun andIntBF(ir: IntRange) = andIntBF(ir.first(), ir.last()) /** * We want to find the highest differing bit between x and y. * Say x = 111000 * y = 111100 * The highest differing bit is 2^2. Every number between x and y will be anded together * to get the result, and thus to get from x to y, every number at and below the highest * differing bit will appear: * 111000 * 111001 * 111010 * 111011 * 111100 * Thus, these positions will all contain a number with a 0 in the bit position, so * they will have a 0 in the final result. * * Thus, we can simply shift both x and y right until they are equal, and then shift them * left to get them back to their original positions, at which point, they are the and * of all the numbers x to y. */ fun andInt(x: Int, y: Int): Int { require(x <= y) tailrec fun aux(i: Int = 0, xs: Int = x, ys: Int = y): Int = when (xs) { ys -> xs shl i else -> aux(i+1, xs shr 1, ys shr 1) } return aux() } fun main() { for (i in 0 until 32) for (j in i until 32) if (andInt(i, j) != 0) println("$i, $j ${andInt(i, j)} ${andIntBF(i, j)}") }
0
C++
1
0
5981e97106376186241f0fad81ee0e3a9b0270b5
1,499
daily-coding-problem
MIT License
kotlin/strings/AhoCorasick.kt
polydisc
281,633,906
true
{"Java": 540473, "Kotlin": 515759, "C++": 265630, "CMake": 571}
package strings // https://en.wikipedia.org/wiki/Aho–Corasick_algorithm class AhoCorasick { val ALPHABET_SIZE = 26 val MAX_STATES = 200000 var transitions = Array(MAX_STATES) { IntArray(ALPHABET_SIZE) } var sufflink = IntArray(MAX_STATES) var escape = IntArray(MAX_STATES) var states = 1 fun addString(s: String): Int { var v = 0 for (c in s.toCharArray()) { (c -= 'a').toChar() if (transitions[v][c.toInt()] == 0) { transitions[v][c.toInt()] = states++ } v = transitions[v][c.toInt()] } escape[v] = v return v } fun buildLinks() { val q = IntArray(MAX_STATES) var s = 0 var t = 1 while (s < t) { val v = q[s++] val u = sufflink[v] if (escape[v] == 0) { escape[v] = escape[u] } for (c in 0 until ALPHABET_SIZE) { if (transitions[v][c] != 0) { q[t++] = transitions[v][c] sufflink[transitions[v][c]] = if (v != 0) transitions[u][c] else 0 } else { transitions[v][c] = transitions[u][c] } } } } companion object { // Usage example fun main(args: Array<String?>?) { val ahoCorasick = AhoCorasick() ahoCorasick.addString("a") ahoCorasick.addString("aa") ahoCorasick.addString("abaaa") ahoCorasick.buildLinks() val t = ahoCorasick.transitions val e = ahoCorasick.escape val s = "abaa" var state = 0 for (i in 0 until s.length()) { state = t[state][s.charAt(i) - 'a'] if (e[state] != 0) System.out.println(i) } } } }
1
Java
0
0
4566f3145be72827d72cb93abca8bfd93f1c58df
1,891
codelibrary
The Unlicense
src/main/java/challenges/cracking_coding_interview/bit_manipulation/next_number/QuestionB.kt
ShabanKamell
342,007,920
false
null
package challenges.cracking_coding_interview.bit_manipulation.next_number /** * Given a positive integer, print the next smallest and the next largest number that have * the same number of 1 bits in their binary representation. */ object QuestionB { fun getNext(n: Int): Int { var n = n var c = n var c0 = 0 var c1 = 0 while (c and 1 == 0 && c != 0) { c0++ c = c shr 1 } while (c and 1 == 1) { c1++ c = c shr 1 } /* If c is 0, then n is a sequence of 1s followed by a sequence of 0s. This is already the biggest * number with c1 ones. Return error. */if (c0 + c1 == 31 || c0 + c1 == 0) { return -1 } val pos = c0 + c1 // position of right-most non-trailing zero (where the right most bit is bit 0) /* Flip the right-most non-trailing zero (which will be at position pos) */n = n or (1 shl pos) // Flip right-most non-trailing zero /* Clear all bits to the right of pos. * Example with pos = 5 * (1) Shift 1 over by 5 to create 0..0100000 [ mask = 1 << pos ] * (2) Subtract 1 to get 0..0011111 [ mask = mask - 1 ] * (3) Flip all the bits by using '~' to get 1..1100000 [ mask = ~mask ] * (4) AND with n */n = n and ((1 shl pos) - 1).inv() // Clear all bits to the right of pos /* Put (ones-1) 1s on the right by doing the following: * (1) Shift 1 over by (ones-1) spots. If ones = 3, this gets you 0..0100 * (2) Subtract one from that to get 0..0011 * (3) OR with n */n = n or (1 shl c1 - 1) - 1 return n } fun getPrev(n: Int): Int { var n = n var temp = n var c0 = 0 var c1 = 0 while (temp and 1 == 1) { c1++ temp = temp shr 1 } /* If temp is 0, then the number is a sequence of 0s followed by a sequence of 1s. This is already * the smallest number with c1 ones. Return -1 for an error. */if (temp == 0) { return -1 } while (temp and 1 == 0 && temp != 0) { c0++ temp = temp shr 1 } val p = c0 + c1 // position of right-most non-trailing one (where the right most bit is bit 0) /* Flip right-most non-trailing one. * Example: n = 00011100011. * c1 = 2 * c0 = 3 * pos = 5 * * Build up a mask as follows: * (1) ~0 will be a sequence of 1s * (2) shifting left by p + 1 will give you 11.111000000 (six 0s) * (3) ANDing with n will clear the last 6 bits * n is now 00011000000 */n = n and (0.inv() shl p + 1) // clears from bit p onwards (to the right) /* Create a sequence of (c1+1) 1s as follows * (1) Shift 1 to the left (c1+1) times. If c1 is 2, this will give you 0..001000 * (2) Subtract one from that. This will give you 0..00111 */ val mask = (1 shl c1 + 1) - 1 // Sequence of (c1+1) ones /* Move the ones to be right up next to bit p * Since this is a sequence of (c1+1) ones, and p = c1 + c0, we just need to * shift this over by (c0-1) spots. * If c0 = 3 and c1 = 2, then this will look like 00...0011100 * * Then, finally, we OR this with n. */n = n or (mask shl c0 - 1) return n } fun binPrint(i: Int) { println(i.toString() + ": " + Integer.toBinaryString(i)) } @JvmStatic fun main(args: Array<String>) { val i = 13948 val p1 = getPrev(i) val n1 = getNext(i) Tester.binPrint(p1) Tester.binPrint(n1) } }
0
Kotlin
0
0
ee06bebe0d3a7cd411d9ec7b7e317b48fe8c6d70
3,626
CodingChallenges
Apache License 2.0
src/main/kotlin/g1301_1400/s1371_find_the_longest_substring_containing_vowels_in_even_counts/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1301_1400.s1371_find_the_longest_substring_containing_vowels_in_even_counts // #Medium #String #Hash_Table #Bit_Manipulation #Prefix_Sum // #2023_06_06_Time_317_ms_(100.00%)_Space_49.1_MB_(100.00%) class Solution { private var result: Int? = null fun findTheLongestSubstring(s: String): Int { val arr = IntArray(s.length) var sum = 0 val set: Set<Char> = HashSet(mutableListOf('a', 'e', 'i', 'o', 'u')) for (i in 0 until s.length) { val c = s[i] if (set.contains(c)) { sum = if (sum and (1 shl 'a'.code - c.code) == 0) sum or (1 shl 'a'.code - c.code) else sum and (1 shl 'a'.code - c.code).inv() } arr[i] = sum } for (i in 0 until s.length) { if (result != null && result!! > s.length - i) { break } for (j in s.length - 1 downTo i) { val e = arr[j] val k = if (i - 1 < 0) 0 else arr[i - 1] val m = e xor k if (m == 0) { result = if (result == null) j - i + 1 else Math.max(result!!, j - i + 1) break } } } return if (result == null) 0 else result!! } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,311
LeetCode-in-Kotlin
MIT License
constraints/src/main/kotlin/com/alexb/constraints/core/solvers/RecursiveBacktrackingSolver.kt
alexbaryzhikov
201,620,351
false
null
/* Copyright 2019 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.alexb.constraints.core.solvers import com.alexb.constraints.core.Domain import com.alexb.constraints.core.Solver import com.alexb.constraints.utils.ConstraintEnv /** * Recursive problem solver with backtracking capabilities. * * @param forwardcheck If false forward checking will not be requested * to constraints while looking for solutions. */ class RecursiveBacktrackingSolver<V : Any, D : Any>( private val forwardcheck: Boolean = true ) : Solver<V, D> { override fun getSolution( domains: HashMap<V, Domain<D>>, constraints: ArrayList<ConstraintEnv<V, D>>, vconstraints: HashMap<V, ArrayList<ConstraintEnv<V, D>>> ): Map<V, D>? { val solutions = recursiveBacktracking(ArrayList(), domains, vconstraints, HashMap(), true) return if (solutions.isNotEmpty()) solutions[0] else null } override fun getSolutions( domains: HashMap<V, Domain<D>>, constraints: ArrayList<ConstraintEnv<V, D>>, vconstraints: HashMap<V, ArrayList<ConstraintEnv<V, D>>> ): List<Map<V, D>> { return recursiveBacktracking(ArrayList(), domains, vconstraints, HashMap(), false) } override fun getSolutionSequence( domains: HashMap<V, Domain<D>>, constraints: ArrayList<ConstraintEnv<V, D>>, vconstraints: HashMap<V, ArrayList<ConstraintEnv<V, D>>> ): Sequence<Map<V, D>> { throw UnsupportedOperationException() } private fun recursiveBacktracking( solutions: ArrayList<Map<V, D>>, domains: HashMap<V, Domain<D>>, vconstraints: HashMap<V, ArrayList<ConstraintEnv<V, D>>>, assignments: HashMap<V, D>, single: Boolean ): List<Map<V, D>> { val prioritizedVariables = ArrayList(domains.keys).apply { sortWith(compareBy({ -vconstraints[it]!!.size }, { domains[it]!!.size })) } var variable: V? = null for (v in prioritizedVariables) { if (v !in assignments) { variable = v break } } if (variable == null) { solutions.add(HashMap(assignments)) return solutions } val pushDomains: ArrayList<Domain<D>>? if (forwardcheck) { pushDomains = ArrayList() for (x in domains.keys) { if (x !in assignments) { pushDomains.add(domains[x]!!) } } } else { pushDomains = null } for (value in domains[variable]!!) { assignments[variable] = value pushDomains?.forEach { it.pushState() } var found = true for ((constraint, variables) in vconstraints[variable]!!) { if (!constraint(variables, domains, assignments, !pushDomains.isNullOrEmpty())) { // Value is not good. found = false break } } if (found) { // Value is good. Recurse and get next variable. recursiveBacktracking(solutions, domains, vconstraints, assignments, single) if (solutions.isNotEmpty() && single) { return solutions } } pushDomains?.forEach { it.popState() } } assignments.remove(variable) return solutions } }
0
Kotlin
0
0
e67ae6b6be3e0012d0d03988afa22236fd62f122
4,016
kotlin-constraints
Apache License 2.0
src/chapter3/section5/ex30_DuplicatesRevisited.kt
w1374720640
265,536,015
false
{"Kotlin": 1373556}
package chapter3.section5 import chapter2.section5.ex31_Distinct import extensions.formatInt import extensions.random import extensions.spendTimeMillis import kotlin.math.pow /** * 重复元素(续) * 使用3.5.2.1节的dedup过滤器重新完成练习2.5.31,比较两种解决方法的运行时间 * 然后使用dedup运行实验,其中N=10⁷、10⁸和10⁹ * 使用随机的long值重新完成实验并讨论结果 * * 解:应该是统计不重复元素的数量而不是重复元素,两个数相等记数量为1 * [M]代表随机值的取值范围0~M-1,[N]代表元素数量,[T]代表重复次数 */ fun ex30_DuplicatesRevisited(M: Int, N: Int, T: Int): Pair<Int, Double> { var count = 0 repeat(T) { val set = LinearProbingHashSET<Int>() repeat(N) { set.add(random(M)) } count += set.size() } val expect = M * (1 - Math.E.pow(N.toDouble() / M * -1)) return count / T to expect } fun main() { val T = 10 val N = 100_0000 var M = N / 2 repeat(3) { var count1 = 0 var count2 = 0 val time1 = spendTimeMillis { count1 = ex31_Distinct(M, N, T).first } val time2 = spendTimeMillis { count2 = ex30_DuplicatesRevisited(M, N, T).first } println("N:${formatInt(N, 7)} M:${formatInt(M, 7)}") println("count1=$count1 time1=$time1 ms") println("count2=$count2 time2=$time2 ms") println() M *= 2 } }
0
Kotlin
1
6
879885b82ef51d58efe578c9391f04bc54c2531d
1,512
Algorithms-4th-Edition-in-Kotlin
MIT License
src/main/kotlin/se/brainleech/adventofcode/aoc2022/Aoc2022Day07.kt
fwangel
435,571,075
false
{"Kotlin": 150622}
package se.brainleech.adventofcode.aoc2022 import se.brainleech.adventofcode.compute import se.brainleech.adventofcode.readLines import se.brainleech.adventofcode.verify class Aoc2022Day07 { interface FileOrDirectory { val name: String fun size() : Int } data class File(override val name: String, val size: Int) : FileOrDirectory { override fun size() = size } data class Directory(override val name: String, private var contents: MutableList<FileOrDirectory> = mutableListOf()) : FileOrDirectory { fun addEntry(entry: String) { val (info, name) = entry.split(" ") when (info) { "dir" -> contents.add(Directory(name)) else -> contents.add(File(name, info.toInt())) } } fun getDirectory(name: String) : Directory { return contents .filterIsInstance<Directory>() .firstOrNull { entry -> entry.name == name } ?: Directory(name) } override fun size() = contents.sumOf { entry -> entry.size() } } private infix fun String.invokes(command: String) = this.startsWith("$ $command") private fun String.listsAnything() = !this.startsWith("$ ") private fun String.argument() = this.substringAfterLast(' ') private fun MutableList<String>.nextCommand() = this.removeFirst() private fun MutableList<String>.nextEntry() = this.removeFirst() private fun MutableList<String>.root() = this.clear().also { this.add("/") } private fun MutableList<String>.parent() = this.removeLast() private fun MutableList<String>.cd(directory: String) = this.add(directory) private fun MutableList<String>.path() = "/" + this.joinToString("/").trimStart('/') private fun List<String>.toFileSystem() : MutableMap<String, Directory> { if (this.isEmpty()) return mutableMapOf() val lines = this.toMutableList().also { it.add("$ exit") } val fileSystem = mutableMapOf("/" to Directory("/")) val currentPath = mutableListOf("/") while (lines.isNotEmpty()) { val commandLine = lines.nextCommand() when { commandLine invokes "cd /" -> currentPath.root() commandLine invokes "cd .." -> currentPath.parent() commandLine invokes "cd " -> { val directoryName = commandLine.argument() val subDirectory = fileSystem[currentPath.path()]!!.getDirectory(directoryName) currentPath.cd(directoryName) fileSystem.putIfAbsent(currentPath.path(), subDirectory) } commandLine invokes "ls" -> { val path = currentPath.path() while (lines.first().listsAnything()) { fileSystem[path]!!.addEntry(lines.nextEntry()) } } } } return fileSystem } fun part1(input: List<String>) : Int { return input.toFileSystem().values .filter { dir -> dir.size() <= 100_000 } .sumOf { dir -> dir.size() } } fun part2(input: List<String>) : Int { val directories = input.toFileSystem().values val used = directories.first().size() val free = 70_000_000 - used return directories .filter { dir -> (free + dir.size()) >= 30_000_000 } .minOf { dir -> dir.size() } } } fun main() { val solver = Aoc2022Day07() val prefix = "aoc2022/aoc2022day07" val testData = readLines("$prefix.test.txt") val realData = readLines("$prefix.real.txt") verify(954_37, solver.part1(testData)) compute({ solver.part1(realData) }, "$prefix.part1 = ") verify(24_933_642, solver.part2(testData)) compute({ solver.part2(realData) }, "$prefix.part2 = ") }
0
Kotlin
0
0
0bba96129354c124aa15e9041f7b5ad68adc662b
3,931
adventofcode
MIT License
src/Day06.kt
wujingwe
574,096,169
false
null
fun main() { fun findMarker(input: String, size: Int): Int { return input.windowed(size).indexOfFirst { it.toSet().size == size } + size } fun part1(inputs: String): Int { return findMarker(inputs, 4) } fun part2(inputs: String): Int { return findMarker(inputs, 14) } val testInput = readText("../data/Day06_test") check(part1(testInput) == 7) check(part1("bvwbjplbgvbhsrlpgdmjqwftvncz") == 5) check(part1("nppdvjthqldpwncqszvftbrmjlhg") == 6) check(part1("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg") == 10) check(part1("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw") == 11) check(part2(testInput) == 19) check(part2("bvwbjplbgvbhsrlpgdmjqwftvncz") == 23) check(part2("nppdvjthqldpwncqszvftbrmjlhg") == 23) check(part2("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg") == 29) check(part2("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw") == 26) val input = readText("../data/Day06") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
a5777a67d234e33dde43589602dc248bc6411aee
992
advent-of-code-kotlin-2022
Apache License 2.0
ast-transformations-core/src/test/kotlin/org/jetbrains/research/ml/ast/util/FileTestUtil.kt
JetBrains-Research
301,993,261
false
{"Kotlin": 148658, "Python": 27810}
package org.jetbrains.research.ml.ast.util import java.io.File enum class Extension(val value: String) { Py(".py"), Xml(".xml") } enum class Type { Input, Output } class TestFileFormat(private val prefix: String, private val extension: Extension, val type: Type) { data class TestFile(val file: File, val type: Type, val number: Number) fun check(file: File): TestFile? { val number = "(?<=${prefix}_)\\d+(?=(_.*)?${extension.value})".toRegex().find(file.name)?.value?.toInt() return number?.let { TestFile(file, type, number) } } fun match(testFile: TestFile): Boolean { return testFile.type == type } } object FileTestUtil { val File.content: String get() = this.readText().removeSuffix("\n") /** * We assume the format of the test files will be: * * inPrefix_i_anySuffix.inExtension * outPrefix_i_anySuffix.outExtension, * * where: * inPrefix and outPrefix are set in [inFormat] and [outFormat] together with extensions, * i is a number; two corresponding input and output files should have the same number, * suffixes can by any symbols not necessary the same for the corresponding files. */ fun getInAndOutFilesMap( folder: String, inFormat: TestFileFormat = TestFileFormat("in", Extension.Py, Type.Input), outFormat: TestFileFormat? = null ): Map<File, File?> { val (files, folders) = File(folder).listFiles().orEmpty().partition { it.isFile } // Process files in the given folder val inAndOutFilesGrouped = files.mapNotNull { inFormat.check(it) ?: outFormat?.check(it) }.groupBy { it.number } val inAndOutFilesMap = inAndOutFilesGrouped.map { (number, fileInfoList) -> val (f1, f2) = if (outFormat == null) { require(fileInfoList.size == 1) { "There are less or more than 1 test files with number $number" } Pair(fileInfoList.first(), null) } else { require(fileInfoList.size == 2) { "There are less or more than 2 test files with number $number" } fileInfoList.sortedBy { it.type }.zipWithNext().first() } require(inFormat.match(f1)) { "The input file does not match the input format" } outFormat?.let { require(f2 != null && outFormat.match(f2)) { "The output file does not match the output format" } } f1.file to f2?.file }.sortedBy { it.first.name }.toMap() outFormat?.let { require(inAndOutFilesMap.values.mapNotNull { it }.size == inAndOutFilesMap.values.size) { "Output tests" } } // Process all other nested files return folders.sortedBy { it.name }.map { getInAndOutFilesMap(it.absolutePath, inFormat, outFormat) } .fold(inAndOutFilesMap, { a, e -> a.plus(e) }) } }
0
Kotlin
2
17
aff0459b2018f63c1295edc0022556b30113b9c5
2,908
bumblebee
MIT License
kotlin-math-2/src/main/kotlin/com/baeldung/math/sumofprimes/SumOfPrimes.kt
Baeldung
260,481,121
false
{"Kotlin": 1476024, "Java": 43013, "HTML": 4883}
package com.baeldung.math.sumofprimes fun checkPrimeUsingBruteForce(number: Int): Boolean { if (number <= 1) return false for (i in 2 until number) { if (number % i == 0) { return false } } return true } fun canBeExpressedAsSumOfTwoPrimesUsingBruteForceApproach(n: Int): Boolean { for (i in 2..n / 2) { if (checkPrimeUsingBruteForce(i) && checkPrimeUsingBruteForce(n - i)) { return true } } return false } fun sieveOfEratosthenes(n: Int): BooleanArray { val primes = BooleanArray(n + 1) { true } primes[0] = false primes[1] = false for (p in 2..n) { if (primes[p]) { for (i in p * p..n step p) { primes[i] = false } } } return primes } fun canBeExpressedAsSumOfTwoPrimesUsingSieveOfEratosthenes(n: Int): Boolean { if (n < 2) return false val primes = sieveOfEratosthenes(n) for (i in 2 until n) { if (primes[i] && primes[n - i]) { return true } } return false }
10
Kotlin
273
410
2b718f002ce5ea1cb09217937dc630ff31757693
1,079
kotlin-tutorials
MIT License
src/main/kotlin/me/peckb/aoc/_2019/calendar/day18/CaveDijkstra.kt
peckb1
433,943,215
false
{"Kotlin": 956135}
package me.peckb.aoc._2019.calendar.day18 import me.peckb.aoc._2019.calendar.day18.Day18.* import me.peckb.aoc.pathing.Dijkstra import me.peckb.aoc.pathing.DijkstraNodeWithCost class CaveDijkstra( private val caves: Map<Area, Section>, private val result: MutableMap<Section.Source.Key, Route>, private val doorsByArea: MutableMap<Area, Set<Section.Door>>, private val sourceArea: Area ) : Dijkstra<Area, Distance, CaveWithDistance> { override fun Area.withCost(cost: Distance) = CaveWithDistance(this, cost).withResult(result).withDoorsByArea(doorsByArea).withCaves(caves).withSourceArea(sourceArea) override fun Distance.plus(cost: Distance) = this + cost override fun maxCost() = Int.MAX_VALUE override fun minCost() = 0 } class CaveWithDistance(private val area: Area, private val distance: Distance) : DijkstraNodeWithCost<Area, Distance> { private lateinit var caves: Map<Area, Section> private lateinit var doorsByArea: MutableMap<Area, Set<Section.Door>> private lateinit var result: MutableMap<Section.Source.Key, Route> private lateinit var sourceArea: Area fun withResult(result: MutableMap<Section.Source.Key, Route>) = apply { this.result = result } fun withDoorsByArea(doorsByArea: MutableMap<Area, Set<Section.Door>>) = apply { this.doorsByArea = doorsByArea } fun withCaves(caves: Map<Area, Section>) = apply { this.caves = caves } fun withSourceArea(sourceArea: Area) = apply { this.sourceArea = sourceArea } override fun compareTo(other: DijkstraNodeWithCost<Area, Distance>): Int = distance.compareTo(other.cost()) override fun cost(): Distance = distance override fun node(): Area = area override fun neighbors(): List<CaveWithDistance> { var doors = doorsByArea[area]!! when (val section = caves[area]!!) { is Section.Door -> { doors = doors.plus(section) } is Section.Source.Key -> { result[section] = Route(distance, doors) if (area != sourceArea) { return emptyList() } } Section.Empty, Section.Wall, is Section.Source.Robot -> { /* ignore */ } } val (x, y) = area val neighborAreas = listOf( Area(x - 1, y), Area(x, y - 1), Area(x, y + 1), Area(x + 1, y) ) val neighborsToSearch = neighborAreas.mapNotNull { neighbor -> if (neighbor !in caves || neighbor in doorsByArea || caves[neighbor] is Section.Wall) { null } else { doorsByArea[neighbor] = doors neighbor } } return neighborsToSearch.map { CaveWithDistance(it, 1) } } }
0
Kotlin
1
3
2625719b657eb22c83af95abfb25eb275dbfee6a
2,560
advent-of-code
MIT License
Extra_primes/Kotlin/src/main/kotlin/ExtraPrimes.kt
ncoe
108,064,933
false
{"D": 425100, "Java": 399306, "Visual Basic .NET": 343987, "C++": 328611, "C#": 289790, "C": 216950, "Kotlin": 162468, "Modula-2": 148295, "Groovy": 146721, "Lua": 139015, "Ruby": 84703, "LLVM": 58530, "Python": 46744, "Scala": 43213, "F#": 21133, "Perl": 13407, "JavaScript": 6729, "CSS": 453, "HTML": 409}
private fun nextPrimeDigitNumber(n: Int): Int { return if (n == 0) { 2 } else when (n % 10) { 2 -> n + 1 3, 5 -> n + 2 else -> 2 + nextPrimeDigitNumber(n / 10) * 10 } } private fun isPrime(n: Int): Boolean { if (n < 2) { return false } if (n and 1 == 0) { return n == 2 } if (n % 3 == 0) { return n == 3 } if (n % 5 == 0) { return n == 5 } val wheel = intArrayOf(4, 2, 4, 2, 4, 6, 2, 6) var p = 7 while (true) { for (w in wheel) { if (p * p > n) { return true } if (n % p == 0) { return false } p += w } } } private fun digitSum(n: Int): Int { var nn = n var sum = 0 while (nn > 0) { sum += nn % 10 nn /= 10 } return sum } fun main() { val limit = 10000 var p = 0 var n = 0 println("Extra primes under $limit:") while (p < limit) { p = nextPrimeDigitNumber(p) if (isPrime(p) && isPrime(digitSum(p))) { n++ println("%2d: %d".format(n, p)) } } println() }
0
D
0
4
c2a9f154a5ae77eea2b34bbe5e0cc2248333e421
1,201
rosetta
MIT License
src/main/kotlin/g0801_0900/s0805_split_array_with_same_average/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0801_0900.s0805_split_array_with_same_average // #Hard #Array #Dynamic_Programming #Math #Bit_Manipulation #Bitmask // #2023_03_16_Time_142_ms_(100.00%)_Space_33.7_MB_(100.00%) @Suppress("NAME_SHADOWING") class Solution { private lateinit var nums: IntArray private lateinit var sums: IntArray fun splitArraySameAverage(nums: IntArray): Boolean { val len = nums.size if (len == 1) { return false } nums.sort() sums = IntArray(len + 1) for (i in 0 until len) { sums[i + 1] = sums[i] + nums[i] } val sum = sums[len] this.nums = nums var i = 1 val stop = len / 2 while (i <= stop) { if (sum * i % len == 0 && findSum(i, len, sum * i / len)) { return true } i++ } return false } private fun findSum(k: Int, pos: Int, target: Int): Boolean { var pos = pos if (k == 1) { while (true) { if (nums[--pos] <= target) { break } } return nums[pos] == target } var i = pos while (sums[i] - sums[i-- - k] >= target) { if (sums[k - 1] <= target - nums[i] && findSum(k - 1, i, target - nums[i])) { return true } } return false } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,424
LeetCode-in-Kotlin
MIT License
src/main/kotlin/com/github/shmvanhouten/adventofcode/day8/Screen.kt
SHMvanHouten
109,886,692
false
{"Kotlin": 616528}
package com.github.shmvanhouten.adventofcode.day8 import com.github.shmvanhouten.adventofcode.day8.PixelState.OFF import com.github.shmvanhouten.adventofcode.day8.PixelState.ON class Screen(private val width: Int, private val height: Int) { private var grid: Map<Int, Map<Int, PixelState>> = initializeGrid() private fun initializeGrid(): Map<Int, Map<Int, PixelState>> { val row = 0.until(width).associateBy({ it }, { OFF }) return 0.until(height).associateBy({it}, {row}) } fun turnOnPixelsTopLeft(width: Int, height: Int) { val xRange = 0.until(width) val yRange = 0.until(height) for (y in yRange) { if(grid.containsKey(y)) { var newRow = grid.getValue(y) for (x in xRange) { newRow = newRow.minus(x).plus(x to ON) } grid = grid.minus(y).plus(y to newRow) } } } fun rotateRowByAmount(row: Int, amount: Int) { val oldRow = grid.getValue(row) val rotatedRow = oldRow.entries.associateBy ({ calculateIndex(it.key + amount, width)}, {it.value }) grid = grid.minus(row).plus(row to rotatedRow) } fun rotateColumnByAmount(column: Int, amount: Int) { val mutableGrid = grid.toMutableMap() val mapOfNewPixelStateAtColumnForEachRow = grid.entries .associateBy({ calculateIndex(it.key + amount, height) }, { it.value.getValue(column) }) mapOfNewPixelStateAtColumnForEachRow.forEach { mutableGrid.put(it.key, mutableGrid.getValue(it.key).minus(column).plus(column to it.value)) } grid = mutableGrid } fun getPixel(x: Int, y: Int): PixelState { return grid.getValue(y).getValue(x) } fun amountOfPixelsLit(): Int = grid.values.sumBy { it.values.count { it == ON } } fun display() { for (row in grid.toSortedMap().values) { println(row.toSortedMap().values.map { if(it == ON) 'X' else ' ' }.joinToString("")) } } private fun calculateIndex(newIndex: Int, size: Int): Int { return if (newIndex < size) newIndex else newIndex - size } } enum class PixelState{ ON, OFF }
0
Kotlin
0
0
a8abc74816edf7cd63aae81cb856feb776452786
2,225
adventOfCode2016
MIT License
src/main/kotlin/leetcode/Problem2257.kt
fredyw
28,460,187
false
{"Java": 1280840, "Rust": 363472, "Kotlin": 148898, "Shell": 604}
package leetcode /** * https://leetcode.com/problems/count-unguarded-cells-in-the-grid/ */ class Problem2257 { fun countUnguarded(m: Int, n: Int, guards: Array<IntArray>, walls: Array<IntArray>): Int { val grid = Array(m) { IntArray(n) { UNGUARDED } } for ((r, c) in guards) { grid[r][c] = GUARD } for ((r, c) in walls) { grid[r][c] = WALL } for ((r, c) in guards) { // Up var i = r - 1 while (i >= 0 && (grid[i][c] != WALL && grid[i][c] != GUARD)) { grid[i][c] = GUARDED i-- } // Right i = c + 1 while (i < n && (grid[r][i] != WALL && grid[r][i] != GUARD)) { grid[r][i] = GUARDED i++ } // Down i = r + 1 while (i < m && (grid[i][c] != WALL && grid[i][c] != GUARD)) { grid[i][c] = GUARDED i++ } // Left i = c - 1 while (i >= 0 && (grid[r][i] != WALL && grid[r][i] != GUARD)) { grid[r][i] = GUARDED i-- } } var answer = 0 for (i in 0 until m) { for (j in 0 until n) { if (grid[i][j] == UNGUARDED) { answer++ } } } return answer } companion object { private const val GUARD = 1 private const val WALL = 2 private const val GUARDED = 3 private const val UNGUARDED = 4 } }
0
Java
1
4
a59d77c4fd00674426a5f4f7b9b009d9b8321d6d
1,629
leetcode
MIT License
src/main/aoc2020/Day8.kt
nibarius
154,152,607
false
{"Kotlin": 963896}
package aoc2020 class Day8(input: List<String>) { private data class Instruction(val operation: String, val argument: Int) private class Computer(val program: List<Instruction>) { var accumulator = 0 private set /** * Runs the program. Returns true if successful or false if an infinite loop was detected. */ fun run(): Boolean { var pc = 0 val seen = mutableSetOf<Int>() while (pc < program.size) { if (seen.contains(pc)) return false seen.add(pc) val (op, arg) = program[pc] when (op) { "acc" -> accumulator += arg "jmp" -> pc += arg - 1 } pc++ } return true } } private val program = input .map { it.split(" ") .let { (op, arg) -> Instruction(op, arg.toInt()) } } /** * Generate a sequence of all possible programs with one nop/jmp instruction swapped */ private fun generatePrograms(): Sequence<List<Instruction>> { val ret = mutableListOf<List<Instruction>>() for (i in program.indices) { val (op, arg) = program[i] if (op in listOf("nop", "jmp")) { val newOp = if (op == "nop") "jmp" else "nop" program.toMutableList() .apply { this[i] = Instruction(newOp, arg) } .also { ret.add(it) } } } return ret.asSequence() } fun solvePart1(): Int { return Computer(program).apply { run() }.accumulator } fun solvePart2(): Int { return generatePrograms() .map { Computer(it) } .first { it.run() } .accumulator } }
0
Kotlin
0
6
f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22
1,864
aoc
MIT License
special_shop.kt
drochecsp2017
416,443,867
false
{"C++": 3542, "Java": 2962, "Rust": 2396, "JavaScript": 1733, "Haskell": 1619, "C": 1590, "Kotlin": 1316, "Julia": 1237, "Lua": 1156, "Python": 1152}
import kotlin.math.round; class Parabola(potCount: Long, xMult: Long, yMult: Long) { private val coeffA = xMult + yMult; private val coeffB = -2 * yMult * potCount; private val coeffC = potCount * potCount * yMult; fun minXCoord(): Long { val numerator = -1.0 * coeffB; val denominator = coeffA * 2.0; val result = round(numerator / denominator); return result.toLong(); } fun solveAt(xCoord: Double): Long { val termA = xCoord * xCoord * coeffA; val termB = xCoord * coeffB; val termC = coeffC.toDouble(); val realResult = termA + termB + termC; return realResult.toLong(); } } fun solveCase(potCount: Long, xMult: Long, yMult: Long): Long { val eq = Parabola(potCount, xMult, yMult); val optimal_a_pots: Long = eq.minXCoord(); val soln: Long = eq.solveAt(optimal_a_pots.toDouble()); return soln; } fun parseTestCase(): Unit { val caseParams = readLine()!!.split(" "); val potsToBuy = caseParams[0].toLong(); val xCost = caseParams[1].toLong(); val yCost = caseParams[2].toLong(); val result = solveCase(potsToBuy, xCost, yCost); println(result); } fun main() { val caseCount = readLine()!!.toInt(); for (i in 1..caseCount) { parseTestCase(); } }
0
C++
0
0
20727ddecfc4e7b3c1c7a4024b8c1d4795cd2911
1,316
special_pots_shop
Creative Commons Zero v1.0 Universal
codechef/snackdown2021/qual/d_tl.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package codechef.snackdown2021.qual private fun solve() { val (n, m) = readInts() val nei = List(n) { mutableListOf<Int>() } repeat(m) { val (u, v) = readInts().map { it - 1 } nei[u].add(v); nei[v].add(u) } val degree = IntArray(n) { nei[it].size } val byDegree = List(n) { mutableSetOf<Int>() } for (v in nei.indices) byDegree[degree[v]].add(v) val mark = BooleanArray(n) var minDegree = 0 var maxSeenMinDegree = 0 val ans = IntArray(n) for (iter in nei.indices) { while (byDegree[minDegree].isEmpty()) minDegree++ maxSeenMinDegree = maxOf(maxSeenMinDegree, minDegree) val v = byDegree[minDegree].first() ans[v] = n - iter byDegree[minDegree].remove(v) mark[v] = true for (u in nei[v]) { if (mark[u]) continue byDegree[degree[u]].remove(u) degree[u]-- byDegree[degree[u]].add(u) minDegree = minOf(minDegree, degree[u]) } } println(maxSeenMinDegree) println(ans.joinToString(" ")) } @Suppress("UNUSED_PARAMETER") // Kotlin 1.2 fun main(args: Array<String>) = repeat(readInt()) { solve() } private fun readLn() = readLine()!! private fun readInt() = readLn().toInt() private fun readStrings() = readLn().split(" ") private fun readInts() = readStrings().map { it.toInt() }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
1,225
competitions
The Unlicense
hoon/HoonAlgorithm/src/main/kotlin/programmers/lv01/Lv1_12948_hide_number.kt
boris920308
618,428,844
false
{"Kotlin": 137657, "Swift": 35553, "Java": 1947, "Rich Text Format": 407}
package main.kotlin.programmers.lv01 /** * * https://school.programmers.co.kr/learn/courses/30/lessons/12948 * * 문제 설명 * 프로그래머스 모바일은 개인정보 보호를 위해 고지서를 보낼 때 고객들의 전화번호의 일부를 가립니다. * 전화번호가 문자열 phone_number로 주어졌을 때, 전화번호의 뒷 4자리를 제외한 나머지 숫자를 전부 *으로 가린 문자열을 리턴하는 함수, solution을 완성해주세요. * * 제한 조건 * phone_number는 길이 4 이상, 20이하인 문자열입니다. * 입출력 예 * phone_number return * "01033334444" "*******4444" * "027778888" "*****8888" */ fun main() { solution("01033334444") solution("027778888") } private fun solution(phone_number: String): String { var answer = "" val numLength = phone_number.length for(i in 1..numLength - 4) { answer += "*" } val result = answer + phone_number.subSequence(numLength - 4, numLength) return result } private fun secondSolution(phone_number: String): String { return "${"".padStart(phone_number.length - 4, '*')}${phone_number.takeLast(4)}" }
1
Kotlin
1
2
88814681f7ded76e8aa0fa7b85fe472769e760b4
1,164
HoOne
Apache License 2.0
src/main/kotlin/Day05.kt
SimonMarquis
434,880,335
false
{"Kotlin": 38178}
class Day05(raw: List<String>) { private val lines: List<Line> = raw.map(Line::parse) fun part1(): Int = lines .filter { it.isHorizontal() || it.isVertical() } .flatMap { it.points() } .groupingBy { it } .eachCount() .count { it.value >= 2 } fun part2(): Int = lines .flatMap { it.points() } .groupingBy { it } .eachCount() .count { it.value >= 2 } data class Point(val x: Int, val y: Int) data class Line(val src: Point, val dst: Point) { override fun toString(): String = "{$src -> $dst}" companion object { private val pattern = """(\d+),(\d+) -> (\d+),(\d+)""".toRegex() fun parse(string: String): Line { val (srcX, srcY, dstX, dstY) = pattern.find(string)!!.destructured return Line( src = Point(x = srcX.toInt(), y = srcY.toInt()), dst = Point(x = dstX.toInt(), y = dstY.toInt()), ) } } fun isVertical(): Boolean = src.x == dst.x fun isHorizontal(): Boolean = src.y == dst.y fun points(): Sequence<Point> = sequence(src.x, dst.x) .zip(sequence(src.y, dst.y)) .map { (x, y) -> Point(x, y) } private fun sequence(src: Int, dst: Int) = when { src < dst -> (src..dst).asSequence() src > dst -> (src downTo dst).asSequence() else -> generateSequence { src } } } }
0
Kotlin
0
0
8fd1d7aa27f92ba352e057721af8bbb58b8a40ea
1,523
advent-of-code-2021
Apache License 2.0
app/src/main/java/tk/pokatomnik/mrakopediareader2/screens/categories/SortingType.kt
pokatomnik
551,521,498
false
{"Kotlin": 187257}
package tk.pokatomnik.mrakopediareader2.screens.categories import tk.pokatomnik.mrakopediareader2.domain.Category import tk.pokatomnik.mrakopediareader2.ui.components.SortDirection internal enum class SortingType { ALPHA, RATING, VOTED, QUANTITY } internal abstract class Sorting { abstract val sortDirection: SortDirection abstract val sortType: SortingType abstract fun sorted(items: List<Category>): List<Category> override fun toString(): String { return this::class.simpleName ?: "" } } internal class AlphaASC : Sorting() { override val sortDirection: SortDirection = SortDirection.ASC override val sortType: SortingType = SortingType.ALPHA override fun sorted(items: List<Category>): List<Category> { return items.sortedWith { a, b -> a.name.lowercase().compareTo(b.name.lowercase()) } } } internal class AlphaDESC : Sorting() { override val sortDirection: SortDirection = SortDirection.DESC override val sortType: SortingType = SortingType.ALPHA override fun sorted(items: List<Category>): List<Category> { return items.sortedWith { a, b -> b.name.lowercase().compareTo(a.name.lowercase()) } } } internal class RatingASC : Sorting() { override val sortDirection: SortDirection = SortDirection.ASC override val sortType: SortingType = SortingType.RATING override fun sorted(items: List<Category>): List<Category> { return items.sortedWith { a, b -> a.avgRating - b.avgRating } } } internal class RatingDESC : Sorting() { override val sortDirection: SortDirection = SortDirection.DESC override val sortType: SortingType = SortingType.RATING override fun sorted(items: List<Category>): List<Category> { return items.sortedWith { a, b -> b.avgRating - a.avgRating } } } internal class VotedASC : Sorting() { override val sortDirection: SortDirection = SortDirection.ASC override val sortType: SortingType = SortingType.VOTED override fun sorted(items: List<Category>): List<Category> { return items.sortedWith { a, b -> a.avgVoted - b.avgVoted } } } internal class VotedDESC : Sorting() { override val sortDirection: SortDirection = SortDirection.DESC override val sortType: SortingType = SortingType.VOTED override fun sorted(items: List<Category>): List<Category> { return items.sortedWith { a, b -> b.avgVoted - a.avgVoted } } } internal class QuantityASC : Sorting() { override val sortDirection: SortDirection = SortDirection.ASC override val sortType: SortingType = SortingType.QUANTITY override fun sorted(items: List<Category>): List<Category> { return items.sortedWith { a, b -> a.size - b.size } } } internal class QuantityDESC : Sorting() { override val sortDirection: SortDirection = SortDirection.DESC override val sortType: SortingType = SortingType.QUANTITY override fun sorted(items: List<Category>): List<Category> { return items.sortedWith { a, b -> b.size - a.size } } } internal val sortingMap = mapOf( AlphaASC::class.simpleName to AlphaASC(), AlphaDESC::class.simpleName to AlphaDESC(), RatingASC::class.simpleName to RatingASC(), RatingDESC::class.simpleName to RatingDESC(), VotedASC::class.simpleName to VotedASC(), VotedDESC::class.simpleName to VotedDESC(), QuantityASC::class.simpleName to QuantityASC(), QuantityDESC::class.simpleName to QuantityDESC(), )
7
Kotlin
0
0
16c4135887d08d5b966f1061cf4652b5523f09d7
3,629
MrakopediaReader2
MIT License
src/main/kotlin/kr/co/programmers/P161988.kt
antop-dev
229,558,170
false
{"Kotlin": 695315, "Java": 213000}
package kr.co.programmers // https://github.com/antop-dev/algorithm/issues/531 class P161988 { fun solution(sequence: IntArray): Long { val pulse1 = max(sequence, 1) // [1, -1, 1, ...] val pulse2 = max(sequence, -1) // [-1, 1, -1, ...] return maxOf(pulse1, pulse2) } private fun max(sequence: IntArray, start: Int): Long { val n = sequence.size val dp = LongArray(n) var sign = start for (i in 0 until n) { dp[i] = sequence[i] * sign * 1L sign *= -1 } var max = dp[0] for (i in 1 until n) { // dp[n] = n번째 원소를 포함했을 때의 최대값 dp[i] = maxOf(dp[i - 1] + dp[i], dp[i]) max = maxOf(max, dp[i]) } return max } }
1
Kotlin
0
0
9a3e762af93b078a2abd0d97543123a06e327164
807
algorithm
MIT License
src/main/kotlin/_0063_UniquePathsII.kt
ryandyoon
664,493,186
false
null
// https://leetcode.com/problems/unique-paths-ii fun uniquePathsWithObstacles(obstacleGrid: Array<IntArray>): Int { val lastRowIndex = obstacleGrid.lastIndex val lastColIndex = obstacleGrid.first().lastIndex val hasObstacle = obstacleGrid[lastRowIndex][lastColIndex] == 1 obstacleGrid[lastRowIndex][lastColIndex] = if (hasObstacle) 0 else 1 for (rowIndex in lastRowIndex - 1 downTo 0) { val row = obstacleGrid[rowIndex] if (row[lastColIndex] == 1 || obstacleGrid[rowIndex + 1][lastColIndex] == 0) { row[lastColIndex] = 0 } else { row[lastColIndex] = 1 } } for (colIndex in lastColIndex - 1 downTo 0) { val row = obstacleGrid.last() if (row[colIndex] == 1 || row[colIndex + 1] == 0) { row[colIndex] = 0 } else { row[colIndex] = 1 } } for (rowIndex in lastRowIndex - 1 downTo 0) { for (colIndex in lastColIndex - 1 downTo 0) { if (obstacleGrid[rowIndex][colIndex] == 1) { obstacleGrid[rowIndex][colIndex] = 0 } else { obstacleGrid[rowIndex][colIndex] = obstacleGrid[rowIndex + 1][colIndex] + obstacleGrid[rowIndex][colIndex + 1] } } } return obstacleGrid[0][0] }
0
Kotlin
0
0
7f75078ddeb22983b2521d8ac80f5973f58fd123
1,301
leetcode-kotlin
MIT License
src/aoc23/Day01.kt
mihassan
575,356,150
false
{"Kotlin": 123343}
@file:Suppress("PackageDirectoryMismatch") package aoc23.day01 import lib.Solution typealias Input = List<String> typealias Output = Int private val solution = object : Solution<Input, Output>(2023, "Day01") { override fun parse(input: String): Input = input.lines() override fun format(output: Output): String = "$output" override fun part1(input: Input): Output = input.sumOf { line -> val firstDigit = line.firstOrNull { it.isDigit() } ?: error("No first digit") val lastDigit = line.lastOrNull { it.isDigit() } ?: error("No last digit") "${firstDigit}${lastDigit}".toInt() } override fun part2(input: Input): Output = input.sumOf { line -> val firstDigit = numbers.findFirst(line)?.wordToInt() ?: error("No first digit") val lastDigit = numbers.findLast(line)?.wordToInt() ?: error("No last digit") "${firstDigit}${lastDigit}".toInt() } private fun Regex.findFirst(input: String): String? = this.find(input)?.value private fun Regex.findLast(input: String): String? = this.pattern.reversed().toRegex().find(input.reversed())?.value?.reversed() private fun String.wordToInt(): Int? = wordToIntMap[this] ?: toIntOrNull() private val numbers = """0|1|2|3|4|5|6|7|8|9|zero|one|two|three|four|five|six|seven|eight|nine""".toRegex() private val wordToIntMap = mapOf( "zero" to 0, "one" to 1, "two" to 2, "three" to 3, "four" to 4, "five" to 5, "six" to 6, "seven" to 7, "eight" to 8, "nine" to 9 ) } fun main() = solution.run()
0
Kotlin
0
0
698316da8c38311366ee6990dd5b3e68b486b62d
1,539
aoc-kotlin
Apache License 2.0
src/test/kotlin/chapter3/exercises/ex28/listing.kt
DavidGomesh
680,857,367
false
{"Kotlin": 204685}
package chapter3.exercises.ex28 import chapter3.Branch import chapter3.Leaf import chapter3.Tree import io.kotest.matchers.shouldBe import io.kotest.core.spec.style.WordSpec import utils.SOLUTION_HERE // tag::init[] fun <A, B> fold(ta: Tree<A>, l: (A) -> B, b: (B, B) -> B): B = when(ta){ is Leaf -> l(ta.value) is Branch -> b(fold(ta.left, l, b), fold(ta.right, l, b)) } fun <A> sizeF(ta: Tree<A>): Int = fold(ta, {_ -> 1}, {b1, b2 -> 1 + b1 + b2}) fun maximumF(ta: Tree<Int>): Int = fold(ta, {a -> a}, {b1, b2 -> maxOf(b1, b2)}) fun <A> depthF(ta: Tree<A>): Int = fold(ta, {_ -> 0}, {b1, b2 -> 1 + maxOf(b1, b2)}) fun <A, B> mapF(ta: Tree<A>, f: (A) -> B): Tree<B> = fold(ta, {a -> Leaf(f(a))}, {b1: Tree<B>, b2: Tree<B> -> Branch(b1, b2)}) // end::init[] //TODO: Enable tests by removing `!` prefix class Exercise28 : WordSpec({ "tree fold" should { val tree = Branch( Branch(Leaf(1), Leaf(2)), Branch( Leaf(3), Branch( Branch(Leaf(4), Leaf(5)), Branch( Leaf(21), Branch(Leaf(7), Leaf(8)) ) ) ) ) "generalise size" { sizeF(tree) shouldBe 15 } "generalise maximum" { maximumF(tree) shouldBe 21 } "generalise depth" { depthF(tree) shouldBe 5 } "generalise map" { mapF(tree) { it * 10 } shouldBe Branch( Branch(Leaf(10), Leaf(20)), Branch( Leaf(30), Branch( Branch(Leaf(40), Leaf(50)), Branch( Leaf(210), Branch(Leaf(70), Leaf(80)) ) ) ) ) } } })
0
Kotlin
0
0
41fd131cd5049cbafce8efff044bc00d8acddebd
2,038
fp-kotlin
MIT License
src/Day01.kt
ben-dent
572,931,260
false
{"Kotlin": 10265}
fun main() { fun getGroups(input: List<String>): List<List<Int>> { val toReturn = ArrayList<ArrayList<Int>>() var current = ArrayList<Int>(); for (s in input) { if (s.isEmpty()) { toReturn.add(current) current = ArrayList(); } else { current.add(s.toInt()) } } toReturn.add(current) return toReturn } fun part1(input: List<String>): Long { val groups = getGroups(input) return groups.maxOf { it.sum().toLong() } } fun part2(input: List<String>): Long { val groups = getGroups(input) return groups.map { it.sum() }.sortedDescending().take(3).sum().toLong() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000L) check(part2(testInput) == 45000L) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
2c3589047945f578b57ceab9b975aef8ddde4878
1,037
AdventOfCode2022Kotlin
Apache License 2.0
src/main/kotlin/com/askrepps/advent2021/day25/Day25.kt
askrepps
726,566,200
false
{"Kotlin": 191862}
/* * MIT License * * Copyright (c) 2021 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.askrepps.advent2021.day25 import com.askrepps.advent2021.util.getInputLines import java.io.File enum class Direction { Right, Down } data class GridCoordinates(val row: Int, val col: Int) data class CucumberState(val rows: Int, val cols: Int, val cucumbers: Map<GridCoordinates, Direction>) fun List<String>.toCucumberState(): CucumberState { val cucumbers = mutableMapOf<GridCoordinates, Direction>() for ((row, line) in this.withIndex()) { for ((col, c) in line.withIndex()) { val direction = when (c) { '>' -> Direction.Right 'v' -> Direction.Down else -> null } if (direction != null) { cucumbers[GridCoordinates(row, col)] = direction } } } return CucumberState(size, first().length, cucumbers) } fun CucumberState.getNextState(moveDirection: Direction): CucumberState { val newCucumbers = mutableMapOf<GridCoordinates, Direction>() for ((coordinates, direction) in cucumbers) { if (direction == moveDirection) { val proposedMove = when (direction) { Direction.Right -> GridCoordinates(coordinates.row, (coordinates.col + 1) % cols) Direction.Down -> GridCoordinates((coordinates.row + 1) % rows, coordinates.col) } if (cucumbers.containsKey(proposedMove)) { newCucumbers[coordinates] = direction } else { newCucumbers[proposedMove] = direction } } else { newCucumbers[coordinates] = direction } } return CucumberState(rows, cols, newCucumbers) } fun awaitCucumberStillness(initialState: CucumberState): Long { var step = 0L var currentState = initialState while (true) { val previousState = currentState currentState = currentState.getNextState(Direction.Right) currentState = currentState.getNextState(Direction.Down) step++ if (previousState == currentState) { return step } } } fun getPart1Answer(initialState: CucumberState) = awaitCucumberStillness(initialState) fun main() { val initialState = File("src/main/resources/day25.txt") .getInputLines().toCucumberState() println("The answer to part 1 is ${getPart1Answer(initialState)}") println("There is no part 2. Go back to enjoying the holidays!") }
0
Kotlin
0
0
89de848ddc43c5106dc6b3be290fef5bbaed2e5a
3,591
advent-of-code-kotlin
MIT License
parserkt-ext/src/commonMain/kotlin/org/parserkt/pat/ext/TriePatternMisc.kt
ParserKt
242,278,819
false
null
package org.parserkt.pat.ext import org.parserkt.* import org.parserkt.util.* import org.parserkt.pat.complex.TriePattern import org.parserkt.pat.complex.PairedTriePattern //// == BackTrie, DictTrie, LazyPairedTrie, GreedyPairedTrie == abstract class BackTrie<K, V>: PairedTriePattern<K, V>() { abstract fun split(value: V): Iterable<K> abstract fun join(parts: Iterable<K>): V val back = TriePattern<K, V>() override fun set(key: Iterable<K>, value: V) { back[split(value)] = join(key) return super.set(key, value) } } open class DictTrie: BackTrie<Char, String>() { override fun split(value: String) = value.asIterable() override fun join(parts: Iterable<Char>) = parts.joinToString("") } open class LazyPairedTrie<V>(private val op: (String) -> V?): PairedTriePattern<Char, V>() { private val currentPath = StringBuilder() private fun clear() { currentPath.clear() } override fun onItem(value: Char) { currentPath.append(value) } override fun onSuccess(value: V) { clear() } override fun onFail(): V? { val path = currentPath.toString() clear(); return op(path)?.also { this[path] = it } } } open class GreedyPairedTrie(private val predicate: Predicate<Char>): LazyPairedTrie<String>({ it.takeIf(String::isNotEmpty) }) { override fun read(s: Feed<Char>) = super.read(s) ?: s.takeWhileNotEnd { it !in routes && predicate(it) } .joinToString("").takeIf { it.isNotEmpty() || s.peek in routes && !isEOS } override fun onEOS() { _isEOS = true } protected val isEOS get() = _isEOS.also { _isEOS = false } private var _isEOS = false }
1
Kotlin
0
11
37599098dc9aafef7b509536e6d17ceca370d6cf
1,591
ParserKt
MIT License
kotlin/0046-permutations.kt
neetcode-gh
331,360,188
false
{"JavaScript": 473974, "Kotlin": 418778, "Java": 372274, "C++": 353616, "C": 254169, "Python": 207536, "C#": 188620, "Rust": 155910, "TypeScript": 144641, "Go": 131749, "Swift": 111061, "Ruby": 44099, "Scala": 26287, "Dart": 9750}
// solution based on the video class Solution { fun permute(nums: IntArray): List<MutableList<Int>> { val res = mutableListOf<MutableList<Int>>() val queue = ArrayDeque<Int>(nums.toList()) // base case if (queue.size == 1) { return listOf(queue.toMutableList()) // queue.toList() is a deep copy } for (i in nums.indices) { val n = queue.removeFirst() val perms = permute(queue.toIntArray()) for (perm in perms) { perm.add(n) res.add(perm) } queue.addLast(n) } return res } } // original solution class Solution { fun permute(nums: IntArray): List<List<Int>> { val res = mutableListOf<List<Int>>() permute(nums, mutableSetOf<Int>(), mutableListOf<Int>(), res) return res } fun permute(nums: IntArray, set: MutableSet<Int>, list: MutableList<Int>, res: MutableList<List<Int>>) { if (list.size == nums.size) { res.add(ArrayList(list)) return } for (i in 0..nums.size-1) { if (!set.contains(nums[i])) { list.add(nums[i]) set.add(nums[i]) permute(nums, set, list, res) list.removeAt(list.size-1) set.remove(nums[i]) } } } }
337
JavaScript
2,004
4,367
0cf38f0d05cd76f9e96f08da22e063353af86224
1,402
leetcode
MIT License
src/adventofcode/blueschu/y2017/day22/solution.kt
blueschu
112,979,855
false
null
package adventofcode.blueschu.y2017.day22 import java.io.File import kotlin.test.assertEquals val input: List<String> by lazy { File("resources/y2017/day22.txt") .bufferedReader() .use { it.readLines() } } fun main(args: Array<String>) { assertEquals( 5587, part1( listOf( "..#", "#..", "..." ) ) ) println("Part 1: ${part1(input)}") assertEquals( 2511944, part2( listOf( "..#", "#..", "..." ) ) ) println("Part 2: ${part2(input)}") } data class Point(var x: Int, var y: Int) enum class Direction { NORTH, EAST, SOUTH, WEST; fun turnedLeft(): Direction = when (this) { NORTH -> WEST WEST -> SOUTH SOUTH -> EAST EAST -> NORTH } fun turnedRight(): Direction = when (this) { NORTH -> EAST EAST -> SOUTH SOUTH -> WEST WEST -> NORTH } } class Position( val loc: Point = Point(0, 0), facing: Direction = Direction.NORTH ) { var facing = facing private set fun advance() = when (facing) { Direction.NORTH -> loc.y += 1 Direction.EAST -> loc.x += 1 Direction.SOUTH -> loc.y -= 1 Direction.WEST -> loc.x -= 1 } fun turnLeft() { facing = facing.turnedLeft() } fun turnRight() { facing = facing.turnedRight() } } abstract class AbstractCarrier(val pos: Position) { var infectionCount = 0 protected set abstract fun burst() } // Carrier for part one class CarrierOne( private val infectedNodes: MutableList<Point>, pos: Position = Position() ) : AbstractCarrier(pos) { override fun burst() { val position = pos.loc if (position in infectedNodes) { pos.turnRight() infectedNodes.remove(position) } else { pos.turnLeft() infectedNodes.add(position.copy()) infectionCount++ } pos.advance() } } // For part two enum class NodeStatus { INFECTED, CLEAN, FLAGGED, WEAKENED } // Carrier for part two class CarrierTwo( private val affectedNodes: MutableMap<Point, NodeStatus>, pos: Position = Position() ) : AbstractCarrier(pos) { override fun burst() { val position = pos.loc when (affectedNodes.getOrDefault(position, NodeStatus.CLEAN)) { NodeStatus.INFECTED -> { affectedNodes.put(position.copy(), NodeStatus.FLAGGED) pos.turnRight() } NodeStatus.CLEAN -> { affectedNodes.put(position.copy(), NodeStatus.WEAKENED) pos.turnLeft() } NodeStatus.FLAGGED -> { affectedNodes.remove(position) // reverse direction pos.turnRight() pos.turnRight() } NodeStatus.WEAKENED -> { affectedNodes.put(position.copy(), NodeStatus.INFECTED) // no change in direction infectionCount++ } } pos.advance() } } fun parseInfectedNodes(desc: List<String>): MutableList<Point> { // grid assumed to be a square with odd dimensions val midOffset = (desc.size - 1) / 2 val infectedNodes = mutableListOf<Point>() for ((row, rowVals) in desc.withIndex()) { for ((col, elem) in rowVals.withIndex()) { if (elem == '#') { infectedNodes.add(Point(col - midOffset, midOffset - row)) } } } return infectedNodes } fun part1(infectionDesc: List<String>): Int { val infectedNodes = parseInfectedNodes(infectionDesc) val carrier = CarrierOne(infectedNodes) repeat(times = 10_000) { carrier.burst() } return carrier.infectionCount } fun part2(infectionDesc: List<String>): Int { val affectedNodes = parseInfectedNodes(infectionDesc) .associateBy({ it }, { NodeStatus.INFECTED }) val carrier = CarrierTwo(affectedNodes.toMutableMap()) repeat(times = 10_000_000) { carrier.burst() } return carrier.infectionCount }
0
Kotlin
0
0
9f2031b91cce4fe290d86d557ebef5a6efe109ed
4,226
Advent-Of-Code
MIT License
src/main/kotlin/com/hj/leetcode/kotlin/problem1582/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem1582 /** * LeetCode page: [1582. Special Positions in a Binary Matrix](https://leetcode.com/problems/special-positions-in-a-binary-matrix/); */ class Solution { /* Complexity: * Time O(MN) and Space O(N) where M and N are the number of rows * and columns of mat; */ fun numSpecial(mat: Array<IntArray>): Int { val memoization = hashMapOf<Int, Boolean>() // entry=(column, containsSingleOne) return candidateColumns(mat).count { containsSingleOne(mat, it, memoization) } } private fun candidateColumns(mat: Array<IntArray>): List<Int> { val result = mutableListOf<Int>() for (row in mat) { val firstOneColumn = row.indexOfFirst { it == 1 } if (firstOneColumn == -1) { continue } val lastOneColumn = row.indexOfLast { it == 1 } if (firstOneColumn == lastOneColumn) { result.add(firstOneColumn) } } return result } private fun containsSingleOne( mat: Array<IntArray>, column: Int, memoization: MutableMap<Int, Boolean>, ): Boolean { if (column in memoization) { return checkNotNull(memoization[column]) } val firstOneRow = mat.indexOfFirst { it[column] == 1 } if (firstOneRow == -1) { memoization[column] = false return false } val lastOneRow = mat.indexOfLast { it[column] == 1 } memoization[column] = firstOneRow == lastOneRow return checkNotNull(memoization[column]) } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
1,640
hj-leetcode-kotlin
Apache License 2.0
hackerrank/missing-numbers/Solution.kts
shengmin
5,972,157
false
null
import java.io.* import java.math.* import java.security.* import java.text.* import java.util.* import java.util.concurrent.* import java.util.function.* import java.util.regex.* import java.util.stream.* import kotlin.collections.* import kotlin.comparisons.* import kotlin.io.* import kotlin.jvm.* import kotlin.jvm.functions.* import kotlin.jvm.internal.* import kotlin.ranges.* import kotlin.sequences.* import kotlin.text.* // Complete the missingNumbers function below. fun missingNumbers(arr: Array<Int>, brr: Array<Int>): IntArray { val originalCounts = countOccurrences(brr) val missingCounts = countOccurrences(arr) val results = mutableListOf<Int>() for (entry in originalCounts) { if (!missingCounts.containsKey(entry.key)) { results.add(entry.key) } else if (missingCounts[entry.key] != entry.value) { results.add(entry.key) } } return results.sorted().toIntArray() } fun countOccurrences(arr: Array<Int>): Map<Int, Int> { val counts = mutableMapOf<Int, Int>() for (item in arr) { val count = counts.getOrDefault(item, 0) counts[item] = count + 1 } return counts } fun main(args: Array<String>) { val scan = Scanner(System.`in`) val n = scan.nextLine().trim().toInt() val arr = scan.nextLine().split(" ").map{ it.trim().toInt() }.toTypedArray() val m = scan.nextLine().trim().toInt() val brr = scan.nextLine().split(" ").map{ it.trim().toInt() }.toTypedArray() val result = missingNumbers(arr, brr) println(result.joinToString(" ")) } main(arrayOf())
0
Java
18
20
08e65546527436f4bd2a2014350b2f97ac1367e7
1,557
coding-problem
MIT License
src/main/kotlin/lesson2/OddOccurrencesInArray.kt
iafsilva
633,017,063
false
null
package lesson2 /** * A non-empty array A consisting of N integers is given. * The array contains an odd number of elements, and each element of the array can be paired with another element that has the same value, except for one element that is left unpaired. * * For example, in array A such that: * ``` * A[0] = 9 A[1] = 3 A[2] = 9 * A[3] = 3 A[4] = 9 A[5] = 7 * A[6] = 9 * ``` * the elements at indexes 0 and 2 have value 9, * the elements at indexes 1 and 3 have value 3, * the elements at indexes 4 and 6 have value 9, * the element at index 5 has value 7 and is unpaired. * * Write a function: * * fun solution(A: IntArray): Int * * that, given an array A consisting of N integers fulfilling the above conditions, returns the value of the unpaired element. * * For example, given array A such that: * ``` * A[0] = 9 A[1] = 3 A[2] = 9 * A[3] = 3 A[4] = 9 A[5] = 7 * A[6] = 9 * ``` * the function should return 7, as explained in the example above. * * Write an efficient algorithm for the following assumptions: * - N is an odd integer within the range [1..1,000,000]; * - each element of array A is an integer within the range [1..1,000,000,000]; * - all but one of the values in A occur an even number of times. */ class OddOccurrencesInArray { fun solution(a: IntArray): Int { var unpairedElement = 0 for (element in a) unpairedElement = unpairedElement xor element return unpairedElement } }
0
Kotlin
0
0
5d86aefe70e9401d160c3d87c09a9bf98f6d7ab9
1,494
codility-lessons
Apache License 2.0
AdventOfCode/Challenge2023Day09.kt
MartinWie
702,541,017
false
{"Kotlin": 90565}
import org.junit.Test import java.io.File import kotlin.math.abs import kotlin.test.assertEquals class Challenge2023Day09 { private fun solve1(lines: List<String>): Int { val results = mutableListOf<Int>() lines.forEach { line -> // Generate the relevant lines val initialNumbers = line.split(" ").map { it.toInt() } val numberRows = mutableListOf<List<Int>>() numberRows.add(initialNumbers) var currentRow = numberRows.first() while (currentRow.reduce { acc, i -> abs(i) + acc } != 0) { val newRow = mutableListOf<Int>() var formerNumber: Int? = null currentRow.forEach { if (formerNumber != null) { newRow.add(it - formerNumber!!) } formerNumber = it } numberRows.add(newRow) currentRow = numberRows.last() } val numberRowsReversed = numberRows.reversed() var currentPredictedNumber = 0 var formerRow: MutableList<Int>? = null for (row in numberRowsReversed) { val formerPredict = currentPredictedNumber if (formerRow != null) { currentPredictedNumber = row.last() + formerPredict } formerRow = row.toMutableList() formerRow.add(formerPredict) } results.add(currentPredictedNumber) } return results.sum() } private fun solve2(lines: List<String>): Int { val results = mutableListOf<Int>() lines.forEach { line -> // Generate the relevant lines val initialNumbers = line.split(" ").map { it.toInt() } val numberRows = mutableListOf<List<Int>>() numberRows.add(initialNumbers) var currentRow = numberRows.first() while (currentRow.reduce { acc, i -> abs(i) + acc } != 0) { val newRow = mutableListOf<Int>() var formerNumber: Int? = null currentRow.forEach { if (formerNumber != null) { newRow.add(it - formerNumber!!) } formerNumber = it } numberRows.add(newRow) currentRow = numberRows.last() } val numberRowsReversed = numberRows.reversed() var currentPredictedNumber = 0 var formerRow: MutableList<Int>? = null for (row in numberRowsReversed) { val formerPredict = currentPredictedNumber if (formerRow != null) { currentPredictedNumber = row.first() - formerPredict } formerRow = row.toMutableList() formerRow.add(formerPredict) } results.add(currentPredictedNumber) } return results.sum() } // Just for fun, here is th ecombined solution -> private fun solve(lines: List<String>): Pair<Int, Int> { var sum1 = 0 var sum2 = 0 lines.forEach { line -> val initialNumbers = line.split(" ").map { it.toInt() } val numberRows = mutableListOf<List<Int>>() numberRows.add(initialNumbers) var currentRow = numberRows.first() while (currentRow.reduce { acc, i -> abs(i) + acc } != 0) { val newRow = mutableListOf<Int>() var formerNumber: Int? = null currentRow.forEach { if (formerNumber != null) { newRow.add(it - formerNumber!!) } formerNumber = it } numberRows.add(newRow) currentRow = numberRows.last() } val numberRowsReversed = numberRows.reversed() var currentPredictedNumber1 = 0 var currentPredictedNumber2 = 0 var formerRow: MutableList<Int>? = null for (row in numberRowsReversed) { val formerPredict1 = currentPredictedNumber1 val formerPredict2 = currentPredictedNumber2 if (formerRow != null) { currentPredictedNumber1 = row.last() + formerPredict1 currentPredictedNumber2 = row.first() - formerPredict2 } formerRow = row.toMutableList() formerRow.add(formerPredict1) // Only need to add for the first calculation } sum1 += currentPredictedNumber1 sum2 += currentPredictedNumber2 } return Pair(sum1, sum2) } @Test fun test() { val lines = File("./AdventOfCode/Data/Day09-1-Test-Data.txt").bufferedReader().readLines() val exampleSolution1 = solve1(lines) println("Example solution 1: $exampleSolution1") assertEquals(114, exampleSolution1) val realLines = File("./AdventOfCode/Data/Day09-1-Data.txt").bufferedReader().readLines() val solution1 = solve1(realLines) println("Solution 1: $solution1") assertEquals(1861775706, solution1) val lines2 = File("./AdventOfCode/Data/Day09-1-Test-Data.txt").bufferedReader().readLines() val exampleSolution2 = solve2(lines2) println("Example solution 2: $exampleSolution2") assertEquals(2, exampleSolution2) val realLines2 = File("./AdventOfCode/Data/Day09-1-Data.txt").bufferedReader().readLines() val solution2 = solve2(realLines2) println("Solution 2: $solution2") assertEquals(1082, solution2) } @Test fun `Test the combined solution`() { val exampleLines = File("./AdventOfCode/Data/Day09-1-Test-Data.txt").bufferedReader().readLines() val (exampleSolution1, exampleSolution2) = solve(exampleLines) println("Example solution 1: $exampleSolution1") assertEquals(114, exampleSolution1) println("Example solution 2: $exampleSolution2") assertEquals(2, exampleSolution2) val realLines = File("./AdventOfCode/Data/Day09-1-Data.txt").bufferedReader().readLines() val (solution1, solution2) = solve(realLines) println("Solution 1: $solution1") assertEquals(1861775706, solution1) println("Solution 2: $solution2") assertEquals(1082, solution2) } }
0
Kotlin
0
0
47cdda484fabd0add83848e6000c16d52ab68cb0
6,575
KotlinCodeJourney
MIT License
2015/kotlin/src/main/kotlin/nl/sanderp/aoc/aoc2015/day11/Day11.kt
sanderploegsma
224,286,922
false
{"C#": 233770, "Kotlin": 126791, "F#": 110333, "Go": 70654, "Python": 64250, "Scala": 11381, "Swift": 5153, "Elixir": 2770, "Jinja": 1263, "Ruby": 1171}
package nl.sanderp.aoc.aoc2015.day11 import nl.sanderp.aoc.common.allPairs const val input = "cqjxjnds" val String.isValid get(): Boolean { if (windowed(3, 1).all { Pair(it[1] - it[0], it[2] - it[1]) != Pair(1, 1) }) { return false } if (any { listOf('i', 'o', 'l').contains(it) }) { return false } val pairs = withIndex() .windowed(2) .filter { it.first().value == it.last().value } .map { setOf(it.first().index, it.last().index) } return pairs.allPairs().any { (a, b) -> a.intersect(b).isEmpty() } } fun increment(password: String): String { val chars = password.toCharArray().reversed().toMutableList() for (i in chars.indices) { if (chars[i] < 'z') { chars[i]++ break } chars[i] = 'a' } return chars.reversed().joinToString(separator = "") } fun findNextPassword(start: String) = generateSequence(start, ::increment).drop(1).first { it.isValid } fun main() { val next = findNextPassword(input) println("Part one: $next") println("Part two: ${findNextPassword(next)}") }
0
C#
0
6
8e96dff21c23f08dcf665c68e9f3e60db821c1e5
1,175
advent-of-code
MIT License
src/main/kotlin/twentytwentytwo/Day20.kt
JanGroot
317,476,637
false
{"Kotlin": 80906}
package twentytwentytwo fun main() { val input = {}.javaClass.getResource("input-20.txt")!!.readText().linesFiltered { it.isNotEmpty() }; val tinput = {}.javaClass.getResource("input-20-1.txt")!!.readText().linesFiltered { it.isNotEmpty() }; val day = Day20(input) val test = Day20(tinput) println(test.part1()) println(test.part2()) println(day.part1()) println(day.part2()) } class Day20(private val input: List<String>) { fun part1(): Long { val original = input.mapIndexed { index, i -> index to i.toLong() } val target = original.toMutableList() original.forEach { target.move(it) } return target.getWrapped(1000) + target.getWrapped(2000) + target.getWrapped(3000) } fun part2(): Long { val key = 811589153 val original = input.mapIndexed { index, i -> index to i.toLong() * key } val target = original.toMutableList() repeat(10) { original.forEach { target.move(it) } } return target.getWrapped(1000) + target.getWrapped(2000) + target.getWrapped(3000) } /* fun MutableList<Pair<Int, Int>>.move(element: Pair<Int, Int>) { val old = indexOf(element) removeAt(old) add((old + element.second).mod(size), element) } fun MutableList<Pair<Int, Int>>.getWrapped(index: Int): Int { return this[(indexOfFirst { it.second == 0 } + index).mod(size)].second } */ fun MutableList<Pair<Int, Long>>.move(element: Pair<Int, Long>) { val old = indexOf(element) removeAt(old) add((old + element.second).mod(size), element) } fun MutableList<Pair<Int, Long>>.getWrapped(index: Int): Long { return this[(indexOfFirst { it.second == 0L } + index).mod(size)].second } }
0
Kotlin
0
0
04a9531285e22cc81e6478dc89708bcf6407910b
1,844
aoc202xkotlin
The Unlicense
src/main/kotlin/com/yanicksenn/miniretrieval/language/LanguageDeterminer.kt
yanicksenn
512,225,699
false
{"Kotlin": 62130}
package com.yanicksenn.miniretrieval.language import com.yanicksenn.miniretrieval.to.Token import java.lang.Integer.max /** * Determines the language of a document by reading its tokens * and matching them to lexicons. */ class LanguageDeterminer(lexicons: Map<Language, Set<Token>>) { private val languageByToken = HashMap<Token, HashSet<Language>>() private val languageScore = HashMap<Language, Int>() private var currentMaxScore = 0 private var tokensRead = 0 private var tokensMatched = 0 /** * Returns the current determined language. */ val currentLanguage: Result get() { if (currentMaxScore == 0) return Nothing val bestMatches = languageScore.filter { it.value == currentMaxScore }.keys.toHashSet() if (bestMatches.size > 1) return Unsure return Match(bestMatches.first()) } /** * Returns the percentage of matches with the currently * determined language. */ val currentAssurance: Double get() = if (tokensMatched > 0) currentMaxScore / tokensMatched.toDouble() else 0.0 init { // Create inverted index of tokens within lexicons for (language in lexicons.keys) for (token in lexicons[language]!!) languageByToken.getOrPut(token) { HashSet() }.add(language) // Initialize score for each language in the lexicons lexicons.keys.forEach { languageScore[it] = 0 } } /** * Reads a single token and adjusts the language score to * determine what language matches this document. * @param token Token */ fun readToken(token: String) { tokensRead ++ if (!languageByToken.containsKey(token)) return tokensMatched ++ val languages = languageByToken[token]!! for (language in languages) { val oldScore = languageScore[language]!! val newScore = oldScore + 1 languageScore[language] = newScore currentMaxScore = max(currentMaxScore, newScore) } } /** * Result of a language determination. */ sealed interface Result /** * No language is matched. */ object Nothing : Result /** * If multiple languages are matched. */ object Unsure : Result /** * When a language is matched. */ data class Match(val language: Language) : Result }
2
Kotlin
0
0
f168ac3a51a30478b21b73e40488266ff8ae9320
2,496
mini-retrieval
MIT License
puzzles/kotlin/src/bender1.kt
hitszjsy
337,974,982
true
{"Python": 88057, "Java": 79734, "Kotlin": 52113, "C++": 33407, "TypeScript": 20480, "JavaScript": 17133, "PHP": 15544, "Go": 15296, "Ruby": 12722, "Haskell": 12635, "C#": 2600, "Scala": 1555, "Perl": 1250, "Shell": 1220, "Clojure": 753, "C": 598, "Makefile": 58}
import java.util.Scanner const val UNBREAKABLE_WALL = '#' const val BREAKABLE_WALL = 'X' const val START = '@' const val FINISH = '$' const val SOUTH = 'S' const val EAST = 'E' const val NORTH = 'N' const val WEST = 'W' const val BEER = 'B' const val INVERTER = 'I' const val TELEPORTER = 'T' const val EMPTY = ' ' fun main(args : Array<String>) { val city = City() val bender = Bender() readGameInput(city, bender) city.printGrid() gameLoop(city, bender) } fun readGameInput(city: City, bender: Bender) { val input = Scanner(System.`in`) city.height = input.nextInt() city.width = input.nextInt() if (input.hasNextLine()) { input.nextLine() } for (y in 0 until city.height) { val row = input.nextLine() val cellList = ArrayList<Cell>() for (x in 0 until row.length) { val symbol = row[x] val cell = Cell(symbol) cellList.add(cell) if (symbol == START) { bender.point.x = x bender.point.y = y } else if (symbol == TELEPORTER) { if (!city.teleporter) { city.teleporter1 = Point(x, y) city.teleporter = true } else { city.teleporter2 = Point(x, y) } } } city.grid.add(cellList) } } fun resetGridState(city: City) { for (y in 0 until city.height) { for (x in 0 until city.width) { city.grid[y][x].reset() } } } fun currentSymbol(city: City, bender: Bender): Char { return city.grid[bender.point.y][bender.point.x].symbol } fun isValidMove(city: City, bender: Bender, direction: Direction): Boolean { return when (direction) { Direction.SOUTH -> isValidPosition(city, bender, bender.point.x, bender.point.y + 1) Direction.EAST -> isValidPosition(city, bender, bender.point.x + 1, bender.point.y) Direction.NORTH -> isValidPosition(city, bender, bender.point.x, bender.point.y - 1) else -> isValidPosition(city, bender, bender.point.x - 1, bender.point.y) // WEST } } fun isValidPosition(city: City, bender: Bender, x: Int, y: Int): Boolean { return x >= 0 && x < city.width && y >= 0 && y < city.height && city.grid[y][x].symbol != UNBREAKABLE_WALL && (bender.breakMode || city.grid[y][x].symbol != BREAKABLE_WALL) } fun updateBenderState(city: City, bender: Bender) { val symbol = currentSymbol(city, bender) if (symbol == START || symbol == SOUTH) { bender.direction = Direction.SOUTH } else if (symbol == EAST) { bender.direction = Direction.EAST } else if (symbol == NORTH) { bender.direction = Direction.NORTH } else if (symbol == WEST) { bender.direction = Direction.WEST } else if (symbol == BEER) { bender.breakMode = !bender.breakMode } else if (symbol == INVERTER) { bender.reverse = !bender.reverse bender.priorites.reverse() } else if (symbol == TELEPORTER) { if (bender.point == city.teleporter1) { bender.point = city.teleporter2.copy() } else { bender.point = city.teleporter1.copy() } } } fun addMove(city: City, bender: Bender) { updateBenderState(city, bender) if (isValidMove(city, bender, bender.direction)) { bender.addMove() } else { for (direction in bender.priorites) { if (isValidMove(city, bender, direction)) { bender.direction = direction bender.addMove() break } } } val cell = city.grid[bender.point.y][bender.point.x] if (cell.visited && Triple(cell.reverse, cell.breakMode, cell.direction) == Triple(bender.reverse, bender.breakMode, bender.direction)) { city.loop = true } else { cell.visited = true cell.reverse = bender.reverse cell.breakMode = bender.breakMode cell.direction = bender.direction } } fun gameLoop(city: City, bender: Bender) { while (currentSymbol(city, bender) != FINISH) { addMove(city, bender) if (city.loop) { break } if (bender.breakMode && currentSymbol(city, bender) == BREAKABLE_WALL) { city.grid[bender.point.y][bender.point.x] = Cell(EMPTY) resetGridState(city) } } if (city.loop) { println("LOOP") } else { for (move in bender.moves) { println(move) } } } data class Point(var x: Int, var y: Int) enum class Direction { SOUTH, EAST, NORTH, WEST } class Cell(val symbol: Char) { var visited = false var direction = Direction.SOUTH var reverse = false var breakMode = false fun reset() { visited = false direction = Direction.SOUTH reverse = false breakMode = false } override fun toString(): String { return symbol.toString() } } class Bender { val priorites = arrayListOf(Direction.SOUTH, Direction.EAST, Direction.NORTH, Direction.WEST) var direction = Direction.SOUTH var reverse = false var breakMode = false var point = Point(0, 0) val moves = ArrayList<Direction>() fun addMove() { when (direction) { Direction.SOUTH -> point.y++ Direction.EAST -> point.x++ Direction.NORTH -> point.y-- else -> point.x-- // WEST } moves.add(direction) } } class City { val grid = ArrayList<ArrayList<Cell>>() var teleporter = false var teleporter1 = Point(0, 0) var teleporter2 = Point(0, 0) var height = 0 var width = 0 var loop = false fun printGrid() { System.err.println("$height $width") for (y in 0 until height) { for (x in 0 until width) { System.err.print(grid[y][x].toString()) } System.err.println() } } }
0
null
0
1
59d9856e66b1c4a3d660c60bc26a19c4dfeca6e2
5,471
codingame
MIT License
kotlin/StalinSort.kt
nikitabobko
267,869,432
true
{"Coq": 189028, "Python": 7234, "C++": 7096, "TeX": 7094, "Scala": 5257, "Assembly": 4885, "C#": 4674, "Rust": 4076, "Agda": 2521, "REXX": 2241, "R": 2214, "Shell": 2069, "Java": 2010, "Go": 1655, "Julia": 1475, "Kotlin": 1311, "Crystal": 1306, "Perl": 1222, "Pascal": 1189, "APL": 1180, "Swift": 1084, "Scheme": 1043, "F#": 740, "Visual Basic .NET": 723, "V": 710, "Tcl": 699, "DM": 671, "Standard ML": 664, "JavaScript": 663, "Common Lisp": 652, "C": 616, "AutoIt": 605, "Haskell": 584, "Shen": 564, "D": 493, "Forth": 483, "Haxe": 483, "Makefile": 467, "PowerShell": 443, "Ruby": 436, "Groovy": 431, "Reason": 415, "PHP": 386, "Lua": 319, "Elixir": 315, "Dart": 304, "Vim Script": 303, "Erlang": 283, "Brainfuck": 279, "Clojure": 279, "Elm": 249, "OCaml": 208, "MATLAB": 191, "TypeScript": 180, "MoonScript": 175, "Awk": 154, "Prolog": 121, "Gnuplot": 115}
fun main(args: Array<String>) { val intComrades = listOf(0, 2, 1, 4, 3, 6, 5).sortComrades() val charComrades = listOf('A', 'C', 'B', 'E', 'D').sortComrades() val redArmyRanks = listOf( RedArmyRank.SOLDIER, RedArmyRank.ASSISTANT_PLATOON_LEADER, RedArmyRank.SQUAD_LEADER).sortComrades() val dickwads = listOf( RedArmyDickwad("Stalin", RedArmyRank.SUPREME_COMMANDER), RedArmyDickwad("Pablo", RedArmyRank.NOT_EVEN_RUSSIAN), RedArmyDickwad("Putin", RedArmyRank.BEAR_RIDER)).sortComrades() println("$intComrades\n$charComrades\n$redArmyRanks\n$dickwads") } fun <T: Comparable<T>> Iterable<T>.sortComrades(): List<T> { var max = firstOrNull() ?: return emptyList() return mapIndexedNotNull { index, comrade -> if (index == 0 || comrade >= max) { max = comrade comrade } else { null } } } enum class RedArmyRank { NOT_EVEN_RUSSIAN, SOLDIER, SQUAD_LEADER, ASSISTANT_PLATOON_LEADER, COMPANY_SERGEANT, BEAR_RIDER, SUPREME_COMMANDER } data class RedArmyDickwad( val name: String, val rank: RedArmyRank ) : Comparable<RedArmyDickwad> { override operator fun compareTo(other: RedArmyDickwad) = rank.compareTo(other.rank) }
0
null
0
0
6098af3dbebdcbb8d23491a0be51775bddaee4a4
1,311
stalin-sort
MIT License
src/adventofcode/blueschu/y2017/day23/solution.kt
blueschu
112,979,855
false
null
package adventofcode.blueschu.y2017.day23 import adventofcode.blueschu.y2017.day18.RegisterRepository import java.io.File val input: List<String> by lazy { File("resources/y2017/day23.txt") .bufferedReader() .use { r -> r.readLines() } } fun main(args: Array<String>) { println("Part 1: ${part1(input)}") println("Part 2: ${part2(input)}") } // Instruction value tokens sealed class Value data class RegisterKey(val key: Char) : Value() data class Literal(val value: Long) : Value() // Assembly instructions sealed class Instruction data class Set(val register: RegisterKey, val newValue: Value) : Instruction() data class Sub(val register: RegisterKey, val delta: Value) : Instruction() data class Mult(val register: RegisterKey, val factor: Value) : Instruction() data class JumpNotZero(val condition: Value, val offset: Value) : Instruction() // parse input line into assembly-like instruction fun parseInstruction(line: String): Instruction { fun valueFor(token: String) = if (token.length == 1 && token.first() in 'a'..'h') { RegisterKey(token.first()) } else Literal(token.toInt().toLong()) val instr = line.slice(0..2) val tokens = line.substring(4).split(' ') .map { valueFor(it) } return when (instr) { "set" -> Set(tokens[0] as RegisterKey, tokens[1]) "sub" -> Sub(tokens[0] as RegisterKey, tokens[1]) "mul" -> Mult(tokens[0] as RegisterKey, tokens[1]) "jnz" -> JumpNotZero(tokens[0], tokens[1]) else -> throw IllegalArgumentException("Malformed line could not be parsed: $line") } } class Interpreter(registerInitializer: Long) { // Key must be boxed, otherwise a JVM internal error occurs during compilation val registerTable = RegisterRepository<Char?, Long>().apply { set('a', registerInitializer) } // For part one var multInstrCount = 0 private var pos = 0 fun execute(prog: List<Instruction>) { while (pos < prog.size) { val instr = prog[pos] if (instr is Mult) { multInstrCount++ } executeInstruction(instr) } } private fun executeInstruction(instr: Instruction) { var nextJump = 1 when (instr) { is Set -> registerTable[instr.register.key] = instr.newValue.inferredValue is Sub -> registerTable[instr.register.key] -= instr.delta.inferredValue is Mult -> registerTable[instr.register.key] *= instr.factor.inferredValue is JumpNotZero -> if (instr.condition.inferredValue != 0L) { nextJump = instr.offset.inferredValue.toInt() } } pos += nextJump } private val Value.inferredValue get() = when (this) { is RegisterKey -> registerTable[this.key] is Literal -> this.value } } fun part1(lines: List<String>): Int { val instructions = lines.map { parseInstruction(it) } val interpreter = Interpreter(0) interpreter.execute(instructions) return interpreter.multInstrCount } // Brute force // todo Implement optimization fun part2(lines: List<String>): Long { val instructions = lines.map { parseInstruction(it) } val interpreter = Interpreter(1) interpreter.execute(instructions) return interpreter.registerTable['h'] } // registers b and c altered by initializing a to 1 // b and c are only referenced in conditions near the end of the program
0
Kotlin
0
0
9f2031b91cce4fe290d86d557ebef5a6efe109ed
3,501
Advent-Of-Code
MIT License
src/commonMain/kotlin/dev/achammer/tuwea/core/Core.kt
fachammer
354,805,674
false
null
package dev.achammer.tuwea.core import kotlin.random.Random data class StudentCheckmarksEntry( val firstName: String, val lastName: String, val idNumber: String, val checkmarks: Set<String> ) data class ParseConfiguration( val csvDelimiter: Char, val csvLineOffset: Int, val preCheckmarksFieldOffset: Int, val firstNameKey: String, val lastNameKey: String, val idNumberKey: String, val exerciseEndSignifierKey: String, val checkmarkSignifiers: Set<String> ) val tuwelParseConfiguration = ParseConfiguration( csvDelimiter = ';', csvLineOffset = 6, preCheckmarksFieldOffset = 3, firstNameKey = "Vorname", lastNameKey = "Nachname", idNumberKey = "ID-Nummer", exerciseEndSignifierKey = "Kreuzerl", checkmarkSignifiers = setOf("X", "(X)") ) data class ParseResult(val exercises: List<String>, val studentCheckmarksEntries: List<StudentCheckmarksEntry>) typealias ExerciseStudentAssignment = List<Pair<String, StudentCheckmarksEntry>> fun findExerciseAssignment( parseResult: ParseResult, isStudentPresent: (StudentCheckmarksEntry) -> Boolean ): ExerciseStudentAssignment { val exercises = parseResult.exercises val entries = parseResult.studentCheckmarksEntries return exercises .sortedBy { exercise -> entries.count { it.checkmarks.contains(exercise) } } .fold(emptyList()) { chosenAssignments, exercise -> val potentialEntries = entries .filter { it.checkmarks.contains(exercise) } .filter { isStudentPresent(it) } .filterNot { entry -> chosenAssignments.firstOrNull { it.second == entry } != null } if (potentialEntries.isEmpty()) { chosenAssignments } else { chosenAssignments + Pair(exercise, potentialEntries[Random.nextInt(potentialEntries.size)]) } } } fun parseCsvContent(parseConfiguration: ParseConfiguration, csvContent: String): ParseResult { parseConfiguration.apply { val csvLines = csvContent.split("\n") val sanitizedCsvLines = csvLines.drop(csvLineOffset) val headerRow = sanitizedCsvLines.first() val fields = headerRow.split(csvDelimiter) val exercises = fields .drop(preCheckmarksFieldOffset) .takeWhile { s -> s != exerciseEndSignifierKey } .map { sanitizeExerciseName(it) } val entries = sanitizedCsvLines .drop(1) .map { line -> fields.zip(line.split(csvDelimiter)).toMap() } .map { entry -> parseCsvLine(entry) } return ParseResult(exercises, entries) } } private fun ParseConfiguration.parseCsvLine(entry: Map<String, String>): StudentCheckmarksEntry { val checkmarks = entry.keys .filterNot { it in setOf(firstNameKey, lastNameKey, idNumberKey) } .filter { entry[it] in checkmarkSignifiers } .map { sanitizeExerciseName(it) } .toSet() return StudentCheckmarksEntry( firstName = sanitizeFirstName(entry[firstNameKey]!!), lastName = entry[lastNameKey]!!, idNumber = entry[idNumberKey]!!, checkmarks = checkmarks ) } private fun sanitizeExerciseName(exerciseName: String): String = firstWordOf(exerciseName) private fun sanitizeFirstName(firstName: String): String = firstWordOf(firstName) private fun firstWordOf(string: String) = string.trim().split(" ").first()
0
Kotlin
0
0
bc880bcfb78be90016ede48c9eaf99cc689905cc
3,457
tuwea
MIT License
app/src/main/java/edu/upf/aism/tfgroommeasurements/Utils.kt
guillemmr00
654,006,318
false
null
package edu.upf.aism.tfgroommeasurements import com.github.psambit9791.jdsp.transform.DiscreteFourier import com.github.psambit9791.jdsp.transform.FastFourier import java.io.* import java.lang.Math.pow import kotlin.math.* fun bit8_to16bit(bit8_low : Int, bit8_high : Int) : Short{ val lowByteDecimal = bit8_low and 0xff val highByteDecimal = bit8_high and 0xff // example high 8-bit value in decimal // example low 8-bit value in decimal return ((highByteDecimal shl 8) or lowByteDecimal).toShort() } fun convolve(a: ShortArray, b: ShortArray, mode: String = "same"): ShortArray { val m = a.size val n = b.size var result = ShortArray(m+n-1) for (i in 0 until m+n-1) { var sum = 0.0 for (j in max(0, i - n + 1) until min(i + 1, m)) { sum += a[j] * b[i - j] } result[i] = sum.toInt().toShort() } result = when (mode) { "full" -> result "same" -> takeMiddle(result, max(m, n)) "valid" -> takeMiddle(result, max(m, n) - min(m, n) + 1) else -> result } return result } fun convolve(a: DoubleArray, b: DoubleArray, mode: String = "same"): DoubleArray { val m = a.size val n = b.size var result = DoubleArray(m+n-1) for (i in 0 until m+n-1) { var sum = 0.0 for (j in max(0, i - n + 1) until min(i + 1, m)) { sum += a[j] * b[i - j] } result[i] = sum } result = when (mode) { "full" -> result "same" -> takeMiddle(result, max(m, n)) "valid" -> takeMiddle(result, max(m, n) - min(m, n) + 1) else -> result } return result } fun takeMiddle(a: ShortArray, x: Int) : ShortArray{ val start = (a.size - x) / 2 val end = start + x val slice = a.slice(start until end) return slice.toShortArray() // Output: [4, 5, 6] } fun takeMiddle(a: DoubleArray, x: Int) : DoubleArray{ val start = (a.size - x) / 2 val end = start + x val slice = a.slice(start until end) return slice.toDoubleArray() // Output: [4, 5, 6] } fun decibelsToGain(decibels : Double, dbType : String ="dBFS") : Double{ val factor = if (dbType=="dBu"){ 0.775 } else if(dbType == "dBFS" || dbType=="dBV"){ 1.0 } else { 1.0 } return Math.pow(10.0, decibels / 20.0) * factor } fun decibelsToGain(decibels: DoubleArray, dbType: String = "dBFS"): DoubleArray { val factor = if (dbType == "dBu") { 0.775 } else if (dbType == "dBFS" || dbType == "dBV") { 1.0 } else { 1.0 } return DoubleArray(decibels.size) { Math.pow(10.0, decibels[it] / 20.0) * factor } } fun gainToDecibels(gain : Double) : Double{ return 20.0 * log10(gain/Short.MAX_VALUE) } fun gainToDecibels(gain : DoubleArray) : DoubleArray{ var peak = 0.0 for (i in gain.indices) { if (gain[i] > peak) { peak = gain[i] } } return DoubleArray(gain.size){20.0 * log10(gain[it]/peak)} } fun dBFS(gain : Double) : Double{ return 20* log10(gain/1.0) } fun invDBFS(db : Double) : Double{ return Math.pow(10.0, db/20) } fun findIndexOfMaxValue(numbers: DoubleArray): Int { var maxIndex = -1 var maxValue = Double.MIN_VALUE for (i in numbers.indices) { if (numbers[i] > maxValue) { maxValue = numbers[i] maxIndex = i } } return maxIndex } fun normalizeShortArray(array: ShortArray): DoubleArray { val max = array.maxOrNull()?.toDouble() ?: 1.0 // Find the maximum value, default to 1 if the array is empty val normalizedArray = DoubleArray(array.size) val maxInv = 1.0 / max // Calculate the inverse of the maximum value outside the loop for efficiency for (i in array.indices) { normalizedArray[i] = array[i].toDouble() * maxInv // Multiply each element by the inverse of the maximum value to normalize } return normalizedArray } fun normalizeDoubleArray(array: DoubleArray): DoubleArray { val max = array.maxOrNull() ?: 1.0 // Find the maximum value, default to 1 if the array is empty val normalizedArray = DoubleArray(array.size) val maxInv = 1.0 / max // Calculate the inverse of the maximum value outside the loop for efficiency for (i in array.indices) { normalizedArray[i] = array[i] * maxInv // Multiply each element by the inverse of the maximum value to normalize } return normalizedArray } fun doubleArrayToShortArray(doubleArray: DoubleArray): ShortArray { val shortArray = ShortArray(doubleArray.size) for (i in doubleArray.indices) { val value = doubleArray[i].toInt().coerceIn(Short.MIN_VALUE.toInt(), Short.MAX_VALUE.toInt()) shortArray[i] = value.toShort() } return shortArray } fun shortArrayToDoubleArray(shortArray: ShortArray): DoubleArray { val doubleArray = DoubleArray(shortArray.size) for (i in shortArray.indices) { doubleArray[i] = shortArray[i].toDouble() } return doubleArray } fun savePcmToFile2(pcmData: ShortArray, filePath: String) : String{ var filePathDefinitive = filePath var file = File(filePath) var counter = 1 while (file.exists()){ val fileName = file.nameWithoutExtension val fileExtension = file.extension val newFileName = "$fileName-$counter.$fileExtension" val parentDirectory = file.parent filePathDefinitive = "$parentDirectory/$newFileName" file = File(filePathDefinitive) counter++ } val outputStream = FileOutputStream(file) val dataOutputStream = DataOutputStream(outputStream) try { for (sample in pcmData) { dataOutputStream.writeShort(sample.toInt()) } } catch (e: Exception) { e.printStackTrace() } finally { dataOutputStream.close() } return filePathDefinitive } fun loadPcmFromFile2(filePath: String): ShortArray? { val file = File(filePath) if (!file.exists()) { println("File does not exist.") return null } val inputStream = FileInputStream(file) val dataInputStream = DataInputStream(inputStream) val pcmData = mutableListOf<Short>() try { while (dataInputStream.available() > 0) { val sample = dataInputStream.readShort() pcmData.add(sample) } } catch (e: Exception) { e.printStackTrace() } finally { dataInputStream.close() } return pcmData.toShortArray() } fun savePcmToFile(pcmData: DoubleArray, filePath: String) : String{ var filePathDefinitive = filePath var file = File(filePath) var counter = 1 while (file.exists()){ val fileName = file.nameWithoutExtension val fileExtension = file.extension val newFileName = "$fileName-$counter.$fileExtension" val parentDirectory = file.parent filePathDefinitive = "$parentDirectory/$newFileName" file = File(filePathDefinitive) counter++ } val outputStream = FileOutputStream(file) val dataOutputStream = DataOutputStream(outputStream) try { for (sample in pcmData) { dataOutputStream.writeDouble(sample) } } catch (e: Exception) { e.printStackTrace() } finally { dataOutputStream.close() } return filePathDefinitive } fun loadPcmFromFile(filePath: String): DoubleArray? { val file = File(filePath) if (!file.exists()) { println("File does not exist.") return null } val inputStream = FileInputStream(file) val dataInputStream = DataInputStream(inputStream) val pcmData = mutableListOf<Double>() try { while (dataInputStream.available() > 0) { val sample = dataInputStream.readDouble() pcmData.add(sample) } } catch (e: Exception) { e.printStackTrace() } finally { dataInputStream.close() } return pcmData.toDoubleArray() } fun fadeLin(size : Int, fadeInEndSample : Int) : DoubleArray{ val fadeOutStartSample = size - fadeInEndSample val array = DoubleArray(size) for (i in 0 until size) { val value = when { i < fadeInEndSample -> i.toDouble() / fadeInEndSample.toDouble() i >= fadeOutStartSample -> (size - i).toDouble() / (size - fadeOutStartSample).toDouble() else -> 1.0 } array[i] = value } return array } fun fadeLog(size : Int, fadeInEndSample : Int) : DoubleArray{ val fadeOutStartSample = size - fadeInEndSample val array = DoubleArray(size) for (i in 0 until size) { val value = when { i < fadeInEndSample ->1.0 - 10.0.pow(-i.toDouble() / fadeInEndSample.toDouble()) i >= fadeOutStartSample ->1.0 - 10.0.pow(-(size - i).toDouble() / (size - fadeOutStartSample).toDouble()) else -> 1.0 } array[i] = value } return array } fun signalRms(signal : DoubleArray) : Double { val sigSquared = DoubleArray(signal.size){signal[it]*signal[it]} val meanSquared = sigSquared.sum()/signal.size return sqrt(meanSquared) } fun signalRms(signal : ShortArray) : Double { val sigSquared = DoubleArray(signal.size){signal[it].toDouble()*signal[it]} val meanSquared = sigSquared.sum()/signal.size return sqrt(meanSquared) } fun scaleSignal(signal : DoubleArray, outGain : Double) : Double{ val energy = DoubleArray(signal.size){pow(signal[it], 2.0)}.sum() return sqrt((signal.size*pow(outGain, 2.0))/energy) }
0
Kotlin
0
0
d75a40b8f150100b9700b0f289f598c2ddd74092
9,576
TFGRoomMeasurements
MIT License
mynlp/src/main/java/com/mayabot/nlp/fasttext/utils/TopMaxK.kt
mayabot
113,726,044
false
{"Java": 985672, "Kotlin": 575923, "Shell": 530}
package com.mayabot.nlp.fasttext.utils import java.util.* import kotlin.math.min /** * 求最大Top K * 内部是小顶堆 * * @author jimichan */ class TopMaxK<T>(private val k: Int=10 ) { private val heap: FloatArray = FloatArray(k) private val idIndex: MutableList<T?> = MutableList(k){null} var size = 0 fun push(id: T, score: Float) { if (size < k) { heap[size] = score idIndex[size] = id size++ if (size == k) { buildMinHeap() } } else { // 如果这个数据大于最下值,那么有资格进入 if (score > heap[0]) { heap[0] = score idIndex[0] = id mintopify(0) } } } fun canPush(score: Float): Boolean { if (size < k) { return true } else { // 如果这个数据大于最下值,那么有资格进入 if (score > heap[0]) { return true } } return false } fun result(): ArrayList<Pair<T, Float>> { val top = min(k, size) val list = ArrayList<Pair<T, Float>>(top) for (i in 0 until top) { val v = idIndex[i] val s = heap[i] if(v!=null){ list += v to s } } list.sortByDescending { it.second } return list } private fun buildMinHeap() { for (i in k / 2 - 1 downTo 0) { // 依次向上将当前子树最大堆化 mintopify(i) } } /** * 让heap数组符合堆特性 * * @param i */ private fun mintopify(i: Int) { val l = 2 * i + 1 val r = 2 * i + 2 var min = 0 min = if (l < k && heap[l] < heap[i]) { l } else { i } if (r < k && heap[r] < heap[min]) { min = r } if (min == i || min >= k) { // 如果largest等于i说明i是最大元素 // largest超出heap范围说明不存在比i节点大的子女 return } swap(i, min) mintopify(min) } private fun swap(i: Int, j: Int) { val tmp = heap[i] heap[i] = heap[j] heap[j] = tmp val tmp2 = idIndex[i] idIndex[i] = idIndex[j] idIndex[j] = tmp2 } }
18
Java
90
658
b980da3a6f9cdcb83e0800f6cab50656df94a22a
2,409
mynlp
Apache License 2.0
src/Day03.kt
Derrick-Mwendwa
573,947,669
false
{"Kotlin": 8707}
fun main() { fun Char.getPriority() = this.code - if (this.isLowerCase()) 96 else 38 fun part1(input: List<String>) = input.sumOf { (it.substring(0, it.length / 2).toSet() intersect it.substring(it.length / 2).toSet()) .single() .getPriority() } fun part2(input: List<String>) = input.chunked(3).sumOf { (it[0].toSet() intersect it[1].toSet() intersect it[2].toSet()) .single() .getPriority() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") check(part2(testInput) == 70) val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
7870800afa54c831c143b5cec84af97e079612a3
723
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/days/Day4.kt
MaciejLipinski
317,582,924
true
{"Kotlin": 60261}
package days class Day4 : Day(4) { override fun partOne(): Any { return splitIntoPassports(inputString) .map { Passport.from(it) } .count { it.isValid() } } override fun partTwo(): Any { return splitIntoPassports(inputString) .map { Passport.from(it) } .count { it.isValid2() } } private fun splitIntoPassports(input: String): List<String> { val passports = mutableListOf<String>() val passportLines = mutableListOf<String>() for (i in inputList.indices) { if (inputList[i].isBlank()) { passports.add(passportLines.reduce { acc, s -> "$acc $s" }) passportLines.clear() continue } passportLines.add(inputList[i]) } passports.add(passportLines.reduce { acc, s -> "$acc $s" }) return passports } } data class Passport( val birthYear: Int?, //byr (Birth Year) val issueYear: Int?, //iyr (Issue Year) val expirationYear: Int?, //eyr (Expiration Year) val height: String?, //hgt (Height) val hairColor: String?, //hcl (Hair Color) val eyeColor: String?, //ecl (Eye Color) val passportId: String?, //pid (Passport ID) val countryId: String? //cid (Country ID) ) { fun isValid(): Boolean { return birthYear != null && issueYear != null && expirationYear != null && height != null && hairColor != null && eyeColor != null && passportId != null } fun isValid2(): Boolean { return birthYear != null && issueYear != null && expirationYear != null && height != null && hairColor != null && eyeColor != null && passportId != null && birthYear >= 1920 && birthYear <= 2002 && issueYear >= 2010 && issueYear <= 2020 && expirationYear >= 2020 && expirationYear <= 2030 && validHeight() && validHairColor() && eyeColor in listOf("amb", "blu", "brn", "gry", "grn", "hzl", "oth") && validPassportId() } private fun validHeight(): Boolean { if (height != null && height.length >= 3) { val value = height.substring(0, height.lastIndex - 1).toInt() val unit = height.substring(height.lastIndex - 1, height.lastIndex + 1) if (unit == "cm" && value >= 150 && value <= 193) { return true } if (unit == "in" && value >= 59 && value <= 76) { return true } } return false } private fun validHairColor(): Boolean { if (hairColor != null) { return hairColor[0] == '#' && hairColor.length == 7 && hairColor.toCharArray(1).all { it.isDigit() || it in listOf('a','b','c','d','e','f') } } return false } private fun validPassportId(): Boolean { if (passportId != null) { return passportId.length == 9 && passportId.toCharArray().all { it.isDigit() } } return false } companion object { fun from(input: String): Passport { val fields = input .split(" ") .map { val pair = it.split(":"); pair.first() to pair.last() } return Passport( birthYear = fields.findLast { it.first == "byr" }?.second?.toInt(), issueYear = fields.findLast { it.first == "iyr" }?.second?.toInt(), expirationYear = fields.findLast { it.first == "eyr" }?.second?.toInt(), height = fields.findLast { it.first == "hgt" }?.second, hairColor = fields.findLast { it.first == "hcl" }?.second, eyeColor = fields.findLast { it.first == "ecl" }?.second, passportId = fields.findLast { it.first == "pid" }?.second, countryId = fields.findLast { it.first == "cid" }?.second, ) } } }
0
Kotlin
0
0
1c3881e602e2f8b11999fa12b82204bc5c7c5b51
4,343
aoc-2020
Creative Commons Zero v1.0 Universal
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[203]移除链表元素.kt
maoqitian
175,940,000
false
{"Kotlin": 354268, "Java": 297740, "C++": 634}
//给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。 // // // 示例 1: // // //输入:head = [1,2,6,3,4,5,6], val = 6 //输出:[1,2,3,4,5] // // // 示例 2: // // //输入:head = [], val = 1 //输出:[] // // // 示例 3: // // //输入:head = [7,7,7,7], val = 7 //输出:[] // // // // // 提示: // // // 列表中的节点在范围 [0, 104] 内 // 1 <= Node.val <= 50 // 0 <= k <= 50 // // Related Topics 链表 // 👍 621 👎 0 //leetcode submit region begin(Prohibit modification and deletion) /** * Example: * var li = ListNode(5) * var v = li.`val` * Definition for singly-linked list. * class ListNode(var `val`: Int) { * var next: ListNode? = null * } */ class Solution { fun removeElements(head: ListNode?, `val`: Int): ListNode? { val res = ListNode(0) res.next = head //记录当前的节点值 var temp = res while (temp.next != null){ if (temp.next.`val` == `val`){ //跳过当前节点 temp.next = temp.next.next }else{ temp = temp.next } } return res.next } } //leetcode submit region end(Prohibit modification and deletion)
0
Kotlin
0
1
8a85996352a88bb9a8a6a2712dce3eac2e1c3463
1,350
MyLeetCode
Apache License 2.0
src/aoc2018/kot/Day19.kt
Tandrial
47,354,790
false
null
package aoc2018.kot import VM18 import getWords import java.io.File import kotlin.math.sqrt object Day19 { fun partOne(input: List<String>) = solve(input, listOf("0" to 0L, "1" to 0L, "2" to 0L, "3" to 0L, "4" to 0L, "5" to 0L)) fun partTwo(input: List<String>) = solve(input, listOf("0" to 1L, "1" to 0L, "2" to 0L, "3" to 0L, "4" to 0L, "5" to 0L)) fun solve(input: List<String>, regs: List<Pair<String, Long>>): Long { val vm = VM18(input.drop(1), regs, input.first().getWords()[1]) val num = vm.run(day19 = true) return (1L..(sqrt(num.toDouble()).toLong() + 1L)).map { if (num % it == 0L) it + num / it else 0 }.sum() } } fun main(args: Array<String>) { val input = File("./input/2018/Day19_input.txt").readLines() println("Part One = ${Day19.partOne(input)}") println("Part Two = ${Day19.partTwo(input)}") }
0
Kotlin
1
1
9294b2cbbb13944d586449f6a20d49f03391991e
844
Advent_of_Code
MIT License
src/main/kotlin/github/walkmansit/aoc2020/Day23.kt
walkmansit
317,479,715
false
null
package github.walkmansit.aoc2020 class Day23(val input: String) : DayAoc<String, Long> { private class Game(input: String, extra: IntRange = 0..1) { private class Node(val value: Int, var left: Node?, var right: Node?) private var current: Node? = null private var nodesArr: Array<Node?>? = null init { var head = Node(0, null, null) var tale = head nodesArr = if (extra.first == 0) { Array(10) { null } } else { Array(1000001) { null } } for ((i, v) in input.withIndex()) { val vInt = v.toString().toInt() if (i == 0) { head = Node(v.toString().toInt(), null, null) nodesArr!![vInt] = head tale = head continue } val new = Node(vInt, tale, null) nodesArr!![vInt] = new tale.right = new tale = new } if (extra.first != 0) { for (e in extra) { val new = Node(e, tale, null) nodesArr!![e] = new tale.right = new tale = new } } tale.right = head head.left = tale current = head } fun turn() { val cutSet = mutableSetOf<Int>() val cutStart = current!!.right!! cutSet.add(cutStart.value) cutSet.add(cutStart.right!!.value) val cutEnd = cutStart.right!!.right!! cutSet.add(cutEnd.value) cutEnd.right!!.left = current current!!.right = cutEnd.right!! cutStart.left = null cutEnd.right = null fun findDestination(): Node { fun decrement(value: Int): Int { var suppose = value - 1 val max = if (nodesArr!!.size == 10) 9 else 1000000 return if (suppose == 0) max else suppose } var destValue: Int = decrement(current!!.value) while (cutSet.contains(destValue)) destValue = decrement(destValue) return nodesArr!![destValue]!! } val destination = findDestination() destination.right!!.left = cutEnd cutEnd.right = destination.right!! cutStart.left = destination destination.right = cutStart current = current!!.right!! } fun getNextTo(destValue: Int): String { val sb = StringBuilder() var search = nodesArr!![destValue]!!.right do { sb.append(search!!.value) search = search!!.right!! } while (search!!.value != destValue) return sb.toString() } fun multNextToOne(): Long { val first = nodesArr!![1] val a = first!!.right!!.value.toLong() val b = first!!.right!!.right!!.value return a * b } } override fun getResultPartOne(): String { val game = Game(input) repeat(100) { game.turn() } return game.getNextTo(1) } override fun getResultPartTwo(): Long { val game = Game(input, 10..1000000) repeat(10000000) { game.turn() } return game.multNextToOne() } }
0
Kotlin
0
0
9c005ac4513119ebb6527c01b8f56ec8fd01c9ae
3,534
AdventOfCode2020
MIT License
src/main/kotlin/days/Day11.kt
sicruse
315,469,617
false
null
package days class Day11 : Day(11) { // landscape bitmap states // - floor : can never have person occupancy // - chair : can be empty or host a person // distribution states // - no-person // - person // I imagine that each map "frame" can be modelled as a sequence private val rows = inputList.size private val cols = inputList.first().length private val landscapeMask: Array<IntArray> by lazy { Array(rows) { row -> IntArray(cols) { col -> if (inputList[row][col] == '#' || inputList[row][col] == 'L') 1 else 0 } } } private fun applyMask(data: Array<IntArray>): Array<IntArray> { // assume both arrays are the same size return Array(rows) { row -> IntArray(cols) { col -> if (landscapeMask[row][col] + data[row][col] == 2) 1 else 0 } } } private fun printFrame(data: Array<IntArray>) { val output = Array(rows) { row -> String(CharArray(cols) { col -> when { landscapeMask[row][col] + data[row][col] == 2 -> '#' landscapeMask[row][col] == 1 -> 'L' else -> '.' }})} println(output.joinToString("\n") + "\n") } private fun occupyByNeighbor(frame: Array<IntArray>, row: Int, col:Int): Boolean { // If a seat is empty (L) and there are no occupied seats adjacent to it, the seat becomes occupied. // If a seat is occupied (#) and four or more seats adjacent to it are also occupied, the seat becomes empty. // Otherwise, the seat's state does not change. if (landscapeMask[row][col] == 0) return false // no chair! val occupied = frame[row][col] == 1 val rowrange = ((row - 1)..(row + 1)).filter { it in 0..rows-1 } val colrange = ((col - 1)..(col + 1)).filter { it in 0..cols-1 } val surroundingOccupancy = rowrange.fold(0) { acc1, r -> acc1 + colrange.fold(0) { acc2, c -> acc2 + frame[r][c] } } - frame[row][col] return when(occupied) { true -> surroundingOccupancy < 4 false -> surroundingOccupancy == 0 } } private val populateByNeighbor: (Array<IntArray>) -> Array<IntArray> = { frame -> Array(rows) { row -> IntArray(cols) { col -> if (occupyByNeighbor(frame, row, col)) 1 else 0 } } } private fun paths(row: Int, col:Int): List<List<Pair<Int, Int>>> { // consider the first seat in each of [those] eight directions. val nesw = listOf ( if (row > 0) ((row - 1) downTo 0).map { Pair(it, col) } else emptyList(), if (col < cols) ((col +1)..cols-1).map { Pair(row, it) } else emptyList(), if (row < rows) ((row + 1)..rows-1).map { Pair(it, col) } else emptyList(), if (col > 0) ((col - 1) downTo 0).map { Pair(row, it) } else emptyList(), ) val neseswnw = listOf( nesw[0].map { it.first } zip nesw[1].map { it.second }, nesw[2].map { it.first } zip nesw[1].map { it.second }, nesw[2].map { it.first } zip nesw[3].map { it.second }, nesw[0].map { it.first } zip nesw[3].map { it.second }, ) return nesw + neseswnw } private fun visibleChairs(row: Int, col: Int) = paths(row, col).mapNotNull { path -> path.find { (r, c) -> landscapeMask[r][c] == 1 } } private fun occupyByVisibility(frame: Array<IntArray>, row: Int, col:Int): Boolean { if (landscapeMask[row][col] == 0) return false // no chair! val visibleOccupancy = visibleChairs(row, col).fold(0) { acc, (r,c) -> acc + frame[r][c] } return if (frame[row][col] == 1) visibleOccupancy < 5 else visibleOccupancy == 0 } private val populateByVisibility: (Array<IntArray>) -> Array<IntArray> = { frame -> Array(rows) { row -> IntArray(cols) { col -> if (occupyByVisibility(frame, row, col)) 1 else 0 } } } private fun frames(populate: (Array<IntArray>) -> Array<IntArray>): Sequence<Array<IntArray>> = sequence { var currentFrame = Array(rows) { IntArray(cols) { 0 } } var priorFrame: Array<IntArray>? = null yield(currentFrame) while (priorFrame == null || !priorFrame.contentDeepEquals(currentFrame)) { priorFrame = currentFrame currentFrame = applyMask(populate(priorFrame)) yield(currentFrame) } } override fun partOne(): Any { return frames(populateByNeighbor).last().fold(0) { acc1, r -> acc1 + r.fold(0, { acc2, c -> acc2 + c }) } } override fun partTwo(): Any { return frames(populateByVisibility).last().fold(0) { acc1, r -> acc1 + r.fold(0, { acc2, c -> acc2 + c }) } } }
0
Kotlin
0
0
9a07af4879a6eca534c5dd7eb9fc60b71bfa2f0f
4,706
aoc-kotlin-2020
Creative Commons Zero v1.0 Universal
src/Day07.kt
colmmurphyxyz
572,533,739
false
{"Kotlin": 19871}
import javax.swing.tree.TreeNode fun main() { class FileTreeNode(val name: String, val type: String, private val size: Int?, val parent: FileTreeNode?, val children: MutableList<FileTreeNode> = mutableListOf<FileTreeNode>()) { override fun toString(): String { return "$type $name, size: ${getSize()}\t parent: ${parent?.name}" } fun depth(): Int { if (parent == null) return 0 return 1 + parent.depth() } fun printTree() { println("${"\t" * depth()} ${toString()}") children.forEach { child -> child.printTree() } } fun getSize(): Int { if (type == "file") { return size!! } var s = 0 for (child in children) { s += child.getSize() } return s } fun hasChild(childName: String): Boolean { for (child in children) { if (child.name == childName) { return true } } return false } fun addChild(node: FileTreeNode) { children.add(node) } fun getChildByNameOrNull(childName: String): FileTreeNode? { for (child in children) { if (child.name == childName) { return child } } return null } } fun part1(input: List<String>): Int { val fileTreeRoot = FileTreeNode("/", "dir", null, null) var currentDirectory = fileTreeRoot val directories = mutableListOf<FileTreeNode>(fileTreeRoot) var i = 1 while (i < input.size) { val line = input[i] val components = line.split(" ") val command = components.slice(1 until components.size) if (command[0] == "cd") { if (command[1] == "..") { // go back 1 directory currentDirectory = currentDirectory.parent!! } else { val dirExists = currentDirectory.hasChild(command[1]) if (dirExists) { currentDirectory = currentDirectory.getChildByNameOrNull(command[1])!! } else { println("dir does not exist, creating now") val newNode = FileTreeNode(command[1], "dir", null, currentDirectory) currentDirectory.addChild(newNode) currentDirectory = newNode directories.add(newNode) } } } else { // command[0] == "ls" var j = i + 1 while (j < input.size && input[j][0] != '$') j += 1 val fileList = input.slice((i+1) until j).map { it -> it.split(" ") } for (file in fileList) { if (!currentDirectory.hasChild(file[1])) { val newNode = FileTreeNode( file[1], if (file[0] == "dir") "dir" else "file", if (file[0] == "dir") null else file[0].toInt(), currentDirectory ) currentDirectory.addChild(newNode) if (newNode.type == "dir") { directories.add(newNode) } } } i = j - 1 } i += 1 } var smallDirsSize = 0 for (dir in directories) { if (dir.getSize() < 100_000) { smallDirsSize += dir.getSize() } } return smallDirsSize } fun part2(input: List<String>): Int { val fileTreeRoot = FileTreeNode("/", "dir", null, null) var currentDirectory = fileTreeRoot val directories = mutableListOf<FileTreeNode>(fileTreeRoot) var i = 1 while (i < input.size) { val line = input[i] val components = line.split(" ") val command = components.slice(1 until components.size) if (command[0] == "cd") { if (command[1] == "..") { // go back 1 directory currentDirectory = currentDirectory.parent!! } else { val dirExists = currentDirectory.hasChild(command[1]) if (dirExists) { currentDirectory = currentDirectory.getChildByNameOrNull(command[1])!! } else { println("dir does not exist, creating now") val newNode = FileTreeNode(command[1], "dir", null, currentDirectory) currentDirectory.addChild(newNode) currentDirectory = newNode directories.add(newNode) } } } else { // command[0] == "ls" var j = i + 1 while (j < input.size && input[j][0] != '$') j += 1 val fileList = input.slice((i+1) until j).map { it -> it.split(" ") } for (file in fileList) { if (!currentDirectory.hasChild(file[1])) { val newNode = FileTreeNode( file[1], if (file[0] == "dir") "dir" else "file", if (file[0] == "dir") null else file[0].toInt(), currentDirectory ) currentDirectory.addChild(newNode) if (newNode.type == "dir") { directories.add(newNode) } } } i = j - 1 } i += 1 } val freeSpace = 70_000_000 - fileTreeRoot.getSize() val spaceToDelete = 30_000_000 - freeSpace println("need to delete a directory with size > $spaceToDelete") var smallestSuitableDirSize = Int.MAX_VALUE for (dir in directories) { val size = dir.getSize() if (size in (spaceToDelete + 1) until smallestSuitableDirSize) { smallestSuitableDirSize = size } } return smallestSuitableDirSize } val input = readInput("Day07") println("Part 1 answer: ${part1(input)}") println("Part 2 answer: ${part2(input)}") }
0
Kotlin
0
0
c5653691ca7e64a0ee7f8e90ab1b450bcdea3dea
6,682
aoc-2022
Apache License 2.0
y2023/src/main/kotlin/adventofcode/y2023/Day09.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2023 import adventofcode.io.AdventSolution fun main() { Day09.solve() } object Day09 : AdventSolution(2023, 9, "Mirage Maintenance") { override fun solvePartOne(input: String) = parse(input).sumOf { seq -> differences(seq).sumOf { it.last() } } override fun solvePartTwo(input: String) = parse(input).sumOf { seq -> differences(seq).map { it.first() }.toList().foldRight(0, Int::minus) } private fun parse(input: String) = input.lineSequence().map { it.split(" ").map(String::toInt) } private fun differences(seq: List<Int>) = generateSequence(seq) { it.zipWithNext { a, b -> b - a } }.takeWhile { row -> !row.all(0::equals) } }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
718
advent-of-code
MIT License
src/org/aoc2021/Day25.kt
jsgroth
439,763,933
false
{"Kotlin": 86732}
package org.aoc2021 import java.nio.file.Files import java.nio.file.Path object Day25 { private fun solve(lines: List<String>): Int { var grid = parseInput(lines) var turns = 0 while (true) { turns++ val prevGrid = grid grid = simulateTurn(grid) if (prevGrid == grid) { return turns } } } private fun simulateTurn(grid: List<List<Char>>): List<List<Char>> { return moveDown(moveRight(grid)) } private fun moveRight(grid: List<List<Char>>): List<List<Char>> { val newGrid = Array(grid.size) { Array(grid[0].size) { 'X' } } for (i in grid.indices) { for (j in grid[0].indices) { if (grid[i][j] == '>') { val nj = (j + 1) % grid[0].size if (grid[i][nj] == '.') { newGrid[i][j] = '.' newGrid[i][nj] = '>' } else if (newGrid[i][j] == 'X') { newGrid[i][j] = '>' } } else if (newGrid[i][j] == 'X') { newGrid[i][j] = grid[i][j] } } } return newGrid.map(Array<Char>::toList) } private fun moveDown(grid: List<List<Char>>): List<List<Char>> { val newGrid = Array(grid.size) { Array(grid[0].size) { 'X' } } for (i in grid.indices) { for (j in grid[0].indices) { if (grid[i][j] == 'v') { val ni = (i + 1) % grid.size if (grid[ni][j] == '.') { newGrid[i][j] = '.' newGrid[ni][j] = 'v' } else if (newGrid[i][j] == 'X') { newGrid[i][j] = 'v' } } else if (newGrid[i][j] == 'X') { newGrid[i][j] = grid[i][j] } } } return newGrid.map(Array<Char>::toList) } private fun parseInput(lines: List<String>): List<List<Char>> { return lines.map { line -> line.toCharArray().toList() } } @JvmStatic fun main(args: Array<String>) { val lines = Files.readAllLines(Path.of("input25.txt"), Charsets.UTF_8) val solution = solve(lines) println(solution) } }
0
Kotlin
0
0
ba81fadf2a8106fae3e16ed825cc25bbb7a95409
2,385
advent-of-code-2021
The Unlicense
src/main/kotlin/com/adrielm/aoc2020/solutions/day11/SeatingSimulator.kt
Adriel-M
318,860,784
false
null
package com.adrielm.aoc2020.solutions.day11 private val DIRECTIONS = listOf( Pair(-1, -1), Pair(-1, 0), Pair(-1, 1), Pair(0, -1), Pair(0, 1), Pair(1, -1), Pair(1, 0), Pair(1, 1) ) class SeatingSimulator( private val seatingData: List<List<Char>> ) { fun simulate(): SeatingSimulator { val copy = seatingData.map { it.toMutableList() } iterateAll { currentRow, currentCol, _ -> copy[currentRow][currentCol] = calculateNextState(currentRow, currentCol, 4) { r, c -> countNumberOfNeighbours(r, c) } } return SeatingSimulator(copy) } fun simulate2(): SeatingSimulator { val copy = seatingData.map { it.toMutableList() } iterateAll { currentRow, currentCol, _ -> copy[currentRow][currentCol] = calculateNextState(currentRow, currentCol, 5) { r, c -> countNumberOfNeighbours2(r, c) } } return SeatingSimulator(copy) } private fun calculateNextState( row: Int, col: Int, neighbourTolerance: Int, neighbourCounter: (r: Int, c: Int) -> Int ): Char { val currentState = seatingData[row][col] if (currentState == Seating.FLOOR.char) return currentState val numberOfNeighbours = neighbourCounter(row, col) return when { currentState == Seating.EMPTY_SEAT.char && numberOfNeighbours == 0 -> Seating.OCCUPIED_SEAT.char currentState == Seating.OCCUPIED_SEAT.char && numberOfNeighbours >= neighbourTolerance -> { Seating.EMPTY_SEAT.char } else -> currentState } } private fun countNumberOfNeighbours(currentRow: Int, currentCol: Int): Int { var numberOfNeighbours = 0 for (direction in DIRECTIONS) { val rowToCheck = currentRow + direction.first val colToCheck = currentCol + direction.second if (rowToCheck < 0 || rowToCheck >= seatingData.size) continue if (colToCheck < 0 || colToCheck >= seatingData[rowToCheck].size) continue if (seatingData[rowToCheck][colToCheck] == Seating.OCCUPIED_SEAT.char) numberOfNeighbours++ } return numberOfNeighbours } private fun countNumberOfNeighbours2(currentRow: Int, currentCol: Int): Int { var numberOfNeighbours = 0 for (direction in DIRECTIONS) { var magnitude = 1 while (true) { val rowToCheck = currentRow + (magnitude * direction.first) val colToCheck = currentCol + (magnitude * direction.second) if (rowToCheck < 0 || rowToCheck >= seatingData.size) break if (colToCheck < 0 || colToCheck >= seatingData[rowToCheck].size) break when (seatingData[rowToCheck][colToCheck]) { Seating.OCCUPIED_SEAT.char -> { numberOfNeighbours++ break } Seating.EMPTY_SEAT.char -> break } magnitude++ } } return numberOfNeighbours } fun countOccupiedSeats(): Int { var count = 0 iterateAll { _, _, currentValue -> if (currentValue == Seating.OCCUPIED_SEAT.char) count++ } return count } private inline fun iterateAll(lambda: (currentRow: Int, currentCol: Int, currentValue: Char) -> Unit) { for (row in seatingData.indices) { for (col in seatingData[row].indices) { lambda(row, col, seatingData[row][col]) } } } override fun equals(other: Any?): Boolean { return seatingData == (other as? SeatingSimulator)?.seatingData } override fun hashCode(): Int { return seatingData.hashCode() } override fun toString(): String { return seatingData.map { it.joinToString("") }.joinToString("\n") } }
0
Kotlin
0
0
8984378d0297f7bc75c5e41a80424d091ac08ad0
4,029
advent-of-code-2020
MIT License
src/d14.main.kts
cjfuller
317,725,797
false
null
import java.io.File data class Mask(val maskStr: String) { val orForm: Long = maskStr.replace(Regex("X"), "0").toLong(2) val andForm: Long = maskStr.replace(Regex("X"), "1").toLong(2) operator fun invoke(toValue: Long): Long { return (toValue and andForm) or orForm } fun addresses(baseAddr: Int): Sequence<Long> = sequence { val preFloatAddr = baseAddr.toLong() or orForm val floatingPositions = maskStr.reversed().withIndex().mapNotNull { (i, c) -> if (c == 'X') { i } else { null } } (0 until (1 shl floatingPositions.size)).forEach { floatingMask -> var building = preFloatAddr floatingPositions.withIndex().forEach { (i, pos) -> building = if (floatingMask and (1 shl i) == 0) { building.setBitAt(pos, false) } else { building.setBitAt(pos, true) } } yield(building) } } } fun parseMask(inputLine: String): Mask { return Mask(inputLine.substringAfter("mask = ")) } data class Write(val address: Int, val value: Long) { companion object { val parser = Regex("""mem\[(\d+)\] = (\d+)""") fun parse(inputLine: String): Write { val (_, addr, value) = parser.find(inputLine)?.groupValues!! return Write(addr.toInt(), value.toLong()) } } } data class Operation(val mask: Mask, val writes: List<Write>) fun Long.setBitAt(target: Int, value: Boolean): Long { return if (value) { this or (1L shl target) } else { this and (1L shl target).inv() } } fun parseInput(): List<Operation> = File("./data/d14.txt").readLines() .fold(listOf()) { ops, currLine -> if (currLine.startsWith("mask = ")) { ops + Operation(parseMask(currLine), listOf()) } else { ops.dropLast(1) + ops.last() .let { it.copy(writes = it.writes + Write.parse(currLine)) } } } println("Part 1:") val memory: MutableMap<Int, Long> = mutableMapOf() parseInput().forEach { op -> op.writes.forEach { w -> memory[w.address] = op.mask(w.value) } } println(memory.values.sum()) println("Part 2:") val memoryP2: MutableMap<Long, Long> = mutableMapOf() parseInput().forEach { op -> op.writes.forEach { w -> op.mask.addresses(w.address) .forEach { a -> memoryP2[a] = w.value } } } println(memoryP2.values.sum())
0
Kotlin
0
0
c3812868da97838653048e63b4d9cb076af58a3b
2,626
adventofcode2020
MIT License
scripts/Day17.kts
matthewm101
573,325,687
false
{"Kotlin": 63435}
import java.io.File import kotlin.math.max data class Pos(val x: Int, val y: Int) { operator fun plus(a: Pos) = Pos(x + a.x, y + a.y) fun inbounds() = x in 0..6 && y >= 0 } val RIGHT = Pos(1, 0) val LEFT = Pos(-1, 0) val DOWN = Pos(0, -1) data class Block(val blocks: List<Pos>) { val width = blocks.maxOf { it.x } + 1 val height = blocks.maxOf { it.y } + 1 fun at(pos: Pos) = blocks.map { it + pos } } val block1 = Block(listOf(Pos(0,0), Pos(1,0), Pos(2,0), Pos(3,0))) val block2 = Block(listOf(Pos(1,0), Pos(0,1), Pos(1,1), Pos(2, 1), Pos(1, 2))) val block3 = Block(listOf(Pos(0,0), Pos(1,0), Pos(2,0), Pos(2,1), Pos(2,2))) val block4 = Block(listOf(Pos(0,0), Pos(0,1), Pos(0,2), Pos(0,3))) val block5 = Block(listOf(Pos(0,0), Pos(1,0), Pos(0,1), Pos(1,1))) val blockCycle = listOf(block1, block2, block3, block4, block5) val wind = File("../inputs/17.txt").readText().map { if (it == '>') RIGHT else LEFT } data class State(val block: Int, val wind: Int, val h1: Int, val h2: Int, val h3: Int, val h4: Int, val h5: Int, val h6: Int, val h7: Int) class Tower { var blockIndex = 0 var windIndex = 0 val tower = mutableSetOf<Pos>() var height = 0 fun drop() { val block = blockCycle[blockIndex++] if (blockIndex == 5) blockIndex = 0 var blockPos = Pos(2, height + 3) while (true) { if (block.at(blockPos + wind[windIndex]).all { it.inbounds() && it !in tower }) blockPos += wind[windIndex] windIndex++ if (windIndex == wind.size) windIndex = 0 if (block.at(blockPos + DOWN).all {it.inbounds() && it !in tower}) blockPos += DOWN else { val newBlocks = block.at(blockPos) height = max(height, newBlocks.maxOf { it.y } + 1) tower.addAll(newBlocks) break } } } fun printTower() { for (i in height downTo 0) { print("|") (0..6).forEach { if (Pos(it,i) in tower) print("#") else print(".") } println("|") } println("+-------+") println() } fun probe(i: Int): Int { var j = 0 while (height-j-1 >= 0 && Pos(i,height-j-1) !in tower) j++ return j } fun dumpState() = State(blockIndex, windIndex, probe(0), probe(1), probe(2), probe(3), probe(4), probe(5), probe(6)) } run { val tower = Tower() for (i in 1..2022) { tower.drop() } println("After 2022 blocks are dropped, the tower's height is ${tower.height}.") } run { val tower = Tower() val states = mutableMapOf(tower.dumpState() to Pair(0,0L)) val heights = mutableListOf(0L) var cycleStart = 0L var cycleLength = 0L var cycleHeightGain = 0L for (i in 1..1000000) { tower.drop() heights += tower.height.toLong() val last = states.put(tower.dumpState(), Pair(i,tower.height.toLong())) if (last != null) { cycleStart = last.first.toLong() cycleLength = i - cycleStart cycleHeightGain = tower.height.toLong() - last.second break } } val elapsedCycles = (1000000000000 - cycleStart) / cycleLength val lastCycles = (1000000000000 - cycleStart) % cycleLength val totalCycleHeight = elapsedCycles * cycleHeightGain val startingEndingHeight = heights[(cycleStart + lastCycles).toInt()] val finalHeight = totalCycleHeight + startingEndingHeight println("After a trillion blocks are dropped, the final height is $finalHeight.") }
0
Kotlin
0
0
bbd3cf6868936a9ee03c6783d8b2d02a08fbce85
3,686
adventofcode2022
MIT License
00-code(源代码)/src/com/hi/dhl/algorithms/offer/_17/kotlin/Solution.kt
hi-dhl
256,677,224
false
null
package com.hi.dhl.algorithms.offer._17.kotlin /** * <pre> * author: dhl * date : 2020/8/5 * desc : * </pre> */ class Solution { // 方法一 fun printNumbers2(n: Int): IntArray { var max = 1; for (i in 1..n) { max = max * 10; } val result = IntArray(max - 1) for (i in 1 until max) { result[i - 1] = i } return result; } // 方法二 val defNum = charArrayOf('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'); var index = 0; fun printNumbers(n: Int): IntArray { val num = CharArray(n) var max = 1 // kotlin 中使用 Math.pow 要求参数都是double类型,所以这里自动生成对应的位数 for (i in 1..n) { max = max * 10; } val result = IntArray(max - 1) dfs(num, result, 0) // 开始递归遍历 return result; } fun dfs(num: CharArray, result: IntArray, x: Int) { if (x == num.size) { // 生成的数字前面可能有 0 例如:000,001,002... 等等 // parstInt 方法去删除高位多余的 0 val res = parstInt(num); // 过滤掉第一个数字 0 if (res > 0) { result[index] = res index = index + 1 } return; } for (c in defNum) { num[x] = c dfs(num, result, x + 1) } } fun parstInt(num: CharArray): Int { var sum = 0 var isNotZero = false for (c in num) { // 生成的数字前面可能有 0 例如:000,001,002... 等等 // 过滤掉高位多余的 0 if (!isNotZero) { if (c == '0') { continue } else { isNotZero = true } } sum = sum * 10 + (c - '0') } return sum; } }
0
Kotlin
48
396
b5e34ac9d1da60adcd9fad61da4ec82e2cefc044
1,983
Leetcode-Solutions-with-Java-And-Kotlin
Apache License 2.0
src/questions/common/LeetTreeNode.kt
realpacific
234,499,820
false
null
package questions.common import _utils.SkipDocumentation import algorithmdesignmanualbook.padLeft import java.util.* import kotlin.test.assertFalse import kotlin.test.assertTrue @SkipDocumentation class TreeNode(var `val`: Int) { var left: TreeNode? = null var right: TreeNode? = null override fun toString(): String { return "TreeNode(${`val`})" } fun isLeaf() = left == null && right == null fun breadthFirstTraversal() { val queue = LinkedList<TreeNode?>() queue.add(this) while (queue.isNotEmpty()) { val current = queue.removeFirst() print(current?.`val`?.toString()?.padLeft(3) ?: " null ") if (current != null) { queue.addLast(current.left) queue.addLast(current.right) } } } fun isSameAs(node: TreeNode?): Boolean { return Companion.isSameAs(this, node) } companion object { fun from(arr: Array<Int?>): TreeNode? { if (arr.isEmpty()) { return null } val node = TreeNode(arr[0]!!) val queue = LinkedList<TreeNode?>() queue.add(node) for (i in 1..arr.lastIndex) { var current = queue.first while (current == null) { queue.removeFirstOrNull() current = queue.first } val newNode = arr.getOrNull(i)?.let { TreeNode(it) } if (i % 2 != 0) { current.left = newNode queue.addLast(current.left) } else { current.right = newNode queue.addLast(current.right) queue.removeFirstOrNull() } } return node } fun from(first: Int, vararg arr: Int): TreeNode { return from(arrayOf(first, *arr.toTypedArray()))!! } fun isSameAs(n1: TreeNode?, n2: TreeNode?): Boolean { if (n1 == null && n2 == null) { return true } if ((n1 == null && n2 != null) || (n1 != null && n2 == null)) { return false } if (n1 != null && n2 != null && n1.`val` != n2.`val`) { return false } if ( ((n1!!.left == null && n2!!.left == null) || (n1.left?.`val` == n2!!.left?.`val`)) && ((n1.right == null && n2.right == null) || (n1.right?.`val` == n2.right?.`val`)) ) { return isSameAs(n1.left, n2.left) && isSameAs(n1.right, n2.right) } return false } } } fun main() { // https://assets.leetcode.com/uploads/2021/01/18/pathsum1.jpg val node = TreeNode.from(arrayOf(5, 4, 8, 11, null, 13, 4, 7, 2, null, null, null, 1)) node?.breadthFirstTraversal() assertTrue(node!!.isSameAs(node)) assertFalse(node.isSameAs(TreeNode.from(arrayOf(5, 4, 8, 11, null, 13, 4, 7, 2, null, null, null))!!)) assertTrue(TreeNode.from(1, 2, 3, 4, 5).isSameAs(TreeNode.from(1, 2, 3, 4, 5))) assertFalse(TreeNode.from(1, 2, 3, 4, 5).isSameAs(TreeNode.from(1, 2, 3, 4, 5, 6))) assertFalse(TreeNode.from(1, 2, 3, 4, 5, 6, 7).isSameAs(TreeNode.from(1, 2, 3, 4, 5, 6))) assertFalse(TreeNode.from(1, 3, 2).isSameAs(TreeNode.from(1, 2, 3))) }
4
Kotlin
5
93
22eef528ef1bea9b9831178b64ff2f5b1f61a51f
3,450
algorithms
MIT License
src/aoc2017/kot/Day06.kt
Tandrial
47,354,790
false
null
package aoc2017.kot import toIntList import java.io.File object Day06 { fun f(mem: List<Int>): List<Int> { val next = mem.toMutableList() var (idx, max) = mem.withIndex().maxBy { it.value }!! next[idx] = 0 while (max-- > 0) { next[++idx % mem.size]++ } return next.toList() } fun solve(x0: List<Int>): Pair<Int, Int> { var tortoise = f(x0) var hare = f(f(x0)) while (tortoise != hare) { tortoise = f(tortoise) hare = f(f(hare)) } var mu = 0 tortoise = x0 while (tortoise != hare) { tortoise = f(tortoise) hare = f(hare) mu += 1 } var lambda = 1 hare = f(tortoise) while (tortoise != hare) { hare = f(hare) lambda += 1 } return Pair(mu, lambda) } } fun main(args: Array<String>) { val input = File("./input/2017/Day06_input.txt").readText().toIntList() val (mu, lambda) = Day06.solve(input) println("Part One = ${mu + lambda}") println("Part Two = $lambda") }
0
Kotlin
1
1
9294b2cbbb13944d586449f6a20d49f03391991e
1,008
Advent_of_Code
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/MaxProfitStock.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 kotlin.math.max /** * 309. Best Time to Buy and Sell Stock with Cooldown * @see <a href="https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown"> * Source</a> */ fun interface MaxProfitStock { operator fun invoke(prices: IntArray): Int } class MaxProfitStockImpl : MaxProfitStock { override operator fun invoke(prices: IntArray): Int { var coolDown = 0 var sell = 0 var hold = Int.MIN_VALUE for (stockPrice in prices) { val prevCoolDown = coolDown val prevHold = hold coolDown = max(prevCoolDown, sell) sell = prevHold + stockPrice hold = max(hold, prevCoolDown - stockPrice) } return max(coolDown, sell) } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,411
kotlab
Apache License 2.0
src/Day02.kt
colmmurphyxyz
572,533,739
false
{"Kotlin": 19871}
fun main() { val pointsOnPlay: (Char) -> Int = { c: Char -> if (c.code !in 88..90) { throw IllegalArgumentException("input must be a character in (X, Y, Z)") } c.code - 87 } fun part1(): Int { val input = readInput("Day02") val keyLosesToVal = mapOf<Char, Char>( 'A' to 'Y', 'B' to 'Z', 'C' to 'X' ) var score = 0 // for each 'round', simulate the result for (round in input) { val opponentChoice = round[0] val playerChoice = round[2] if (keyLosesToVal[opponentChoice] == playerChoice) { // player wins score += 6 } else if (opponentChoice.code + 23 == playerChoice.code) { // draw score += 3 } // else, player loses score += pointsOnPlay(playerChoice) } return score } fun part2(): Int { val input = readInput("Day02") var score = 0 for (round in input) { val opponentChoice = round[0] val neededOutcome = round[2] when (neededOutcome) { /* rock -> 1 paper -> 2 scissors -> 3 */ 'X' -> { // must lose var s = (opponentChoice.code - 64) + 2 if (s > 3) s %= 3 score += s // println("need to lose, opponent chose $opponentChoice, picking $s") } 'Y' -> { // must draw score += 3 score += opponentChoice.code - 64 // println("need to draw, opponent chose $opponentChoice, picking ${opponentChoice.code - 64}") } 'Z' -> { // must win score += 6 var s = (((opponentChoice.code - 64) + 1)) if (s > 3) s -= 3 score += s // println("need to win, opponent chose $opponentChoice, picking $s") } else -> throw IllegalArgumentException() } } return score } println("Part 1 answer: ${part1()}") println("Part 2 answer: ${part2()}") }
0
Kotlin
0
0
c5653691ca7e64a0ee7f8e90ab1b450bcdea3dea
2,325
aoc-2022
Apache License 2.0
src/main/kotlin/com/quakbo/euler/Euler4.kt
quincy
120,237,243
false
null
package com.quakbo.euler /* A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers. */ internal fun isPalindrome(n: Int): Boolean { val s = n.toString() return s.reversed() == s } fun main(args: Array<String>) { done@ for (i in 999 downTo 900) { for (j in 999 downTo 900) { val product = i * j if (isPalindrome(product)) { println(product) break@done } } } } /* Earlier was saw the range operator which creates a Sequence. 1..999 We can also create a sequence of decreasing values with the downTo operator. In Kotlin we write a foreach loop as for (v in someRangeOfValues) The in operator can be used in the following ways - specifies the object being iterated in a for loop - is used as an infix operator to check that a value belongs to a range, a collection or another entity that defines the 'contains' method - is used in when expressions for the same purpose done@ is a label to help with flow control. When we say break@done, we're saying break out of the loop labeled with done@. Without the label we would have broken out of the loop at line 16 and begun another iteration of the outer for loop. There are implicit labels for loop constructs. So you can do things like this... while (foo < 100) { for (i in 1..foo) { if (foo == 2) { continue@while } } } If blocks are known as conditional expressions because they return a value. So you are allowed to assign from them. fun maxOf(a: Int, b: Int) = if (a > b) a else b */
0
Kotlin
0
0
01d96f61bda6e87f1f58ddf7415d9bca8a4913de
1,751
euler-kotlin
The Unlicense
src/main/kotlin/adventofcode/year2015/Day16AuntSue.kt
pfolta
573,956,675
false
{"Kotlin": 199554, "Dockerfile": 227}
package adventofcode.year2015 import adventofcode.Puzzle import adventofcode.PuzzleInput class Day16AuntSue(customInput: PuzzleInput? = null) : Puzzle(customInput) { private val aunts by lazy { input .lines() .map { aunt -> val id = aunt.split(": ").first().split(" ").last().toInt() val fields = aunt.substring(4 + id.toString().length + 2).split(", ").map { it.split(": ") } val children = fields.find { it.first() == "children" }?.last()?.toInt() val cats = fields.find { it.first() == "cats" }?.last()?.toInt() val samoyeds = fields.find { it.first() == "samoyeds" }?.last()?.toInt() val pomeranians = fields.find { it.first() == "pomeranians" }?.last()?.toInt() val akitas = fields.find { it.first() == "akitas" }?.last()?.toInt() val vizslas = fields.find { it.first() == "vizslas" }?.last()?.toInt() val goldfish = fields.find { it.first() == "goldfish" }?.last()?.toInt() val trees = fields.find { it.first() == "trees" }?.last()?.toInt() val cars = fields.find { it.first() == "cars" }?.last()?.toInt() val perfumes = fields.find { it.first() == "perfumes" }?.last()?.toInt() AuntSue(id, children, cats, samoyeds, pomeranians, akitas, vizslas, goldfish, trees, cars, perfumes) } } override fun partOne() = aunts .asSequence() .filter { it.children == null || it.children == TICKER_TAPE_SUE.children!! } .filter { it.cats == null || it.cats == TICKER_TAPE_SUE.cats!! } .filter { it.samoyeds == null || it.samoyeds == TICKER_TAPE_SUE.samoyeds!! } .filter { it.pomeranians == null || it.pomeranians == TICKER_TAPE_SUE.pomeranians!! } .filter { it.akitas == null || it.akitas == TICKER_TAPE_SUE.akitas!! } .filter { it.vizslas == null || it.vizslas == TICKER_TAPE_SUE.vizslas!! } .filter { it.goldfish == null || it.goldfish == TICKER_TAPE_SUE.goldfish!! } .filter { it.trees == null || it.trees == TICKER_TAPE_SUE.trees!! } .filter { it.cars == null || it.cars == TICKER_TAPE_SUE.cars!! } .filter { it.perfumes == null || it.perfumes == TICKER_TAPE_SUE.perfumes!! } .first() .id!! override fun partTwo() = aunts .asSequence() .filter { it.children == null || it.children == TICKER_TAPE_SUE.children!! } .filter { it.cats == null || it.cats > TICKER_TAPE_SUE.cats!! } .filter { it.samoyeds == null || it.samoyeds == TICKER_TAPE_SUE.samoyeds!! } .filter { it.pomeranians == null || it.pomeranians < TICKER_TAPE_SUE.pomeranians!! } .filter { it.akitas == null || it.akitas == TICKER_TAPE_SUE.akitas!! } .filter { it.vizslas == null || it.vizslas == TICKER_TAPE_SUE.vizslas!! } .filter { it.goldfish == null || it.goldfish < TICKER_TAPE_SUE.goldfish!! } .filter { it.trees == null || it.trees > TICKER_TAPE_SUE.trees!! } .filter { it.cars == null || it.cars == TICKER_TAPE_SUE.cars!! } .filter { it.perfumes == null || it.perfumes == TICKER_TAPE_SUE.perfumes!! } .first() .id!! companion object { private val TICKER_TAPE_SUE = AuntSue( children = 3, cats = 7, samoyeds = 2, pomeranians = 3, akitas = 0, vizslas = 0, goldfish = 5, trees = 3, cars = 2, perfumes = 1 ) private data class AuntSue( val id: Int? = null, val children: Int? = null, val cats: Int? = null, val samoyeds: Int? = null, val pomeranians: Int? = null, val akitas: Int? = null, val vizslas: Int? = null, val goldfish: Int? = null, val trees: Int? = null, val cars: Int? = null, val perfumes: Int? = null ) } }
0
Kotlin
0
0
72492c6a7d0c939b2388e13ffdcbf12b5a1cb838
4,057
AdventOfCode
MIT License
year2019/day12/body/src/main/kotlin/com/curtislb/adventofcode/year2019/day12/body/NBodySystem.kt
curtislb
226,797,689
false
{"Kotlin": 2146738}
package com.curtislb.adventofcode.year2019.day12.body import com.curtislb.adventofcode.common.iteration.uniquePairs import com.curtislb.adventofcode.common.io.mapLines import com.curtislb.adventofcode.common.vector.IntVector import java.io.File /** * A system of multiple celestial bodies, which move and exert gravity on each other in 3D space. * * @param file The file from which the initial positions for all bodies will be read, one per line. */ class NBodySystem(file: File) { /** * The current states (positions and velocities) of all bodies in the system. */ var bodies: List<Body> = file.mapLines { Body.fromPositionString(it) } private set /** * Returns the current total energy (potential and kinetic) of the system. */ fun totalEnergy(): Int = bodies.sumOf { it.totalEnergy() } /** * Updates the positions and velocities of all bodies for a given number of time [steps]. */ fun simulate(steps: Int = 1) { for (step in 1..steps) { for ((bodyA, bodyB) in bodies.uniquePairs()) { bodyA.applyGravity(bodyB) bodyB.applyGravity(bodyA) } for (body in bodies) { body.applyVelocity() } } } /** * Returns a vector representing the periodicity of the system along each 3D axis. * * The period of an axis is the number of iterations required for the position and velocity of * all bodies along that axis to return to their initial values. * * Note that calling this function may cause the positions and velocities of bodies in the * system to change. */ fun findPerAxisPeriods(): IntVector { // Store the initial body configurations for each axis val axisFilter = BooleanArray(Body.DIMENSION_COUNT) { true } val initialValues = perAxisComponentValues(axisFilter) // Run simulation until the periods of all axes are found val periods = IntVector(Body.DIMENSION_COUNT) { -1 } var steps = 0 while (axisFilter.any { it }) { // Update the positions and velocities of all bodies simulate() steps++ // Check if any axes have returned to their initial configurations val axisValues = perAxisComponentValues(axisFilter) for (index in initialValues.indices) { if (axisFilter[index] && axisValues[index] == initialValues[index]) { periods[index] = steps } } for (index in axisFilter.indices) { axisFilter[index] = periods[index] == -1 } } return periods } private fun perAxisComponentValues(axisFilter: BooleanArray): List<List<Int>> { val values = List(axisFilter.size) { index -> if (axisFilter[index]) mutableListOf<Int>() else emptyList() } for (body in bodies) { val position = body.position() val velocity = body.velocity() for (index in values.indices) { if (axisFilter[index]) { with(values[index] as MutableList<Int>) { add(position[index]) add(velocity[index]) } } } } return values } override fun toString(): String = bodies.joinToString(separator = "\n") }
0
Kotlin
1
1
6b64c9eb181fab97bc518ac78e14cd586d64499e
3,485
AdventOfCode
MIT License
src/main/App.kt
neelkamath
185,819,512
false
null
package com.neelkamath.life /** * Uses [seed] to create a [System] having the specified number of [columns]. * * [seed] should contain `A` for [Cell.ALIVE], and `D` for [Cell.DEAD]. For example, if [columns] is `4`, and [seed] is * `ADDDADDDDAAD`, the [System] returned will have three rows, and four columns. */ private fun createSystem(seed: String, columns: Int) = seed.map { if (it == 'A') Cell.ALIVE else Cell.DEAD }.chunked(columns).map { it.toMutableList() } /** Returns whether [system] has at least one [Cell.ALIVE]. */ private fun hasPopulation(system: System) = system.flatten().count { it == Cell.ALIVE } > 0 /** * Returns [system] as a human readable [String]. * * The [String] will look like: * ``` * 1 0 1 * 1 1 0 * 0 0 0 * ``` * Each row is separated by a new line, and each column a space. `1` denotes [Cell.ALIVE], and `0` [Cell.DEAD]. */ private fun prettifySystem(system: System) = system .asSequence() .flatten() .map { if (it == Cell.ALIVE) 1 else 0 } .chunked(system[0].size) .map { it.joinToString(" ") } .joinToString("\n") fun main() { println("Enter options without quotation marks.") print("Enter the number of ticks to perform (\"-1\" generates until the game ends): ") val ticks = readLine()!!.toInt() print("Enter the number of columns: ") val columns = readLine()!!.toInt() val life: Life loop@ while (true) { print("Enter \"s\" to specify the seed, or \"r\" to use a randomly generated seed: ") life = when (readLine()) { "s" -> { print("Use \"A\" for alive cells, and \"D\" for dead cells. ") print("Enter the seed (e.g., \"ADDDADDDDAAD\" is a grid with three rows and four columns): ") Life(createSystem(readLine()!!, columns)) } "r" -> { print("Enter the number of rows: ") Life(readLine()!!.toInt(), columns) } else -> continue@loop } break } with(life) { println("Seed:\n${prettifySystem(system)}") if (ticks == -1) { var generation = 0 while (true) { if (!hasPopulation(system)) { println("The game is over.") return } tick() println("Generation ${++generation}:\n${prettifySystem(system)}") } } else { repeat(ticks) { if (!hasPopulation(system)) { println("The game is over.") return } tick() println("Generation ${it + 1}:\n${prettifySystem(system)}") } } } }
0
Kotlin
0
0
24cdb2409cc25229db492344bba72a90c584292e
2,760
conways-game-of-life
MIT License
src/Day03.kt
jinie
572,223,871
false
{"Kotlin": 76283}
class Day03(private val input: List<String>) { fun part1(): Int = input.sumOf { it.sharedItems().priority() } fun part2(): Int = input.chunked(3).sumOf { it.sharedItems().priority() } private fun Char.priority(): Int = when (this) { in 'a'..'z' -> (this - 'a') + 1 in 'A'..'Z' -> (this - 'A') + 27 else -> 0 } private fun String.sharedItems(): Char = listOf( substring(0..length / 2), substring(length / 2) ).sharedItems() private fun List<String>.sharedItems(): Char = map { it.toSet() }.reduce { l, r -> l intersect r}.first() } fun main() { measureTimeMillisPrint { val input = readInput("Day03") println("Part 1: ${Day03(input).part1()}") println("Part 2: ${Day03(input).part2()}") } }
0
Kotlin
0
0
4b994515004705505ac63152835249b4bc7b601a
863
aoc-22-kotlin
Apache License 2.0
year2019/day15/part2/src/main/kotlin/com/curtislb/adventofcode/year2019/day15/part2/Year2019Day15Part2.kt
curtislb
226,797,689
false
{"Kotlin": 2146738}
/* --- Part Two --- You quickly repair the oxygen system; oxygen gradually fills the area. Oxygen starts in the location containing the repaired oxygen system. It takes one minute for oxygen to spread to all open locations that are adjacent to a location that already contains oxygen. Diagonal locations are not adjacent. In the example above, suppose you've used the droid to explore the area fully and have the following map (where locations that currently contain oxygen are marked O): ## #..## #.#..# #.O.# ### Initially, the only location which contains oxygen is the location of the repaired oxygen system. However, after one minute, the oxygen spreads to all open (.) locations that are adjacent to a location containing oxygen: ## #..## #.#..# #OOO# ### After a total of two minutes, the map looks like this: ## #..## #O#O.# #OOO# ### After a total of three minutes: ## #O.## #O#OO# #OOO# ### And finally, the whole region is full of oxygen after a total of four minutes: ## #OO## #O#OO# #OOO# ### So, in this example, all locations contain oxygen after 4 minutes. Use the repair droid to get a complete map of the area. How many minutes will it take to fill with oxygen? */ package com.curtislb.adventofcode.year2019.day15.part2 import com.curtislb.adventofcode.year2019.day15.repair.Droid import java.nio.file.Path import java.nio.file.Paths import kotlin.math.max /** * Returns the solution to the puzzle for 2019, day 15, part 2. * * @param inputPath The path to the input file for this puzzle. */ fun solve(inputPath: Path = Paths.get("..", "input", "input.txt")): Long? { // Have the droid fully explore the grid val droid = Droid(inputPath.toFile()).apply { explore() } // Get the position of the oxygen system val oxygenStartPosition = droid.goalPosition ?: return null // Use BFS to find the furthest open space from the oxygen system var maxDistance = 0L droid.exploredGraph.bfsApply(oxygenStartPosition) { _, distance -> maxDistance = max(maxDistance, distance) false // Keep searching } return maxDistance } fun main() { when (val solution = solve()) { null -> println("No solution") else -> println(solution) } }
0
Kotlin
1
1
6b64c9eb181fab97bc518ac78e14cd586d64499e
2,245
AdventOfCode
MIT License
src/main/kotlin/me/giacomozama/adventofcode2022/days/Day12.kt
giacomozama
572,965,253
false
{"Kotlin": 75671}
package me.giacomozama.adventofcode2022.days import java.io.File import java.util.* class Day12 : Day() { private lateinit var input: List<CharArray> override fun parseInput(inputFile: File) { input = inputFile.useLines { lines -> lines.map { it.toCharArray() }.toList() } } // n = numbers of squares // time: O(n), space: O(n) override fun solveFirstPuzzle(): Int { val dirs = arrayOf(intArrayOf(-1, 0), intArrayOf(0, 1), intArrayOf(1, 0), intArrayOf(0, -1)) var curChar = 'a' var cur: IntArray? = null y@ for (y in input.indices) { for (x in input[0].indices) { if (input[y][x] == 'S') { cur = intArrayOf(y, x, 0) break@y } } } cur ?: error("No square marked with 'S'") val visited = Array(input.size) { BooleanArray(input[0].size) } visited[cur[0]][cur[1]] = true val queue = LinkedList<IntArray>() while (cur != null) { val (y, x, d) = cur for ((dy, dx) in dirs) { val ty = y + dy val tx = x + dx if (ty !in input.indices || tx !in input[0].indices || visited[ty][tx]) continue val tc = input[ty][tx] if (tc != 'E' && tc <= curChar + 1 || tc == 'E' && curChar >= 'y') { if (tc == 'E') return d + 1 queue.offer(intArrayOf(ty, tx, d + 1)) visited[ty][tx] = true } } cur = queue.poll()?.also { (cy, cx) -> curChar = input[cy][cx] } } error("No squares marked with 'E'") } // time: O(n), space: O(n) override fun solveSecondPuzzle(): Any { val dirs = arrayOf(intArrayOf(-1, 0), intArrayOf(0, 1), intArrayOf(1, 0), intArrayOf(0, -1)) var curChar = 'z' var cur: IntArray? = null y@ for (y in input.indices) { for (x in input[0].indices) { if (input[y][x] == 'E') { cur = intArrayOf(y, x, 0) break@y } } } cur ?: error("No square marked with 'E'") val visited = Array(input.size) { BooleanArray(input[0].size) } visited[cur[0]][cur[1]] = true val queue = LinkedList<IntArray>() while (cur != null) { val (y, x, d) = cur for ((dy, dx) in dirs) { val ty = y + dy val tx = x + dx if (ty !in input.indices || tx !in input[0].indices || visited[ty][tx]) continue val tc = input[ty][tx] if (tc >= curChar - 1 || tc == 'S' && curChar == 'b') { if (tc == 'a' || tc == 'S') return d + 1 queue.offer(intArrayOf(ty, tx, d + 1)) visited[ty][tx] = true } } cur = queue.poll()?.also { (cy, cx) -> curChar = input[cy][cx] } } error("No squares marked with 'a' or 'S'") } }
0
Kotlin
0
0
c30f4a37dc9911f3e42bbf5088fe246aabbee239
3,114
aoc2022
MIT License