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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Contest/Biweekly Contest 73/Sort the Jumbled Numbers/SortJumbledNumbers.kt
|
xuedong
| 189,745,542 | false |
{"Kotlin": 332182, "Java": 294218, "Python": 237866, "C++": 97190, "Rust": 82753, "Go": 37320, "JavaScript": 12030, "Ruby": 3367, "C": 3121, "C#": 3117, "Swift": 2876, "Scala": 2868, "TypeScript": 2134, "Shell": 149, "Elixir": 130, "Racket": 107, "Erlang": 96, "Dart": 65}
|
class Solution {
fun sortJumbled(mapping: IntArray, nums: IntArray): IntArray {
val newList = ArrayList<Pair<Int, Int>>()
for (i in 0..nums.size-1) {
val pair = Pair(transform(mapping, nums[i]), i)
newList.add(pair)
}
val sortedList = newList.sortedWith(compareBy({ it.first }))
val result = IntArray(nums.size) { it -> nums[sortedList.get(it).second] }
return result
}
private fun transform(mapping: IntArray, num: Int): Int {
var result = 0
var multiply = 1
var curr = num
while (curr / 10 > 0) {
val rest = curr % 10
result += mapping[rest] * multiply
multiply *= 10
curr /= 10
}
result += mapping[curr] * multiply
return result
}
}
| 0 |
Kotlin
| 0 | 1 |
5e919965b43917eeee15e4bff12a0b6bea4fd0e7
| 861 |
leet-code
|
MIT License
|
calendar/day04/Day4.kt
|
rocketraman
| 573,845,375 | false |
{"Kotlin": 45660}
|
package day04
import Day
import Lines
class Day4 : Day() {
override fun part1(input: Lines): Any {
return input
.count { line ->
val (range1, range2) = line.split(",").map { p ->
p.split("-").let { it[0].toInt()..it[1].toInt() }
}
range1.containsRange(range2) || range2.containsRange(range1)
}
}
override fun part2(input: Lines): Any {
return input
.count { line ->
val (range1, range2) = line.split(",").map { p ->
p.split("-").let { it[0].toInt()..it[1].toInt() }
}
range1.overlapsRange(range2)
}
}
fun IntRange.containsRange(other: IntRange): Boolean =
this.first <= other.first && this.last >= other.last
fun IntRange.overlapsRange(other: IntRange): Boolean =
this.first in other || this.last in other || other.first in this || other.last in this
}
| 0 |
Kotlin
| 0 | 0 |
6bcce7614776a081179dcded7c7a1dcb17b8d212
| 878 |
adventofcode-2022
|
Apache License 2.0
|
kotlin/sort/Partition.kt
|
polydisc
| 281,633,906 | true |
{"Java": 540473, "Kotlin": 515759, "C++": 265630, "CMake": 571}
|
package sort
import java.util.Random
object Partition {
// like http://www.cplusplus.com/reference/algorithm/partition/
// but additionally places separator at the end of the first group
fun partition(a: IntArray, fromInclusive: Int, toExclusive: Int, separatorIndex: Int): Int {
var i = fromInclusive
var j = toExclusive - 1
val separator = a[separatorIndex]
swap(a, i++, separatorIndex)
while (i <= j) {
while (i <= j && a[i] < separator) ++i
while (i <= j && a[j] > separator) --j
if (i >= j) break
swap(a, i++, j--)
}
swap(a, j, fromInclusive)
return j
}
fun swap(a: IntArray, i: Int, j: Int) {
val t = a[j]
a[j] = a[i]
a[i] = t
}
// Random test
fun main(args: Array<String?>?) {
val rnd = Random(1)
for (step in 0..99999) {
val n: Int = rnd.nextInt(10) + 1
val a: IntArray = rnd.ints(n, 0, 10).toArray()
for (i in 0 until n) {
for (j in i until n) {
for (k in i..j) {
val b: IntArray = a.clone()
check(b, partition(b, i, j + 1, k), i, j)
}
}
}
}
}
fun check(a: IntArray, k: Int, lo: Int, hi: Int) {
if (k < lo || k > hi) throw RuntimeException()
for (i in lo..k) for (j in k..hi) if (a[i] > a[j]) throw RuntimeException()
}
}
| 1 |
Java
| 0 | 0 |
4566f3145be72827d72cb93abca8bfd93f1c58df
| 1,524 |
codelibrary
|
The Unlicense
|
src/main/java/dev/haenara/mailprogramming/solution/y2019/m08/d11/UseCase190811.kt
|
HaenaraShin
| 226,032,186 | false | null |
package dev.haenara.mailprogramming.solution.y2019.m08.d11
import dev.haenara.mailprogramming.solution.InvaildProgramArgumentException
import dev.haenara.mailprogramming.solution.UseCase
class UseCase190811(args: Array<String>) : UseCase<Pair<String, String>, String>(args) {
override val solution = Solution190811()
override val sampleInput = Pair("", "")
override val description = "* 매일프로그래밍 2019. 08. 11\n" +
" * 연결 리스트로 표현된 두 정수 A 와 B 가 있습니다. A 와 B 를 더한 결과를 연결 리스트로 리턴하시오.\n" +
" * Given two integers represented as linked lists, return a linked list that is a sum of the two given linked lists.\n" +
" *\n" +
" * Input: 1->2->3, 1->2->3 // 321 + 321\n" +
" * Output: 2->4->6 // 642\n" +
" *\n" +
" * Input: 1->5->6, 0->0->4 // 651 + 400\n" +
" * Output: 1->5->0->1 // 1051\n" +
" *\n" +
" * 풀이\n" +
" * 링크드리스트를 사용하는 대신 배열로 풀었으나, 순차적으로 더해나가므로 어느쪽이든 상관 없다.\n" +
" * N자리수의 자연수 합이므로 A1->A2->... , B1->B2->... 을 더하는 경우\n" +
" * An+Bn+(n-1)항의 받아올림(carrier) 으로 표현가능하다.\n" +
" * 따라서 이전 carrier만 기억하고 있다면 A와B와 덧셈없이 3차 배열로 값을 구할 수 있다."
override fun parseInput(args: Array<String>): Pair<String, String> {
return if (args.isEmpty()) {
throw InvaildProgramArgumentException()
} else if (args[0].trim().endsWith(",")){
Pair(args[0].substringBefore(","), args[1])
} else if (args.size == 1 && args[0].contains(",")){
args[0].split(",").let{
Pair(it[0], it[1])
}
} else if (args.size > 1 && args[0].contains(",").not()){
Pair(args[0], args[1])
} else {
throw InvaildProgramArgumentException()
}
}
override fun inputToString(input: Pair<String, String>) = "${input.first} , ${input.second}"
override fun outputToString(output: String) = output
}
| 0 |
Kotlin
| 0 | 7 |
b5e50907b8a7af5db2055a99461bff9cc0268293
| 2,264 |
MailProgramming
|
MIT License
|
src/main/kotlin/22-aug.kt
|
aladine
| 276,334,792 | false |
{"C++": 70308, "Kotlin": 53152, "Java": 10020, "Makefile": 511}
|
class Solution(rects: Array<IntArray>) {
private var totalPoints:Int = 0
private var prefixSum : List<Int> = mutableListOf()
private var rectangles:List<IntArray> = mutableListOf()
init {
val areas = rects.map { (it[2]-it[0]+1)*(it[3]-it[1]+1) }
totalPoints = areas.sum()
rectangles = rects.toList()
prefixSum = prefixSumsFunctional(areas)
println(prefixSum)
}
fun prefixSumsFunctional(numbers:List<Int>): List<Int>{
return generateSequence(numbers.fold(Any() to 0) { stack, value ->
stack to stack.second + value
}) { it.first as Pair<Any, Int> }
.map { it.second }
.take(numbers.size)
.toList().asReversed()
}
fun pick(): IntArray {
val index = (Math.random() * totalPoints).toInt()
var i = 0
while (i < prefixSum.size){
if(index < prefixSum[i]) break
i++
}
var currIdx = index
if(i!=0) currIdx = index - prefixSum[i-1]
val r = rectangles[i]
val width = r[3] - r[1]+1
val x = r[0]+currIdx / width
val y = r[1]+currIdx % width
return intArrayOf(x, y)
}
}
| 0 |
C++
| 1 | 1 |
54b7f625f6c4828a72629068d78204514937b2a9
| 1,215 |
awesome-leetcode
|
Apache License 2.0
|
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2016/2016-23.kt
|
ferinagy
| 432,170,488 | false |
{"Kotlin": 787586}
|
package com.github.ferinagy.adventOfCode.aoc2016
fun main() {
println("Part1:")
println(solve(testInput1, 0))
println(solve(input, 7))
println(solve2(7))
println(solve2(12))
println()
println("Part2:")
println(solve2(12))
}
private fun solve(input: String, value: Int): Long {
val comp = AssembunnyComputer()
val instructions = input.lines().map { AssembunnyComputer.Instruction.parse(it) }
comp.setRegister("a", value.toLong())
comp.execute(instructions)
return comp.state.registers["a"]!!
}
private fun solve2(value: Int) = 81 * 94 + factorial(value)
private fun factorial(n: Int): Int = if (n == 1) 1 else n * factorial(n - 1)
private const val testInput1 = """cpy 2 a
tgl a
tgl a
tgl a
cpy 1 a
dec a
dec a"""
private const val input = """cpy a b
dec b
cpy a d
cpy 0 a
cpy b c
inc a
dec c
jnz c -2
dec d
jnz d -5
dec b
cpy b c
cpy c d
dec d
inc c
jnz d -2
tgl c
cpy -16 c
jnz 1 c
cpy 81 c
jnz 94 d
inc a
inc d
jnz d -2
inc c
jnz c -5"""
| 0 |
Kotlin
| 0 | 1 |
f4890c25841c78784b308db0c814d88cf2de384b
| 1,001 |
advent-of-code
|
MIT License
|
src/main/kotlin/g0001_0100/s0018_4sum/Solution.kt
|
javadev
| 190,711,550 | false |
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
|
package g0001_0100.s0018_4sum
// #Medium #Array #Sorting #Two_Pointers #2023_07_03_Time_229_ms_(98.59%)_Space_37.8_MB_(100.00%)
class Solution {
fun fourSum(nums: IntArray, target: Int): List<List<Int>> {
val n = nums.size
nums.sort()
val result: MutableList<List<Int>> = ArrayList()
for (i in 0 until n - 3) {
if (i > 0 && nums[i] == nums[i - 1]) {
continue
}
if (nums[i].toLong() + nums[i + 1] + nums[i + 2] + nums[i + 3] > target) {
break
}
if (nums[i].toLong() + nums[n - 3] + nums[n - 2] + nums[n - 1] < target) {
continue
}
for (j in i + 1 until n - 2) {
if (j > i + 1 && nums[j] == nums[j - 1]) {
continue
}
if (nums[j].toLong() + nums[j + 1] + nums[j + 2] > target - nums[i]) {
break
}
if (nums[j].toLong() + nums[n - 2] + nums[n - 1] < target - nums[i]) {
continue
}
val tempTarget = target - (nums[i] + nums[j])
var low = j + 1
var high = n - 1
while (low < high) {
val curSum = nums[low] + nums[high]
if (curSum == tempTarget) {
val tempList: MutableList<Int> = ArrayList()
tempList.add(nums[i])
tempList.add(nums[j])
tempList.add(nums[low])
tempList.add(nums[high])
result.add(tempList)
low++
high--
while (low < high && nums[low] == nums[low - 1]) {
low++
}
while (low < high && nums[high] == nums[high + 1]) {
high--
}
} else if (curSum < tempTarget) {
low++
} else {
high--
}
}
}
}
return result
}
}
| 0 |
Kotlin
| 14 | 24 |
fc95a0f4e1d629b71574909754ca216e7e1110d2
| 2,245 |
LeetCode-in-Kotlin
|
MIT License
|
detekt-formatting/src/main/kotlin/io/gitlab/arturbosch/detekt/formatting/OffsetsToLineColumn.kt
|
hcknl
| 212,993,385 | true |
{"Kotlin": 1474242, "Groovy": 3832, "Shell": 1055, "HTML": 698}
|
package io.gitlab.arturbosch.detekt.formatting
import java.util.ArrayList
/**
* Extracted and adapted from KtLint.
*/
internal fun calculateLineColByOffset(text: String): (offset: Int) -> Pair<Int, Int> {
var i = -1
val e = text.length
val arr = ArrayList<Int>()
do {
arr.add(i + 1)
i = text.indexOf('\n', i + 1)
} while (i != -1)
arr.add(e + if (arr.last() == e) 1 else 0)
val segmentTree = SegmentTree(arr.toTypedArray())
return { offset ->
val line = segmentTree.indexOf(offset)
if (line != -1) {
val col = offset - segmentTree.get(line).left
line + 1 to col + 1
} else {
1 to 1
}
}
}
internal fun calculateLineBreakOffset(fileContent: String): (offset: Int) -> Int {
val arr = ArrayList<Int>()
var i = 0
do {
arr.add(i)
i = fileContent.indexOf("\r\n", i + 1)
} while (i != -1)
arr.add(fileContent.length)
return if (arr.size != 2) {
SegmentTree(arr.toTypedArray()).let { return { offset -> it.indexOf(offset) } }
} else { _ ->
0
}
}
internal class SegmentTree(sortedArray: Array<Int>) {
private val segments: List<Segment>
fun get(i: Int): Segment = segments[i]
fun indexOf(v: Int): Int = binarySearch(v, 0, this.segments.size - 1)
private fun binarySearch(v: Int, l: Int, r: Int): Int = if (l > r) -1 else {
val i = l + (r - l) / 2
val s = segments[i]
if (v < s.left) binarySearch(v, l, i - 1)
else (if (s.right < v) binarySearch(v, i + 1, r) else i)
}
init {
require(sortedArray.size > 1) { "At least two data points are required" }
sortedArray.reduce { r, v -> require(r <= v) { "Data points are not sorted (ASC)" }; v }
segments = sortedArray.take(sortedArray.size - 1)
.mapIndexed { i: Int, v: Int -> Segment(v, sortedArray[i + 1] - 1) }
}
}
internal data class Segment(val left: Int, val right: Int)
| 4 |
Kotlin
| 1 | 1 |
565d86d780c15ade77b5468a9e342ba334181333
| 2,006 |
detekt
|
Apache License 2.0
|
kotlin/src/main/kotlin/adventofcode/y2019/Day3.kt
|
3ygun
| 115,948,057 | false | null |
package adventofcode.y2019
import adventofcode.DataLoader
import adventofcode.Day
import adventofcode.commons.Point
import adventofcode.commons.xy
import kotlin.math.abs
/**
* Final solution holds all the points for each wire in memory.
* While this isn't super memory efficient it is sure easier to build a solution off.
*
* Other thoughts:
* You could probably build a solution that determines if 2 points overlap and then only hold
* the points of each wire turn in memory. Then calculate values from there. I tried building such
* a solution for a bit but it wasn't clicking. Therefore I went with the following more strait
* forward solution for now.
*/
object Day3 : Day {
internal val STAR1 = DataLoader.readNonBlankLinesFrom("/y2019/Day3Star1.txt")
.apply { require(this.size == 2) { "Too many wires in 2019, Day 3 Star 1" } }
.let { it[0] to it[1] }
internal val STAR2 = STAR1
override val day = 3
override val debug = false
// <editor-fold desc="Star 1">
override fun star1Run(): String {
val result = star1Calc(STAR2.first, STAR2.second)
return "The closest wire intersection to the starting point is: $result distance away"
}
internal fun star1Calc(
rawWire1: String,
rawWire2: String
): Int {
val wire1 = star1WireOf(rawWire1)
val wire2 = star1WireOf(rawWire2)
val intersections = star1IntersectionsOf(wire1, wire2)
.filterNot { it.x == 0 && it.y == 0 }
debug { "Intersections size=${intersections.size} and $intersections" }
val distanceAndPoint = intersections
.map { point ->
val distance = abs(point.x) + abs(point.y)
distance to point
}
.minBy { it.first }!!
return distanceAndPoint.first
}
private class Star1Wire(
val points: Set<Point>
)
private fun star1WireOf(rawWire: String): Star1Wire {
val movements = rawWire.split(",")
var x = 0
var y = 0
val points = mutableSetOf(x xy y)
for (movement in movements) {
val direction = Direction.of(movement[0])
val amount = movement.substring(1).toInt()
when {
direction.xAxis -> for (i in 1..amount) {
x += direction.amountEncoding
points.add(x xy y)
}
else -> for (i in 1..amount) {
y += direction.amountEncoding
points.add(x xy y)
}
}
}
return Star1Wire(points)
}
/** Note: This only deals with segments that are NOT diagonal */
private fun star1IntersectionsOf(wire1: Star1Wire, wire2: Star1Wire): Set<Point> {
val intersections = mutableSetOf<Point>()
wire1.points.forEach { w1Point ->
if (w1Point in wire2.points) intersections.add(w1Point)
}
return intersections
}
// </editor-fold>
// <editor-fold desc="Star 2">
override fun star2Run(): String {
val result = star2Calc(STAR2.first, STAR2.second)
return "The intersection with the fewest combined wire steps occurred: $result steps away"
}
internal fun star2Calc(
rawWire1: String,
rawWire2: String
): Int {
val wire1 = star2WireOf(rawWire1)
val wire2 = star2WireOf(rawWire2)
// Rotating to iterate through the smallest wire didn't seem to do anything
return star2DistanceToClosestIntersection(wire1, wire2)
}
private fun star2DistanceToClosestIntersection(
wire1: Star2Wire,
wire2: Star2Wire
): Int {
var distanceToClosestIntersection: Int = Int.MAX_VALUE
w1@ for ((w1Point, w1d) in wire1.pointToDistance) {
// Did we already pass the shortest distance without finding on the other wire?
if (w1d > distanceToClosestIntersection) break@w1
// Look for an intersection with the other wire
val w2d: Int = wire2.pointToDistance[w1Point]
?: continue@w1 // Not an intersection..next!
// Intersection found how long did it take us to get here?
val distance = w1d + w2d
if (distance < distanceToClosestIntersection) {
distanceToClosestIntersection = distance
}
}
return distanceToClosestIntersection
}
private class Star2Wire(
val pointToDistance: Map<Point, Int>
)
private fun star2WireOf(rawWire: String): Star2Wire {
val movements = rawWire.split(",")
var x = 0
var y = 0
var d = 0
val pointToDistance = mutableMapOf<Point, Int>()
for (movement in movements) {
val direction = Direction.of(movement[0])
val amount = movement.substring(1).toInt()
when {
direction.xAxis -> for (i in 1..amount) {
x += direction.amountEncoding
d++
pointToDistance.merge(x xy y, d) { old, new ->
if (old >= new) old else new // Only keep the shortest distance to the point
}
}
else -> for (i in 1..amount) {
y += direction.amountEncoding
d++
pointToDistance.merge(x xy y, d) { old, new ->
if (old >= new) old else new // Only keep the shortest distance to the point
}
}
}
}
// Don't have the starting point it messes with stuff
// Do down here incase it got added again
pointToDistance.remove(0 xy 0)
return Star2Wire(pointToDistance)
}
// </editor-fold>
// <editor-fold desc="Common">
private enum class Direction(
val direction: Char,
val amountEncoding: Int,
val xAxis: Boolean
) {
Right('R', 1, true),
Left('L', -1, true),
Up('U', 1, false), // top left be 0, 0
Down('D', -1, false), // top left be 0, 0
;
companion object {
fun of(rawDirection: Char): Direction {
return values().firstOrNull { it.direction == rawDirection }
?: throw IllegalArgumentException("Unknown direction: $rawDirection")
}
}
}
// </editor-fold>
}
| 0 |
Kotlin
| 0 | 0 |
69f95bca3d22032fba6ee7d9d6ec307d4d2163cf
| 6,484 |
adventofcode
|
MIT License
|
vimcash.kt
|
rogerkeays
| 514,601,375 | false |
{"Kotlin": 1520}
|
//usr/bin/env [ $0 -nt $0.jar ] && kotlinc -d $0.jar $0; [ $0.jar -nt $0 ] && kotlin -cp $0.jar VimcashKt $@; exit 0
import java.io.File
fun String.parseAmount(account: String): Double {
return substring(22, 34).toDouble() * if (indexOf(" $account ") > 34) -1 else 1
}
fun File.calculateBalance(account: String, currency: String): Double {
val filterRegex = Regex(".{15}\\| $currency [0-9. ]+[^ ]* $account .*")
return readLines()
.filter { it.matches(filterRegex) }
.map { it.parseAmount(account) }
.sum()
}
fun File.calculateBalances(account: String): Map<String, Double> {
val filterRegex = Regex(".{15}\\| ... [0-9. ]+[^ ]* $account .*")
val results = mutableMapOf<String, Double>()
readLines()
.filter { it.matches(filterRegex) }
.forEach {
val currency = it.slice(18..20)
val amount = it.parseAmount(account)
results.put(currency, results.get(currency)?.plus(amount) ?: amount)
}
return results
}
fun File.collectAccounts(): Set<String> {
return readLines()
.flatMap { it.substring(34, 52).split(' ') }
.toSortedSet()
}
fun File.reportBalances() {
collectAccounts()
.filter { it.matches(allCapsRegex) }
.associate { Pair(it, calculateBalances(it).filter { it.value.abs() > 0.005 }) }
.filter { it.value.size > 0 }
.forEach { println(it) }
}
val allCapsRegex = Regex("[0-9A-Z]+")
fun Double.abs(): Double = kotlin.math.abs(this)
| 0 |
Kotlin
| 0 | 0 |
f6a1c67e76148d6e1d8f305c64e894d12b2e0c4b
| 1,520 |
vimcash
|
MIT License
|
kotlin/graphs/lca/LcaSparseTable.kt
|
polydisc
| 281,633,906 | true |
{"Java": 540473, "Kotlin": 515759, "C++": 265630, "CMake": 571}
|
package graphs.lca
import java.util.stream.Stream
// Answering LCA queries in O(1) with O(n*log(n)) preprocessing
class LcaSparseTable(tree: Array<List<Integer>>, root: Int) {
var len: Int
var up: Array<IntArray>
var tin: IntArray
var tout: IntArray
var time = 0
fun dfs(tree: Array<List<Integer>>, u: Int, p: Int) {
tin[u] = time++
up[0][u] = p
for (i in 1 until len) up[i][u] = up[i - 1][up[i - 1][u]]
for (v in tree[u]) if (v != p) dfs(tree, v, u)
tout[u] = time++
}
fun isParent(parent: Int, child: Int): Boolean {
return tin[parent] <= tin[child] && tout[child] <= tout[parent]
}
fun lca(a: Int, b: Int): Int {
var a = a
if (isParent(a, b)) return a
if (isParent(b, a)) return b
for (i in len - 1 downTo 0) if (!isParent(up[i][a], b)) a = up[i][a]
return up[0][a]
}
companion object {
// Usage example
fun main(args: Array<String?>?) {
val tree: Array<List<Integer>> = Stream.generate { ArrayList() }.limit(5).toArray { _Dummy_.__Array__() }
tree[0].add(1)
tree[1].add(0)
tree[1].add(2)
tree[2].add(1)
tree[3].add(1)
tree[1].add(3)
tree[0].add(4)
tree[4].add(0)
val t = LcaSparseTable(tree, 0)
System.out.println(1 == t.lca(3, 2))
System.out.println(0 == t.lca(2, 4))
}
}
init {
val n = tree.size
len = 32 - Integer.numberOfLeadingZeros(n)
up = Array(len) { IntArray(n) }
tin = IntArray(n)
tout = IntArray(n)
dfs(tree, root, root)
}
}
| 1 |
Java
| 0 | 0 |
4566f3145be72827d72cb93abca8bfd93f1c58df
| 1,710 |
codelibrary
|
The Unlicense
|
src/Day10/Day10.kt
|
Nathan-Molby
| 572,771,729 | false |
{"Kotlin": 95872, "Python": 13537, "Java": 3671}
|
package Day10
import kotlin.math.*
import readInput
import java.util.Dictionary
class CPU() {
var cycleNum = 1
var x = 1
var part1Result = 0
fun part1(input: List<String>): Int {
for (line in input) {
processLine(line)
}
return part1Result
}
fun part2(input: List<String>) {
for (line in input) {
processLine(line)
}
}
fun processLine(line: String) {
val lineSplit = line.split(" ")
when(lineSplit[0]) {
"noop" -> noop()
"addx" -> addx(lineSplit[1].toInt())
}
}
fun noop() {
checkPart1()
part2()
cycleNum++
}
fun addx(numToAdd: Int) {
checkPart1()
part2()
cycleNum++
checkPart1()
part2()
cycleNum++
x += numToAdd
}
fun checkPart1() {
if ((cycleNum - 20) % 40 == 0) {
part1Result += cycleNum * x
}
}
fun part2() {
if ((cycleNum - 1) % 40 in (x - 1) % 40 .. (x + 1) % 40) {
print("#")
} else {
print(".")
}
if (cycleNum % 40 == 0) {
println()
}
}
}
fun main() {
fun part1(input: List<String>): Int {
val cpu = CPU()
return cpu.part1(input)
}
fun part2(input: List<String>) {
val cpu = CPU()
cpu.part2(input)
}
// val testInput = readInput("Day10","Day10_test")
// println(part1(testInput))
// check(part1(testInput) == 13140)
// println(part2(testInput))
// check(part2(testInput) == 36)
val input = readInput("Day10","Day10")
// println(part1(input))
part2(input)
}
| 0 |
Kotlin
| 0 | 0 |
750bde9b51b425cda232d99d11ce3d6a9dd8f801
| 1,721 |
advent-of-code-2022
|
Apache License 2.0
|
src/main/kotlin/days/Day2.kt
|
butnotstupid
| 433,717,137 | false |
{"Kotlin": 55124}
|
package days
class Day2 : Day(2) {
override fun partOne(): Any {
return inputList.map { it.split(" ").let { it[0] to it[1].toLong() } }
.fold(Position(0, 0)) { pos, (dir, steps) ->
when (dir) {
"forward" -> Position(pos.x + steps, pos.depth)
"down" -> Position(pos.x, pos.depth + steps)
"up" -> Position(pos.x, pos.depth - steps)
else -> throw IllegalArgumentException("Unknown command")
}
}.let { it.x * it.depth }
}
override fun partTwo(): Any {
return inputList.map { it.split(" ").let { it[0] to it[1].toLong() } }
.fold(Position(0, 0, 0)) { pos, (dir, steps) ->
when (dir) {
"forward" -> Position(pos.x + steps, pos.depth + steps * pos.aim, pos.aim)
"down" -> Position(pos.x, pos.depth, pos.aim + steps)
"up" -> Position(pos.x, pos.depth, pos.aim - steps)
else -> throw IllegalArgumentException("Unknown command")
}
}.let { it.x * it.depth }
}
data class Position(val x: Long, val depth: Long, val aim: Long = 0)
}
| 0 |
Kotlin
| 0 | 0 |
a06eaaff7e7c33df58157d8f29236675f9aa7b64
| 1,232 |
aoc-2021
|
Creative Commons Zero v1.0 Universal
|
TallerRecursion/src/ean/estructuradedatos/taller/TallerRecursion.kt
|
DinaTuesta27
| 599,303,436 | false | null |
package ean.estructuradedatos.taller
/**
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Universidad EAN (Bogotá - Colombia)
* Departamento de Sistemas
* Faculta de Ingeniería
*
* Taller Funciones Recursivas
* Fecha: 18 de abril de 2023
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
//Realizado por: <NAME> y <NAME>
import kotlin.math.pow
import kotlin.math.sqrt
/**
* Halla el factorial del número entero n
* n! = n * (n-1) * (n-2) * ... * 2 * 1
*/
fun factorial(n: Int): Int =
when(n){
1->1
else-> factorial(n-1)*n
}
/**
* Halla el n-ésimo término de la serie de fibonacci
*/ //Recursión binaria
fun fibonacci(n: Int): Int =
when(n){
1,2->1
else-> fibonacci(n-1) + fibonacci(n-2)
}
/**
* Permite determinar el término n,m del triángulo de Pascal
* n = fila, m = término
*/
fun pascal(n: Int, m: Int): Int {
if (m==1 || m==n+1) {
return 1
}
return pascal (n-1,m) + pascal(n-1,m-1)
}
/**
* Halla el valor de x^y =
* si y es cero entonces retorne 1
* sino retorne x multiplicado por elevar x a la y - 1
*/
fun elevar(x: Int, y: Int): Int =
when(y){
0->1
else->x* elevar(x,y-1)
}
/**
* Halla la suma de todos los números enteros entre 1 y n
*/
fun sumatoria(n: Int): Int =
when (n){
1->1
else-> sumatoria(n-1) + n
}
/**
* Halla la suma de los cuadrados de los números de 1 hasta n
*/
fun sumaCuadrados(n: Int): Int =
when(n) {
0->0
else-> sumaCuadrados(n-1) + (n*n)
}
/**
* Hallar el valor de la sumatoria de 1/(2i+1) desde 1 hasta n
*/
fun serie(n: Int): Double =
when(n) {
1->1.0/3.0
else-> serie(n-1) + 1.0/(2*n+1.0)
}
/**
* Hallar el valor de la sumatoria de 1 hasta n de i/(i^2+1)
*/
fun sumatoria2(n: Int): Double =
when (n){
1->1.0/2.0
else-> sumatoria2(n-1) + n/((n*n)+1.0)
}
/**
* Permite saber la cantidad de digitos que posee un número entero positivo n
*/
fun contarDigitos(n: Int): Int =
when(n) {
in 0 .. 9->1 //Tiene un dígito
else->{
val resto= n / 10 //le quito el último dígito
val c= contarDigitos(resto)
c+1 //le sumo uno para tenerelos completos
}
}
/**
* Permite saber el número de ceros que tiene un número.
* Por ejemplo: 2020 tiene dos ceros.
*/
fun numeroDeCeros(n: Int): Int =
if (n < 10) {
if (n == 0) {
1
} else {
0
}
} else {
val ult=n%10
val resto=n/10
val c= numeroDeCeros(resto)
if (ult == 0) {
c + 1
} else {
c
}
}
/**
* Permite hallar la suma de los dígitos de un número entero positivo n
*/
fun sumarDigitos(n: Int): Int =
when(n){
0->0
in 0 .. 9->n
else-> {
val ult = n % 10
val resto = n / 10
val c = sumarDigitos(resto)
c + ult
}
}
/**
* Un número entero positivo en múltiplo de 3 si:
* - tiene una cifra y es 0, 3, 6, o 9
* - tiene más de una cifra y la suma de sus dígitos es múltiplo de 3 (recursion)
* - en cualquier otro caso, el número no es múltiplo de 3
*
* - NO PUEDEN USAR LA OPERACIÓN MÓDULO (%) PARA SABER SI ES DIVISIBLE
*/
fun esMultiploDe3(n: Int): Boolean {
if (n == 0 || n == 3 || n == 6 || n == 9) {
return true
} else if (n > 10) {
val m = (sumarDigitos(n))
if (esMultiploDe3(m)==true) {
return true
}
}
return false
}
/**
* Cuenta el número de dígitos pares que tiene un número entero positivo >= 1
*/
fun cantidadDigitosPares(n: Int): Int =
if (n < 10) {
if (n == 0 || n==2 || n==4 || n == 6 || n==8 ) {
1
} else {
0
}
} else {
val ult=n%10
val resto=n/10
val c= cantidadDigitosPares(resto)
if (ult == 0 || ult==2 || ult==4 || ult == 6 || ult==8) {
c + 1
} else {
c
}
}
/**
* Determina si el número dado es binario o no.
* Los números binarios solo contienen los dígitos 1 y 0
* Por ejemplo: el numero 100011110 es binario, pero 231 no lo es
*/
fun esNumeroBinario(n: Int): Boolean {
if (n==0 ||n==1){
return true
}
if (n%10 > 1) {
return false
}
return esNumeroBinario(n/10)
}
/**
* Permite saber si el número dado posee el dígito indicado
*/
fun poseeDigito(n: Int, digito: Int): Boolean {
/*
si el numero n posee un solo digito, entonces
si n y el digito son iguales -> retorne true sino retorne false
sino si el número n tiene más de un dígito, entonces
si el ultimo dígito del número n es igual al dígito, entonces
listo, lo encontramos, retorne true
sino
halle el resto de n
mire si el resto de n posee el dígito indicado
*/
if (n in 0 .. 9) {
return n == digito
}else {
val ult = n % 10
if (ult == digito) {
return true
} else {
val sobra = n / 10
return poseeDigito(sobra, digito)
}
}
}
/**
* Retorna el dígito más grande que hace parte del número n
* Ejemplo: el dígito más grande del númer 381704 es el 8
* si el número tiene un solo dígito, el digito más grande es el numero
* sino
* halle el resto y el último
* halla el digito mas grande del resto
* retorne el mayor entre el último y el dígito más grande del resto
*/
fun digitoMasGrande(n: Int): Int {
if (contarDigitos(n) == 1) {
return n
} else {
val ult=n%10
val resto=n/10
var digitoMasGrande=digitoMasGrande(resto)
if (digitoMasGrande>ult) {
return digitoMasGrande
}
return ult
}
}
/**
* Halla el máximo común divisor entre m y n, utilizando el método de
* Euclides.
*/
fun mcd(m: Int, n: Int): Int =
when(n) {
0->m
else-> mcd(n,m%n)
}
/**
* Imprimir cada elemento de la lista, pero de manera recursiva
*/
fun <T> imprimirLista(lista: List<T>) {
if (lista.isEmpty()) { //si está vacía
println()
} else {
val prim = lista.first()
val resto=lista.subList(1,lista.size)//Desde la posición uno hasta la última
println(prim) //Imprimir
imprimirLista(resto)
}
}
/**
* Obtiene recursivamente la lista de los dígitos del número entero positivo n
* Ejemplo: digitos(351804) == [3, 5, 1, 8, 0, 4]
*/
fun digitos(n: Int): List<Int> {
if (n in 0 .. 9) {
return listOf(n)
}else{
val ult=n%10
val resto=n/10
var lst= digitos(resto)
lst += ult
return lst
}
}
/**
* Dado un número entero positivo >= 0, retorna una lista con la representación binaria
* del número dado.
* Ejemplo: convertirDecimalBinario(231) = List(1, 1, 0, 0, 1, 1, 1, 1, 1, 1)
*/
fun convertirDecimalBinario(n: Int): List<Int> {
if (n > 1) {
val ult = n % 2
val resto = n / 2
var deci = convertirDecimalBinario(resto)
deci += ult
return deci
}else if (n == 0) {
return listOf(0)
}
return listOf(1)
}
/**
* Determina cuantas palabras en la lista son verbos.
* Recursivamente.
*/
fun contarVerbos(palabras: List<String>): Int {
if (palabras.isEmpty()) { //si está vacía
return 0
} else {
var prim= palabras.first() //se toma el primer elemento
val resto= palabras.subList(1,palabras.size) //que "recora" la lista desde el 1 hasta el final
var sonVerbos= contarVerbos(resto) //que obtenga los verbos del resto
if (prim.endsWith("ar") || prim.endsWith("er") || prim.endsWith("ir")) {
sonVerbos += 1 // si el prim es un verbo que lo sume al resto
}
return sonVerbos
}
}
/**
* Recursion con listas: Hallar la suma de los números pares de la lista que se recibe
* como parámetro.
* Ejemplo: sumarParesLista([40, 21, 8, 31, 6]) == 54
*/
fun sumarParesLista(lista: List<Int>): Int {
if (lista.isEmpty()) { //si está vacía
return 0
} else {
val prim= lista.first()
val resto= lista.subList(1,lista.size)
var sum= sumarParesLista(resto)
if (prim%2==0){
sum+=prim
}
return sum
}
}
/**
* Recursión con listas: construir una función recursiva que retorne la posición del elemento en la lista
* Si la lista está vacía, retorne -1. No se puede usar indexOf o lastIndexOf
*/
fun buscarElementoEnUnaLista(lista: List<Int>, elem: Int): Int {
if (lista.isEmpty()) { //si está vacía
return -1
} else {
var prim= lista.first()
val resto= lista.subList(1,lista.size)
var busc= buscarElementoEnUnaLista(resto,elem)
if (prim == elem) {
return 0
}else if (busc == -1) {
return -1
} else {
return busc + 1
}
}
}
/**
* Traduce los diversos dígitos de la lista a un número entero
* Ejemplo: convertirListaDigitosNumero([3, 4, 1, 7, 9]) == 34179
*/
fun convertirListaDigitosNumero(digitos: List<Int>): Int {
if (digitos.isEmpty()) {
return 0
} else {
val ult = digitos.last()
val resto = digitos.subList(0, digitos.size - 1) //para llegar antes del último
return ult + 10 * convertirListaDigitosNumero(resto) // es para mover el valor en el que esta hasta el último
}
}
/**
* Función genérica y recursiva que permite saber si un elemento está dentro
* de la lista. No debe usarse la función indexOf o contains. Debe ser
* recursiva. Para buscar un elemento hay que tener en cuenta
* - si la lista está vacía, el elemento no está
* - si el primero de la lista es igual al elemento, retornamos true (el elemento está)
* - sino es igual al primero, entonces hay que ver si el elemento está en el resto de la lista
*/
fun <T> existeElemento(lista: List<T>, elem: T): Boolean {
if (lista.isEmpty()) { //si está vacía
return false
} else {
var prim= lista.first()
val resto= lista.subList(1,lista.size)
var exis= existeElemento(resto,elem)
if (prim == elem) {
return true
}else if (exis == true) {
return true
} else {
return false
}
}
}
/** Escribir una función recursiva que, sin usar pilas ni colas
* ni ninguna otra lista, obtenga la misma lista, pero invertida
*/
fun invertirLista(lista: List<Char>): List<Char> {
if (lista.isEmpty()) {
return lista
} else {
val ult = lista.last()
val resto = lista.subList(0, lista.size - 1) //toma del primero hasta el anterior al último
return listOf(ult) + invertirLista(resto)
}
}
/**
* Una palabra es palíndrome si se lee igual de izquierda a derecha y de derecha
* a izquierda. Esta función recibe la palabra (sin espacios) y de forma recursiva
* determina si la palabra es palíndrome.
*/
fun esPalindrome(palabra: String): Boolean =
if (palabra.length <= 1) {
true
} else {
val primera = palabra.first()
val ultima = palabra.last()
if (primera == ultima) {
esPalindrome(palabra.substring(1, palabra.length - 1))// substring invierte las letras desde la pos 1 hasta la anterior a la última
} else {
false
}
}
/**
* Recursividad con listas. Escriba una función recursiva
* Obtiene el número más grande de la lista. Si la lista está vacía retorne el número
* entero más pequeño.
*/
fun mayorDeUnaLista(lista: List<Int>): Int {
if (lista.isEmpty()) {
return Int.MIN_VALUE
} else {
val prim = lista.first()
val resto = lista.subList(1, lista.size)
val mayorResto = mayorDeUnaLista(resto)
if (prim > mayorResto) {
return prim
} else {
return mayorResto
}
}
}
/**
* Una clase auxiliar
*/
data class Punto(val x: Int, val y: Int) {
fun distanciaAlOrigen(): Double = sqrt(x.toDouble().pow(2) + y.toDouble().pow(2))
}
/**
* Recursivamente, obtener una lista con aquellos puntos que están en el origen o
* que hacen parte del primer cuadrante.
*/
fun puntosPrimerCuadrante(puntos: List<Punto>): List<Punto> {
if (puntos.isEmpty()) {
return listOf()
} else {
val prim=puntos.first()
val resto = puntos.subList(1, puntos.size)
var c= puntosPrimerCuadrante(resto)
if (prim.x >= 0 && prim.y >= 0) {
return listOf(prim) + c
} else {
return c
}
}
}
/**
* Recursivamente, obtiene el punto que está más lejano del origen.
* Si la lista esta vacía, retorne null
* Si la lista tiene un solo elemento, retorne ese elemento
* si la lista tiene más de un elemento, tome el primer elemento y
* compárelo con el punto más lejano del resto de la lista.
*/
fun puntoMasLejano(puntos: List<Punto>): Punto? {
if (puntos.isEmpty()) {
return null
} else if(puntos.size==1) {
return puntos[0]
}else{
val prim=puntos.first()
val resto = puntos.subList(1, puntos.size)
var m= puntoMasLejano(resto)
if (m==null) {
return null
} else {
if (prim.distanciaAlOrigen() > m.distanciaAlOrigen()) {
return prim
} else {
return m
}
}
}
}
| 0 |
Kotlin
| 0 | 0 |
ef8ce29b13ab3e7ce2f036447cceb84863046c14
| 14,203 |
kotlin
|
MIT License
|
day14/kotlin/RJPlog/day2114_1_2.kts
|
razziel89
| 433,724,464 | true |
{"Rust": 368326, "Python": 219109, "Go": 200337, "Kotlin": 80185, "Groovy": 67858, "JavaScript": 45619, "TypeScript": 43504, "CSS": 35030, "Shell": 18611, "C": 5260, "Ruby": 2359, "Dockerfile": 2285, "HTML": 227, "C++": 153}
|
import java.io.File
// tag::poly[]
fun poly(input1: Int): Int {
var rules = mutableMapOf<String, String>()
var polyTemp: String = ""
File("day2114_puzzle_input.txt").forEachLine {
if (it != "") {
if (!it.contains("->")) {
polyTemp = it
} else {
var instruction = it.split(" -> ")
rules.put(instruction[0], instruction[1])
}
}
}
//iterate input1 number of steps and create new string with replacement of each pair with given rules
var newPolyTemp: String = polyTemp.take(1)
for (i in 1..input1) {
for (j in 0..polyTemp.length - 2) {
if (rules.containsKey(polyTemp.subSequence(j, j + 2).toString())) {
newPolyTemp = newPolyTemp + rules.getValue(polyTemp.subSequence(j, j + 2).toString()) + polyTemp[j + 1]
} else
newPolyTemp = newPolyTemp + polyTemp[j + 1]
}
polyTemp = newPolyTemp
newPolyTemp = polyTemp.take(1)
}
// count elements and determine max and min value
var countMap = mutableMapOf<Char, Int>()
polyTemp.forEach {
if (countMap.contains(it)) {
countMap.set(it, countMap.getValue(it) + 1)
} else {
countMap.put(it, 1)
}
}
var max: Int = 0
var min: Int = 10000
countMap.forEach {
if (it.value > max) {
max = it.value
} else if (it.value < min) {
min = it.value
}
}
return max - min
}
// end::poly[]
// tag::polyAdv[]
fun polyAdv(input1: Int): Long {
var rules = mutableMapOf<String, String>()
var polyTemp: String = ""
File("day2114_puzzle_input.txt").forEachLine {
if (it != "") {
if (!it.contains("->")) {
polyTemp = it
} else {
var instruction = it.split(" -> ")
rules.put(instruction[0], instruction[1])
}
}
}
//setup Map with subSequences and counter for occurency
var polyPairs = mutableMapOf<String, Long>()
var newPolyPairs = mutableMapOf<String, Long>()
polyPairs.put(polyTemp.takeLast(1), 1)
for (j in 0..polyTemp.length - 2) {
if (polyPairs.containsKey(polyTemp.subSequence(j, j + 2).toString())) {
polyPairs.set(
polyTemp.subSequence(j, j + 2).toString(),
polyPairs.getValue(polyTemp.subSequence(j, j + 2).toString()) + 1
)
} else {
polyPairs.put(polyTemp.subSequence(j, j + 2).toString(), 1)
}
}
// iterate input1 number of steps and determine, how many new sequences will be created for the current step
for (i in 1..input1) {
polyPairs.forEach {
if (rules.contains(it.key)) {
var new1 = it.key.take(1) + rules.getValue(it.key)
var new2 = rules.getValue(it.key) + it.key.takeLast(1)
if (newPolyPairs.containsKey(new1)) {
newPolyPairs.put(
new1,
newPolyPairs.getValue(new1) + it.value
)
} else {
newPolyPairs.put(new1, it.value)
}
if (newPolyPairs.containsKey(new2)) {
newPolyPairs.put(new2, newPolyPairs.getValue(new2) + it.value)
} else {
newPolyPairs.put(new2, it.value)
}
} else {
newPolyPairs.put(it.key, it.value)
}
}
polyPairs.clear()
polyPairs.putAll(newPolyPairs)
newPolyPairs.clear()
}
// count elements and determine max and min value
var countMap = mutableMapOf<String, Long>()
for ((key, value) in polyPairs) {
if (countMap.contains(key.take(1))) {
countMap.set(key.take(1), countMap.getValue(key.take(1)) + value)
} else {
countMap.put(key.take(1), value)
}
}
var max: Long = countMap.getValue(polyTemp.take(1))
var min: Long = countMap.getValue(polyTemp.take(1))
countMap.forEach {
if (it.value > max) {
max = it.value
} else if (it.value < min) {
min = it.value
}
}
return (max - min)
}
// end::polyAdv[]
//fun main(args: Array<String>) {
var solution1 = poly(10)
var solution2 = polyAdv(40)
// tag::output[]
// print solution for part 1
println("****************************************")
println("--- Day 14: Extended Polymerization ---")
println("****************************************")
println("Solution for part1")
println(" $solution1 you get if you take the quantity of the most common element and subtract the quantity of the least common element")
println()
// print solution for part 2
println("*******************************")
println("Solution for part2")
println(" $solution2 you get if you take the quantity of the most common element and subtract the quantity of the least common element")
println()
// end::output[]
//}
| 1 |
Rust
| 0 | 0 |
0042891cfcecdc2b65ee32882bd04de80ecd7e1c
| 4,293 |
aoc-2021
|
MIT License
|
src/Day06.kt
|
icoffiel
| 572,651,851 | false |
{"Kotlin": 29350}
|
private const val DIFFERENCE_TO_UNIQUE_INDEX_START = 1
fun main() {
fun firstNonUniqueStrings(input: String, uniqueStringLength: Int) = input
.windowedSequence(uniqueStringLength) // Move over the expected length at a time
.takeWhile { it.toSet().size != uniqueStringLength }
fun part1(input: String): Int {
val uniqueStringLength = 4
val previousNonUniqueStrings: Sequence<String> = firstNonUniqueStrings(input, uniqueStringLength)
return input.indexOf(previousNonUniqueStrings.last()) + DIFFERENCE_TO_UNIQUE_INDEX_START + uniqueStringLength
}
fun part2(input: String): Int {
val uniqueStringLength = 14
val previousNonUniqueStrings: Sequence<String> = firstNonUniqueStrings(input, uniqueStringLength)
return input.indexOf(previousNonUniqueStrings.last()) + DIFFERENCE_TO_UNIQUE_INDEX_START + uniqueStringLength
}
val testInput = readInputAsText("Day06_test")
check(part1(testInput) == 7)
check(part2(testInput) == 19)
val input = readInputAsText("Day06")
println("Part One: ${part1(input)}")
check(part1(input) == 1623)
println("Part Two: ${part2(input)}")
check(part2(input) == 3774)
}
| 0 |
Kotlin
| 0 | 0 |
515f5681c385f22efab5c711dc983e24157fc84f
| 1,211 |
advent-of-code-2022
|
Apache License 2.0
|
kotlin/src/main/kotlin/divisible_sum_pairs/divisible-sum-pairs.kt
|
francisakpan
| 299,567,682 | false |
{"Kotlin": 16639, "Dart": 2622, "Java": 2384}
|
package divisible_sum_pairs
fun main() {
val a = "50 44 77 66 70 58 9 59 74 82 87 15 10 95 10 81 2 4 87 85 28 " +
"96 76 18 86 91 94 59 19 58 98 48 38 70 36 38 66 9 72 54 23 23 17 " +
"18 8 16 9 56 12 59 73 31 10 62 83 84 28 91 29 22 73 22 3 75 26 31 " +
"93 57 15 32 46 74 99 10 15 58 60 53 41 49 71 59 4 20 38 78 1 94 76 " +
"5 70 68 42 34 77 28 19 25 20 15"
val aArray = a.split(" ")
val aInt = Array(aArray.size) { aArray[it].toInt() }
println(divisibleSumPairs(66, aInt))
}
// Complete the divisibleSumPairs function below.
fun divisibleSumPairs(k: Int, ar: Array<Int>): Int {
// O(n)
var count = 0
for (i in ar.indices) {
for (j in ar.indices) {
if (i < j && (ar[i] + ar[j]) % k == 0) {
count ++
}
}
}
return count
}
| 0 |
Kotlin
| 0 | 0 |
efb8fa9ee0249c01a4822485c40f86bec8a8e4cc
| 867 |
random-exercises
|
MIT License
|
src/DijkstraAlgorithm.kt
|
dkoscica
| 74,512,586 | false | null |
import java.util.*
import models.*
class DijkstraAlgorithm(graph: Graph) {
private val nodes: List<Vertex>
private val edges: List<Edge>
private var settledNodes: MutableSet<Vertex> = HashSet()
private var unSettledNodes: MutableSet<Vertex> = HashSet()
private var predecessors: MutableMap<Vertex, Vertex> = HashMap()
private var distance: MutableMap<Vertex, Int> = HashMap()
init {
// create a copy of the array so that we can operate on this array
this.nodes = ArrayList(graph.vertexes)
this.edges = ArrayList(graph.edges)
}
fun execute(source: Vertex) {
unSettledNodes.add(source)
while (unSettledNodes.size > 0) {
val node = getMinimum(unSettledNodes as HashSet<Vertex>)
settledNodes.add(node as Vertex)
unSettledNodes.remove(node)
findMinimalDistances(node)
}
}
private fun findMinimalDistances(node: Vertex) {
val adjacentNodes = getNeighbors(node)
for (target in adjacentNodes) {
if (getShortestDistance(target) > getShortestDistance(node) + getDistance(node, target)) {
distance.put(target, getShortestDistance(node) + getDistance(node, target))
predecessors.put(target, node)
unSettledNodes.add(target)
}
}
}
private fun getDistance(node: Vertex, target: Vertex): Int {
for ((id, source, destination, weight) in edges) {
if (source == node && destination == target) {
return weight
}
}
throw RuntimeException("Should not happen")
}
private fun getNeighbors(node: Vertex): List<Vertex> {
val neighbors = ArrayList<Vertex>()
for ((id, source, destination) in edges) {
if (source == node && !isSettled(destination)) {
neighbors.add(destination)
}
}
return neighbors
}
private fun getMinimum(vertexes: Set<Vertex>): Vertex? {
var minimum: Vertex? = null
for (vertex in vertexes) {
if (minimum == null) {
minimum = vertex
} else {
if (getShortestDistance(vertex) < getShortestDistance(minimum)) {
minimum = vertex
}
}
}
return minimum
}
private fun isSettled(vertex: Vertex): Boolean {
return settledNodes.contains(vertex)
}
private fun getShortestDistance(destination: Vertex): Int {
val d = distance[destination]
if (d == null) {
return Integer.MAX_VALUE
} else {
return d
}
}
/*
* This method returns the path from the source to the selected target and
* NULL if no path exists
*/
fun getPath(target: Vertex): LinkedList<Vertex>? {
val path = LinkedList<Vertex>()
var step: Vertex = target
// check if a path exists
if (predecessors[step] == null) {
return null
}
path.add(step)
while (predecessors[step] != null) {
step = predecessors[step] as Vertex
path.add(step)
}
// Put it into the correct order
Collections.reverse(path)
return path
}
}
| 0 |
Kotlin
| 0 | 0 |
d204fc5dbb97d63bc0be025b3c4616dcfb11c483
| 3,336 |
APUI-Dijkstra-Algorithm-Kotlin
|
MIT License
|
module-tool/src/main/kotlin/de/twomartens/adventofcode/day11/graph/Graph.kt
|
2martens
| 729,312,999 | false |
{"Kotlin": 89431}
|
package de.twomartens.adventofcode.day11.graph
data class Graph(val name: String, val galaxies: Collection<Pair<Int, Int>>) {
override fun toString(): String {
return name
}
companion object {
fun of(name: String, rows: List<String>, emptySpaceMultiplier: Int): Graph {
if (emptySpaceMultiplier < 1) {
throw IllegalArgumentException("Empty space cannot be deleted")
}
val galaxies = mutableListOf<Pair<Int, Int>>()
val colIndices = mutableMapOf<Int, Boolean>()
val rowIndicesWithoutGalaxies = mutableListOf<Int>()
rows.map { it.split("") }.forEachIndexed { indexRow, row ->
var rowContainsGalaxy = false
row.filterNot { it.isBlank() }.forEachIndexed { indexCol, col ->
colIndices.putIfAbsent(indexCol, false)
val index = Pair(indexRow, indexCol)
if (col == "#") {
galaxies.add(index)
rowContainsGalaxy = true
colIndices[indexCol] = true
}
}
if (!rowContainsGalaxy) {
rowIndicesWithoutGalaxies.add(indexRow)
}
}
val colIndicesWithoutGalaxy = colIndices.entries
.filterNot { it.value }
.map { it.key }
val updatedGalaxies = updateIndices(galaxies,
colIndicesWithoutGalaxy, rowIndicesWithoutGalaxies,
emptySpaceMultiplier)
return Graph(name, updatedGalaxies)
}
private fun updateIndices(
galaxies: Collection<Pair<Int, Int>>,
colIndicesWithoutGalaxy: Collection<Int>,
rowIndicesWithoutGalaxy: Collection<Int>,
emptySpaceMultiplier: Int
): Collection<Pair<Int, Int>> {
return galaxies.map { galaxy ->
val emptyRowsBefore = rowIndicesWithoutGalaxy.filter { it < galaxy.first }.size
val emptyColumnsBefore = colIndicesWithoutGalaxy.filter { it < galaxy.second }.size
Pair(
calculateExpandedRowIndex(galaxy, emptySpaceMultiplier, emptyRowsBefore),
calculateExpandedColumnIndex(galaxy, emptySpaceMultiplier, emptyColumnsBefore)
)
}
}
private fun calculateExpandedColumnIndex(galaxy: Pair<Int, Int>,
emptySpaceMultiplier: Int,
emptyColumnsBefore: Int
) = galaxy.second + emptySpaceMultiplier * emptyColumnsBefore - emptyColumnsBefore
private fun calculateExpandedRowIndex(
galaxy: Pair<Int, Int>,
emptySpaceMultiplier: Int,
emptyRowsBefore: Int
) = galaxy.first + emptySpaceMultiplier * emptyRowsBefore - emptyRowsBefore
}
}
| 0 |
Kotlin
| 0 | 0 |
03a9f7a6c4e0bdf73f0c663ff54e01daf12a9762
| 3,036 |
advent-of-code
|
Apache License 2.0
|
app/src/main/java/com/itscoder/ljuns/practise/algorithm/InsertionSort.kt
|
ljuns
| 148,606,057 | false |
{"Java": 26841, "Kotlin": 25458}
|
package com.itscoder.ljuns.practise.algorithm
/**
* Created by ljuns at 2019/1/5.
* I am just a developer.
* 插入排序
* 从第 2 个元素开始和前面的元素比较并排序
* 例如:1, 3, 2
* 1、第一次 for 循环:3 和 1 比较,不需要改变
* 2.1、第二次 for 循环:2 和 3 比较,调换位置变成 1, 2, 3,此时 j == 1
* 2.2、2 再和 1 比较,不需要改变,排序结束
*/
class InsertionSort {
fun main(args: Array<String>) {
val arr = intArrayOf(3, 1, 1, 6, 2, 4, 19)
sort(arr)
}
private fun sort(arr: IntArray) {
for (i in arr.indices) {
var j = i
// 判断 j > 0 有两层意义:1、第一个元素不用比较;2、后面的比较排序到第 1 个元素时停止
while (j > 0 && arr[j] < arr[j - 1]) {
val temp = arr[j]
arr[j] = arr[j - 1]
arr[j - 1] = temp
j --
}
}
for (i in arr) {
println(i)
}
}
}
| 0 |
Java
| 0 | 0 |
365062b38a7ac55468b202ebeff1b760663fc676
| 1,055 |
Practise
|
Apache License 2.0
|
Others/Kotlin/kotlin-koans/src/iii_conventions/MyDate.kt
|
mrkajetanp
| 81,245,804 | false |
{"C++": 1603629, "C": 402718, "Java": 283190, "Rust": 261526, "Python": 116934, "Dart": 86632, "Kotlin": 71503, "Ruby": 45722, "Makefile": 32375, "Shell": 31662, "Emacs Lisp": 23199, "JavaScript": 21065, "Go": 17512, "TypeScript": 13585, "CMake": 6829, "HTML": 2467, "Assembly": 139}
|
package iii_conventions
data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int) : Comparable<MyDate> {
override fun compareTo(other: MyDate): Int = when {
year != other.year -> year - other.year
month != other.month -> month - other.month
else -> dayOfMonth - other.dayOfMonth
}
}
operator fun MyDate.rangeTo(other: MyDate): DateRange = DateRange(this, other)
class DateIterator(val dateRange: DateRange) : Iterator<MyDate> {
var current: MyDate = dateRange.start
override fun next(): MyDate {
val result = current
current = current.nextDay()
return result
}
override fun hasNext(): Boolean = current <= dateRange.endInclusive
}
enum class TimeInterval {
DAY,
WEEK,
YEAR
}
class DateRange(override val start: MyDate, override val endInclusive: MyDate):
ClosedRange<MyDate>, Iterable<MyDate> {
override fun contains(value: MyDate): Boolean = value >= start && value <= endInclusive
override fun iterator(): Iterator<MyDate> = DateIterator(this)
}
class RepeatedTimeInterval(val timeInterval: TimeInterval, val number: Int)
operator fun TimeInterval.times(number: Int) = RepeatedTimeInterval(this, number)
operator fun MyDate.plus(timeInterval: TimeInterval) = addTimeIntervals(timeInterval, 1)
operator fun MyDate.plus(timeIntervals: RepeatedTimeInterval) = addTimeIntervals(timeIntervals.timeInterval, timeIntervals.number)
| 158 |
C++
| 0 | 2 |
aee01ff3208ab14e7d0e0a7077798342123bc3e6
| 1,448 |
programming-exercises
|
MIT License
|
src/main/kotlin/com/github/michaelbull/advent2023/day5/Almanac.kt
|
michaelbull
| 726,012,340 | false |
{"Kotlin": 195941}
|
package com.github.michaelbull.advent2023.day5
private val SEEDS_REGEX = "seeds: (.*)".toRegex()
private val MAP_REGEX = "(.*)-to-(.*) map:".toRegex()
fun Sequence<String>.toAlmanac(): Almanac {
var seeds = emptyList<Long>()
var source = ""
var destination = ""
val entries = mutableListOf<AlmanacEntry>()
val maps = mutableListOf<AlmanacMap>()
fun addMap() {
if (entries.isNotEmpty()) {
check(source.isNotEmpty())
check(destination.isNotEmpty())
maps += AlmanacMap(
source = source,
destination = destination,
entries = entries.toList()
)
}
}
fun reset() {
source = ""
destination = ""
entries.clear()
}
for ((index, line) in withIndex()) {
if (index == 0) {
seeds = line.toSeedList()
} else if (line.isEmpty()) {
addMap()
reset()
} else {
val result = MAP_REGEX.matchEntire(line)
if (result != null) {
val values = result.groupValues
source = values[1]
destination = values[2]
} else {
entries += line.toAlmanacEntry()
}
}
}
addMap()
return Almanac(
seeds = seeds.toList(),
maps = maps.toList()
)
}
data class Almanac(
val seeds: List<Long>,
val maps: List<AlmanacMap>,
)
private fun String.toSeedList(): List<Long> {
val result = requireNotNull(SEEDS_REGEX.matchEntire(this)) {
"$this must match $SEEDS_REGEX"
}
val (numbers) = result.destructured
return numbers
.split(" ")
.map(String::toLong)
}
| 0 |
Kotlin
| 0 | 1 |
ea0b10a9c6528d82ddb481b9cf627841f44184dd
| 1,750 |
advent-2023
|
ISC License
|
src/main/kotlin/se/radicalcode/aoc/1.kt
|
gwendo
| 162,547,004 | false | null |
package se.radicalcode.aoc
import java.io.File
fun main(args: Array<String>) {
println(reduceNumbers(readFileAsInts(args[0])))
}
fun <T> Sequence<T>.repeat() = sequence { while (true) yieldAll(this@repeat)}
fun findDuplicateFrequencies(numbers: List<Int>) : Int {
val frequencies = mutableListOf<Int>(0)
val infiniteNumbers = numbers.asSequence().repeat().iterator()
var dupFound = false;
while (!dupFound) {
val currChange = infiniteNumbers.next()
val currFreq = frequencies.last() + currChange
dupFound = frequencies.contains(currFreq)
frequencies.add(currFreq);
}
return frequencies.last()
}
fun containsNumber(i: Int, frequencyList: MutableList<Int>) : Boolean {
println("test: $i")
println("lastFreq: ${frequencyList.last()}")
return frequencyList.contains(i + frequencyList.last())
}
fun reduceNumbers(numbers: List<Int>) : Int {
return numbers.reduce {acc, b -> acc + b}
}
fun readFileAsInts(fileName: String) : List<Int> = File(fileName).useLines { it.map { it1 -> it1.removePrefix("+").toInt() }.toList() }
fun readFileAsStrings(fileName: String) : List<String> = File(fileName).useLines { it.toList() }
| 0 |
Kotlin
| 0 | 0 |
12d0c841c91695e215f06efaf62d06a5480ba7a2
| 1,201 |
advent-of-code-2018
|
MIT License
|
distributed-systems/distributed-dijkstra/src/sequential/SequentialDijkstraHeap.kt
|
Lascor22
| 331,294,681 | false |
{"Java": 1706475, "HTML": 436528, "CSS": 371563, "C++": 342426, "Jupyter Notebook": 274491, "Kotlin": 248153, "Haskell": 189045, "Shell": 186916, "JavaScript": 159132, "Vue": 45665, "Python": 25957, "PLpgSQL": 23402, "Clojure": 11410, "Batchfile": 9677, "FreeMarker": 7201, "Yacc": 7148, "ANTLR": 6303, "Scala": 3020, "Lex": 1136, "Makefile": 473, "Grammatical Framework": 113}
|
package dijkstra.sequential
import dijkstra.graph.Graph
import java.util.*
import kotlin.collections.HashSet
private fun getClosestNode(notVisitedNodes: TreeMap<Long, HashSet<Int>>): Pair<Int, Long> {
val nodesWithMinDist = notVisitedNodes.firstEntry()
val closestNodes = nodesWithMinDist.value
val minDist = nodesWithMinDist.key
assert(closestNodes.isNotEmpty())
val res = closestNodes.iterator().next()
val removeResult = closestNodes.remove(res)
assert(removeResult)
if (closestNodes.isEmpty()) {
val setRemoveResult = notVisitedNodes.remove(minDist)
assert(setRemoveResult === closestNodes)
}
return Pair(res, minDist)
}
private fun deleteNode(notVisitedNodes: TreeMap<Long, HashSet<Int>>, dist: Long, nodeId: Int) {
val sameDistSet = notVisitedNodes[dist] ?: throw AssertionError()
assert(sameDistSet.contains(nodeId))
sameDistSet.remove(nodeId)
if (sameDistSet.isEmpty()) {
notVisitedNodes.remove(dist)
}
}
private fun addNode(notVisitedNodes: TreeMap<Long, HashSet<Int>>, dist: Long, nodeId: Int) {
val sameDistSet = notVisitedNodes[dist]
if (sameDistSet == null) {
notVisitedNodes[dist] = hashSetOf(nodeId)
} else {
assert(!sameDistSet.contains(nodeId))
sameDistSet.add(nodeId)
}
}
fun dijkstraHeap(graph: Graph, sId: Int): List<Long?> {
val result = MutableList<Long?>(graph.graph.size) { null }
result[sId] = 0
val notVisitedNodes = TreeMap<Long, HashSet<Int>>()
notVisitedNodes[0] = hashSetOf(sId)
while (notVisitedNodes.isNotEmpty()) {
val (closestNode, minDist) = getClosestNode(notVisitedNodes)
val curDist = result[closestNode] ?: throw AssertionError()
assert(curDist == minDist)
for ((curNeighbour, w) in graph.graph[closestNode]) {
val neighbourDist = result[curNeighbour]
if (neighbourDist == null) {
result[curNeighbour] = curDist + w
addNode(notVisitedNodes, curDist + w, curNeighbour)
} else if (neighbourDist > curDist + w) {
result[curNeighbour] = curDist + w
deleteNode(notVisitedNodes, neighbourDist, curNeighbour)
addNode(notVisitedNodes, curDist + w, curNeighbour)
}
}
}
return result.toList()
}
| 0 |
Java
| 0 | 0 |
c41dfeb404ce995abdeb18fc93502027e54239ee
| 2,350 |
ITMO-university
|
MIT License
|
src/Day13.kt
|
joshpierce
| 573,265,121 | false |
{"Kotlin": 46425}
|
import java.io.File
fun main() {
var directions: List<String> = File("Day13.txt").readLines()
var pairs = directions.chunked(3).map { Pair(it[0], it[1])}
var validIndexes: MutableList<Int> = mutableListOf()
var allPackets: MutableList<Any> = mutableListOf()
pairs.forEachIndexed { idx, it ->
println("== Pair ${idx+1} ==")
var left = parseList(it.first.substring(1, it.first.length - 1))
allPackets.add(left)
var right = parseList(it.second.substring(1, it.second.length - 1))
allPackets.add(right)
println("- Compare ${left.toString()} vs ${right.toString()}")
if(compare(left, right, 0) == 1) {
validIndexes.add(idx+1)
}
println("")
}
//Part 1
println("Sum Of Valid Indexes Is: ${validIndexes.sum()}")
//Part 2
val comparator = Comparator { a: Any, b: Any ->
return@Comparator compare(a as MutableList<Any>, b as MutableList<Any>, 0)
}
allPackets.sortWith(comparator)
var pkt2Index: Int = 0
var pkt6Index: Int = 0
allPackets.reversed().forEachIndexed { idx, it ->
println("${idx+1} - ${it.toString()}")
if (it.toString() == "[[2]]") pkt2Index = idx + 1
if (it.toString() == "[[6]]") pkt6Index = idx + 1
}
println("The Decoder Key is ${pkt2Index * pkt6Index}")
}
fun compare(left: MutableList<Any>, right: MutableList<Any>, level: Int): Int {
left.forEachIndexed { idx, leftVal ->
if (right.size < idx + 1) {
println("Right (${right.toString()}) List Is Shorter (${right.size}) Than Left List, Stopping Checks - INVALID ❌❌❌")
return -1
}
println("${"".padStart(level*2)}- Compare ${leftVal} vs ${right[idx]}")
if (leftVal is Int && right[idx] is Int) {
// both Values are ints, make sure that left is <= right to continue
if (leftVal.toString().toInt() == right[idx].toString().toInt()) {
return@forEachIndexed
} else if (leftVal.toString().toInt() < right[idx].toString().toInt()) {
println("LeftVal: ${leftVal} is < than RightVal: ${right[idx]} - VALID ✅✅✅")
return 1
} else {
println("LeftVal: ${leftVal} is > than RightVal: ${right[idx]} - INVALID ❌❌❌")
return -1
}
} else {
var leftToCheck: MutableList<Any> = mutableListOf()
if (leftVal is Int) {
leftToCheck = mutableListOf(leftVal)
} else if (leftVal is MutableList<*>) {
leftToCheck = leftVal as MutableList<Any>
}
var rightToCheck: MutableList<Any> = mutableListOf()
if (right[idx] is Int) {
rightToCheck = mutableListOf(right[idx])
} else if (right[idx] is MutableList<*>) {
rightToCheck = right[idx] as MutableList<Any>
}
// The Right Side is a List, Convert the Left Side To A List and Compare
var innerCheck = compare(leftToCheck, rightToCheck, level + 1)
if (innerCheck == 0) {
return@forEachIndexed
} else {
return innerCheck
}
}
}
// According to the Rules we shouldn't get here as our ultimate check??
if(left.size < right.size) {
println("Left List Is Smaller Than Right List, But All Items Are The Same - VALID ✅✅✅")
return 1
} else {
return 0
}
}
fun parseList(str: String): MutableList<Any> {
//println("Parser Started for | ${str}")
var newList: MutableList<Any> = mutableListOf()
var idx: Int = 0
while (idx < str.length) {
//println("Idx ${idx.toString()} | Char ${str.get(idx).toString()}")
if (str.get(idx) == '[') {
var endBracketPos = getValidCloseBracket(str.substring(idx, str.length))
//println("Found Valid Close Bracket | Start ${idx} | End ${endBracketPos}")
newList.add(parseList(str.substring(idx+1, idx+endBracketPos)))
idx = idx+endBracketPos + 1
} else if (listOf(',',']').contains(str.get(idx))) {
idx++
}
else {
// println(str)
//grab addl characters
var tmpstr = str.get(idx).toString()
// println("tmpstr ${tmpstr}")
var tmpidx = idx
// println("tmpidx ${tmpidx}")
while (str.length > tmpidx+1 && !listOf('[',']',',').contains(str.get(tmpidx+1))) {
//println("NextChar: ${str.get(tmpidx+1)}")
tmpstr += str.get(tmpidx+1).toString()
tmpidx++
}
newList.add(tmpstr.toInt())
idx++
}
}
return newList
}
fun getValidCloseBracket(str: String): Int {
//println("Getting Close Bracket Position for ${str}")
var brackets: MutableList<Char> = mutableListOf()
str.toMutableList().forEachIndexed { idx, char ->
if (char == '[') {
brackets.add('[')
} else if (char == ']') {
if (brackets.last() == '[') brackets.removeLast()
if (brackets.size == 0) { return idx }
}
}
return -1
}
| 0 |
Kotlin
| 0 | 1 |
fd5414c3ab919913ed0cd961348c8644db0330f4
| 5,334 |
advent-of-code-22
|
Apache License 2.0
|
src/main/kotlin/dev/shtanko/algorithms/leetcode/BasicCalculator.kt
|
ashtanko
| 203,993,092 | false |
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
|
/*
* Copyright 2020 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import dev.shtanko.algorithms.DECIMAL
import java.util.Stack
import kotlin.math.pow
fun interface CalculationStrategy {
fun calculate(s: String): Int
}
class StackAndStringReversal : CalculationStrategy {
private fun evaluateExpr(stack: Stack<Any?>): Int {
var res = 0
if (!stack.empty()) {
res = stack.pop() as Int
}
// Evaluate the expression till we get corresponding ')'
while (!stack.empty() && stack.peek() as Char != ')') {
val sign = stack.pop() as Char
if (sign == '+') {
res += stack.pop() as Int
} else {
res -= stack.pop() as Int
}
}
return res
}
override fun calculate(s: String): Int {
var operand = 0
var n = 0
val stack = Stack<Any?>()
for (i in s.length - 1 downTo 0) {
val ch: Char = s[i]
if (Character.isDigit(ch)) {
// Forming the operand - in reverse order.
operand += DECIMAL.toDouble().pow(n.toDouble()).toInt() * (ch - '0')
n += 1
} else if (ch != ' ') {
if (n != 0) {
// Save the operand on the stack
// As we encounter some non-digit.
stack.push(operand)
n = 0
operand = 0
}
if (ch == '(') {
val res = evaluateExpr(stack)
stack.pop()
// Append the evaluated result to the stack.
// This result could be of a sub-expression within the parenthesis.
stack.push(res)
} else {
// For other non-digits just push onto the stack.
stack.push(ch)
}
}
}
// Push the last operand to stack, if any.
if (n != 0) {
stack.push(operand)
}
// Evaluate any left overs in the stack.
return evaluateExpr(stack)
}
}
class StackAndNoStringReversal : CalculationStrategy {
override fun calculate(s: String): Int {
val stack = Stack<Int>()
var operand = 0
var result = 0 // For the on-going result
var sign = 1 // 1 means positive, -1 means negative
for (i in s.indices) {
val ch: Char = s[i]
when {
Character.isDigit(ch) -> {
// Forming operand, since it could be more than one digit
operand = DECIMAL * operand + ch.minus('0')
}
ch == '+' -> {
// Evaluate the expression to the left,
// with result, sign, operand
result += sign * operand
// Save the recently encountered '+' sign
sign = 1
// Reset operand
operand = 0
}
ch == '-' -> {
result += sign * operand
sign = -1
operand = 0
}
ch == '(' -> {
// Push the result and sign on to the stack, for later
// We push the result first, then sign
stack.push(result)
stack.push(sign)
// Reset operand and result, as if new evaluation begins for the new sub-expression
sign = 1
result = 0
}
ch == ')' -> {
// Evaluate the expression to the left
// with result, sign and operand
result += sign * operand
// ')' marks end of expression within a set of parenthesis
// Its result is multiplied with sign on top of stack
// as stack.pop() is the sign before the parenthesis
result *= stack.pop()
// Then add to the next operand on the top.
// as stack.pop() is the result calculated before this parenthesis
// (operand on stack) + (sign on stack * (result from parenthesis))
result += stack.pop()
// Reset the operand
operand = 0
}
}
}
return result + sign * operand
}
}
| 4 |
Kotlin
| 0 | 19 |
776159de0b80f0bdc92a9d057c852b8b80147c11
| 5,154 |
kotlab
|
Apache License 2.0
|
src/main/kotlin/nl/dirkgroot/adventofcode/year2020/Day08.kt
|
dirkgroot
| 317,968,017 | false |
{"Kotlin": 187862}
|
package nl.dirkgroot.adventofcode.year2020
import nl.dirkgroot.adventofcode.util.Input
import nl.dirkgroot.adventofcode.util.Puzzle
class Day08(input: Input) : Puzzle() {
private val program by lazy { parseProgram(input.lines()) }
private fun parseProgram(code: List<String>) = code.map {
it.split(" ").let { (instruction, argument) -> instruction to argument.toInt() }
}
override fun part1() = run().second
override fun part2() = program.asSequence().withIndex()
.filter { it.value.first != "acc" }
.map { run(flip = it.index) }
.first { (isLoop, _) -> !isLoop }
.let { (_, acc) -> acc }
private tailrec fun run(flip: Int = -1, ip: Int = 0, acc: Int = 0, visited: Set<Int> = emptySet()): Pair<Boolean, Int> =
when {
ip >= program.size -> false to acc
visited.contains(ip) -> true to acc
else -> {
val (instruction, argument) = instruction(ip, ip == flip)
when (instruction) {
"acc" -> run(flip, ip + 1, acc + argument, visited + ip)
"jmp" -> run(flip, ip + argument, acc, visited + ip)
"nop" -> run(flip, ip + 1, acc, visited + ip)
else -> throw IllegalStateException()
}
}
}
private fun instruction(index: Int, flip: Boolean) = program[index].let { (instruction, argument) ->
if (flip) (if (instruction == "jmp") "nop" else "jmp") to argument
else instruction to argument
}
}
| 1 |
Kotlin
| 1 | 1 |
ffdffedc8659aa3deea3216d6a9a1fd4e02ec128
| 1,564 |
adventofcode-kotlin
|
MIT License
|
year2023/day12/part2/src/main/kotlin/com/curtislb/adventofcode/year2023/day12/part2/Year2023Day12Part2.kt
|
curtislb
| 226,797,689 | false |
{"Kotlin": 2146738}
|
/*
--- Part Two ---
As you look out at the field of springs, you feel like there are way more springs than the condition
records list. When you examine the records, you discover that they were actually folded up this
whole time!
To unfold the records, on each row, replace the list of spring conditions with five copies of itself
(separated by `?`) and replace the list of contiguous groups of damaged springs with five copies of
itself (separated by `,`).
So, this row:
```
.# 1
```
Would become:
```
.#?.#?.#?.#?.# 1,1,1,1,1
```
The first line of the above example would become:
```
???.###????.###????.###????.###????.### 1,1,3,1,1,3,1,1,3,1,1,3,1,1,3
```
In the above example, after unfolding, the number of possible arrangements for some rows is now much
larger:
```
???.### 1,1,3 - 1 arrangement
.??..??...?##. 1,1,3 - 16384 arrangements
?#?#?#?#?#?#?#? 1,3,1,6 - 1 arrangement
????.#...#... 4,1,1 - 16 arrangements
????.######..#####. 1,6,5 - 2500 arrangements
?###???????? 3,2,1 - 506250 arrangements
```
After unfolding, adding all of the possible arrangement counts together produces 525152.
Unfold your condition records; what is the new sum of possible arrangement counts?
*/
package com.curtislb.adventofcode.year2023.day12.part2
import com.curtislb.adventofcode.year2023.day12.spring.SpringRecord
import java.nio.file.Path
import java.nio.file.Paths
/**
* Returns the solution to the puzzle for 2023, day 12, part 2.
*
* @param inputPath The path to the input file for this puzzle.
* @param foldFactor The number of copies of the original spring conditions and group sizes strings
* contained in the unfolded versions of both strings.
*/
fun solve(inputPath: Path = Paths.get("..", "input", "input.txt"), foldFactor: Int = 5): Long {
var total = 0L
inputPath.toFile().forEachLine { line ->
val springRecord = SpringRecord.fromString(line, foldFactor)
total += springRecord.countPossibleArrangements()
}
return total
}
fun main() {
println(solve())
}
| 0 |
Kotlin
| 1 | 1 |
6b64c9eb181fab97bc518ac78e14cd586d64499e
| 2,023 |
AdventOfCode
|
MIT License
|
Kotlin/src/dev/aspid812/leetcode/problem0539/Solution.kt
|
Const-Grigoryev
| 367,924,342 | false |
{"Python": 35682, "Kotlin": 11162, "C++": 2688, "Java": 2168, "C": 1076}
|
package dev.aspid812.leetcode.problem0539
/* 539. Minimum Time Difference
* ----------------------------
* Given a list of 24-hour clock time points in **"HH:MM"** format, return the *minimum **minutes** difference
* between any two time-points in the list*.
*
* ### Constraints:
*
* * `2 <= timePoints <= 2 * 10^4`
* * `timePoints[i]` is in the format **"HH:MM"**.
*/
class Solution {
fun findMinDifference(timePoints: List<String>): Int {
return timePoints.asSequence()
.map { timePoint ->
val hours = timePoint.substringBefore(':').toInt()
val minutes = timePoint.substringAfter(':').toInt()
hours * 60 + minutes
}
.sorted()
.let { seq ->
val instant = seq.iterator().next()
seq + (instant + 1440)
}
.zipWithNext { start, end -> end - start }
.minOrNull() ?: 1440
}
}
fun main() {
val s = Solution()
val timePoints1 = listOf("23:59", "00:00")
println("${s.findMinDifference(timePoints1)} == 1")
val timePoints2 = listOf("00:00", "23:59", "00:00")
println("${s.findMinDifference(timePoints2)} == 1")
}
| 0 |
Python
| 0 | 0 |
cea8e762ff79878e2d5622c937f34cf20f0b385e
| 1,221 |
LeetCode
|
MIT License
|
day03/kotlin/RJPlog/day2003_1_2.kts
|
smarkwart
| 317,009,367 | true |
{"Python": 528881, "Rust": 179510, "Kotlin": 92549, "Ruby": 59698, "TypeScript": 57721, "Groovy": 56394, "CSS": 38649, "Java": 36866, "JavaScript": 27433, "HTML": 5424, "Dockerfile": 3230, "C++": 2171, "Go": 1733, "Jupyter Notebook": 988, "Shell": 897, "Clojure": 567, "PHP": 68, "Tcl": 46, "Dart": 41, "Haskell": 37}
|
import java.io.File
//tag::identify_wood_width[]
fun WidthGrid2003(): Int {
var width: Int = 0
File("day2003_puzzle_input.txt").forEachLine { width = it.length }
return width
}
//end::identify_wood_width[]
//tag::identify_wood_depth[]
fun DepthGrid2003(): Int {
var depth: Int = 0
File("day2003_puzzle_input.txt").forEachLine { depth = depth + 1 }
return depth
}
//end::identify_wood_depth[]
//tag::setup_wood_grid[]
fun SetupGrid2003(): MutableMap<String, String> {
val Grid = mutableMapOf<String, String>()
var Position: String
var Texture: String
var ypos: Int = 0
File("day2003_puzzle_input.txt").forEachLine {
for (xpos in 0..it.length - 1) {
Position = (xpos).toString() + "=" + ypos.toString()
Texture = it[xpos].toString()
Grid.put(Position, Texture)
}
ypos = ypos + 1
}
return Grid
}
//end::setup_wood_grid[]
//tag::toboggan_wood_grid[]
fun WalkGrid2003(Grid_input: MutableMap<String, String>, width: Int, depth: Int, xstep: Int, ystep: Int): Int {
var solution: Int = 0
var x: Int = 0
var y: Int = 0
var Grid = Grid_input
while (y < depth) {
if (Grid.getValue(x.toString() + "=" + y.toString()) == "#") {
solution++
}
x = (x + xstep).rem(width)
y = y + ystep
}
return solution
}
//end::toboggan_wood_grid[]
//fun main(args: Array<String>) {
var solution1: Int
var solution2: Long = 1
var xstep: Int
var ystep: Int
//tag::read_puzzle[]
var width = WidthGrid2003()
var depth = DepthGrid2003()
var Grid_Init = SetupGrid2003()
//end::read_puzzle[]
// tag::part_1[]
xstep = 3
ystep = 1
solution1 = WalkGrid2003(Grid_Init, width, depth, xstep, ystep)
// end::part_1[]
// tag::part_2[]
xstep = 1
ystep = 1
solution2 = solution2 * WalkGrid2003(Grid_Init, width, depth, xstep, ystep)
xstep = 3
ystep = 1
solution2 = solution2 * WalkGrid2003(Grid_Init, width, depth, xstep, ystep)
xstep = 5
ystep = 1
solution2 = solution2 * WalkGrid2003(Grid_Init, width, depth, xstep, ystep)
xstep = 7
ystep = 1
solution2 = solution2 * WalkGrid2003(Grid_Init, width, depth, xstep, ystep)
xstep = 1
ystep = 2
solution2 = solution2 * WalkGrid2003(Grid_Init, width, depth, xstep, ystep)
// end::part_2[]
// tag::output[]
// print solution for part 1
println("****************************")
println("--- Day 3: Toboggan Trajectory ---")
println("****************************")
println("Solution for part1")
println(" $solution1 trees would you encounter")
println()
// print solution for part 2
println("****************************")
println("Solution for part2")
println(" $solution2")
println()
// end::output[]
//}
| 0 |
Python
| 0 | 0 |
b1f9e04177afaf7e7c15fdc7bf7bc76f27a029f6
| 2,601 |
aoc-2020
|
MIT License
|
src/main/kotlin/string/easy/RomanToInteger.kt
|
jiahaoliuliu
| 747,189,993 | false |
{"Kotlin": 97631}
|
package string.easy
import org.junit.Assert.assertEquals
import org.junit.Test
/**
* Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
*
* Symbol Value
* I 1
* V 5
* X 10
* L 50
* C 100
* D 500
* M 1000
*
* For example, 2 is written as II in Roman numeral, just two ones added together. 12 is written as XII,
* which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.
*
* Roman numerals are usually written largest to smallest from left to right. However, the numeral for four
* is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it
* making four. The same principle applies to the number nine, which is written as IX. There are six instances
* where subtraction is used:
*
* I can be placed before V (5) and X (10) to make 4 and 9.
* X can be placed before L (50) and C (100) to make 40 and 90.
* C can be placed before D (500) and M (1000) to make 400 and 900.
* Given a roman numeral, convert it to an integer.
*
* Example 1:
* Input: s = "III"
* Output: 3
* Explanation: III = 3.
*
* Example 2:
* Input: s = "LVIII"
* Output: 58
* Explanation: L = 50, V= 5, III = 3.
*
* Example 3:
* Input: s = "MCMXCIV"
* Output: 1994
* Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
*
* Constraints:
* 1 <= s.length <= 15
* s contains only the characters ('I', 'V', 'X', 'L', 'C', 'D', 'M').
* It is guaranteed that s is a valid roman numeral in the range [1, 3999].
*/
class RomanToInteger {
/** IV III VI
* Initial though
* 1. Build a dictionary of roman numbers
* init previous element as -1
* 2. Loop (from the first element to the last element)
* Get the current element
* If the current element is smaller or equals than the previous element
* add the previous element to the result
* assign the value of the current element to the previous element
* else
* extract from the current element the value of the previous element
* add it to the result
* assign MAX value to the previous element (it is not very good)
* 3. return the result
*
* Improvement
* M CM X C IV
* Going through the list
* check the value of the previous element
* if it is bigger than the current element, add current element
* if it smaller than the current element, add the current element, and extra 2 * value of the previous element
* So we just have to track one element at the time
*
* Small optimization -> Have a variable to keep the value of the previous element
*
*/
private fun romanToInt(s: String): Int {
// 1. Init the value
var previousValue = 0
var result = 0
val dict = IntArray(26)
dict['I' - 'A'] = 1
dict['V' - 'A'] = 5
dict['X' - 'A'] = 10
dict['L' - 'A'] = 50
dict['C' - 'A'] = 100
dict['D' - 'A'] = 500
dict['M' - 'A'] = 1000
// 2. Loop
for (element in s) {
val currentValue = dict[element - 'A']
result += currentValue
if (currentValue > previousValue) {
result -= previousValue * 2
}
previousValue = currentValue
}
// 3. Show result
return result
}
@Test
fun test1() {
// Given
val input = "III"
// When
val result = romanToInt(input)
// Then
assertEquals(3, result)
}
@Test
fun test2() {
// Given
val input = "LVIII"
// When
val result = romanToInt(input)
// Then
assertEquals(58, result)
}
@Test
fun test3() {
// Given
val input = "IV"
// When
val result = romanToInt(input)
// Then
assertEquals(4, result)
}
@Test
fun test4() {
// Given
val input = "MCMXCIV"
// When
val result = romanToInt(input)
// Then
assertEquals(1994, result)
}
}
| 0 |
Kotlin
| 0 | 0 |
c5ed998111b2a44d082fc6e6470d197554c0e7c9
| 4,308 |
CodingExercises
|
Apache License 2.0
|
src/main/kotlin/days/y22/Day03.kt
|
kezz
| 572,635,766 | false |
{"Kotlin": 20772}
|
package days.y22
import util.Day
import util.mapInner
public fun main() {
Day3().run()
}
public class Day3 : Day(22, 3) {
override fun part1(input: List<String>): Any = input
.asSequence()
.map(String::toCharArray)
.map { items -> items.slice(0 until items.size / 2) to items.slice(items.size / 2 until items.size) }
.map { (firstCompartment, secondCompartment) -> firstCompartment.intersect(secondCompartment.toSet()) }
.map(Set<Char>::first)
.map(Char::code)
.sumOf { code -> if (code <= 90) { code - 38 } else { code - 96 } }
override fun part2(input: List<String>): Any = input
.asSequence()
.chunked(3)
.mapInner(String::toCharArray)
.map { (first, second, third) -> first.intersect(second.toSet()).intersect(third.toSet()) }
.map(Set<Char>::first)
.map(Char::code)
.sumOf { code -> if (code <= 90) { code - 38 } else { code - 96 } }
}
| 0 |
Kotlin
| 0 | 0 |
1cef7fe0f72f77a3a409915baac3c674cc058228
| 969 |
aoc
|
Apache License 2.0
|
src/main/java/com/barneyb/aoc/aoc2022/day17/PyroclasticFlow.kt
|
barneyb
| 553,291,150 | false |
{"Kotlin": 184395, "Java": 104225, "HTML": 6307, "JavaScript": 5601, "Shell": 3219, "CSS": 1020}
|
package com.barneyb.aoc.aoc2022.day17
import com.barneyb.aoc.util.Solver
import com.barneyb.aoc.util.toSlice
import com.barneyb.util.Dir
import com.barneyb.util.HashMap
import com.barneyb.util.HashSet
import com.barneyb.util.Vec2
import kotlin.math.max
import kotlin.math.min
fun main() {
Solver.execute(
::parse,
::heightOfTower, // 3161
::heightOfReallyTallTower // 1575931232076
)
}
private const val WIDTH = 7
private const val ROCK_COUNT = 1_000_000_000_000
internal data class Rock(
val parts: List<Vec2>,
val width: Int = parts.maxOf(Vec2::x) - parts.minOf(Vec2::x) + 1,
val height: Int = parts.maxOf(Vec2::y) - parts.minOf(Vec2::y) + 1,
) {
companion object {
fun parse(input: String) =
Rock(buildList {
input.toSlice()
.trim()
.lines()
.withIndex()
.forEach { (y, l) ->
for ((x, c) in l.withIndex()) {
if (c == '#') add(Vec2(x, y))
}
}
})
}
val top get() = parts.maxOf(Vec2::y) - height
fun move(dir: Dir, delta: Int = 1) =
copy(parts = parts.map { it.move(dir, delta) })
fun down(delta: Int = 1) =
move(Dir.SOUTH, delta)
fun right(delta: Int = 1) =
move(Dir.EAST, delta)
fun left(delta: Int = 1) =
move(Dir.WEST, delta)
}
internal val rocks = listOf(
Rock.parse("""####"""),
Rock.parse(".#.\n###\n.#."),
Rock.parse("..#\n..#\n###"),
Rock.parse("#\n#\n#\n#"),
Rock.parse("##\n##"),
)
internal fun parse(input: String) =
input.toSlice().trim()
internal fun heightOfTower(jets: CharSequence, rockCount: Long = 2022): Long {
var idxRock = 0
var idxJet = 0
val atRest = HashSet<Vec2>()
var heightOfTower = 0
val shapesOfTops = HashMap<List<Int>, Pair<Int, Int>>()
@Suppress("unused")
fun draw(rock: Rock? = null) =
buildString {
for (y in min(-heightOfTower, rock?.top ?: 0)..0) {
for (x in -1..WIDTH) {
if (x < 0 || x == WIDTH) append('|')
else if (atRest.contains(Vec2(x, y))) append('#')
else if (rock == null) append('.')
else if (rock.parts.contains(Vec2(x, y))) append('@')
else append('.')
}
append('\n')
}
append('+')
append("-".repeat(WIDTH))
append('+')
append('\n')
}
fun valid(r: Rock) =
r.parts.all {
it.x in 0..6 &&
it.y <= 0 &&
!atRest.contains(it)
}
while (idxRock < rockCount) {
val ir = idxRock++ % rocks.size
var rock = rocks[ir]
rock = rock.move(Dir.NORTH, heightOfTower + rock.height + 2)
rock = rock.move(Dir.EAST, 2)
while (true) {
val ij = idxJet++ % jets.length
val jet = when (jets[ij]) {
'<' -> rock.move(Dir.WEST)
'>' -> rock.move(Dir.EAST)
else -> throw IllegalArgumentException("bad jet")
}
if (valid(jet)) rock = jet
val drop = rock.move(Dir.SOUTH)
if (valid(drop)) rock = drop
else {
atRest.addAll(rock.parts)
heightOfTower = max(heightOfTower, -rock.top)
val shape = (0 until WIDTH).map { x ->
var v = Vec2(x, -heightOfTower)
while (!atRest.contains(v) && v.y <= 0) {
v = v.south()
}
heightOfTower + v.y - 1
} + listOf(ir, ij)
if (shapesOfTops.contains(shape)) {
val (preIdx, preHeight) = shapesOfTops[shape]
val cycleLen = idxRock - preIdx
val heightPerCycle = heightOfTower - preHeight
val remaining = rockCount - preIdx
return heightOfTower(
jets,
preIdx.toLong() + remaining % cycleLen
) + (remaining / cycleLen) * heightPerCycle
} else {
shapesOfTops[shape] = Pair(idxRock, heightOfTower)
}
break
}
}
}
return heightOfTower.toLong()
}
internal fun heightOfReallyTallTower(jets: CharSequence): Long =
heightOfTower(jets, ROCK_COUNT)
| 0 |
Kotlin
| 0 | 0 |
8b5956164ff0be79a27f68ef09a9e7171cc91995
| 4,608 |
aoc-2022
|
MIT License
|
src/main/kotlin/computerScience/dataStructures/ListDataStructure.kt
|
rccorreia
| 739,621,618 | false |
{"Kotlin": 51255}
|
package com.github.rccorreia.computerScience.dataStructures
import kotlin.math.abs
class ListDataStructureInterviewQuestions {
// Question: Given an array a that contains only numbers in the range from 1 to a.length, find
// the first duplicate number for which the second occurrence has the minimal index.
// In other words, if there are more than 1 duplicated numbers, return the number for which the
// second occurrence has a smaller index than the second occurrence of the other number does.
// If there are no such elements, return -1.
//
// Example
//
// For a = [2, 1, 3, 5, 3, 2], the output should be solution(a) = 3.
//
// There are 2 duplicates: numbers 2 and 3. The second occurrence of 3 has a smaller index than
// the second occurrence of 2 does, so the answer is 3.
//
// For a = [2, 2], the output should be solution(a) = 2;
// For a = [2, 4, 3, 5, 1], the output should be solution(a) = -1.
//
// Guaranteed constraints:
// 1 ≤ a.length ≤ 105,
// 1 ≤ a[i] ≤ a.length.
//
// Answer:
//
// Without memory restriction
//
// val search = mutableSetOf<Int>()
// for(number in a){
// if (number in search) return number else search.add(number)
// }
// return -1
fun firstDuplicate(a: MutableList<Int>): Int{
for (i in a.indices){
if(a[abs(a[i])-1] < 0){
return abs(a[i])
} else {
a[abs(a[i])-1]=-a[abs(a[i])-1]
}
}
return -1
}
// Given a string s consisting of small English letters, find and return the first instance of a non-repeating
// character in it. If there is no such character, return '_'.
//
// Example
//
// For s = "abacabad", the output should be
// solution(s) = 'c'.
//
// There are 2 non-repeating characters in the string: 'c' and 'd'. Return c since it appears in the string first.
//
// For s = "abacabaabacaba", the output should be
// solution(s) = '_'.
//
// There are no characters in this string that do not repeat.
//
// Input/Output
//
// [execution time limit] 3 seconds (kt)
//
// [memory limit] 1 GB
//
// [input] string s
//
// A string that contains only lowercase English letters.
//
// Guaranteed constraints:
// 1 ≤ s.length ≤ 105.
//
// [output] char
//
// The first non-repeating character in s, or '_' if there are no characters that do not repeat.
// First function made:
// fun solution(s: String): Char {
// for (character in s){
// if (s.indexOf(character) == s.lastIndexOf(character)){
// return character
// }
// }
// return '_'
// }
fun firstNotRepeatingCharacter(s: String) =
s.groupingBy { it }.eachCount()
.filter { it.value == 1 }.toList().firstOrNull()?.first ?: '_'
// You are given an n x n 2D matrix that represents an image. Rotate the image by 90 degrees (clockwise).
//
// Example
//
// For
//
// a = [[1, 2, 3],
// [4, 5, 6],
// [7, 8, 9]]
// the output should be
//
// solution(a) =
// [[7, 4, 1],
// [8, 5, 2],
// [9, 6, 3]]
// Input/Output
//
// [execution time limit] 3 seconds (kt)
//
// [memory limit] 1 GB
//
// [input] array.array.integer a
//
// Guaranteed constraints:
// 1 ≤ a.length ≤ 100,
// a[i].length = a.length,
// 1 ≤ a[i][j] ≤ 104.
//
// [output] array.array.integer
//Remember:
// Rotate + 90º -> Transpose + Reverse row
// Rotate - 90º -> Reverse row + Transpose
fun rotateImage(a: MutableList<MutableList<Int>>): List<List<Int>> {
var helper: Int
for (rowIndex in a.indices){
for (columnIndex in rowIndex+1 until a[0].size){
helper = a[rowIndex][columnIndex]
a[rowIndex][columnIndex] = a[columnIndex][rowIndex]
a[columnIndex][rowIndex] = helper
}
}
a.map { it.reverse() }
return a
}
// Sudoku is a number-placement puzzle. The objective is to fill a 9 × 9 grid with numbers in such a way that each column, each row, and each of the nine 3 × 3 sub-grids that compose the grid all contain all of the numbers from 1 to 9 one time.
//
// Implement an algorithm that will check whether the given grid of numbers represents a valid Sudoku puzzle according to the layout rules described above. Note that the puzzle represented by grid does not have to be solvable.
//
// Example
//
// For
//
// grid =
// [['.', '.', '.', '1', '4', '.', '.', '2', '.'],
// ['.', '.', '6', '.', '.', '.', '.', '.', '.'],
// ['.', '.', '.', '.', '.', '.', '.', '.', '.'],
// ['.', '.', '1', '.', '.', '.', '.', '.', '.'],
// ['.', '6', '7', '.', '.', '.', '.', '.', '9'],
// ['.', '.', '.', '.', '.', '.', '8', '1', '.'],
// ['.', '3', '.', '.', '.', '.', '.', '.', '6'],
// ['.', '.', '.', '.', '.', '7', '.', '.', '.'],
// ['.', '.', '.', '5', '.', '.', '.', '7', '.']]
// the output should be
// solution(grid) = true;
//
// For
//
// grid =
// [['.', '.', '.', '.', '2', '.', '.', '9', '.'],
// ['.', '.', '.', '.', '6', '.', '.', '.', '.'],
// ['7', '1', '.', '.', '7', '5', '.', '.', '.'],
// ['.', '7', '.', '.', '.', '.', '.', '.', '.'],
// ['.', '.', '.', '.', '8', '3', '.', '.', '.'],
// ['.', '.', '8', '.', '.', '7', '.', '6', '.'],
// ['.', '.', '.', '.', '.', '2', '.', '.', '.'],
// ['.', '1', '.', '2', '.', '.', '.', '.', '.'],
// ['.', '2', '.', '.', '3', '.', '.', '.', '.']]
// the output should be
// solution(grid) = false.
//
// The given grid is not correct because there are two 1s in the second column. Each column, each row, and each 3 × 3 subgrid can only contain the numbers 1 through 9 one time.
//
// Input/Output
//
// [execution time limit] 3 seconds (kt)
//
// [memory limit] 1 GB
//
// [input] array.array.char grid
//
// A 9 × 9 array of characters, in which each character is either a digit from '1' to '9' or a period '.'.
//
// [output] boolean
//
// Return true if grid represents a valid Sudoku puzzle, otherwise return false.
fun sudoku2(grid: List<List<Char>>): Boolean =
grid.all { it.filter { it != '.'}.noDuplicates() }.and(
grid.flatMap { it.withIndex() }.groupBy { it.index }.all {it.value.map { it.value }.filter {it != '.'}.noDuplicates()}.and(
grid.windowed(3,3).all { it.flatMap { it.windowed(3,3).withIndex() }.groupBy { it.index }.all { it.value.flatMap { it.value }.filter { it != '.' }.noDuplicates()} }
)
)
private fun <T> List<T>.noDuplicates() = this.distinct().size == this.size
// A cryptarithm is a mathematical puzzle for which the goal is to find the correspondence between letters and digits, such that the given arithmetic equation consisting of letters holds true when the letters are converted to digits.
//
// You have an array of strings crypt, the cryptarithm, and an an array containing the mapping of letters and digits, solution. The array crypt will contain three non-empty strings that follow the structure: [word1, word2, word3], which should be interpreted as the word1 + word2 = word3 cryptarithm.
//
// If crypt, when it is decoded by replacing all of the letters in the cryptarithm with digits using the mapping in solution, becomes a valid arithmetic equation containing no numbers with leading zeroes, the answer is true. If it does not become a valid arithmetic solution, the answer is false.
//
// Note that number 0 doesn't contain leading zeroes (while for example 00 or 0123 do).
//
// Example
//
// For crypt = ["SEND", "MORE", "MONEY"] and
//
// solution = [['O', '0'],
// ['M', '1'],
// ['Y', '2'],
// ['E', '5'],
// ['N', '6'],
// ['D', '7'],
// ['R', '8'],
// ['S', '9']]
// the output should be
// solution(crypt, solution) = true.
//
// When you decrypt "SEND", "MORE", and "MONEY" using the mapping given in crypt, you get 9567 + 1085 = 10652 which is correct and a valid arithmetic equation.
//
// For crypt = ["TEN", "TWO", "ONE"] and
//
// solution = [['O', '1'],
// ['T', '0'],
// ['W', '9'],
// ['E', '5'],
// ['N', '4']]
// the output should be
// solution(crypt, solution) = false.
//
// Even though 054 + 091 = 145, 054 and 091 both contain leading zeroes, meaning that this is not a valid solution.
//
// Input/Output
//
// [execution time limit] 3 seconds (kt)
//
// [memory limit] 1 GB
//
// [input] array.string crypt
//
// An array of three non-empty strings containing only uppercase English letters.
//
// Guaranteed constraints:
// crypt.length = 3,
// 1 ≤ crypt[i].length ≤ 14.
//
// [input] array.array.char solution
//
// An array consisting of pairs of characters that represent the correspondence between letters and numbers in the cryptarithm. The first character in the pair is an uppercase English letter, and the second one is a digit in the range from 0 to 9.
//
// It is guaranteed that solution only contains entries for the letters present in crypt and that different letters have different values.
//
// Guaranteed constraints:
// solution[i].length = 2,
// 'A' ≤ solution[i][0] ≤ 'Z',
// '0' ≤ solution[i][1] ≤ '9',
// solution[i][0] ≠ solution[j][0], i ≠ j,
// solution[i][1] ≠ solution[j][1], i ≠ j.
//
// [output] boolean
//
// Return true if the solution represents the correct solution to the cryptarithm crypt, otherwise return false.
fun isCryptSolution(crypt: List<String>, solution: List<List<Char>>): Boolean {
val mappedSolution = solution.associate { it[0] to it[1] }
if (thereIsALeadingZero(crypt, mappedSolution)) return false
val intOfString1 = crypt[0].map { mappedSolution[it] ?: '0' }.joinToString("").toIntOrNull() ?: 0
val intOfString2 = crypt[1].map { mappedSolution[it] ?: '0' }.joinToString("").toIntOrNull() ?: 0
val intOfString3 = crypt[2].map { mappedSolution[it] ?: '0' }.joinToString("").toIntOrNull() ?: 0
return intOfString1 + intOfString2 == intOfString3
}
private fun thereIsALeadingZero(crypt: List<String>, mappedSolution: Map<Char, Char>): Boolean{
(0 until 3 ).forEach { if ( mappedSolution[crypt[it][0]] == '0' && crypt[it].length > 1) return true }
return false
}
}
| 0 |
Kotlin
| 0 | 0 |
33204487651afb603704bea044908d47e3986b8b
| 10,476 |
software-engineer-roadmap
|
MIT License
|
src/main/kotlin/adventofcode/day07/CamelCardsHand.kt
|
jwcarman
| 731,408,177 | false |
{"Kotlin": 137289}
|
/*
* Copyright (c) 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package adventofcode.day07
import adventofcode.util.removeAll
import adventofcode.util.splitByWhitespace
private const val HIGH_CARD = "11111"
private const val ONE_PAIR = "2111"
private const val TWO_PAIR = "221"
private const val THREE_OF_A_KIND = "311"
private const val FULL_HOUSE = "32"
private const val FOUR_OF_A_KIND = "41"
private const val FIVE_OF_A_KIND = "5"
data class CamelCardsHand(val hand: String, val bid: Int = 0){
val value = "${hand.handTypePrefix()}${hand.hexify()}".toLong(16)
val wildCardValue = "${hand.wildCardHandTypePrefix()}${hand.wildCardHexify()}".toLong(16)
private fun Char.hexify(): Char {
return when (this) {
'A' -> 'E'
'K' -> 'D'
'Q' -> 'C'
'J' -> 'B'
'T' -> 'A'
else -> this
}
}
private fun Char.wildCardHexify(): Char {
return when (this) {
'A' -> 'E'
'K' -> 'D'
'Q' -> 'C'
'J' -> '1'
'T' -> 'A'
else -> this
}
}
private fun String.hexify(): String {
return map { c -> c.hexify() }.joinToString(separator = "")
}
private fun String.wildCardHexify(): String {
return map { c -> c.wildCardHexify() }.joinToString(separator = "")
}
private fun String.wildCardHandTypePrefix(): String {
val signature = removeAll("J").groupingBy { c -> c }.eachCount().values.sortedDescending().joinToString(separator = "")
return when(signature) {
HIGH_CARD -> "1"
ONE_PAIR, "1111"-> "2"
TWO_PAIR -> "3"
THREE_OF_A_KIND, "211", "111" -> "4"
FULL_HOUSE, "22" -> "5"
FOUR_OF_A_KIND, "31", "21", "11" -> "6"
FIVE_OF_A_KIND, "4", "3", "2", "1", "" -> "7"
else -> ""
}
}
private fun String.handTypePrefix(): String {
val signature = groupingBy { c -> c }.eachCount().values.sortedDescending().joinToString(separator = "")
return when (signature) {
HIGH_CARD -> "1"
ONE_PAIR -> "2"
TWO_PAIR -> "3"
THREE_OF_A_KIND -> "4"
FULL_HOUSE -> "5"
FOUR_OF_A_KIND -> "6"
FIVE_OF_A_KIND -> "7"
else -> ""
}
}
companion object {
fun parse(input: String): CamelCardsHand {
val (hand, bid) = input.splitByWhitespace()
return CamelCardsHand(hand, bid.toInt())
}
}
}
| 0 |
Kotlin
| 0 | 0 |
dfb226e92a03323ad48c50d7e970d2a745b479bb
| 3,108 |
adventofcode2023
|
Apache License 2.0
|
buildSrc/src/main/kotlin/kotlinx/html/generate/tag-unions.kt
|
Kotlin
| 33,301,379 | false |
{"Kotlin": 554316}
|
package kotlinx.html.generate
fun tagUnions(repository: Repository) {
val groupings = repository.groupsByTags.filter { it.value.size > 1 }
val groups = groupings.values.map { it.map { it.name }.toHashSet() }.distinct().sortedByDescending { it.size }
val allUnions = repository.groupUnions
// initial pass
groups.forEach { group ->
val name = unionName(group)
val superGroups = groups.filter { it !== group && it.containsAll(group) }
val members = group.toList()
val intersection = members.map { repository.tagGroups[it]!!.tags.toSet() }.reduce { a, b -> a.intersect(b) }
val union = GroupUnion(members, intersection, emptyList(), emptyList(), superGroups.map(::unionName))
require(union.name == name)
allUnions[name] = union
}
// pass2: fill additionalTags and ambiguityTags
groups.forEach { groupMembers ->
val unionName = unionName(groupMembers)
val union = allUnions[unionName]!!
val additionalTags = union.intersectionTags.filter { tag -> union.superGroups.none { tag in allUnions[it]!!.intersectionTags } }
val ambiguityTags = union.intersectionTags.filter { tag -> union.superGroups.count { tag in allUnions[it]!!.intersectionTags } > 1 }
allUnions[unionName] = union.copy(additionalTags = additionalTags, ambiguityTags = ambiguityTags)
}
// transpose map
val unionsByGroups = allUnions.values.flatMap { u -> u.members.map { it to u.name } }.groupBy({ it.first }, { allUnions[it.second]!! })
repository.unionsByGroups = unionsByGroups
}
fun unionName(members: Iterable<String>) = humanizeJoin(members, "Or")
| 89 |
Kotlin
| 177 | 1,514 |
6c926dda0567d765fe84239e13606e43ff2e3657
| 1,667 |
kotlinx.html
|
Apache License 2.0
|
src/Day02.kt
|
mdtausifahmad
| 573,116,146 | false |
{"Kotlin": 5783}
|
import java.io.File
fun main(){
val score = File("src/Day02.txt")
.readText()
.split("\n")
.flatMap { it.lines() }
.map { it.split(" ") }
.sumOf { getPointOfRoundSecondPart(it[0].first(), it[1].first()) }
println(score)
}
fun getPointOfRound(first: Char, second: Char): Int {
return when (second) {
'X' -> {
return when (first) {
'A' -> 1 + 3
'B' -> 1
'C' -> 1 + 6
else -> error("Check Input")
}
}
'Y' -> {
return when (first) {
'A' -> 2 + 6
'B' -> 2 + 3
'C' -> 2
else -> error("Check Input")
}
}
'Z' -> {
return when (first) {
'A' -> 3
'B' -> 3 + 6
'C' -> 3 + 3
else -> error("Check Input")
}
}
else -> error("Check Input")
}
}
fun getPointOfRoundSecondPart(first: Char, second: Char): Int {
return when (second) {
'X' -> {
return when (first) {
'A' -> 3
'B' -> 1
'C' -> 2
else -> error("Check Input")
}
}
'Y' -> {
return when (first) {
'A' -> 1 + 3
'B' -> 2 + 3
'C' -> 3 + 3
else -> error("Check Input")
}
}
'Z' -> {
return when (first) {
'A' -> 2 + 6
'B' -> 3 + 6
'C' -> 1 + 6
else -> error("Check Input")
}
}
else -> error("Check Input")
}
}
| 0 |
Kotlin
| 0 | 0 |
13295fd5f5391028822243bb6880a98c70475ee2
| 1,707 |
adventofcode2022
|
Apache License 2.0
|
src/main/java/challenges/cracking_coding_interview/trees_graphs/paths_with_sum/PathsWithSumB.kt
|
ShabanKamell
| 342,007,920 | false | null |
package challenges.cracking_coding_interview.trees_graphs.paths_with_sum
import challenges.util.TreeNode
object PathsWithSumB {
fun countPathsWithSum(root: TreeNode?, targetSum: Int): Int {
return countPathsWithSum(root, targetSum, 0, HashMap())
}
private fun countPathsWithSum(
node: TreeNode?,
targetSum: Int,
runningSum: Int,
pathCount: HashMap<Int?, Int>
): Int {
var runningSum = runningSum
if (node == null) return 0 // Base case
runningSum += node.data
/* Count paths with sum ending at the current node. */
val sum = runningSum - targetSum
var totalPaths = pathCount.getOrDefault(sum, 0)
/* If runningSum equals targetSum, then one additional path starts at root. Add in this path.*/
if (runningSum == targetSum) {
totalPaths++
}
/* Add runningSum to pathCounts. */
incrementHashTable(pathCount, runningSum, 1)
/* Count paths with sum on the left and right. */
totalPaths += countPathsWithSum(
node.left,
targetSum,
runningSum,
pathCount
)
totalPaths += countPathsWithSum(node.right, targetSum, runningSum, pathCount)
incrementHashTable(pathCount, runningSum, -1) // Remove runningSum
return totalPaths
}
private fun incrementHashTable(hashTable: HashMap<Int?, Int>, key: Int, delta: Int) {
val newCount = hashTable.getOrDefault(key, 0) + delta
if (newCount == 0) { // Remove when zero to reduce space usage
hashTable.remove(key)
} else {
hashTable[key] = newCount
}
}
@JvmStatic
fun main(args: Array<String>) {
/*
TreeNode root = new TreeNode(5);
root.left = new TreeNode(3);
root.right = new TreeNode(1);
root.left.left = new TreeNode(-8);
root.left.right = new TreeNode(8);
root.right.left = new TreeNode(2);
root.right.right = new TreeNode(6);
root.right.left.left = new TreeNode(0);
println(countPathsWithSum(root, 0));
*/
/*TreeNode root = new TreeNode(-7);
root.left = new TreeNode(-7);
root.left.right = new TreeNode(1);
root.left.right.left = new TreeNode(2);
root.right = new TreeNode(7);
root.right.left = new TreeNode(3);
root.right.right = new TreeNode(20);
root.right.right.left = new TreeNode(0);
root.right.right.left.left = new TreeNode(-3);
root.right.right.left.left.right = new TreeNode(2);
root.right.right.left.left.right.left = new TreeNode(1);
println(countPathsWithSum(root, 0));*/
val root = TreeNode(0)
root.left = TreeNode(0)
root.right = TreeNode(0)
root.right?.left = TreeNode(0)
root.right?.left?.right = TreeNode(0)
root.right?.right = TreeNode(0)
println(countPathsWithSum(root, 0))
println(countPathsWithSum(root, 4))
}
}
| 0 |
Kotlin
| 0 | 0 |
ee06bebe0d3a7cd411d9ec7b7e317b48fe8c6d70
| 2,928 |
CodingChallenges
|
Apache License 2.0
|
src/Day04.kt
|
alexladeira
| 573,196,827 | false |
{"Kotlin": 3920}
|
import kotlin.streams.toList
fun main() {
val result = part2()
println(result)
}
private fun part2() = readInput("Day04").fold(0) { acc, s ->
val values = s.replace("-", ",").split(",").stream().mapToInt { it.toInt() }.toList()
if (values[1] >= values[2] && values[0] <= values[3]) {
acc + 1
} else {
acc
}
}
private fun part1() = readInput("Day04").fold(0) { acc, s ->
val values = s.replace("-", ",").split(",").stream().mapToInt { it.toInt() }.toList()
val firstRange = IntRange(values[0], values[1])
val secondRange = IntRange(values[2], values[3])
if ((firstRange.contains(secondRange.first) && firstRange.contains(secondRange.last)) || secondRange.contains(
firstRange.first
) && secondRange.contains(firstRange.last)
) {
acc + 1
} else {
acc
}
}
| 0 |
Kotlin
| 0 | 0 |
facafc2d92de2ad2b6264610be4159c8135babcb
| 860 |
aoc-2022-in-kotlin
|
Apache License 2.0
|
app/src/main/kotlin/kotlinadventofcode/2015/2015-06.kt
|
pragmaticpandy
| 356,481,847 | false |
{"Kotlin": 1003522, "Shell": 219}
|
// Originally generated by the template in CodeDAO
package kotlinadventofcode.`2015`
import com.github.h0tk3y.betterParse.grammar.Grammar
import com.github.h0tk3y.betterParse.parser.Parser
import kotlinadventofcode.Day
import kotlinadventofcode.`2015`.`2015-06`.Instruction.*
import kotlin.math.max
import com.github.h0tk3y.betterParse.combinators.*
import com.github.h0tk3y.betterParse.grammar.parseToEnd
import com.github.h0tk3y.betterParse.lexer.*
class `2015-06` : Day {
data class Light(val x: Int, val y: Int) {
operator fun rangeTo(end: Light): Set<Light> {
val result: MutableSet<Light> = mutableSetOf()
for (x in x..end.x) for (y in y..end.y) result += Light(x, y)
return result
}
}
enum class Instruction { ON, OFF, TOGGLE; }
private fun parseInstructions(input: String): List<InstructionForRange> {
val grammar = object : Grammar<List<InstructionForRange>>() {
val turnOn by literalToken("turn on")
val turnOff by literalToken("turn off")
val toggle by literalToken("toggle")
val instruction by
(turnOn asJust Instruction.ON) or
(turnOff asJust Instruction.OFF) or
(toggle asJust Instruction.TOGGLE)
val digits by regexToken("\\d+")
val int by digits use { text.toInt() }
val comma by literalToken(",")
val light by int and skip(comma) and int map { (x, y) -> Light(x, y) }
val through by literalToken(" through ")
val space by literalToken(" ")
val instructionForRange by instruction and skip(space) and light and skip(through) and light map
{ (instruction, startLight, endLight) ->
InstructionForRange(instruction, startLight..endLight)
}
val newLine by literalToken("\n")
override val rootParser: Parser<List<InstructionForRange>> by separatedTerms(instructionForRange, newLine)
}
return grammar.parseToEnd(input)
}
data class InstructionForRange(val instruction: Instruction, val range: Set<Light>)
/**
* After verifying your solution on the AoC site, run `./ka continue` to add a test for it.
*/
override fun runPartOneNoUI(input: String): String {
val litLights: MutableSet<Light> = mutableSetOf()
parseInstructions(input).forEach {
when (it.instruction) {
ON -> litLights += it.range
OFF -> litLights -= it.range
TOGGLE -> it.range.forEach { if (it in litLights) litLights -= it else litLights += it }
}
}
return litLights.size.toString()
}
/**
* After verifying your solution on the AoC site, run `./ka continue` to add a test for it.
*/
override fun runPartTwoNoUI(input: String): String {
val brightnesses: MutableMap<Light, Int> = mutableMapOf()
fun addToRange(range: Set<Light>, level: Int) {
range.forEach {
brightnesses[it] = max(0, (brightnesses[it] ?: 0) + level)
}
}
parseInstructions(input).forEach {
when (it.instruction) {
ON -> addToRange(it.range, 1)
OFF -> addToRange(it.range, -1)
TOGGLE -> addToRange(it.range, 2)
}
}
return brightnesses.values.sum().toString()
}
override val defaultInput = """turn off 660,55 through 986,197
turn off 341,304 through 638,850
turn off 199,133 through 461,193
toggle 322,558 through 977,958
toggle 537,781 through 687,941
turn on 226,196 through 599,390
turn on 240,129 through 703,297
turn on 317,329 through 451,798
turn on 957,736 through 977,890
turn on 263,530 through 559,664
turn on 158,270 through 243,802
toggle 223,39 through 454,511
toggle 544,218 through 979,872
turn on 313,306 through 363,621
toggle 173,401 through 496,407
toggle 333,60 through 748,159
turn off 87,577 through 484,608
turn on 809,648 through 826,999
toggle 352,432 through 628,550
turn off 197,408 through 579,569
turn off 1,629 through 802,633
turn off 61,44 through 567,111
toggle 880,25 through 903,973
turn on 347,123 through 864,746
toggle 728,877 through 996,975
turn on 121,895 through 349,906
turn on 888,547 through 931,628
toggle 398,782 through 834,882
turn on 966,850 through 989,953
turn off 891,543 through 914,991
toggle 908,77 through 916,117
turn on 576,900 through 943,934
turn off 580,170 through 963,206
turn on 184,638 through 192,944
toggle 940,147 through 978,730
turn off 854,56 through 965,591
toggle 717,172 through 947,995
toggle 426,987 through 705,998
turn on 987,157 through 992,278
toggle 995,774 through 997,784
turn off 796,96 through 845,182
turn off 451,87 through 711,655
turn off 380,93 through 968,676
turn on 263,468 through 343,534
turn on 917,936 through 928,959
toggle 478,7 through 573,148
turn off 428,339 through 603,624
turn off 400,880 through 914,953
toggle 679,428 through 752,779
turn off 697,981 through 709,986
toggle 482,566 through 505,725
turn off 956,368 through 993,516
toggle 735,823 through 783,883
turn off 48,487 through 892,496
turn off 116,680 through 564,819
turn on 633,865 through 729,930
turn off 314,618 through 571,922
toggle 138,166 through 936,266
turn on 444,732 through 664,960
turn off 109,337 through 972,497
turn off 51,432 through 77,996
turn off 259,297 through 366,744
toggle 801,130 through 917,544
toggle 767,982 through 847,996
turn on 216,507 through 863,885
turn off 61,441 through 465,731
turn on 849,970 through 944,987
toggle 845,76 through 852,951
toggle 732,615 through 851,936
toggle 251,128 through 454,778
turn on 324,429 through 352,539
toggle 52,450 through 932,863
turn off 449,379 through 789,490
turn on 317,319 through 936,449
toggle 887,670 through 957,838
toggle 671,613 through 856,664
turn off 186,648 through 985,991
turn off 471,689 through 731,717
toggle 91,331 through 750,758
toggle 201,73 through 956,524
toggle 82,614 through 520,686
toggle 84,287 through 467,734
turn off 132,367 through 208,838
toggle 558,684 through 663,920
turn on 237,952 through 265,997
turn on 694,713 through 714,754
turn on 632,523 through 862,827
turn on 918,780 through 948,916
turn on 349,586 through 663,976
toggle 231,29 through 257,589
toggle 886,428 through 902,993
turn on 106,353 through 236,374
turn on 734,577 through 759,684
turn off 347,843 through 696,912
turn on 286,699 through 964,883
turn on 605,875 through 960,987
turn off 328,286 through 869,461
turn off 472,569 through 980,848
toggle 673,573 through 702,884
turn off 398,284 through 738,332
turn on 158,50 through 284,411
turn off 390,284 through 585,663
turn on 156,579 through 646,581
turn on 875,493 through 989,980
toggle 486,391 through 924,539
turn on 236,722 through 272,964
toggle 228,282 through 470,581
toggle 584,389 through 750,761
turn off 899,516 through 900,925
turn on 105,229 through 822,846
turn off 253,77 through 371,877
turn on 826,987 through 906,992
turn off 13,152 through 615,931
turn on 835,320 through 942,399
turn on 463,504 through 536,720
toggle 746,942 through 786,998
turn off 867,333 through 965,403
turn on 591,477 through 743,692
turn off 403,437 through 508,908
turn on 26,723 through 368,814
turn on 409,485 through 799,809
turn on 115,630 through 704,705
turn off 228,183 through 317,220
toggle 300,649 through 382,842
turn off 495,365 through 745,562
turn on 698,346 through 744,873
turn on 822,932 through 951,934
toggle 805,30 through 925,421
toggle 441,152 through 653,274
toggle 160,81 through 257,587
turn off 350,781 through 532,917
toggle 40,583 through 348,636
turn on 280,306 through 483,395
toggle 392,936 through 880,955
toggle 496,591 through 851,934
turn off 780,887 through 946,994
turn off 205,735 through 281,863
toggle 100,876 through 937,915
turn on 392,393 through 702,878
turn on 956,374 through 976,636
toggle 478,262 through 894,775
turn off 279,65 through 451,677
turn on 397,541 through 809,847
turn on 444,291 through 451,586
toggle 721,408 through 861,598
turn on 275,365 through 609,382
turn on 736,24 through 839,72
turn off 86,492 through 582,712
turn on 676,676 through 709,703
turn off 105,710 through 374,817
toggle 328,748 through 845,757
toggle 335,79 through 394,326
toggle 193,157 through 633,885
turn on 227,48 through 769,743
toggle 148,333 through 614,568
toggle 22,30 through 436,263
toggle 547,447 through 688,969
toggle 576,621 through 987,740
turn on 711,334 through 799,515
turn on 541,448 through 654,951
toggle 792,199 through 798,990
turn on 89,956 through 609,960
toggle 724,433 through 929,630
toggle 144,895 through 201,916
toggle 226,730 through 632,871
turn off 760,819 through 828,974
toggle 887,180 through 940,310
toggle 222,327 through 805,590
turn off 630,824 through 885,963
turn on 940,740 through 954,946
turn on 193,373 through 779,515
toggle 304,955 through 469,975
turn off 405,480 through 546,960
turn on 662,123 through 690,669
turn off 615,238 through 750,714
turn on 423,220 through 930,353
turn on 329,769 through 358,970
toggle 590,151 through 704,722
turn off 884,539 through 894,671
toggle 449,241 through 984,549
toggle 449,260 through 496,464
turn off 306,448 through 602,924
turn on 286,805 through 555,901
toggle 722,177 through 922,298
toggle 491,554 through 723,753
turn on 80,849 through 174,996
turn off 296,561 through 530,856
toggle 653,10 through 972,284
toggle 529,236 through 672,614
toggle 791,598 through 989,695
turn on 19,45 through 575,757
toggle 111,55 through 880,871
turn off 197,897 through 943,982
turn on 912,336 through 977,605
toggle 101,221 through 537,450
turn on 101,104 through 969,447
toggle 71,527 through 587,717
toggle 336,445 through 593,889
toggle 214,179 through 575,699
turn on 86,313 through 96,674
toggle 566,427 through 906,888
turn off 641,597 through 850,845
turn on 606,524 through 883,704
turn on 835,775 through 867,887
toggle 547,301 through 897,515
toggle 289,930 through 413,979
turn on 361,122 through 457,226
turn on 162,187 through 374,746
turn on 348,461 through 454,675
turn off 966,532 through 985,537
turn on 172,354 through 630,606
turn off 501,880 through 680,993
turn off 8,70 through 566,592
toggle 433,73 through 690,651
toggle 840,798 through 902,971
toggle 822,204 through 893,760
turn off 453,496 through 649,795
turn off 969,549 through 990,942
turn off 789,28 through 930,267
toggle 880,98 through 932,434
toggle 568,674 through 669,753
turn on 686,228 through 903,271
turn on 263,995 through 478,999
toggle 534,675 through 687,955
turn off 342,434 through 592,986
toggle 404,768 through 677,867
toggle 126,723 through 978,987
toggle 749,675 through 978,959
turn off 445,330 through 446,885
turn off 463,205 through 924,815
turn off 417,430 through 915,472
turn on 544,990 through 912,999
turn off 201,255 through 834,789
turn off 261,142 through 537,862
turn off 562,934 through 832,984
turn off 459,978 through 691,980
turn off 73,911 through 971,972
turn on 560,448 through 723,810
turn on 204,630 through 217,854
turn off 91,259 through 611,607
turn on 877,32 through 978,815
turn off 950,438 through 974,746
toggle 426,30 through 609,917
toggle 696,37 through 859,201
toggle 242,417 through 682,572
turn off 388,401 through 979,528
turn off 79,345 through 848,685
turn off 98,91 through 800,434
toggle 650,700 through 972,843
turn off 530,450 through 538,926
turn on 428,559 through 962,909
turn on 78,138 through 92,940
toggle 194,117 through 867,157
toggle 785,355 through 860,617
turn off 379,441 through 935,708
turn off 605,133 through 644,911
toggle 10,963 through 484,975
turn off 359,988 through 525,991
turn off 509,138 through 787,411
toggle 556,467 through 562,773
turn on 119,486 through 246,900
turn on 445,561 through 794,673
turn off 598,681 through 978,921
turn off 974,230 through 995,641
turn off 760,75 through 800,275
toggle 441,215 through 528,680
turn off 701,636 through 928,877
turn on 165,753 through 202,780
toggle 501,412 through 998,516
toggle 161,105 through 657,395
turn on 113,340 through 472,972
toggle 384,994 through 663,999
turn on 969,994 through 983,997
turn on 519,600 through 750,615
turn off 363,899 through 948,935
turn on 271,845 through 454,882
turn off 376,528 through 779,640
toggle 767,98 through 854,853
toggle 107,322 through 378,688
turn off 235,899 through 818,932
turn on 445,611 through 532,705
toggle 629,387 through 814,577
toggle 112,414 through 387,421
toggle 319,184 through 382,203
turn on 627,796 through 973,940
toggle 602,45 through 763,151
turn off 441,375 through 974,545
toggle 871,952 through 989,998
turn on 717,272 through 850,817
toggle 475,711 through 921,882
toggle 66,191 through 757,481
turn off 50,197 through 733,656
toggle 83,575 through 915,728
turn on 777,812 through 837,912
turn on 20,984 through 571,994
turn off 446,432 through 458,648
turn on 715,871 through 722,890
toggle 424,675 through 740,862
toggle 580,592 through 671,900
toggle 296,687 through 906,775"""
}
| 0 |
Kotlin
| 0 | 3 |
26ef6b194f3e22783cbbaf1489fc125d9aff9566
| 13,023 |
kotlinadventofcode
|
MIT License
|
src/main/kotlin/me/grison/aoc/y2016/Day04.kt
|
agrison
| 315,292,447 | false |
{"Kotlin": 267552}
|
package me.grison.aoc.y2016
import me.grison.aoc.*
class Day04 : Day(4, 2016) {
override fun title() = "Security Through Obscurity"
private val rooms = inputList.map {
Triple(
it.substringBeforeLast("-").replace("-", ""),
it.allInts(includeNegative = false).first(),
it.after("[").before("]")
)
}
override fun partOne() = findRooms().first
override fun partTwo() = findRooms().second?.first
private fun findRooms(): Pair<Int, Pair<Int, String>?> {
var total = 0
var wanted: Pair<Int, String>? = null
for ((name, sector, checksum) in rooms) {
if (mostCommon(name) == checksum) {
total += sector
val decrypted = name.map { letter -> (((letter.toInt() - 97 + sector) % 26) + 97).toChar() }.join()
if (decrypted.startsWith("northpole")) {
wanted = p(sector, decrypted)
}
}
}
return p(total, wanted)
}
private fun mostCommon(name: String): String {
return name.toSet().map { letter -> p(0 - name.count { it == letter }, letter) }
.sortedWith(compareBy({ it.first }, { it.second }))
.slice(0..4)
.map { it.second }.join()
}
}
| 0 |
Kotlin
| 3 | 18 |
ea6899817458f7ee76d4ba24d36d33f8b58ce9e8
| 1,307 |
advent-of-code
|
Creative Commons Zero v1.0 Universal
|
advent/src/test/kotlin/org/elwaxoro/advent/y2021/Dec04.kt
|
elwaxoro
| 328,044,882 | false |
{"Kotlin": 376774}
|
package org.elwaxoro.advent.y2021
import org.elwaxoro.advent.PuzzleDayTester
import org.elwaxoro.advent.rowColSwap
/**
* Giant Squid
* (in which I abuse for loops)
*/
class Dec04 : PuzzleDayTester(4, 2021) {
override fun part1(): Any = loadBoards().let { (calls, boards) ->
calls.forEach { call ->
boards.forEach { board ->
if (board.callNumber(call)) {
return board.score()
}
}
}
}
override fun part2(): Any = loadBoards().let { (calls, boards) ->
val remainingBoards = boards.toMutableList()
val winningBoards = mutableListOf<Board>()
calls.forEach { call ->
val iter = remainingBoards.iterator()
while (iter.hasNext()) {
val board = iter.next()
if (board.callNumber(call)) {
iter.remove()
winningBoards.add(board)
}
}
}
winningBoards.last().score()
}
data class Board(
val rows: MutableList<MutableList<Pair<Int, Boolean>>>
) {
var lastCall: Int = -1
val cols: MutableList<MutableList<Pair<Int, Boolean>>> = rows.rowColSwap()
fun callNumber(call: Int): Boolean {
rows.forEachIndexed { rowIdx, row ->
row.forEachIndexed { colIdx, col ->
if (col.first == call) {
rows[rowIdx][colIdx] = Pair(call, true)
cols[colIdx][rowIdx] = Pair(call, true)
}
}
}
lastCall = call
return checkWin()
}
fun checkWin(): Boolean =
rows.any { row ->
row.all { it.second }
} || cols.any { col ->
col.all { it.second }
}
fun score(): Int =
lastCall * rows.flatMap { row ->
row.filterNot { it.second }
}.sumOf { it.first }
}
private fun loadBoards(): Pair<List<Int>, List<Board>> = load(delimiter = "\n\n").let { chunks ->
val calls = chunks[0].split(",").map { it.toInt() }
val boards = chunks.drop(1).map { raw ->
Board(raw.split("\n").map { row -> row.trim().split(Regex("\\W+")).map { Pair(it.toInt(), false) }.toMutableList() }.toMutableList())
}
Pair(calls, boards)
}
}
| 0 |
Kotlin
| 4 | 0 |
1718f2d675f637b97c54631cb869165167bc713c
| 2,433 |
advent-of-code
|
MIT License
|
src/main/kotlin/aoc2021/Day11.kt
|
j4velin
| 572,870,735 | false |
{"Kotlin": 285016, "Python": 1446}
|
package aoc2021
import readInput
import java.util.*
import kotlin.math.max
import kotlin.math.min
typealias Octopus = Pair<Int, Int>
private const val ENERGY_THRESHOLD = 9
private class OctopusArray(input: List<String>) {
private val maxX: Int
private val maxY: Int
/**
* The number of octopuses in this array
*/
val elementCount: Int
// internally represented as a 2D Byte array
private val data = input.map { str -> str.map { it.digitToInt().toByte() }.toByteArray() }.toTypedArray()
init {
maxX = data.size - 1
maxY = (data.firstOrNull()?.size ?: 0) - 1
elementCount = data.size * (maxY + 1)
}
/**
* Performs a 'step': Increases all levels & flashes all octopuses, which have or get the required energy level
*
* @return the number of octopuses, which have flashed during this step
*/
fun step(): Int {
val readyToFlash = increaseAllLevels()
val flashed = flashAll(readyToFlash)
// reset the energy level of the flashed ones
flashed.forEach { data[it.first][it.second] = 0 }
return flashed.size
}
/**
* Increases all octopuses energy levels
* @return the positions of all octopuses, which now have an energy level > [ENERGY_THRESHOLD]
*/
private fun increaseAllLevels() = increaseArea(Pair(0, 0), Pair(maxX, maxY))
/**
* Increases the energy level of the center octopus and all the octopuses in its surrounding neighbourhood
*
* @param center the position of the octopus in the center
* @return a collection of all octopuses which became ready to flash during this increase operation
*/
private fun increaseNeighbours(center: Octopus) =
increaseArea(Pair(center.first - 1, center.second - 1), Pair(center.first + 1, center.second + 1))
/**
* Increases the energy level of the octopuses covered by the given area
*
* @param topLeft the top left position of the area
* @param bottomRight the bottom right position of the area
* @return a collection of all octopuses which became ready to flash during this increase operation
*/
private fun increaseArea(topLeft: Pair<Int, Int>, bottomRight: Pair<Int, Int>): Collection<Octopus> {
val readyToFlash = mutableSetOf<Octopus>()
for (i in max(0, topLeft.first)..min(maxX, bottomRight.first)) {
for (j in max(0, topLeft.second)..min(maxY, bottomRight.second)) {
if (++data[i][j] > ENERGY_THRESHOLD) {
readyToFlash.add(Pair(i, j))
}
}
}
return readyToFlash
}
/**
* Flashes all ready octopuses, which are ready to flash or become ready to flash in the process of flashing its
* neighbours
*
* @param init an initial list of positions of octopuses to flash
* @return a collection of all the flashed octopuses
*/
private fun flashAll(init: Collection<Octopus>): Collection<Octopus> {
val flashed = mutableSetOf<Octopus>()
val readyToFlash: Queue<Octopus> = LinkedList()
readyToFlash.addAll(init)
while (readyToFlash.isNotEmpty()) {
val flashing = readyToFlash.poll()
// consider neighbours only, if we haven't already flashed that octopus in this step
if (flashed.add(flashing)) {
readyToFlash.addAll(increaseNeighbours(flashing))
}
}
return flashed
}
}
private fun part1(input: List<String>): Int {
val array = OctopusArray(input)
var flashCount = 0
repeat(100) { flashCount += array.step() }
return flashCount
}
private fun part2(input: List<String>): Int {
val array = OctopusArray(input)
var step = 1
while (array.step() < array.elementCount) {
step++
}
return step
}
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day11_test")
check(part1(testInput) == 1656)
check(part2(testInput) == 195)
val input = readInput("Day11")
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
f67b4d11ef6a02cba5b206aba340df1e9631b42b
| 4,171 |
adventOfCode
|
Apache License 2.0
|
src/main/kotlin/com/ginsberg/advent2018/Day20.kt
|
tginsberg
| 155,878,142 | false | null |
/*
* Copyright (c) 2018 by <NAME>
*/
/**
* Advent of Code 2018, Day 20 - A Regular Map
*
* Problem Description: http://adventofcode.com/2018/day/20
* Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2018/day20/
*/
package com.ginsberg.advent2018
import java.util.ArrayDeque
class Day20(rawInput: String) {
private val grid: Map<Point, Int> = parseGrid(rawInput)
fun solvePart1(): Int =
grid.maxBy { it.value }!!.value
fun solvePart2(): Int =
grid.count { it.value >= 1000 }
private fun parseGrid(input: String): Map<Point, Int> {
val grid = mutableMapOf(startingPoint to 0)
val stack = ArrayDeque<Point>()
var current = startingPoint
input.forEach {
when (it) {
'(' -> stack.push(current)
')' -> current = stack.pop()
'|' -> current = stack.peek()
in movementRules -> {
// If we are moving to a spot we haven't seen before, we can
// record this as a new distance.
val nextDistance = grid.getValue(current) + 1
current = movementRules.getValue(it).invoke(current)
grid[current] = minOf(grid.getOrDefault(current, Int.MAX_VALUE), nextDistance)
}
}
}
return grid
}
companion object {
private val startingPoint = Point(0, 0)
private val movementRules = mapOf(
'N' to Point::up,
'S' to Point::down,
'E' to Point::right,
'W' to Point::left
)
}
}
| 0 |
Kotlin
| 1 | 18 |
f33ff59cff3d5895ee8c4de8b9e2f470647af714
| 1,652 |
advent-2018-kotlin
|
MIT License
|
plugins/evaluation-plugin/core/src/com/intellij/cce/metric/LatencyMetrics.kt
|
JetBrains
| 2,489,216 | false | null |
// Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.cce.metric
import com.intellij.cce.core.Lookup
import com.intellij.cce.core.Session
import com.intellij.cce.metric.util.Bootstrap
abstract class LatencyMetric(override val name: String) : Metric {
private val sample = mutableListOf<Double>()
override val value: Double
get() = compute(sample)
override fun confidenceInterval(): Pair<Double, Double>? = Bootstrap.computeInterval(sample) { compute(it) }
override fun evaluate(sessions: List<Session>): Double {
val fileSample = mutableListOf<Double>()
sessions
.flatMap { session -> session.lookups }
.filter(::shouldInclude)
.forEach {
this.sample.add(it.latency.toDouble())
fileSample.add(it.latency.toDouble())
}
return compute(fileSample)
}
abstract fun compute(sample: List<Double>): Double
open fun shouldInclude(lookup: Lookup) = true
}
class MaxLatencyMetric : LatencyMetric("Max Latency") {
override val description: String = "Maximum invocation latency"
override val valueType = MetricValueType.INT
override val showByDefault: Boolean = false
override fun compute(sample: List<Double>): Double = sample.maxOrNull() ?: Double.NaN
}
class TotalLatencyMetric : LatencyMetric("Total Latency") {
override val description: String = "Sum of invocations latencies"
override val valueType = MetricValueType.DOUBLE
override val showByDefault = false
override fun compute(sample: List<Double>): Double = sample.sum()
}
class MeanLatencyMetric(private val filterZeroes: Boolean = false) : LatencyMetric("Mean Latency") {
override val valueType = MetricValueType.DOUBLE
override val description: String = "Average latency by all invocations"
override fun compute(sample: List<Double>): Double = sample.average()
override fun shouldInclude(lookup: Lookup) = !filterZeroes || lookup.latency > 0
}
class SuccessMeanLatencyMetric(private val filterZeroes: Boolean = false) : LatencyMetric("Mean Success Latency") {
override val valueType = MetricValueType.DOUBLE
override val description: String = "Average latency by invocations with selected proposal"
override val showByDefault = false
override fun compute(sample: List<Double>): Double = sample.average()
override fun shouldInclude(lookup: Lookup) = lookup.selectedPosition >= 0 && (!filterZeroes || lookup.latency > 0)
}
class PercentileLatencyMetric(private val percentile: Int) : LatencyMetric("Latency Percentile $percentile") {
override val valueType = MetricValueType.INT
override val description: String = "Latency $percentile percentile by all invocations"
override val showByDefault = false
override fun compute(sample: List<Double>): Double = computePercentile(sample, percentile)
}
class SuccessPercentileLatencyMetric(private val percentile: Int) : LatencyMetric("Latency Success Percentile $percentile") {
override val valueType = MetricValueType.INT
override val description: String = "Latency $percentile percentile by invocations with selected proposal"
override val showByDefault = false
override fun compute(sample: List<Double>): Double = computePercentile(sample, percentile)
override fun shouldInclude(lookup: Lookup): Boolean = lookup.selectedPosition >= 0
}
private fun computePercentile(sample: List<Double>, percentile: Int): Double {
if (sample.isEmpty()) return Double.NaN
require(percentile in 0..100) { "Percentile must be between 0 and 100" }
val index = (sample.size * percentile / 100).coerceAtMost(sample.size - 1)
return sample.sorted()[index]
}
| 251 | null | 5,079 | 16,158 |
831d1a4524048aebf64173c1f0b26e04b61c6880
| 3,669 |
intellij-community
|
Apache License 2.0
|
src/main/kotlin/Day11.kt
|
chjaeggi
| 728,738,815 | false |
{"Kotlin": 87254}
|
import utils.*
import kotlin.math.abs
data class GalaxyMap(
val map: Map<Point2D, List<Point2D>>,
val galaxyFreeRows: List<Int>,
val galaxyFreeCols: List<Int>,
)
class Day11 {
fun solve() {
val galaxies = createGalaxyMap()
println(solve(galaxies))
println(solve(galaxies, 1000000))
}
private fun createGalaxyMap(): GalaxyMap {
// TODO replace forEachIndexed calls with mapIndexed/flatMapIndexed Coni heeeelp and save
// their results directly into the according variables (make them immutable):
// - galaxies
// - emptyRows
// - emptyCols
val fileName = "./inputs/input11.txt"
val originalGalaxies =
Array(numberOfLinesPerFile(fileName)) { CharArray(numberOfCharsPerLine(fileName)) }
val galaxies = mutableMapOf<Point2D, List<Point2D>>()
val emptyRows = mutableListOf<Int>()
val emptyCols = mutableListOf<Int>()
execFileByLineIndexed(fileName) { line, index ->
line.forEachIndexed { i, v ->
originalGalaxies[index][i] = v
}
if (line.all { it == '.' }) {
emptyRows.add(index)
}
}
originalGalaxies.transpose().forEachIndexed { index, chars ->
if (chars.all { it == '.' }) {
emptyCols.add(index)
}
}
val galaxyCoords = mutableListOf<Point2D>()
originalGalaxies.forEachIndexed { y, chars ->
chars.forEachIndexed { x, c ->
if (c == '#') {
galaxyCoords.add(Point2D(y.toLong(), x.toLong()))
}
}
}
galaxyCoords.forEachIndexed { index, point ->
if (index < galaxyCoords.lastIndex) {
galaxies[point] = galaxyCoords.subList(index + 1, galaxyCoords.lastIndex + 1)
}
}
return GalaxyMap(galaxies, emptyRows, emptyCols)
}
private fun solve(galaxies: GalaxyMap, voidMultiplier: Long = 2): Long {
val ySkip = galaxies.galaxyFreeCols
val xSkip = galaxies.galaxyFreeRows
return galaxies.map.flatMap { galaxy ->
val source = galaxy.key
galaxy.value.map { dest ->
val maxY = maxOf(dest.y, source.y)
val minY = minOf(dest.y, source.y)
val maxX = maxOf(dest.x, source.x)
val minX = minOf(dest.x, source.x)
val sumY = ySkip.count { it in minY..<maxY } * (voidMultiplier - 1)
val sumX = xSkip.count { it in minX..<maxX } * (voidMultiplier - 1)
abs(dest.y - source.y) + sumY + abs(dest.x - source.x) + sumX
}
}.sum()
}
}
| 0 |
Kotlin
| 1 | 1 |
a6522b7b8dc55bfc03d8105086facde1e338086a
| 2,757 |
aoc2023
|
Apache License 2.0
|
src/main/kotlin/com/psmay/exp/advent/y2021/day17/Day17.kt
|
psmay
| 434,705,473 | false |
{"Kotlin": 242220}
|
@file:Suppress("MemberVisibilityCanBePrivate", "unused")
package com.psmay.exp.advent.y2021.day17
import com.psmay.exp.advent.y2021.util.repeatedForever
import kotlin.math.abs
import kotlin.math.sign
private typealias IntPair = Pair<Int, Int>
private inline val IntPair.x get() = this.first
private inline val IntPair.y get() = this.second
data class TargetArea(val xRange: IntRange, val yRange: IntRange) {
val bottom get() = yRange.first
val top get() = yRange.last
val left get() = xRange.first
val right get() = xRange.last
fun contains(position: IntPair): Boolean {
val (x, y) = position
return xRange.contains(x) && yRange.contains(y)
}
}
private val targetAreaRegex = run {
val number = """(?:-?[0-9]+)"""
val thru = """(?:\.\.)"""
val targetAreaPattern = """^target area: x=($number)$thru($number), y=($number)$thru($number)$"""
targetAreaPattern.toRegex()
}
fun parseTargetAreaOrNull(value: String): TargetArea? {
val (x0, x1, y0, y1) = targetAreaRegex.matchEntire(value)?.destructured ?: return null
return TargetArea(x0.toInt()..x1.toInt(), y0.toInt()..y1.toInt())
}
fun parseTargetArea(value: String): TargetArea =
parseTargetAreaOrNull(value) ?: throw IllegalArgumentException("Input does not match expected target area format.")
private fun Int.compareTo(range: IntRange): Int =
if (this < range.first) -1 else if (this > range.last) 1 else 0
fun IntPair.compareTo(targetArea: TargetArea): IntPair {
val (x, y) = this
return x.compareTo(targetArea.xRange) to y.compareTo(targetArea.yRange)
}
data class SimulatedInstant(val position: IntPair, val velocity: IntPair) {
val x get() = position.x
val y get() = position.y
val dx get() = velocity.x
val dy get() = velocity.y
val next: SimulatedInstant
get() {
val ddx = -dx.sign // Drag
val ddy = -1 // Gravity
return SimulatedInstant(x + dx to y + dy, dx + ddx to dy + ddy)
}
val isRising get() = dy > 0
}
fun simulatedInstants(startVelocity: IntPair, startAt: IntPair = (0 to 0)): Sequence<SimulatedInstant> {
return repeatedForever()
.runningFold(SimulatedInstant(startAt, startVelocity)) { acc, _ -> acc.next }
}
fun scanForHighestHit(area: TargetArea): Pair<IntPair, IntPair> {
val simulatedHits = scanForAllHits(area)
val simulatedArcHighs = simulatedHits.map { (startVelocity, instants) ->
val topInstant = instants.filter { !it.isRising }.firstOrNull() ?: instants.last()
(startVelocity to topInstant.position)
}
return simulatedArcHighs.maxByOrNull { (_, top) -> top.y }
?: throw Exception("We blame the input")
}
fun scanForAllHits(area: TargetArea): Sequence<Pair<IntPair, Sequence<SimulatedInstant>>> {
val simulations = velocitiesToScan(area).map { startVelocity ->
// Take number is borrowed from other people's solutions
(startVelocity to simulatedInstants(startVelocity).take(2 * abs(area.bottom) + 2))
}
return simulations.filter { (_, instants) -> instants.any { area.contains(it.position) } }
}
private fun velocitiesToScan(area: TargetArea): Sequence<IntPair> {
val yTestRange = abs(area.bottom) downTo -abs(area.bottom)
val xTestRange = 1..area.right + 1
return yTestRange.asSequence().flatMap { y -> xTestRange.asSequence().map { x -> x to y } }
}
| 0 |
Kotlin
| 0 | 0 |
c7ca54612ec117d42ba6cf733c4c8fe60689d3a8
| 3,400 |
advent-2021-kotlin
|
Creative Commons Zero v1.0 Universal
|
advent-of-code-2021/src/main/kotlin/eu/janvdb/aoc2021/day05/Day05.kt
|
janvdbergh
| 318,992,922 | false |
{"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335}
|
package eu.janvdb.aoc2021.day05
import eu.janvdb.aocutil.kotlin.point2d.Line2D
import eu.janvdb.aocutil.kotlin.point2d.Point2D
import eu.janvdb.aocutil.kotlin.readLines
const val FILENAME = "input05.txt"
fun main() {
val lines = readLines(2021, FILENAME)
.map { parseLine(it) }
val heatMap = HashMap<Point2D, Int>()
lines.asSequence()
.flatMap { it.getPointsHorizontallyVerticallyOrDiagonally() }
.forEach { addToHeatMap(heatMap, it) }
val result = heatMap.count { it.value >= 2 }
println(result)
}
fun addToHeatMap(heatMap: MutableMap<Point2D, Int>, point: Point2D) {
val current = heatMap.getOrDefault(point, 0)
heatMap[point] = current + 1
}
private fun parseLine(line: String): Line2D {
val parts = line.split(Regex(" -> "))
return Line2D(parsePoint(parts[0]), parsePoint(parts[1]))
}
private fun parsePoint(s: String): Point2D {
val parts = s.split(",")
return Point2D(parts[0].toInt(), parts[1].toInt())
}
| 0 |
Java
| 0 | 0 |
78ce266dbc41d1821342edca484768167f261752
| 938 |
advent-of-code
|
Apache License 2.0
|
src/chapter07/Intro_运算符重载.kt
|
xu33liang33
| 252,216,839 | false | null |
package chapter07
import java.lang.IndexOutOfBoundsException
import java.math.BigDecimal
import java.time.LocalDate
import kotlin.ranges.ClosedRange as ClosedRange1
/**
*
*运算符重载
* BigDecimal运算
* 约定 operator
*
* a * b | times
* a / b | div
* a % b | mod
* a + b | plus
* a - b | minus
*
*/
fun main(args: Array<String>) {
BigDecimal.ZERO
var p1 = Point(10, 20)
val p2 = Point(30, 40)
println(p1 + p2)
println(p1.plus(p2))
p1 += p2
println(p1)
println(p2 * 5.toDouble())
var bd = BigDecimal.ZERO
println(++bd)
val a = Point(10, 20) == Point(10, 20)
println("equal: $a")
val p111 = Person722("Alice", "Smith")
val p222 = Person722("Bob", "Johnson")
println(p111 < p222)
println(p2[1])
println('a' in "abc")
}
data class Point(val x: Int, val y: Int) {
operator fun plus(other: Point): Point {
return Point(x + other.x, y + other.y)
}
fun and(other: Point): Point {
return Point(x + other.x, y + other.y)
}
/**
* Point(10,20) == Point(10,20)
*/
override fun equals(obj: Any?): Boolean {
if (obj === this) return true
if (obj !is Point) return false
return obj.x == x && obj.y == y
}
}
operator fun Point.times(scale: Double): Point {
return Point((x * scale).toInt(), (y * scale).toInt())
}
/**
*
* 重载一元运算符
*
* +a | unaryPlus
* -a | unaryMinus
* !a | not
* ++a,a++ | inc
* --a,a-- | dec
*
*/
operator fun Point.unaryMinus(): Point {
return Point(-x, -y)
}
operator fun BigDecimal.inc() = this + BigDecimal.ONE
/**
* 比较运算符
*
* equals
* == 运算符
*
*/
/**
*
* 排序运算符
* compareTo 接口
*
*/
class Person722(val firstName: String, val lastName: String) : Comparable<Person722> {
override fun compareTo(other: Person722): Int {
return compareValuesBy(this, other, Person722::lastName, Person722::firstName)
}
}
/**
* 集合与区别的约定
* a[b] 下标运算符 "get"和"set"
*
*
*/
operator fun Point.get(index: Int): Int {
return when (index) {
0 -> x
1 -> y
else ->
throw IndexOutOfBoundsException("Invalid coordinate $index")
}
}
/**
* "in"的约定
* contains
*
*
*/
data class Rectangle732(val upperLeft: Point, val lowerRight: Point)
operator fun Rectangle732.contains(p: Point): Boolean {
return p.x in upperLeft.x until lowerRight.x &&
p.y in upperLeft.y until lowerRight.y
}
/**
* rangeTo 约定
* ".."符号 1..10
*实现了Comparable 接口就不需要实现rangeTo了~因为标准库已经实现
*/
//operator fun<T:Comparable<T>> T.rangeTo(that:T) : kotlin.ranges.ClosedRange<T> {
// 1..10
//}
/**
* for循环中使用iterator的约定
*
*
*
*/
| 0 |
Kotlin
| 0 | 1 |
cdc74e445c8c487023fbc7917183d47e73ff4bc8
| 2,914 |
actioninkotlin
|
Apache License 2.0
|
kotlin/0647-palindromic-substrings.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}
|
/*
* Two pointer with outwards extension solution, time O(N^2) and space O(1)
*/
class Solution {
fun countSubstrings(s: String): Int {
var res = 0
for(i in s.indices) {
var l = i
var r = i
while(l >= 0 && r < s.length && s[l] == s[r]) {
res++
l--
r++
}
l = i
r = i+1
while(l >= 0 && r < s.length && s[l] == s[r]) {
res++
l--
r++
}
}
return res
}
}
/*
* Two pointer with outwards extension solution, but with helper function. time O(N^2) and space O(1)
*/
class Solution {
fun countSubstrings(s: String): Int {
var res = 0
fun extend(_l: Int, _r: Int) {
var l = _l
var r = _r
while(l >= 0 && r < s.length && s[l] == s[r]) {
res++
l--
r++
}
}
for(i in s.indices) {
extend(i,i)
extend(i,i+1)
}
return res
}
}
/*
* DP solution, time O(N^2) and space O(N^2)
*/
class Solution {
fun countSubstrings(s: String): Int {
var res = 0
val dp = Array(s.length){ BooleanArray(s.length) }
for(i in s.lastIndex downTo 0) {
for(j in i..s.lastIndex) {
dp[i][j] = s[i] == s[j] && (j-i+1 < 3 || dp[i+1][j-1])
if(dp[i][j]) res++
}
}
return res
}
}
| 337 |
JavaScript
| 2,004 | 4,367 |
0cf38f0d05cd76f9e96f08da22e063353af86224
| 1,548 |
leetcode
|
MIT License
|
src/Day08.kt
|
calindumitru
| 574,154,951 | false |
{"Kotlin": 20625}
|
fun main() {
val part1 = Implementation("Consider your map; how many trees are visible from outside the grid?",
21) { lines ->
val map = convertToMap(lines)
return@Implementation map.countVisible()
}
val part2 = Implementation("Consider your map; how many trees are visible from outside the grid?",
8) { lines ->
val map = convertToMap(lines)
return@Implementation map.calculateScenicScore()
}
OhHappyDay(8, part1, part2).checkResults()
}
fun convertToMap(lines: List<String>): Map {
val map = Map(lines.first().length , lines.size)
lines.forEachIndexed {lineIndex, line -> line.toCharArray()
.forEachIndexed { charIndex, c -> map.add(lineIndex, charIndex, c.digitToInt()) }}
return map
}
data class Map(private val width: Int, private val height: Int, private val matrix: Array<Array<Int?>?> = arrayOfNulls(height)) {
init {
for (i in 0 until height) {
matrix[i] = arrayOfNulls(width)
}
}
fun add(x: Int ,y:Int, tree: Int) {
matrix[x]!![y] = tree
}
fun isVisible(x: Int ,y:Int, tree: Int): Boolean {
if (x == 0 || y == 0 || x == width -1 || y == height -1) {
return true
}
var visibleRight = true
for (i in x+1 until width) {
if (matrix[i]!![y]!! >= tree) {
visibleRight = false
}
}
if (visibleRight) return true
var visibleLeft = true
for (i in 0 until x) {
if (matrix[i]!![y]!! >= tree) {
visibleLeft = false
break
}
}
if (visibleLeft) return true
var visibleUp = true
for (i in y+1 until height) {
if (matrix[x]!![i]!! >= tree) {
visibleUp = false
break
}
}
if (visibleUp) return true
var visibleDown = true
for (i in 0 until y) {
if (matrix[x]!![i]!! >= tree) {
visibleDown = false
break
}
}
if (visibleDown) return true
return false
}
fun countVisible(): Int {
var count = 0
for (i in 0 until height) {
for (j in 0 until width) {
if (isVisible(i, j, matrix[i]!![j]!!)) {
//println("is visible ${matrix[i]!![j]!!} [${i+1},${j+1}]")
count++
}
}
}
return count
}
fun calculateScore(x: Int ,y:Int, tree: Int): Int {
return calculateRight(x, y, tree) * calculateLeft(x, y, tree) * calculateUp(y, x, tree) * calculateDown(y, x, tree)
}
private fun calculateDown(y: Int, x: Int, tree: Int): Int {
var score = 0
for (i in y - 1 downTo 0) {
if (matrix[x]!![i]!! < tree) {
score++
} else {
score++
break
}
}
return score
}
private fun calculateUp(y: Int, x: Int, tree: Int): Int {
var score = 0
for (i in y + 1 until height) {
if (matrix[x]!![i]!! < tree) {
score++
} else {
score++
break
}
}
return score
}
private fun calculateLeft(x: Int, y: Int, tree: Int): Int {
var score = 0
for (i in x - 1 downTo 0) {
if (matrix[i]!![y]!! < tree) {
score++
} else {
score++
break
}
}
return score
}
private fun calculateRight(x: Int, y: Int, tree: Int): Int {
var score = 0
for (i in x + 1 until width) {
if (matrix[i]!![y]!! < tree) {
score++
}else {
score++
break
}
}
return score
}
fun calculateScenicScore(): Int {
val scores = mutableListOf<Int>()
for (i in 0 until height) {
for (j in 0 until width) {
//println("scenic score: ${matrix[i]!![j]!!} [${i+1},${j+1} ${calculateScore(i,j,matrix[i]!![j]!!)}")
scores.add(calculateScore(i,j,matrix[i]!![j]!!))
}
}
return scores.max()
}
fun printMatrix() {
matrix.forEach { println(it!!.joinToString { it.toString() }) }
}
}
| 0 |
Kotlin
| 0 | 0 |
d3cd7ff5badd1dca2fe4db293da33856832e7e83
| 4,458 |
advent-of-code-2022
|
Apache License 2.0
|
src/main/kotlin/dk/lessor/Day13.kt
|
aoc-team-1
| 317,571,356 | false |
{"Java": 70687, "Kotlin": 34171}
|
package dk.lessor
fun main() {
val lines = readFile("day_13.txt")
val timestamp = lines.first().toLong()
val busses = lines.last().split(",").toList()
println(simpleBusTable(timestamp, busses))
println(busContestSolver(busses))
}
fun simpleBusTable(goal: Long, busses: List<String>): Long {
val table = busses.filter { it != "x" }.associate { it.toLong() to it.toLong() }.toMutableMap()
while (true) {
for (bus in table) {
val last = bus.value
val next = last + bus.key
table[bus.key] = next
}
if (table.any { it.value >= goal }) break
}
val earliest = table
.filterValues { it >= goal }
.toList()
.sortedBy { (_, value) -> value }
.first()
return earliest.first * (earliest.second - goal)
}
fun busContestSolver(busses: List<String>): Long {
val ids = busses.mapIndexedNotNull { index, value -> if (value == "x") null else index to value.toLong() }
var current = 0L
var timeJump = 1L
for ((start, step) in ids) {
while ((current + start) % step != 0L) current += timeJump
timeJump *= step
}
return current
}
| 0 |
Java
| 0 | 0 |
48ea750b60a6a2a92f9048c04971b1dc340780d5
| 1,189 |
lessor-aoc-comp-2020
|
MIT License
|
src/day06/Day06.kt
|
veronicamengyan
| 573,063,888 | false |
{"Kotlin": 14976}
|
package day06
import readInput
fun main() {
fun findMarker(input: List<String>): Int {
input.get(0).windowed(4, 1).forEachIndexed{
idx, value ->
if (value.length == value.toCharArray().toSet().size) {
return idx + 4
}
}
return -10000
}
fun findMarker2(input: List<String>): Int {
input.get(0).windowed(14, 1).forEachIndexed{
idx, value ->
if (value.length == value.toCharArray().toSet().size) {
return idx + 14
}
}
return -10000
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("day06/Day06_test")
val testInput2 = readInput("day06/Day06_test2")
val testInput3 = readInput("day06/Day06_test3")
val testInput4 = readInput("day06/Day06_test4")
val testInput5 = readInput("day06/Day06_test5")
check(findMarker(testInput) == 7)
check(findMarker(testInput2) == 5)
check(findMarker(testInput3) == 6)
check(findMarker(testInput4) == 10)
check(findMarker(testInput5) == 11)
println(findMarker2(testInput))
check(findMarker2(testInput) == 19)
check(findMarker2(testInput2) == 23)
check(findMarker2(testInput3) == 23)
check(findMarker2(testInput4) == 29)
check(findMarker2(testInput5) == 26)
val input = readInput("day06/Day06")
println(findMarker(input))
println(findMarker2(input))
}
| 0 |
Kotlin
| 0 | 0 |
d443cfa49e9d8c9f76fdb6303ecf104498effb88
| 1,494 |
aoc-2022-in-kotlin
|
Apache License 2.0
|
core-kotlin-modules/core-kotlin-strings-4/src/test/kotlin/com/baeldung/sortalphabetically/SortStringAlphabeticallyUnitTest.kt
|
Baeldung
| 260,481,121 | false |
{"Kotlin": 1476024, "Java": 43013, "HTML": 4883}
|
package com.baeldung.sortalphabetically
import org.junit.Test
import kotlin.test.assertEquals
class SortStringAlphabeticallyUnitTest {
private fun sortStringWithCharArrayAndSorted(input : String) : String{
return input.toCharArray().sorted().joinToString("")
}
private fun sortStringWithCharArrayAnddistinct(input : String) : String {
return input.toCharArray().sorted().distinct().joinToString("")
}
private fun sortStringWithtoCharArrayAndCompareBy(input: String) : String {
val vowels = setOf('a', 'e', 'i', 'o', 'u')
return input.toCharArray().sortedWith(compareBy<Char> { it in vowels }
.thenBy { it }
).joinToString("")
}
@Test
fun `using toCharArray and then sorted`() {
val inputString = "laibkcedfgjh"
assertEquals("abcdefghijkl", sortStringWithCharArrayAndSorted(inputString))
}
@Test
fun `using sorted and distinct`() {
val inputString = "lakibkcekdghfgjhh"
assertEquals("abcdefghijkl", sortStringWithCharArrayAnddistinct(inputString))
}
@Test
fun `using compareBy`() {
val inputString = "laibkcedfgjh"
assertEquals("bcdfghjklaei", sortStringWithtoCharArrayAndCompareBy(inputString))
}
// If we use extension function
private fun String.sortStringWithCompareBy() : String {
val vowels = setOf('a', 'e', 'i', 'o', 'u')
return toCharArray().sortedWith(compareBy<Char> { it in vowels }
.thenBy { it }
).joinToString("")
}
private fun String.sortAsc() = toCharArray().sorted().joinToString("")
@Test
fun `simplify compareBy with extension`() {
val inputString = "laibkcedfgjh"
assertEquals("bcdfghjklaei", inputString.sortStringWithCompareBy())
}
@Test
fun `simplify toCharArray and sorted with extension`() {
assertEquals("abcde", "cdbae".sortAsc())
}
}
| 10 |
Kotlin
| 273 | 410 |
2b718f002ce5ea1cb09217937dc630ff31757693
| 1,953 |
kotlin-tutorials
|
MIT License
|
src/test/kotlin/com/psmay/exp/advent/y2021/tests/Day09Test.kt
|
psmay
| 434,705,473 | false |
{"Kotlin": 242220}
|
package com.psmay.exp.advent.y2021.tests
import com.psmay.exp.advent.y2021.Day09
import com.psmay.exp.advent.y2021.Day09.mapSurroundingBasin
import com.psmay.exp.advent.y2021.tests.helpers.asUseLinesSource
import com.psmay.exp.advent.y2021.tests.helpers.getTextLineSource
import com.psmay.exp.advent.y2021.util.Grid
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.DynamicTest.dynamicTest
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.TestFactory
internal class Day09Test {
private val exampleInput = sequenceOf(
listOf(2, 1, 9, 9, 9, 4, 3, 2, 1, 0),
listOf(3, 9, 8, 7, 8, 9, 4, 9, 2, 1),
listOf(9, 8, 5, 6, 7, 8, 9, 8, 9, 2),
listOf(8, 7, 6, 7, 8, 9, 6, 7, 8, 9),
listOf(9, 8, 9, 9, 9, 6, 5, 6, 7, 8),
)
private val exampleRawInput = sequenceOf(
"2199943210",
"3987894921",
"9856789892",
"8767896789",
"9899965678"
).asUseLinesSource()
private val puzzleRawInput = getTextLineSource("y2021/Day09Input")
private fun parseLine(line: String): List<Int> = line.toCharArray().map { it.toString().toInt() }
@TestFactory
fun `raw input cooks to correct cooked form`() = listOf(
exampleRawInput to exampleInput.toList()
).map { (input, expected) ->
dynamicTest("$input to $expected") {
val result = input.useLines { lines -> lines.map { parseLine(it) }.toList() }
Assertions.assertEquals(expected, result)
}
}
private fun part1(input: Sequence<List<Int>>): Int {
val lowPoints = Day09.getCellWindows(input)
.filter { it.isLowPoint() }
val riskLevels = lowPoints.map { it.height + 1 }
return riskLevels.sum()
}
private fun part2(input: Sequence<List<Int>>): Int {
val heightMap = Grid(input.toList())
val seen = mutableSetOf<Pair<Int, Int>>()
val basins = mutableSetOf<Set<Pair<Int, Int>>>()
for (position in heightMap.allPositions) {
if (!seen.contains(position)) {
val basin = heightMap.mapSurroundingBasin(position)
if (basin.isNotEmpty()) {
basins.add(basin)
seen.addAll(basin)
}
}
}
val largestBasinSizes = basins.map { it.size }.sortedByDescending { it }.take(3)
if (largestBasinSizes.size != 3) {
throw Exception("Number of basins found was ${largestBasinSizes.size}, not 3.")
}
return largestBasinSizes.reduce { a, b -> a * b }
}
@TestFactory
fun `part1 produces sample results as expected`() = listOf(
exampleRawInput to 15
).map { (input, expected) ->
dynamicTest("$input to $expected") {
val result = input.useLines { lines -> part1(lines.map { parseLine(it) }) }
Assertions.assertEquals(expected, result)
}
}
@TestFactory
fun `part2 produces sample results as expected`() = listOf(
exampleRawInput to 1134
).map { (input, expected) ->
dynamicTest("$input to $expected") {
val result = input.useLines { lines -> part2(lines.map { parseLine(it) }) }
Assertions.assertEquals(expected, result)
}
}
@Test
fun `part1 on puzzle input succeeds`() {
val result = puzzleRawInput.useLines { lines -> part1(lines.map { parseLine(it) }) }
println("Result: $result")
}
@Test
fun `part2 on puzzle input succeeds`() {
val result = puzzleRawInput.useLines { lines -> part2(lines.map { parseLine(it) }) }
println("Result: $result")
}
}
| 0 |
Kotlin
| 0 | 0 |
c7ca54612ec117d42ba6cf733c4c8fe60689d3a8
| 3,678 |
advent-2021-kotlin
|
Creative Commons Zero v1.0 Universal
|
src/strings/LongestSubString.kt
|
develNerd
| 456,702,818 | false |
{"Kotlin": 37635, "Java": 5892}
|
package strings
import java.util.regex.Matcher
fun main(){
val mom = " fqabcdeee ghfjkddddlopiugfds "
val regex = Regex("([a-z])\\1+")
val rGX = Regex("\\s+")
val m1 = rGX.findAll(mom)
println(m1.toMutableList().size)
val m = mom.split(regex)
println("3,4.5".split(",","."))
val lengths = m.map(String::length).toTypedArray()
for (i in lengths.indices){
when (i) {
0 -> {
lengths[i] = lengths[i] + 1
}
lengths.size - 1 -> {
lengths[i] = lengths[i] + 1
}
else -> {
lengths[i] = lengths[i] + 2
}
}
}
println(m)
println(lengths.maxOrNull())
println(lengthOfLongestSubstring(mom))
}
fun lengthOfLongestSubstring(s: String): Int {
val n = s.length
var ans = 0
val map: MutableMap<Char, Int> = HashMap() // current index of character
// try to extend the range [i, j]
var j = 0
var i = 0
while (j < n) {
if (map.containsKey(s[j])) {
i = Math.max(map[s[j]]!!, i)
}
ans = Math.max(ans, j - i + 1)
map[s[j]] = j + 1
j++
}
return ans
}
fun solution(N: Int): Int {
val zeroAndOnes = Integer.toBinaryString(N)
.replace(Regex("0+$"), "")
val zeros = zeroAndOnes.split(Regex("1+"))
val lengths = zeros.map(String::length)
.filter { it > 0 }
return lengths.maxOrNull()!!.or(0)
}
| 0 |
Kotlin
| 0 | 0 |
4e6cc8b4bee83361057c8e1bbeb427a43622b511
| 1,491 |
Blind75InKotlin
|
MIT License
|
src/Day01.kt
|
kaeaton
| 572,831,118 | false |
{"Kotlin": 7766}
|
fun main() {
fun part1(input: List<String>): Int {
var maxCalories = 0
var currentCalories = 0
input.forEach {
if(it.isNotEmpty()) {
currentCalories += it.toInt()
} else {
if(currentCalories > maxCalories) {
maxCalories = currentCalories
}
currentCalories = 0
}
}
return maxCalories
}
fun part2(input: List<String>): Int {
var maxCalories = ArrayList<Int>()
var currentCalories = 0
input.forEach {
if(it.isNotEmpty()) {
currentCalories += it.toInt()
} else {
maxCalories.add(currentCalories)
currentCalories = 0
}
}
maxCalories.sortDescending()
return maxCalories.slice(0..2).sum()
}
val input = readInput("input_1")
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
c2a92c68bd5822c72c1075f055fc2163762d6deb
| 987 |
AoC-2022
|
Apache License 2.0
|
src/main/kotlin/g2801_2900/s2876_count_visited_nodes_in_a_directed_graph/Solution.kt
|
javadev
| 190,711,550 | false |
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
|
package g2801_2900.s2876_count_visited_nodes_in_a_directed_graph
// #Hard #Dynamic_Programming #Graph #Memoization
// #2023_12_25_Time_922_ms_(100.00%)_Space_76.6_MB_(100.00%)
class Solution {
fun countVisitedNodes(edges: List<Int>): IntArray {
val n = edges.size
val visited = BooleanArray(n)
val ans = IntArray(n)
val level = IntArray(n)
for (i in 0 until n) {
if (!visited[i]) {
visit(edges, 0, i, ans, visited, level)
}
}
return ans
}
private fun visit(
edges: List<Int>,
count: Int,
curr: Int,
ans: IntArray,
visited: BooleanArray,
level: IntArray
): IntArray {
if (ans[curr] != 0) {
return intArrayOf(-1, ans[curr])
}
if (visited[curr]) {
return intArrayOf(level[curr], count - level[curr])
}
level[curr] = count
visited[curr] = true
val ret = visit(edges, count + 1, edges[curr], ans, visited, level)
if (ret[0] == -1 || count < ret[0]) {
ret[1]++
}
ans[curr] = ret[1]
return ret
}
}
| 0 |
Kotlin
| 14 | 24 |
fc95a0f4e1d629b71574909754ca216e7e1110d2
| 1,182 |
LeetCode-in-Kotlin
|
MIT License
|
day15/src/main/kotlin/com/nohex/aoc/day15/PathComputer.kt
|
mnohe
| 433,396,563 | false |
{"Kotlin": 105740}
|
package com.nohex.aoc.day15
import com.nohex.aoc.Matrix
import com.nohex.aoc.Point
import org.slf4j.LoggerFactory
import java.util.*
val neighbourLocations = setOf(
Point(0, -1), // North
Point(1, 0), // West
Point(-1, 0),// East
Point(0, 1) // South
)
/**
* The [risk] involved in arriving at the location specified by [to].
*/
class Path(val to: Point, val risk: Int) : Comparable<Path> {
// Less risk goes first.
override fun compareTo(other: Path): Int =
this.risk.compareTo(other.risk)
override fun toString() = "<$risk to ${to.x},${to.y}>"
}
class PathComputer(private val riskMatrix: Matrix) {
companion object {
@Suppress("JAVA_CLASS_ON_COMPANION")
@JvmStatic
private val logger = LoggerFactory.getLogger(javaClass.enclosingClass)
}
var lowestRisk: Int? = null
private set
private val startLocation = Point(0, 0)
private val endLocation = riskMatrix.end
init {
lowestRisk = calculateLowestRisk()
}
/**
* Calculates the lowest risk found for any paths that start in the top-left corner and end in the bottom-right corner.
*/
private fun calculateLowestRisk(): Int {
// A priority queue sorted by risk.
val pathsToExplore = PriorityQueue<Path>().apply { add(Path(startLocation, 0)) }
val visited = mutableListOf<Point>()
while (pathsToExplore.isNotEmpty()) {
pathsToExplore.poll()?.let { path ->
// If the end has been reached, return the total risk.
val location = path.to
logger.debug("Checking $location...")
if (location == endLocation) {
logger.debug("Found the end ${path.to} at risk ${path.risk}")
return path.risk
}
// If not yet visited, explore neighbours.
if (location !in visited) {
visited += location
logger.info("Exploring $location...")
neighbourLocations
.map { location.transform(it) }
.filter { it !in visited }
.forEach {
riskMatrix[it]?.let { neighbourRisk ->
logger.debug("Scheduling $it for ${path.risk + neighbourRisk}")
pathsToExplore.offer(Path(it, path.risk + neighbourRisk))
}
}
}
}
logger.info("${pathsToExplore.size} locations to check")
logger.debug("$pathsToExplore")
}
error("No minimum risk was found")
}
}
| 0 |
Kotlin
| 0 | 0 |
4d7363c00252b5668c7e3002bb5d75145af91c23
| 2,730 |
advent_of_code_2021
|
MIT License
|
year2019/day06/part1/src/main/kotlin/com/curtislb/adventofcode/year2019/day06/part1/Year2019Day06Part1.kt
|
curtislb
| 226,797,689 | false |
{"Kotlin": 2146738}
|
/*
--- Day 6: Universal Orbit Map ---
You've landed at the Universal Orbit Map facility on Mercury. Because navigation in space often
involves transferring between orbits, the orbit maps here are useful for finding efficient routes
between, for example, you and Santa. You download a map of the local orbits (your puzzle input).
Except for the universal Center of Mass (COM), every object in space is in orbit around exactly one
other object. An orbit looks roughly like this:
\
\
|
|
AAA--> o o <--BBB
|
|
/
/
In this diagram, the object BBB is in orbit around AAA. The path that BBB takes around AAA (drawn
with lines) is only partly shown. In the map data, this orbital relationship is written AAA)BBB,
which means "BBB is in orbit around AAA".
Before you use your map data to plot a course, you need to make sure it wasn't corrupted during the
download. To verify maps, the Universal Orbit Map facility uses orbit count checksums - the total
number of direct orbits (like the one shown above) and indirect orbits.
Whenever A orbits B and B orbits C, then A indirectly orbits C. This chain can be any number of
objects long: if A orbits B, B orbits C, and C orbits D, then A indirectly orbits D.
For example, suppose you have the following map:
COM)B
B)C
C)D
D)E
E)F
B)G
G)H
D)I
E)J
J)K
K)L
Visually, the above map of orbits looks like this:
G - H J - K - L
/ /
COM - B - C - D - E - F
\
I
In this visual representation, when two objects are connected by a line, the one on the right
directly orbits the one on the left.
Here, we can count the total number of orbits as follows:
- D directly orbits C and indirectly orbits B and COM, a total of 3 orbits.
- L directly orbits K and indirectly orbits J, E, D, C, B, and COM, a total of 7 orbits.
- COM orbits nothing.
The total number of direct and indirect orbits in this example is 42.
What is the total number of direct and indirect orbits in your map data?
*/
package com.curtislb.adventofcode.year2019.day06.part1
import com.curtislb.adventofcode.year2019.day06.orbits.Universe
import java.nio.file.Path
import java.nio.file.Paths
/**
* Returns the solution to the puzzle for 2019, day 6, part 1.
*
* @param inputPath The path to the input file for this puzzle.
* @param center The name of the node representing the universal center of mass.
*/
fun solve(inputPath: Path = Paths.get("..", "input", "input.txt"), center: String = "COM"): Int {
val universe = Universe(inputPath.toFile())
return universe.countOrbits(center)
}
fun main() {
println(solve())
}
| 0 |
Kotlin
| 1 | 1 |
6b64c9eb181fab97bc518ac78e14cd586d64499e
| 2,776 |
AdventOfCode
|
MIT License
|
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2023/2023-18.kt
|
ferinagy
| 432,170,488 | false |
{"Kotlin": 787586}
|
@file:OptIn(ExperimentalStdlibApi::class)
package com.github.ferinagy.adventOfCode.aoc2023
import com.github.ferinagy.adventOfCode.Coord2D
import com.github.ferinagy.adventOfCode.println
import com.github.ferinagy.adventOfCode.readInputLines
fun main() {
val input = readInputLines(2023, "18-input")
val test1 = readInputLines(2023, "18-test1")
println("Part1:")
part1(test1).println()
part1(input).println()
println()
println("Part2:")
part2(test1).println()
part2(input).println()
}
private fun part1(input: List<String>): Long {
val parsed = input.map {
val (dir, steps) = regex.matchEntire(it)!!.destructured
steps.toInt() to dir
}
val points = mutableListOf(Coord2D(0, 0))
parsed.forEach { (steps, d) ->
points += dirs[d]!! * steps + points.last()
}
return calculateArea(points)
}
@OptIn(ExperimentalStdlibApi::class)
private fun part2(input: List<String>): Long {
val parsed = input.map {
val hex = regex.matchEntire(it)!!.groupValues[3]
hex.take(5).hexToInt() to hex[5]
}
val points = mutableListOf(Coord2D(0, 0))
parsed.forEach { (steps, d) ->
points += hexDirs[d]!! * steps + points.last()
}
return calculateArea(points)
}
private fun calculateArea(points: List<Coord2D>): Long {
val shoelace = points.windowed(2).sumOf { (p1, p2) ->
p1.x.toLong() * p2.y.toLong() - p2.x.toLong() * p1.y.toLong()
}
val len = points.windowed(2).sumOf { (p1, p2) -> p1.distanceTo(p2).toLong() }
return (shoelace + len) / 2 + 1
}
private val hexDirs = mapOf(
'0' to Coord2D(1, 0),
'1' to Coord2D(0, 1),
'2' to Coord2D(-1, 0),
'3' to Coord2D(0, -1),
)
private val dirs = mapOf(
"U" to Coord2D(0, -1),
"D" to Coord2D(0, 1),
"L" to Coord2D(-1, 0),
"R" to Coord2D(1, 0),
)
private val regex = """([UDLR]) (\d+) \(#([a-f0-9]{6})\)""".toRegex()
| 0 |
Kotlin
| 0 | 1 |
f4890c25841c78784b308db0c814d88cf2de384b
| 1,931 |
advent-of-code
|
MIT License
|
src/main/kotlin/aoc19/Day6.kt
|
tahlers
| 225,198,917 | false | null |
package aoc19
import io.vavr.collection.HashMap
import io.vavr.collection.Map
import io.vavr.kotlin.tuple
object Day6 {
fun parseOrbits(orbits: String): Map<String, String> {
val lines = orbits.split("\n")
val entries = lines.map {
val (center, satellite) = it.split(')')
tuple(satellite, center)
}
return HashMap.ofEntries(entries)
}
private fun generateOrbits(
sat: String,
orbits: Map<String, String>,
orbitPaths: Map<String, List<String>>
): Map<String, List<String>> {
return if (sat in orbitPaths.keySet()) {
orbitPaths
} else {
val center = orbits.getOrElse(sat, "")
if (orbits.containsKey(center)) {
val updatedPaths = generateOrbits(center, orbits, orbitPaths)
val centerPath = updatedPaths.getOrElse(center, emptyList())
updatedPaths.put(sat, listOf(sat) + centerPath)
} else {
orbitPaths.put(sat, listOf(sat, center))
}
}
}
fun countOrbits(orbits: Map<String, String>): Int {
val initMap: Map<String, List<String>> = HashMap.empty()
val orbitMap = orbits.keysIterator().fold(initMap) { map, sat ->
generateOrbits(sat, orbits, map)
}
return orbitMap.values().map { it.size - 1 }.toJavaList().sum()
}
fun numberOfTransitions(sat1: String, sat2: String, orbits: Map<String, String>): Int {
val initMap: Map<String, List<String>> = HashMap.empty()
val orbitMap = orbits.keysIterator().fold(initMap) { map, sat ->
generateOrbits(sat, orbits, map)
}
val sat1Orbits = orbitMap.getOrElse(sat1, listOf(sat1))
val sat2Orbits = orbitMap.getOrElse(sat2, listOf(sat2))
val sat1Transitions = sat1Orbits.takeWhile { it !in sat2Orbits }.drop(1)
val sat2Transitions = sat2Orbits.takeWhile { it !in sat1Orbits }.drop(1)
return sat1Transitions.size + sat2Transitions.size
}
}
| 0 |
Kotlin
| 0 | 0 |
dae62345fca42dd9d62faadf78784d230b080c6f
| 2,059 |
advent-of-code-19
|
MIT License
|
algorithms/src/main/kotlin/com/kotlinground/algorithms/luhn/Luhn.kt
|
BrianLusina
| 113,182,832 | false |
{"Kotlin": 483489, "Shell": 7283, "Python": 1725}
|
package com.kotlinground.algorithms.luhn
/**
* @author lusinabrian on 13/03/18.
*/
@Suppress("MagicNumber")
object Luhn {
fun isValid(cardNumber: String): Boolean {
val newCardNumber = cardNumber.replace(" ", "")
if (newCardNumber.length <= 1) {
return false
}
val reversed = newCardNumber.reversed()
val evenlyPositioned = reversed.filterIndexed { index, _ -> index % 2 == 0 }.sumBy { it - '0' }
val oddlyPositioned =
reversed.filterIndexed { index, _ -> index % 2 == 1 }.map { sumDigits((it - '0') * 2) }.sum()
return (evenlyPositioned + oddlyPositioned) % 10 == 0
}
/**
* Second variation of isValid
*/
fun isValid2(number: String): Boolean {
val code = number.replace(" ", "")
// if not number with 2 or more digits
if (!code.matches(Regex("^\\d{2,}$"))) {
return false
}
val sum = code.reversed().map { Character.getNumericValue(it) }
.mapIndexed { index, num ->
if (index % 2 == 0) {
doubleDigit(num)
} else {
num
}
}.sum()
return sum % 10 == 0
}
private fun doubleDigit(n: Int): Int {
val res = n * 2
return if (res > 9) {
res - 9
} else {
res
}
}
private fun sumDigits(n: Int) = n / 10 + n % 10
}
| 1 |
Kotlin
| 1 | 0 |
5e3e45b84176ea2d9eb36f4f625de89d8685e000
| 1,469 |
KotlinGround
|
MIT License
|
src/iii_conventions/MyDate.kt
|
gcx11
| 107,715,456 | false | null |
package iii_conventions
data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int) : Comparable<MyDate> {
override operator fun compareTo(other: MyDate): Int {
return if (year == other.year && month == other.month && dayOfMonth == other.dayOfMonth) 0
else if (year > other.year || (year == other.year && month > other.month) ||
(year == other.year && month == other.month && dayOfMonth > other.dayOfMonth)) 1
else -1
}
operator fun plus(timeInterval: TimeInterval): MyDate {
return this.copy().addTimeIntervals(timeInterval, 1)
}
operator fun plus(timeInterval: MultipleTimeInterval): MyDate {
return this.copy().addTimeIntervals(timeInterval.interval, timeInterval.count)
}
}
operator fun MyDate.rangeTo(other: MyDate): DateRange = DateRange(this, other)
enum class TimeInterval {
DAY,
WEEK,
YEAR;
operator fun times(count: Int): MultipleTimeInterval {
return MultipleTimeInterval(count, this)
}
}
data class MultipleTimeInterval(val count: Int, val interval: TimeInterval)
class DateRange(val start: MyDate, val endInclusive: MyDate) {
operator fun contains(date: MyDate): Boolean {
return (start <= date) && (date <= endInclusive)
}
operator fun iterator(): Iterator<MyDate> {
return object : Iterator<MyDate> {
var currentDay: MyDate = start
override fun next(): MyDate {
val temp = currentDay
currentDay = currentDay.nextDay()
return temp
}
override fun hasNext(): Boolean {
return currentDay <= endInclusive
}
}
}
}
| 0 |
Kotlin
| 0 | 0 |
38a201d3622a59c808dc95caa54824a9f7dace99
| 1,716 |
kotlin-koans
|
MIT License
|
src/main/kotlin/com/simonorono/aoc2015/solutions/Day07.kt
|
simonorono
| 662,846,819 | false |
{"Kotlin": 28492}
|
package com.simonorono.aoc2015.solutions
import com.simonorono.aoc2015.lib.Day
object Day07 : Day(7) {
private val input = getInput().lines().map { parseInput(it) }
private val values = mutableMapOf<String, UShort?>()
private enum class Operator {
OR,
AND,
LSHIFT,
RSHIFT,
NOT,
YES;
companion object {
fun fromString(value: String): Operator {
return when (value) {
"OR" -> OR
"AND" -> AND
"LSHIFT" -> LSHIFT
"RSHIFT" -> RSHIFT
"NOT" -> NOT
"YES" -> YES
else -> throw IllegalStateException()
}
}
}
}
private abstract class Op {
abstract val target: String
abstract fun calculate(): UShort
}
private data class BinaryOp(
val left: String,
val right: String,
val op: Operator,
override val target: String
) : Op() {
override fun calculate(): UShort {
val left = getValue(left)
val right = getValue(right)
return when (op) {
Operator.OR -> left.or(right)
Operator.AND -> left.and(right)
Operator.LSHIFT -> left.toUInt().shl(right.toInt()).toUShort()
Operator.RSHIFT -> left.toUInt().shr(right.toInt()).toUShort()
else -> throw IllegalStateException()
}
}
}
private data class UnaryOp(
val operand: String,
val op: Operator,
override val target: String
) : Op() {
override fun calculate(): UShort {
val operand = getValue(operand)
return when (op) {
Operator.NOT -> operand.inv()
Operator.YES -> operand
else -> throw IllegalStateException()
}
}
}
private fun getValue(target: String): UShort {
val result = values[target]
if (result != null) {
return result
}
if (target.matches("""\d+""".toRegex())) {
return target.toUShort()
}
val res = (input.find { it.target == target }!!).calculate()
values[target] = res
return res
}
private fun parseInput(line: String): Op {
val parts = line.split(" -> ")
val target = parts[1]
val operation = parts[0].split(" ")
return when (operation.size) {
3 -> BinaryOp(
operation[0],
operation[2],
Operator.fromString(operation[1]),
target
)
2 -> UnaryOp(
operation[1],
Operator.fromString(operation[0]),
target
)
1 -> UnaryOp(
operation[0],
Operator.YES,
target
)
else -> throw IllegalStateException("")
}
}
override fun part1(): String {
return getValue("a").toString()
}
override fun part2(): String {
val a = getValue("a")
values.clear()
values["b"] = a
return getValue("a").toString()
}
}
| 0 |
Kotlin
| 0 | 0 |
0fec1d4db5b68ea8ee05b20c535df1b7f5570056
| 3,316 |
aoc2015
|
MIT License
|
src/main/kotlin/me/camdenorrb/timorforest/tree/DecisionTree0.kt
|
camdenorrb
| 202,772,314 | false | null |
package me.camdenorrb.timorforest.tree
// TODO: Change comparable to string, you can use .toDoubleOrNull to determine if it's a number
/*
class DecisionTree0 {
private lateinit var root: NodeBase<*>
var isTrained = false
private set
/**
* Trains the decision tree with fortune and knowledge!
*
* @param inputs Declares the input values [[value, value, label]]
*/
fun train(inputs: List<List<Comparable<*>>>) {
check(!isTrained) {
"This decision tree has already been trained!"
}
root = buildTree(inputs)
isTrained = true
}
/**
* Attempts to predict the label for the [row]
*
* @param row Declares the row of information to inspect
*
* @return The label the tree suspects
*/
fun predict(row: List<Comparable<*>>): Leaf {
var node = root
while (true) {
when(node) {
is Leaf -> return node
is Node -> node = if (node.value.match(row)) node.trueBranch else node.falseBranch
else -> error("Invalid node type ${node::class.simpleName}")
}
}
}
private fun buildTree(inputs: List<List<Comparable<*>>>): NodeBase<*> {
val (gain, question) = findBestSplit(inputs)
if (gain == 0.0) {
return Leaf(countLabels(inputs))
}
val (trueRows, falseRows) = partition(inputs, question)
val trueBranch = buildTree(trueRows)
val falseBranch = buildTree(falseRows)
return Node(question, trueBranch, falseBranch)
}
private fun findBestSplit(inputs: List<List<Comparable<*>>>): Pair<Double, Question> {
var bestGain = 0.0
var bestQuestion: Question? = null
val uncertainty = gini(inputs)
inputs.map { it[] }
// toSet to avoid duplicates
val columns = (0..inputs[0].size - 2).map { index -> inputs.map { it[index] }.toSet() }
columns.forEachIndexed { column, values ->
println(values)
values.forEach { value ->
val question = Question(column, value)
val (trueRows, falseRows) = partition(inputs, question)
if (trueRows.isEmpty() || falseRows.isEmpty()) {
return@forEachIndexed
}
val gain = infoGain(trueRows, falseRows, uncertainty)
if (gain >= bestGain) {
bestGain = gain
bestQuestion = question
}
}
}
return bestGain to bestQuestion!!
}
private fun countLabels(rows: List<List<Comparable<*>>>): Map<Comparable<*>, Int> {
val labelCount = mutableMapOf<Comparable<*>, Int>()
rows.forEach {
val last = it.last()
labelCount[last] = labelCount.getOrDefault(last, 0) + 1
}
return labelCount
}
/**
* Use [partition] to call this
*/
private fun infoGain(trueRows: List<List<Comparable<*>>>, falseRows: List<List<Comparable<*>>>, uncertainty: Double): Double {
val score = trueRows.size.toDouble() / (trueRows.size + falseRows.size)
return uncertainty - score * gini(trueRows) - (1 - score) * gini(falseRows)
}
/**
*
*
* @param rows
* @param question
* @return
*/
private fun partition(rows: List<List<Comparable<*>>>, question: Question?): Pair<List<List<Comparable<*>>>, List<List<Comparable<*>>>> {
return rows.partition { question?.match(it) ?: false }
}
/**
* TODO
*
* @property column
* @property value
*/
data class Question(val column: Int, val value: Comparable<*>) {
fun match(example: List<Comparable<*>>): Boolean {
val exampleValue = example[column]
if (value is Number) {
return (exampleValue as Number).toDouble() >= value.toDouble()
}
return exampleValue == value
}
}
private fun prettyText(node: NodeBase<*>, indent: String = ""): String {
return when(node) {
is Leaf -> "Predict: ${node.value}".prependIndent(indent)
is Node -> "${node.value} \n--> True: \n${prettyText(node.trueBranch, "$indent ")} \n--> False: \n${prettyText(node.falseBranch, "$indent ")}".prependIndent(indent)
else -> error("Unknown node type!")
}
}
private fun gini(rows: List<List<Comparable<*>>>): Double {
var impurity = 1.0
val labelCount = countLabels(rows)
val rowSize = rows.size.toDouble()
labelCount.forEach { (_, count) ->
val probOfLabel = count / rowSize
impurity -= probOfLabel.pow(2.0)
}
return impurity
}
override fun toString(): String {
return prettyText(root)
}
data class Leaf(override val value: Map<Comparable<*>, Int>) : NodeBase<Map<Comparable<*>, Int>>
data class Node(override val value: Question, val trueBranch: NodeBase<*>, val falseBranch: NodeBase<*>) : NodeBase<Question>
}*/
| 0 |
Kotlin
| 0 | 0 |
b746f0ca27b587fbff4dcc08d97051f463cac53e
| 5,161 |
TimorForest
|
MIT License
|
src/main/kotlin/no/chriswk/aoc2019/Day4.kt
|
chriswk
| 317,863,220 | false |
{"Kotlin": 481061}
|
package no.chriswk.aoc2019
class Day4 {
companion object {
@JvmStatic
fun main(args: Array<String>) {
val day4 = Day4()
report { day4.part1() }
report { day4.part2() }
}
}
fun part1(): Int {
val (begin, end) = "day4.txt".fileToString().split("-").map { it.toInt() }
return begin.until(end).count { isValid(it) }
}
fun part2(): Int {
val (begin, end) = "day4.txt".fileToString().split("-").map { it.toInt() }
return begin.until(end).count { isValidByPart2(it) }
}
private fun isStrictlyIncreasing(digits: List<Int>): Boolean {
return digits.sorted() == digits
}
private fun doubles(digits: List<Int>, req: (Int) -> Boolean): Boolean {
return digits.groupBy { it }.entries.any { req(it.value.size) }
}
private fun isStrictlyIncreasingTake(digits: List<Int>): Boolean {
//We know that there's exactly 6 digits
val (a, b, c, d, e, f) = digits
return a <= b && b <= c && c <= d && d <= e && e <= f
}
operator fun List<Int>.component6() = this[5]
fun isValid(candidate: Int): Boolean {
val digs = digits(candidate)
return isStrictlyIncreasingTake(digs) && doubles(digs) { it > 1 }
}
fun isValidByPart2(candidate: Int): Boolean {
val digs = digits(candidate)
return isStrictlyIncreasingTake(digs) && doubles(digs) { it == 2 }
}
fun digits(number: Int): List<Int> {
val digits = mutableListOf<Int>()
var current = number
while (current > 0) {
digits.add(current % 10)
current /= 10
}
return digits.reversed()
}
}
| 116 |
Kotlin
| 0 | 0 |
69fa3dfed62d5cb7d961fe16924066cb7f9f5985
| 1,718 |
adventofcode2019
|
MIT License
|
src/year2021/day05/Field.kt
|
fadi426
| 433,496,346 | false |
{"Kotlin": 44622}
|
package year2021.day01.day05
import java.awt.Point
import kotlin.math.absoluteValue
interface Field {
val coordinates: List<Pair<Point, Point>>
var hydrothermalVentsMap: MutableList<MutableList<Int>>
fun createMap() {
hydrothermalVentsMap =
MutableList(determineMapDimensions().first) { MutableList(determineMapDimensions().second) { 0 } }
}
private fun determineMapDimensions(): Pair<Int, Int> {
val x = coordinates.map { it.let { listOf(it.first.x, it.second.x) } }.flatten().maxOrNull()!!
val y = coordinates.map { it.let { listOf(it.first.y, it.second.y) } }.flatten().maxOrNull()!!
return Pair(x + 1, y + 1)
}
fun fillCoordinates() {
coordinates.forEach { points -> fillHorizontalAndVertical(points) }
}
fun countOverlappingLines(): Int {
return hydrothermalVentsMap.sumOf { it.count { it > 1 } }
}
fun fillHorizontalAndVertical(points: Pair<Point, Point>) {
if (points.first.x != points.second.x && points.first.y != points.second.y) return
val pointDifference = Pair(points.second.x - points.first.x, points.second.y - points.first.y)
if (pointDifference.first != 0) { // horizontal
for (i in 0..pointDifference.first.absoluteValue) {
val x = if (pointDifference.first > 0) i + points.first.x else -i + points.first.x
hydrothermalVentsMap[points.first.y][x]++
}
}
else { // vertical
for (i in 0..pointDifference.second.absoluteValue) {
val y = if (pointDifference.second > 0) i + points.first.y else -i + points.first.y
hydrothermalVentsMap[y][points.first.x]++
}
}
}
}
| 0 |
Kotlin
| 0 | 0 |
acf8b6db03edd5ff72ee8cbde0372113824833b6
| 1,752 |
advent-of-code-kotlin-template
|
Apache License 2.0
|
src/palindrome_int/PalindRomeString.kt
|
AhmedTawfiqM
| 458,182,208 | false |
{"Kotlin": 11105}
|
package palindrome_int
//https://leetcode.com/problems/palindrome-number
object PalindRomeString {
private fun isPalindrome(input: Int): Boolean {
if (input < 0 || input >= Int.MAX_VALUE) return false
if (input in 0..9) return true
val original = input.toString()
original.forEachIndexed { index, num ->
if (num != original[original.length - (index+1)])
return false
}
return true
}
@JvmStatic
fun main(args: Array<String>) {
println(isPalindrome(121))
println(isPalindrome(-121))
println(isPalindrome(10))
}
}
/**
* Given an integer x, return true if x is palindrome integer.
An integer is a palindrome when it reads the same backward as forward.
For example, 121 is a palindrome while 123 is not.
Example 1:
Input: x = 121
Output: true
Explanation: 121 reads as 121 from left to right and from right to left.
Example 2:
Input: x = -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:
Input: x = 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
Constraints:
-231 <= x <= 231 - 1
Follow up: Could you solve it without converting the integer to a string?
**/
| 0 |
Kotlin
| 0 | 1 |
a569265d5f85bcb51f4ade5ee37c8252e68a5a03
| 1,335 |
ProblemSolving
|
Apache License 2.0
|
src/main/kotlin/g2001_2100/s2081_sum_of_k_mirror_numbers/Solution.kt
|
javadev
| 190,711,550 | false |
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
|
package g2001_2100.s2081_sum_of_k_mirror_numbers
// #Hard #Math #Enumeration #2023_06_27_Time_455_ms_(100.00%)_Space_39.9_MB_(100.00%)
class Solution {
fun kMirror(k: Int, n: Int): Long {
val result: MutableList<Long> = ArrayList()
var len = 1
while (result.size < n) {
backtrack(result, CharArray(len++), k, n, 0)
}
var sum: Long = 0
for (num in result) {
sum += num
}
return sum
}
private fun backtrack(result: MutableList<Long>, arr: CharArray, k: Int, n: Int, index: Int) {
if (result.size == n) {
return
}
if (index >= (arr.size + 1) / 2) {
// Number in base-10
val number = String(arr).toLong(k)
if (isPalindrome(number)) {
result.add(number)
}
return
}
// Generate base-k palindrome number in arr.length without leading zeros
for (i in 0 until k) {
if (index == 0 && i == 0) {
// Leading zeros
continue
}
val c: Char = (i + '0'.code).toChar()
arr[index] = c
arr[arr.size - 1 - index] = c
backtrack(result, arr, k, n, index + 1)
}
}
private fun isPalindrome(number: Long): Boolean {
val strNum = number.toString()
var left = 0
var right = strNum.length - 1
while (left < right) {
if (strNum[left] == strNum[right]) {
left++
right--
} else {
return false
}
}
return true
}
}
| 0 |
Kotlin
| 14 | 24 |
fc95a0f4e1d629b71574909754ca216e7e1110d2
| 1,676 |
LeetCode-in-Kotlin
|
MIT License
|
src/main/kotlin/d10/D10_2.kt
|
MTender
| 734,007,442 | false |
{"Kotlin": 108628}
|
package d10
import input.Input
fun main() {
val lines = Input.read("input.txt")
val diagram = padInput(lines)
val pipe = findPipe(diagram)
val start = findStart(diagram)
val startReplacement = startReplacement(start, findConnections(diagram, start))
diagram[start.first] =
diagram[start.first].replaceRange(start.second, start.second + 1, startReplacement.toString())
val expandedDiagram = expand(diagram)
expandedDiagram[start.first * 2 + 1] =
expandedDiagram[start.first * 2 + 1].replaceRange(start.second * 2 + 1, start.second * 2 + 2, "S")
val expandedPipe = findPipe(expandedDiagram)
bfs(expandedDiagram, expandedPipe)
val revertedDiagram = undoExpand(expandedDiagram)
var enclosedCount = 0
for (i in revertedDiagram.indices) {
for (j in revertedDiagram[i].indices) {
if (!pipe.contains(Pair(i, j)) && revertedDiagram[i][j] != '0') {
enclosedCount++
}
}
}
println(enclosedCount)
}
fun startReplacement(start: Pair<Int, Int>, cons: List<Pair<Int, Int>>): Char {
val con1 = cons[0]
val con2 = cons[1]
if (start.first == con1.first && start.first == con2.first) return '-'
if (start.second == con1.second && start.second == con2.second) return '|'
if (
cons.contains(Pair(start.first, start.second - 1)) &&
cons.contains(Pair(start.first - 1, start.second))
) return 'J'
if (
cons.contains(Pair(start.first, start.second - 1)) &&
cons.contains(Pair(start.first + 1, start.second))
) return '7'
if (
cons.contains(Pair(start.first, start.second + 1)) &&
cons.contains(Pair(start.first - 1, start.second))
) return 'L'
if (
cons.contains(Pair(start.first, start.second + 1)) &&
cons.contains(Pair(start.first + 1, start.second))
) return 'F'
throw RuntimeException("start does not have two connecting pipes")
}
fun findPipe(diagram: List<String>): Set<Pair<Int, Int>> {
val start = findStart(diagram)
val firstConnections = findConnections(diagram, start)
var prev = start.copy()
var loc = firstConnections[0].copy()
val pipe = mutableSetOf<Pair<Int, Int>>()
pipe.add(start)
while (loc != start) {
pipe.add(loc)
val cons = findConnections(diagram, loc)
val next = if (cons[0] == prev) cons[1] else cons[0]
prev = loc.copy()
loc = next.copy()
}
return pipe
}
fun undoExpand(diagram: MutableList<String>): MutableList<String> {
val revertedDiagram = mutableListOf<String>()
for (i in diagram.indices) {
if (i % 2 == 0) continue
var line = ""
for (j in diagram[i].indices) {
if (j % 2 == 0) continue
line += diagram[i][j]
}
revertedDiagram.add(line)
}
return revertedDiagram
}
fun expand(diagram: MutableList<String>): MutableList<String> {
val expandedDiagram = mutableListOf<String>()
for (line in diagram) {
expandedDiagram.addAll(expandLine(line))
}
return expandedDiagram
}
fun expandLine(line: String): List<String> {
var prevLine = ""
var newLine = ""
for (c in line) {
prevLine += "."
prevLine += if ("LJ|".contains(c)) "|" else "."
newLine += if ("J7-".contains(c)) "-" else "."
newLine += c
}
return listOf(prevLine, newLine)
}
fun bfs(diagram: MutableList<String>, pipe: Set<Pair<Int, Int>>) {
val q = ArrayDeque<Pair<Int, Int>>()
diagram[0] = diagram[0].replaceRange(0, 1, "0")
q.add(Pair(0, 0))
while (q.isNotEmpty()) {
val loc = q.removeLast()
val surrounding = getSurrounding(diagram, loc)
for (sLoc in surrounding) {
if (!pipe.contains(sLoc) && diagram[sLoc.first][sLoc.second] != '0') {
diagram[sLoc.first] = diagram[sLoc.first].replaceRange(sLoc.second, sLoc.second + 1, "0")
q.add(sLoc)
}
}
}
}
fun getSurrounding(diagram: List<String>, loc: Pair<Int, Int>): List<Pair<Int, Int>> {
val surrounding = mutableListOf<Pair<Int, Int>>()
if (loc.first > 0) {
if (loc.second > 0) surrounding.add(Pair(loc.first - 1, loc.second - 1))
surrounding.add(Pair(loc.first - 1, loc.second))
if (loc.second < diagram[loc.first].lastIndex) surrounding.add(Pair(loc.first - 1, loc.second + 1))
}
if (loc.second > 0) surrounding.add(Pair(loc.first, loc.second - 1))
if (loc.second < diagram[loc.first].lastIndex) surrounding.add(Pair(loc.first, loc.second + 1))
if (loc.first < diagram.lastIndex) {
if (loc.second > 0) surrounding.add(Pair(loc.first + 1, loc.second - 1))
surrounding.add(Pair(loc.first + 1, loc.second))
if (loc.second < diagram[loc.first].lastIndex) surrounding.add(Pair(loc.first + 1, loc.second + 1))
}
return surrounding
}
| 0 |
Kotlin
| 0 | 0 |
a6eec4168b4a98b73d4496c9d610854a0165dbeb
| 4,947 |
aoc2023-kotlin
|
MIT License
|
knowledgebase-importer/src/main/kotlin/com/hartwig/hmftools/knowledgebaseimporter/FusionsAnalysis.kt
|
j-hudecek
| 152,054,013 | true |
{"Java": 4078031, "Kotlin": 381037, "R": 991, "Shell": 765}
|
package com.hartwig.hmftools.knowledgebaseimporter
import com.hartwig.hmftools.knowledgebaseimporter.output.ActionableFusionPairOutput
import com.hartwig.hmftools.knowledgebaseimporter.output.ActionablePromiscuousGeneOutput
import com.hartwig.hmftools.knowledgebaseimporter.output.FusionPair
import com.hartwig.hmftools.knowledgebaseimporter.output.PromiscuousGene
private const val MIN_PARTNER_COUNT = 2
//MIVO: fusions that appear more than MIN_PARTNER_COUNT on the fiveGene side of known fusion pairs
fun inferredPromiscuousFiveGenes(knowledgebases: Collection<Knowledgebase>): List<PromiscuousGene> {
return knowledgebases.flatMap { it.knownFusionPairs }
.distinct()
.groupBy { it.fiveGene }
.filter { it.value.size > MIN_PARTNER_COUNT }
.map { PromiscuousGene(it.key) }
.toList()
}
//MIVO: fusions that appear more than MIN_PARTNER_COUNT on the threeGene side of known fusion pairs
fun inferredPromiscuousThreeGenes(knowledgebases: Collection<Knowledgebase>): List<PromiscuousGene> {
return knowledgebases.flatMap { it.knownFusionPairs }
.distinct()
.groupBy { it.threeGene }
.filter { it.value.size > MIN_PARTNER_COUNT }
.map { PromiscuousGene(it.key) }
.toList()
}
//MIVO: genes that appear as promiscuous in knowledgebases and also appear at least once (as fiveGene) with a specific partner in known fusion pairs
fun externalPromiscuousFiveGenes(knowledgebases: Collection<Knowledgebase>): List<PromiscuousGene> {
return knowledgebases.flatMap { it.promiscuousGenes }
.distinct()
.filter { knowledgebases.flatMap { it.knownFusionPairs }.distinct().map { it.fiveGene }.toSet().contains(it.gene) }
}
//MIVO: genes that appear as promiscuous in knowledgebases and also appear at least once (as threeGene) with a specific partner in known fusion pairs
fun externalPromiscuousThreeGenes(knowledgebases: Collection<Knowledgebase>): List<PromiscuousGene> {
return knowledgebases.flatMap { it.promiscuousGenes }
.distinct()
.filter { knowledgebases.flatMap { it.knownFusionPairs }.distinct().map { it.threeGene }.toSet().contains(it.gene) }
}
fun knownFusionPairs(knowledgebases: Collection<Knowledgebase>): List<FusionPair> {
return knowledgebases.flatMap { it.knownFusionPairs }.distinct()
}
fun knownPromiscuousFive(knowledgebases: Collection<Knowledgebase>): List<PromiscuousGene> {
return (inferredPromiscuousFiveGenes(knowledgebases) + externalPromiscuousFiveGenes(knowledgebases)).distinct()
}
fun knownPromiscuousThree(knowledgebases: Collection<Knowledgebase>): List<PromiscuousGene> {
return (inferredPromiscuousThreeGenes(knowledgebases) + externalPromiscuousThreeGenes(knowledgebases)).distinct()
}
fun actionableFusionPairs(knowledgebases: Collection<Knowledgebase>): List<ActionableFusionPairOutput> {
return knowledgebases.flatMap { it.actionableFusionPairs }.distinct()
}
fun actionablePromiscuousFive(knowledgebases: Collection<Knowledgebase>): List<ActionablePromiscuousGeneOutput> {
val knownPromiscuousFive = knownPromiscuousFive(knowledgebases).toSet()
return actionablePromiscuousGenes(knowledgebases).filter { knownPromiscuousFive.contains(it.event) }
}
fun actionablePromiscuousThree(knowledgebases: Collection<Knowledgebase>): List<ActionablePromiscuousGeneOutput> {
val knownPromiscuousThree = knownPromiscuousThree(knowledgebases).toSet()
return actionablePromiscuousGenes(knowledgebases).filter { knownPromiscuousThree.contains(it.event) }
}
private fun actionablePromiscuousGenes(knowledgebases: Collection<Knowledgebase>): List<ActionablePromiscuousGeneOutput> {
return knowledgebases.flatMap { it.actionablePromiscuousGenes }.distinct()
}
| 0 |
Java
| 0 | 0 |
f619e02cdb166594e7dd4d7d1dd7fe8592267f2d
| 3,803 |
hmftools
|
MIT License
|
src/Day01.kt
|
naturboy
| 572,742,689 | false |
{"Kotlin": 6452}
|
fun main() {
fun part1(input: List<String>): Int {
return input.maxOf { calories -> calories.split("\n").sumOf { it.toInt() } }
}
fun part2(input: List<String>): Int {
return input.map { calories -> calories.split("\n").sumOf { it.toInt() } }.sorted().takeLast(3).sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInputWithDelimiter("Day01_test", "\n\n")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readInputWithDelimiter("Day01", "\n\n")
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
852871f58218d80702c3b49dd0fd453096e56a43
| 629 |
advent-of-code-kotlin-2022
|
Apache License 2.0
|
Day_11/Solution_Part2.kts
|
0800LTT
| 317,590,451 | false | null |
import java.io.File
enum class Seat {
Empty,
Occupied,
Floor
}
fun File.readSeats(): Array<Array<Seat>> {
return readLines().map {
line -> line.map {
when (it) {
'.' -> Seat.Floor
'L' -> Seat.Empty
else -> Seat.Occupied
}
}.toTypedArray()
}.toTypedArray()
}
fun printSeats(seats: Array<Array<Seat>>) {
for (row in seats) {
for (seat in row) {
print(when (seat) {
Seat.Empty -> 'L'
Seat.Occupied -> '#'
Seat.Floor -> '.'
})
}
println("")
}
println("")
}
fun countOccupiedSeats(seats: Array<Array<Seat>>): Int =
seats.map { it.count { it == Seat.Occupied }}.reduce { acc, n -> acc + n }
fun simulate(seats: Array<Array<Seat>>): Int {
val rows = seats.size
val cols = seats[0].size
var current = seats
var next = Array<Array<Seat>>(rows) { Array<Seat>(cols) {Seat.Floor}}
var left = Array<Array<Seat>>(rows) { Array<Seat>(cols) {Seat.Floor}}
var right = Array<Array<Seat>>(rows) { Array<Seat>(cols) {Seat.Floor}}
var top = Array<Array<Seat>>(rows) { Array<Seat>(cols) {Seat.Floor}}
var bottom = Array<Array<Seat>>(rows) { Array<Seat>(cols) {Seat.Floor}}
var leftDiagonalBottom = Array<Array<Seat>>(rows) { Array<Seat>(cols) {Seat.Floor}}
var leftDiagonalTop = Array<Array<Seat>>(rows) { Array<Seat>(cols) {Seat.Floor}}
var rightDiagonalBottom = Array<Array<Seat>>(rows) { Array<Seat>(cols) {Seat.Floor}}
var rightDiagonalTop = Array<Array<Seat>>(rows) { Array<Seat>(cols) {Seat.Floor}}
while (true) {
for (r in 0..rows-1) {
for (c in 0..cols-1) {
// Fill closest to the top
if (r == 0) {
top[r][c] = Seat.Empty
} else if (current[r-1][c] == Seat.Floor) {
top[r][c] = top[r-1][c]
} else {
top[r][c] = current[r-1][c]
}
// Fill the closest to the right diagonal top
if (c == 0 || r == 0) {
rightDiagonalTop[r][c] = Seat.Empty
} else if (current[r-1][c-1] == Seat.Floor) {
rightDiagonalTop[r][c] = rightDiagonalTop[r-1][c-1]
} else {
rightDiagonalTop[r][c] = current[r-1][c-1]
}
}
for (c in cols-1 downTo 0) {
// Fill the closest to the right diagonal top
if (c == cols-1 || r == 0) {
leftDiagonalTop[r][c] = Seat.Empty
} else if (current[r-1][c+1] == Seat.Floor) {
leftDiagonalTop[r][c] = leftDiagonalTop[r-1][c+1]
} else {
leftDiagonalTop[r][c] = current[r-1][c+1]
}
}
}
for (r in rows-1 downTo 0) {
for (c in 0..cols-1) {
// Fill closest to the bottom
if (r == rows-1) {
bottom[r][c] = Seat.Empty
} else if (current[r+1][c] == Seat.Floor) {
bottom[r][c] = bottom[r+1][c]
} else {
bottom[r][c] = current[r+1][c]
}
// Fill the closest to the left
if (c == 0) {
left[r][c] = Seat.Empty
} else if(current[r][c-1] == Seat.Floor) {
left[r][c] = left[r][c-1]
} else {
left[r][c] = current[r][c-1]
}
// Fill the closest to the left diagonal
if (c == 0 || r == rows-1) {
leftDiagonalBottom[r][c] = Seat.Empty
} else if (current[r+1][c-1] == Seat.Floor) {
leftDiagonalBottom[r][c] = leftDiagonalBottom[r+1][c-1]
} else {
leftDiagonalBottom[r][c] = current[r+1][c-1]
}
}
for (c in cols-1 downTo 0) {
// Fill closest to the right
if (c == cols-1) {
right[r][c] = Seat.Empty
} else if (current[r][c+1] == Seat.Floor) {
right[r][c] = right[r][c+1]
} else {
right[r][c] = current[r][c+1]
}
// Fill closest to the right diagonal
if (c == cols-1 || r == rows-1) {
rightDiagonalBottom[r][c] = Seat.Empty
} else if (current[r+1][c+1] == Seat.Floor) {
rightDiagonalBottom[r][c] = rightDiagonalBottom[r+1][c+1]
} else {
rightDiagonalBottom[r][c] = current[r+1][c+1]
}
}
}
var changed = false
for(i in 0..rows-1) {
for (j in 0..cols-1) {
var numOccupiedInSight = 0
if(left[i][j] == Seat.Occupied) numOccupiedInSight++
if(right[i][j] == Seat.Occupied) numOccupiedInSight++
if(top[i][j] == Seat.Occupied) numOccupiedInSight++
if(bottom[i][j] == Seat.Occupied) numOccupiedInSight++
if(leftDiagonalBottom[i][j] == Seat.Occupied) numOccupiedInSight++
if(leftDiagonalTop[i][j] == Seat.Occupied) numOccupiedInSight++
if(rightDiagonalBottom[i][j] == Seat.Occupied) numOccupiedInSight++
if(rightDiagonalTop[i][j] == Seat.Occupied) numOccupiedInSight++
if (current[i][j] == Seat.Empty && numOccupiedInSight == 0) {
next[i][j] = Seat.Occupied
changed = true
} else if (current[i][j] == Seat.Occupied && numOccupiedInSight >= 5) {
next[i][j] = Seat.Empty
changed = true
} else {
next[i][j] = current[i][j]
}
}
}
val tmp = current
current = next
next = tmp
if (!changed) {
break
}
}
return countOccupiedSeats(current)
}
fun main() {
val seats = File("input.txt").readSeats()
println(simulate(seats))
}
main()
| 0 |
Kotlin
| 0 | 0 |
191c8c307676fb0e7352f7a5444689fc79cc5b54
| 4,926 |
advent-of-code-2020
|
The Unlicense
|
src/main/kotlin/g1701_1800/s1728_cat_and_mouse_ii/Solution.kt
|
javadev
| 190,711,550 | false |
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
|
package g1701_1800.s1728_cat_and_mouse_ii
// #Hard #Array #Dynamic_Programming #Math #Matrix #Graph #Memoization #Topological_Sort
// #Game_Theory #2023_06_16_Time_193_ms_(100.00%)_Space_37.2_MB_(100.00%)
@Suppress("NAME_SHADOWING")
class Solution {
private val graphs: Array<Array<List<Int>>> = arrayOf(arrayOf(), arrayOf())
private var foodPos = 0
private lateinit var memo: Array<Array<IntArray>>
fun canMouseWin(grid: Array<String>, catJump: Int, mouseJump: Int): Boolean {
val m = grid.size
val n = grid[0].length
var mousePos = 0
var catPos = 0
for (i in 0 until m) {
for (j in 0 until n) {
val c = grid[i][j]
if (c == 'F') {
foodPos = i * n + j
} else if (c == 'C') {
catPos = i * n + j
} else if (c == 'M') {
mousePos = i * n + j
}
}
}
graphs[0] = buildGraph(mouseJump, grid)
graphs[1] = buildGraph(catJump, grid)
memo = Array(m * n) { Array(m * n) { IntArray(2) } }
for (i in 0 until m) {
for (j in 0 until n) {
val c = grid[i][j]
if (c == '#' || c == 'F') {
continue
}
val catTurn = 1
dfs(i * n + j, foodPos, catTurn)
}
}
return memo[mousePos][catPos][MOUSE_TURN] < 0
}
private fun buildGraph(jump: Int, grid: Array<String>): Array<List<Int>> {
val dirs = arrayOf(intArrayOf(-1, 0), intArrayOf(1, 0), intArrayOf(0, 1), intArrayOf(0, -1))
val m = grid.size
val n = grid[0].length
val graph: Array<List<Int>> = Array(m * n) { mutableListOf() }
for (i in 0 until m) {
for (j in 0 until n) {
val list: MutableList<Int> = ArrayList()
graph[i * n + j] = list
if (grid[i][j] == '#') {
continue
}
list.add(i * n + j)
for (dir in dirs) {
for (step in 1..jump) {
val x = i + dir[0] * step
val y = j + dir[1] * step
if (x < 0 || x >= m || y < 0 || y >= n || grid[x][y] == '#') {
break
}
list.add(x * n + y)
}
}
}
}
return graph
}
private fun dfs(p1: Int, p2: Int, turn: Int) {
var turn = turn
if (p1 == p2) {
return
}
if ((if (turn == 0) p2 else p1) == foodPos) {
return
}
if (memo[p1][p2][turn] < 0) {
return
}
memo[p1][p2][turn] = -1
turn = turn xor 1
for (w in graphs[turn][p2]) {
if (turn == MOUSE_TURN || ++memo[w][p1][turn] == graphs[turn][w].size) {
dfs(w, p1, turn)
}
}
}
companion object {
private const val MOUSE_TURN = 0
}
}
| 0 |
Kotlin
| 14 | 24 |
fc95a0f4e1d629b71574909754ca216e7e1110d2
| 3,141 |
LeetCode-in-Kotlin
|
MIT License
|
src/main/kotlin/QuickSort.kt
|
wenvelope
| 692,706,194 | false |
{"Kotlin": 11474, "Java": 7490}
|
import java.util.*
fun main() {
val mutableList = arrayListOf(3,23,5435,2323,43,32,43)
println(mutableList)
println( mutableList.quickSort().let { mutableList })
}
/**
*快排
* 思想:分治
* 1.从大到小每一层都一分为二 分到不能再分为止
* 2.对于每一个小部分 都选定一个和标志位 使得标志位的左边都小于右边
*/
fun MutableList<Int>.quickSort() {
if (this.isEmpty()) {
return
}
val stack = Stack<Int>()
stack.push(0)
stack.push(this.size - 1)
while (stack.isNotEmpty()) {
val highIndex = stack.pop()
val lowIndex = stack.pop()
if (lowIndex < highIndex) {
val flagIndex = partition(mList = this, lowIndex = lowIndex, highIndex = highIndex)
stack.push(lowIndex)
stack.push(flagIndex - 1)
stack.push(flagIndex + 1)
stack.push(highIndex)
}
}
}
/**
* 选取一个标志位 让列表中的左边小于标志位右边大于标志位
*
* @return 标志位的索引
*/
fun partition(mList: MutableList<Int>, lowIndex: Int, highIndex: Int): Int {
val flag = mList[highIndex]
//最后一个小于flag的元素的位置 初始为lowIndex-1
var theLowIndex = lowIndex - 1
for (index in lowIndex until highIndex){
if (mList[index]<flag){
mList.swap(theLowIndex+1,index)
theLowIndex++
}
}
mList.swap(theLowIndex + 1, highIndex)
return theLowIndex + 1
}
/**
* 交换两个索引对应元素的位置
*/
fun MutableList<Int>.swap(index1: Int, index2: Int) {
val temp = this[index1]
set(index = index1, element = this[index2])
set(index = index2, element = temp)
}
| 0 |
Kotlin
| 0 | 1 |
4a5b2581116944c5bf8cf5ab0ed0af410669b9b6
| 1,743 |
OnlineJudge
|
Apache License 2.0
|
utbot-analytics/src/main/kotlin/org/utbot/RegressionTrainer.kt
|
UnitTestBot
| 480,810,501 | false |
{"Kotlin": 6661796, "Java": 2209528, "Python": 223199, "Go": 99696, "C#": 80947, "JavaScript": 42483, "Shell": 15961, "HTML": 8704, "Batchfile": 8586, "Dockerfile": 2057}
|
package org.utbot
import org.utbot.TrainRegressionModel.*
import org.utbot.metrics.RegressionMetrics
import org.utbot.models.SimpleRegression
import org.utbot.models.SimpleRegressionNeuralNetworks
import smile.data.DataFrame
import smile.data.formula.Formula
import smile.read
class RegressionTrainer(data: DataFrame, val trainRegressionModel: TrainRegressionModel = GBM) :
AbstractTrainer(data) {
val simpleRegression = SimpleRegression()
val simpleNeuralNetworks = SimpleRegressionNeuralNetworks()
var validationResult: Map<String, Pair<DoubleArray, DoubleArray?>>? = null
var metrics: Map<String, RegressionMetrics>? = null
override fun train() {
when (trainRegressionModel) {
CART -> simpleRegression.trainCART(Formula.lhs(targetColumn), trainData)
GBM -> simpleRegression.trainGradientTreeBoosting(Formula.lhs(targetColumn), trainData)
LRM -> simpleRegression.trainLinearRegression(Formula.lhs(targetColumn), trainData)
LASSO -> simpleRegression.trainLassoModel(Formula.lhs(targetColumn), trainData)
RANDOMFOREST -> simpleRegression.trainRandomForest(
Formula.lhs(targetColumn),
trainData
)
RBF -> simpleNeuralNetworks.trainRBFModel(Formula.lhs(targetColumn), trainData)
MLP -> simpleNeuralNetworks.trainMLP(Formula.lhs(targetColumn), trainData)
}
}
override fun validate() {
validationResult = when (trainRegressionModel) {
RBF, MLP -> simpleNeuralNetworks.prediction(
Formula.lhs(targetColumn).expand(validationData.schema()), validationData, trainRegressionModel
)
else -> simpleRegression.prediction(
Formula.lhs(targetColumn).expand(validationData.schema()), validationData, trainRegressionModel
)
}
metrics = validationResult?.mapValues {
RegressionMetrics(it.key, it.value.first, it.value.second!!)
}
}
override fun visualize() {
TODO("Not yet implemented")
}
override fun featureSelection() {
TODO("Not yet implemented")
}
override fun save() {
TODO("Not yet implemented")
}
}
enum class TrainRegressionModel {
GBM, LRM, LASSO, CART, RANDOMFOREST, RBF, MLP
}
fun main() {
val data = read.csv("logs/stats.txt")
values().forEach {
val trainer = RegressionTrainer(data, trainRegressionModel = it)
trainer.fit()
trainer.metrics?.values?.forEach { println(it) }
}
}
| 410 |
Kotlin
| 37 | 110 |
c7f2ac4286b9861485c67ad3b11cd14e2b3ab82f
| 2,596 |
UTBotJava
|
Apache License 2.0
|
kotlin/440.K-th Smallest in Lexicographical Order(字典序的第K小数字).kt
|
learningtheory
| 141,790,045 | false |
{"Python": 4025652, "C++": 1999023, "Java": 1995266, "JavaScript": 1990554, "C": 1979022, "Ruby": 1970980, "Scala": 1925110, "Kotlin": 1917691, "Go": 1898079, "Swift": 1827809, "HTML": 124958, "Shell": 7944}
|
/**
<p>Given integers <code>n</code> and <code>k</code>, find the lexicographically k-th smallest integer in the range from <code>1</code> to <code>n</code>.</p>
<p>Note: 1 ≤ k ≤ n ≤ 10<sup>9</sup>.</p>
<p><b>Example:</b>
<pre>
<b>Input:</b>
n: 13 k: 2
<b>Output:</b>
10
<b>Explanation:</b>
The lexicographical order is [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9], so the second smallest number is 10.
</pre>
</p>
<p>给定整数 <code>n</code> 和 <code>k</code>,找到 <code>1</code> 到 <code>n</code> 中字典序第 <code>k</code> 小的数字。</p>
<p>注意:1 ≤ k ≤ n ≤ 10<sup>9</sup>。</p>
<p><strong>示例 :</strong></p>
<pre>
<strong>输入:</strong>
n: 13 k: 2
<strong>输出:</strong>
10
<strong>解释:</strong>
字典序的排列是 [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9],所以第二小的数字是 10。
</pre>
<p>给定整数 <code>n</code> 和 <code>k</code>,找到 <code>1</code> 到 <code>n</code> 中字典序第 <code>k</code> 小的数字。</p>
<p>注意:1 ≤ k ≤ n ≤ 10<sup>9</sup>。</p>
<p><strong>示例 :</strong></p>
<pre>
<strong>输入:</strong>
n: 13 k: 2
<strong>输出:</strong>
10
<strong>解释:</strong>
字典序的排列是 [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9],所以第二小的数字是 10。
</pre>
**/
class Solution {
fun findKthNumber(n: Int, k: Int): Int {
}
}
| 0 |
Python
| 1 | 3 |
6731e128be0fd3c0bdfe885c1a409ac54b929597
| 1,489 |
leetcode
|
MIT License
|
src/main/kotlin/dev/bogwalk/batch5/Problem58.kt
|
bog-walk
| 381,459,475 | false | null |
package dev.bogwalk.batch5
import dev.bogwalk.util.maths.isPrimeMRBI
/**
* Problem 58: Spiral Primes
*
* https://projecteuler.net/problem=58
*
* Goal: By repeatedly completing a new layer on a square spiral grid, as detailed below, find
* the side length at which the ratio of primes along both diagonals first falls below N%.
*
* Constraints: 8 <= N <= 60
*
* Spiral Pattern: Start with 1 & move to the right in an anti-clockwise direction, incrementing
* the numbers. This creates a grid with all odd squares (area of odd-sided grid & therefore
* composite) along the bottom right diagonal.
*
* e.g.: N = N = 60
* grid = *17* 16 15 14 *13*
* 18 *5* 4 *3* 12
* 19 6 1 2 11
* 20 *7* 8 9 10
* 21 22 23 24 25
* side length = 5, as 5/9 = 55.55% are prime
*/
class SpiralPrimes {
/**
* Generates new diagonal values (except bottom-right) using previous square spiral side
* length & checks their primality.
*
* A newer Miller-Rabin algorithm version is used to check primality, especially meant for very
* large values. The diagonal values in this problem reach very high as the layers increase.
*
* e.g. side length 26241, at which point the ratio only just falls below 10%, has a
* bottom-right diagonal value of 688_590_081.
*
* @param [percent] integer value representing the percentage under which the ratio should
* first fall before returning the final result.
*/
fun spiralPrimeRatio(percent: Int): Int {
val ratio = percent / 100.0
var side = 3
var diagonals = 5
var primes = 3L
while (ratio <= 1.0 * primes / diagonals) {
// check new diagonal elements of next layer using previous side length
val prevArea = 1L * side * side
primes += (1..3).sumOf { i ->
if ((prevArea + i * (side + 1)).isPrimeMRBI()) 1L else 0L
}
side += 2
diagonals += 4
}
return side
}
}
| 0 |
Kotlin
| 0 | 0 |
62b33367e3d1e15f7ea872d151c3512f8c606ce7
| 2,103 |
project-euler-kotlin
|
MIT License
|
leetcode/src/array/Offer21.kt
|
zhangweizhe
| 387,808,774 | false | null |
package array
fun main() {
// 剑指 Offer 21. 调整数组顺序使奇数位于偶数前面
// https://leetcode-cn.com/problems/diao-zheng-shu-zu-shun-xu-shi-qi-shu-wei-yu-ou-shu-qian-mian-lcof/
println(exchange1(intArrayOf(1,3,2,4,5,6)).contentToString())
}
private fun exchange(nums: IntArray): IntArray {
val ret = IntArray(nums.size)
var left = 0
var right = nums.size - 1
for (i in nums) {
if (i % 2 == 0) {
ret[right--] = i
}else {
ret[left++] = i
}
}
return ret
}
private fun exchange1(nums: IntArray): IntArray {
var left = 0
var right = nums.size - 1
val size = nums.size
while (left < right) {
while (left < size && nums[left] % 2 != 0) {
left++
}
while (right >= 0 && nums[right] % 2 == 0) {
right--
}
if (left < right) {
val tmp = nums[left]
nums[left] = nums[right]
nums[right] = tmp
left++
right--
}
}
return nums
}
fun exchange2(nums: IntArray): IntArray {
var left = 0
var right = nums.size - 1
var p = 0
while (left < right) {
while (nums[left] % 2 == 1 && left < right) {
left++
}
while (nums[right] % 2 == 0 && left < right) {
right--
}
val tmp = nums[left]
nums[left] = nums[right]
nums[right] = tmp
}
return nums
}
| 0 |
Kotlin
| 0 | 0 |
1d213b6162dd8b065d6ca06ac961c7873c65bcdc
| 1,491 |
kotlin-study
|
MIT License
|
app/src/main/java/com/binaryquackers/aoc2022/Day2PuzzleSolver.kt
|
MooseTheGoose
| 573,219,554 | false |
{"Kotlin": 16876}
|
package com.binaryquackers.aoc2022
import java.nio.charset.StandardCharsets
class Day2PuzzleSolver: PuzzleSolver() {
private enum class Result {
Lose,
Draw,
Win;
}
private enum class Choice {
Rock,
Paper,
Scissors;
private fun idx(): Int {
return when(this) {
Rock -> 0
Paper -> 1
Scissors -> 2
}
}
fun result(opponent: Choice): Result {
var matrix = arrayOf(
Result.Draw, Result.Lose, Result.Win,
Result.Win, Result.Draw, Result.Lose,
Result.Lose, Result.Win, Result.Draw,
)
return matrix[this.idx() * 3 + opponent.idx()]
}
fun inverse(result: Result): Choice {
var matrix = arrayOf(
Choice.Paper, Choice.Rock, Choice.Scissors,
Choice.Scissors, Choice.Paper, Choice.Rock,
Choice.Rock, Choice.Scissors, Choice.Paper,
)
var idx = when(result) {
Result.Lose -> 0
Result.Draw -> 1
Result.Win -> 2
}
return matrix[this.idx() * 3 + idx]
}
}
private fun solve(fname: String, inverse: Boolean): Int {
var reader = java.io.BufferedReader(
activity.assets!!.open(fname).reader(StandardCharsets.UTF_8))
var score = 0
reader.forEachLine {
var fields = it.trim().split(' ')
if (fields.size < 2)
return@forEachLine
var opponent = when(fields[0][0]) {
'A' -> Choice.Rock
'B' -> Choice.Paper
'C' -> Choice.Scissors
else -> return@forEachLine
}
var ally = if(inverse) when(fields[1][0]) {
'X' -> opponent.inverse(Result.Win)
'Y' -> opponent.inverse(Result.Draw)
'Z' -> opponent.inverse(Result.Lose)
else -> return@forEachLine
} else when(fields[1][0]) {
'X' -> Choice.Rock
'Y' -> Choice.Paper
'Z' -> Choice.Scissors
else -> return@forEachLine
}
score += when(ally.result(opponent)) {
Result.Win -> 6
Result.Draw -> 3
Result.Lose -> 0
}
score += when(ally) {
Choice.Rock -> 1
Choice.Paper -> 2
Choice.Scissors -> 3
}
}
return score
}
private fun onPart1(fname: String) {
message = "Strategy Score: ${solve(fname, false)}"
}
private fun onPart2(fname: String) {
message = "Strategy Score: ${solve(fname, true)}"
}
override fun onPart1Test() {
onPart1("Day2TestInput.txt")
}
override fun onPart1Solution() {
onPart1("Day2Input.txt")
}
override fun onPart2Test() {
onPart2("Day2TestInput.txt")
}
override fun onPart2Solution() {
onPart2("Day2Input.txt")
}
}
| 0 |
Kotlin
| 0 | 0 |
d7f2d6df69dbd74c4d429247213e35da7409015c
| 3,153 |
aoc-2022-android
|
Creative Commons Zero v1.0 Universal
|
src/main/kotlin/dev/shtanko/algorithms/leetcode/DetectCapital.kt
|
ashtanko
| 203,993,092 | false |
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
|
/*
* Copyright 2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
/**
* 520. Detect Capital
* @see <a href="https://leetcode.com/problems/detect-capital/">Source</a>
*/
fun interface DetectCapital {
fun detectCapitalUse(word: String): Boolean
}
/**
* Approach 1: Character by Character
*/
class DetectCapitalCharacter : DetectCapital {
override fun detectCapitalUse(word: String): Boolean {
val n: Int = word.length
if (n == 1) {
return true
} else if (n == 0) {
return false
}
// case 1: All capital
if (word.first().isUpperCase() && word[1].isUpperCase()) {
for (i in 2 until n) {
if (word[i].isLowerCase()) {
return false
}
}
// case 2 and case 3
} else {
for (i in 1 until n) {
if (word[i].isUpperCase()) {
return false
}
}
}
// if pass one of the cases
return true
}
}
/**
* Approach 2: Regex
*/
class DetectCapitalRegex : DetectCapital {
override fun detectCapitalUse(word: String): Boolean {
if (word.isEmpty()) return false
return word.matches("[A-Z]*|.[a-z]*".toRegex())
}
}
| 4 |
Kotlin
| 0 | 19 |
776159de0b80f0bdc92a9d057c852b8b80147c11
| 1,875 |
kotlab
|
Apache License 2.0
|
src/main/kotlin/org/example/adventofcode/puzzle/Day01.kt
|
peterlambrechtDev
| 573,146,803 | false |
{"Kotlin": 39213}
|
package org.example.adventofcode.puzzle
import org.example.adventofcode.util.FileLoader
object Day01 {
fun part1(filePath: String): Int {
val stringLines = FileLoader.loadFromFile<String>(filePath)
var currentSum = 0
var highestCalorie = 0
for (line in stringLines) {
if (line.isEmpty()) {
if (currentSum > highestCalorie) {
highestCalorie = currentSum
}
currentSum = 0
} else {
currentSum += line.toInt()
}
}
if (currentSum > highestCalorie) {
highestCalorie = currentSum
}
return highestCalorie
}
fun part2(filePath: String): Int {
val stringLines = FileLoader.loadFromFile<String>(filePath)
var currentSum = 0
var list = mutableListOf<Int>()
for (line in stringLines) {
if (line.isEmpty() && currentSum != 0) {
list.add(currentSum)
currentSum = 0
} else {
currentSum += line.toInt()
}
}
if (currentSum != 0) {
list.add(currentSum)
}
list.sortDescending()
println("highest: ${list.elementAt(0)} + 2nd: ${list.elementAt(1)} + 3rd: ${list.elementAt(2)}")
val answer = list.elementAt(0) + list.elementAt(1) + list.elementAt(2)
return answer
}
}
fun main() {
var day = "day01"
println("Example 1: ${Day01.part1("/${day}_example.txt")}")
println("Solution 1: ${Day01.part1("/${day}.txt")}")
println("Example 2: ${Day01.part2("/${day}_example.txt")}")
println("Solution 2: ${Day01.part2("/${day}.txt")}")
}
| 0 |
Kotlin
| 0 | 0 |
aa7621de90e551eccb64464940daf4be5ede235b
| 1,736 |
adventOfCode2022
|
MIT License
|
src/main/kotlin/g1301_1400/s1382_balance_a_binary_search_tree/Solution.kt
|
javadev
| 190,711,550 | false |
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
|
package g1301_1400.s1382_balance_a_binary_search_tree
// #Medium #Depth_First_Search #Greedy #Tree #Binary_Tree #Binary_Search_Tree #Divide_and_Conquer
// #2023_06_06_Time_369_ms_(85.71%)_Space_42.9_MB_(92.86%)
import com_github_leetcode.TreeNode
/*
* Example:
* var ti = TreeNode(5)
* var v = ti.`val`
* Definition for a binary tree node.
* class TreeNode(var `val`: Int) {
* var left: TreeNode? = null
* var right: TreeNode? = null
* }
*/
class Solution {
fun balanceBST(root: TreeNode?): TreeNode? {
val inorder = inorder(root, ArrayList())
return dfs(inorder, 0, inorder.size - 1)
}
private fun inorder(root: TreeNode?, list: MutableList<Int>): List<Int> {
if (root == null) {
return list
}
inorder(root.left, list)
list.add(root.`val`)
return inorder(root.right, list)
}
private fun dfs(nums: List<Int>, start: Int, end: Int): TreeNode? {
if (end < start) {
return null
}
val mid = (start + end) / 2
val root = TreeNode(nums[mid])
root.left = dfs(nums, start, mid - 1)
root.right = dfs(nums, mid + 1, end)
return root
}
}
| 0 |
Kotlin
| 14 | 24 |
fc95a0f4e1d629b71574909754ca216e7e1110d2
| 1,209 |
LeetCode-in-Kotlin
|
MIT License
|
2023/src/main/kotlin/net/daams/solutions/5a.kt
|
Michiel-Daams
| 573,040,288 | false |
{"Kotlin": 39925, "Nim": 34690}
|
package net.daams.solutions
import net.daams.Solution
class `5a`(input: String): Solution(input) {
override fun run() {
val splitInput = input.split("\n\n")
val seeds = splitInput[0].removePrefix("seeds: ").split(" ").map{ it.toLong() }
val maps = mutableListOf<List<Pair<LongRange, LongRange>>>()
splitInput.subList(1, splitInput.size).forEach {
val destinationRanges = mutableListOf<Pair<LongRange, LongRange>>()
val rangeText = it.split("\n")
rangeText.subList(1, rangeText.size).forEach {
val meuk = it.split(" ").map { it.toLong() }
val destinationRange = meuk[0]..meuk[0] + meuk[2] - 1
val sourceRange = meuk[1] .. meuk[1] + meuk[2] - 1
destinationRanges.add(Pair(sourceRange, destinationRange))
}
maps.add(destinationRanges)
}
val destinations = mutableListOf<Long>()
seeds.forEach {seed ->
var prevDestination = seed
maps.forEach { map ->
prevDestination = getDestination(map, prevDestination)
}
destinations.add(prevDestination)
}
println(destinations.min())
}
fun getDestination(ranges: List<Pair<LongRange, LongRange>>, source: Long): Long {
ranges.forEach {
if (source in it.first) return source - it.first.first + it.second.first
}
return source
}
}
| 0 |
Kotlin
| 0 | 0 |
f7b2e020f23ec0e5ecaeb97885f6521f7a903238
| 1,482 |
advent-of-code
|
MIT License
|
2023/1/solve-2.kts
|
gugod
| 48,180,404 | false |
{"Raku": 170466, "Perl": 121272, "Kotlin": 58674, "Rust": 3189, "C": 2934, "Zig": 850, "Clojure": 734, "Janet": 703, "Go": 595}
|
import java.io.File
val englishDigits = mapOf(
"1" to 1,
"2" to 2,
"3" to 3,
"4" to 4,
"5" to 5,
"6" to 6,
"7" to 7,
"8" to 8,
"9" to 9,
"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,
)
val sumOfAll = File("input").readLines().map { line ->
val calibers = line.indices.flatMap { i ->
listOf(i+1, i+3, i+4, i+5)
.filter { it <= line.lastIndex + 1 }
.map { englishDigits.getOrDefault(line.substring(i,it), 0) }
.filter { it != 0 }
}
10 * calibers.first() + calibers.last()
}.sum()
println("$sumOfAll")
| 0 |
Raku
| 1 | 5 |
ca0555efc60176938a857990b4d95a298e32f48a
| 701 |
advent-of-code
|
Creative Commons Zero v1.0 Universal
|
src/main/kotlin/co/csadev/advent2020/Day02.kt
|
gtcompscientist
| 577,439,489 | false |
{"Kotlin": 252918}
|
/**
* Copyright (c) 2021 by <NAME>
* Advent of Code 2020, Day 2
* Problem Description: http://adventofcode.com/2020/day/2
*/
package co.csadev.advent2020
class Day02(data: List<String>) {
private val pattern = """^(\d+)-(\d+) (\w): (.+)$""".toRegex()
private val input = data.mapNotNull { pattern.find(it) }.map {
val (min, max, letter, password) = it.destructured
PasswordCheck(min.toInt(), max.toInt(), letter.first(), password)
}
private data class PasswordCheck(val min: Int, val max: Int, val letter: Char, val password: String) {
val isValid: Boolean = password.count { c -> letter == c }.run { this in min..max }
val isValid2 = (password[min - 1] == letter) xor (password[max - 1] == letter)
}
fun solvePart1(): Int = input.count { it.isValid }
fun solvePart2(): Int = input.count { it.isValid2 }
}
| 0 |
Kotlin
| 0 | 1 |
43cbaac4e8b0a53e8aaae0f67dfc4395080e1383
| 886 |
advent-of-kotlin
|
Apache License 2.0
|
src/main/kotlin/problems/Day10.kt
|
PedroDiogo
| 432,836,814 | false |
{"Kotlin": 128203}
|
package problems
class Day10(override val input: String) : Problem {
override val number: Int = 10
private val lines: List<Line> = input.lines().map { Line(it) }
override fun runPartOne(): String {
return lines
.mapNotNull { line -> line.firstIllegalCharacter() }
.sumOf { char -> char.value()!! }
.toString()
}
private fun Char.value(): Int? {
return mapOf(
')' to 3,
']' to 57,
'}' to 1197,
'>' to 25137
)[this]
}
override fun runPartTwo(): String {
val scores = lines
.filter { line -> line.incomplete() }
.map { line -> line.missingString() }
.map { missingString -> missingString.score() }
return scores
.sorted()[scores.size / 2]
.toString()
}
private fun String.score(): Long {
val scores = mapOf(
')' to 1,
']' to 2,
'}' to 3,
'>' to 4,
)
return this
.toCharArray()
.fold(0) { mul, char ->
mul * 5 + scores[char]!!
}
}
class Line(private val line: String) {
private val matchingChunks = mapOf(
'{' to '}',
'(' to ')',
'<' to '>',
'[' to ']'
)
fun firstIllegalCharacter(): Char? {
try {
openChunks()
} catch (e: CorruptedLine) {
return e.lastCharacter
}
return null
}
fun incomplete() : Boolean {
return try {
openChunks().isNotEmpty()
} catch (e: Exception) {
false
}
}
fun missingString(): String {
val openedChunks = openChunks()
return openedChunks
.reversed()
.map { it.oppositeChunk()!! }
.joinToString(separator = "")
}
private fun openChunks(): List<Char> {
val openedChunks = mutableListOf<Char>()
line.toCharArray()
.forEach { char ->
if (char.isOpeningChunk()) {
openedChunks.add(char)
} else {
val lastOpenedChunk = openedChunks.removeLast()
if (!lastOpenedChunk.matches(char)) {
throw CorruptedLine(char, "Corrupted line: $line")
}
}
}
return openedChunks
}
private fun Char.matches(other: Char): Boolean {
return matchingChunks[this] == other
}
private fun Char.isOpeningChunk(): Boolean {
return matchingChunks.keys.any { it == this }
}
private fun Char.oppositeChunk(): Char? {
return matchingChunks[this]
}
private class CorruptedLine(val lastCharacter: Char, message: String?) : Exception(message)
}
}
| 0 |
Kotlin
| 0 | 0 |
93363faee195d5ef90344a4fb74646d2d26176de
| 3,090 |
AdventOfCode2021
|
MIT License
|
src/main/kotlin/dev/shtanko/algorithms/interview/BinaryTreeNode.kt
|
ashtanko
| 203,993,092 | false |
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
|
/*
* Copyright 2020 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.interview
import java.util.Random
@Suppress("UnnecessaryParentheses")
class BinaryTreeNode(private val parent: BinaryTreeNode? = null) {
val left: WeightedTree = WeightedTree()
val right: WeightedTree = WeightedTree()
fun getRandom(getBetween: (range: IntRange) -> Int = { range -> range.random() }): BinaryTreeNode {
val n = right.weight + left.weight
val local = left.weight + right.weight + 1
return when (getBetween(0 until local)) {
in (0 until left.weight) -> left.child?.getRandom(getBetween)
?: throw IllegalStateException("BinaryTreeNode is null")
in (left.weight until n) -> right.child?.getRandom(getBetween)
?: throw IllegalStateException("BinaryTreeNode is null")
else -> this
}
}
fun addLeftChild(newLeftChild: BinaryTreeNode) {
require(newLeftChild.parent == this)
left.addChild(newLeftChild)
updateParents()
}
fun addRightChild(newRightChild: BinaryTreeNode) {
require(newRightChild.parent == this)
right.addChild(newRightChild)
updateParents()
}
private fun updateParents() {
if (parent == null) {
return
}
when {
this == parent.right.child -> parent.right.weight++
this == parent.left.child -> parent.left.weight++
}
return parent.updateParents()
}
}
class WeightedTree {
var weight: Int = 0
var child: BinaryTreeNode? = null
private set
fun addChild(binaryTreeNode: BinaryTreeNode) {
child = binaryTreeNode
weight++
}
}
fun IntRange.random() =
Random().nextInt(endInclusive.plus(1).minus(start)) + start
| 4 |
Kotlin
| 0 | 19 |
776159de0b80f0bdc92a9d057c852b8b80147c11
| 2,377 |
kotlab
|
Apache License 2.0
|
simpleCalculator/Main.kt
|
victorYghor
| 610,409,660 | false | null |
package calculator
val numbers = mutableListOf<Int>()
fun Char.isOperator(): Boolean {
return this == '+' || this == '-'
}
fun start() {
val input = readln().split(' ').joinToString("")
when (input) {
"" -> start()
"/exit" -> throw Exception()
"/help" -> println(
"""The program does the following operations:
sum(+) -> 1 + 3 = 4
subtract(-) -> 3 - 2 = 1
mix operations -> -3 -- 1 +++ 3 -15 = -14
""".trimIndent()
)
else -> fixLine(input)
}
start()
}
fun computePlusMinus(operator1: Char, operator2: Char): Char {
if (operator1 == operator2) {
return '+'
} else {
return '-'
}
}
fun fixLine(line: String) {
var awryLine = line
do {
var operator: Char? = null
do {
var first = awryLine[0]
val second: Char
if (1 <= awryLine.lastIndex && awryLine[1].isOperator() && first.isOperator()) {
second = awryLine[1]
awryLine = awryLine.drop(2)
awryLine = computePlusMinus(first, second) + awryLine
first = awryLine[0]
} else if (first.isOperator()) {
operator = first
awryLine = awryLine.removePrefix(first.toString())
first = awryLine[0]
}
} while (first.digitToIntOrNull() == null)
val numberPattern = Regex("((-?)|(\\+?))?\\d+")
val positionNumber = numberPattern.find(awryLine)
if (positionNumber != null) {
val number = awryLine.substring(positionNumber.range)
val numberAndOperator = if (operator == '-') '-' + number else number
numbers.add(numberAndOperator.toInt())
awryLine = awryLine.removePrefix(number)
}
} while (awryLine.length != 0)
compute()
}
fun compute() {
println(numbers.sum())
numbers.clear()
}
fun getNumbers(input: String): MutableList<Int> {
val numbers = mutableListOf<Int>()
input.split(' ').forEach { numbers.add(it.toInt()) }
return numbers
}
fun main() {
try {
start()
} catch (e: Exception) {
println("Bye!")
}
}
| 0 |
Kotlin
| 0 | 0 |
0d30e37016cd2158d87de59f7cf17125627fc785
| 2,230 |
Kotlin-Problems
|
MIT License
|
src/main/kotlin/com/kishor/kotlin/algo/algorithms/tree/InSufficientPath.kt
|
kishorsutar
| 276,212,164 | false | null |
package com.kishor.kotlin.algo.algorithms.tree
class TreeNode(var `val`: Int) {
var left: TreeNode? = null
var right: TreeNode? = null
}
fun sufficientSubset(root: TreeNode, limit: Int): TreeNode? {
calculate(root, limit, 0)
return if (root.`val` < limit && root.left == null && root.right == null) null else root
}
fun calculate(root: TreeNode?, limit: Int, sum: Int): Boolean {
var sum = sum
if (root == null) return true
if (sum + root.`val` < limit && root.left == null && root.right == null) return true
if (sum + root.`val` >= limit && root.left == null && root.right == null) return false
sum = sum + root.`val`
val left = calculate(root.left, limit, sum)
val right = calculate(root.right, limit, sum)
if (left) {
root.left = null
}
if (right) {
root.right = null
}
return left && right
}
fun singleNonDuplicate(nums: IntArray): Int {
var lo = 0
var hi = nums.size - 1
while (lo < hi) {
val mid = lo + (hi - lo) / 2
val halvesAreEven = (hi - mid) % 2 == 0
if (nums[mid + 1] == nums[mid]) {
if (halvesAreEven) {
lo = mid + 2
} else {
hi = mid - 1
}
} else if (nums[mid - 1] == nums[mid]) {
if (halvesAreEven) {
hi = mid - 2
} else {
lo = mid + 1
}
} else {
return nums[mid]
}
}
return nums[lo]
}
| 0 |
Kotlin
| 0 | 0 |
6672d7738b035202ece6f148fde05867f6d4d94c
| 1,581 |
DS_Algo_Kotlin
|
MIT License
|
algorithm/src/main/java/com/danny/algorithm/RepeatNumber.kt
|
dannycx
| 310,445,112 | false |
{"Kotlin": 90927, "Java": 34893, "AIDL": 319}
|
package com.danny.algorithm
/**
*
* @author danny
* @since 2022/4/11
*/
fun main() {
// println(repeatNumber(intArrayOf(0, 2, 4, 4, 7 , 6, 5, 3)))
// println(repeatNumberTwo(intArrayOf(1, 2, 5, 4, 3 , 6, 5, 3)))
// println(Math.pow(2.0, 3.0))
Test.x3()
}
/**
*/
fun repeatNumber(array: IntArray?) : Int {
when(val length = array?.size ?: 0) {
0 -> return -1
else -> {
for (index in 0 until length) {
if (array!![index] < 0 || array[index] > length - 1) {
return -1
}
}
for (index in 0 until length) {
while (array!![index] != index) {
if (array[index] == array[array[index]]) {
return array[index]
}
// 异或
val temp = array[index]
array[index] = array[index] xor array[temp]
array[temp] = array[index] xor array[temp]
array[index] = array[index] xor array[temp]
}
}
return -1
}
}
}
/**
* 长度为n+1数组,数字范围1 ~ n,求重复数字
*/
fun repeatNumberTwo(array: IntArray?) : Int {
when(val length = array?.size ?: 0) {
0 -> return -1
else -> {
var start = 1
var end = length - 1
while (start <= end) {
// 右移
val middle = ((end - start) shr 1) + start
val count = getCount(array!!, length, start, middle)
if (start == end) {
if (count > 1) {
return start
} else {
break
}
}
if (count > middle - start + 1) {
end = middle
} else {
start = middle + 1
}
}
return -1
}
}
}
fun getCount(array: IntArray, length: Int, start: Int, end: Int): Int {
var count = 0
for (index in 0 until length) {
if (array[index] in start..end) {
count++
}
}
return count
}
| 0 |
Kotlin
| 0 | 0 |
5fbfd4a5db1849d67817364b73f9c9e9b16a2e72
| 2,249 |
XTools
|
Apache License 2.0
|
src/main/kotlin/dev/shtanko/algorithms/leetcode/ZigzagLevelOrder.kt
|
ashtanko
| 203,993,092 | false |
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
|
/*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import java.util.LinkedList
import java.util.Queue
/**
* 103. Binary Tree Zigzag Level Order Traversal
* @see <a href="https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/">Source</a>
*/
fun interface ZigzagLevelOrder {
operator fun invoke(root: TreeNode?): List<List<Int>>
}
class ZigzagLevelOrderQueue : ZigzagLevelOrder {
override operator fun invoke(root: TreeNode?): List<List<Int>> {
val queue: Queue<TreeNode> = LinkedList()
queue.add(root)
val res: MutableList<List<Int>> = ArrayList()
if (root == null) return res
var sub: MutableList<Int>
var level = 0
while (queue.isNotEmpty()) {
val size: Int = queue.size
sub = ArrayList()
for (i in 0 until size) {
val temp: TreeNode = queue.remove()
sub.add(temp.value)
if (temp.left != null) queue.add(temp.left)
if (temp.right != null) queue.add(temp.right)
}
if (level % 2 != 0) sub.reverse()
level++
res.add(sub)
}
return res
}
}
| 4 |
Kotlin
| 0 | 19 |
776159de0b80f0bdc92a9d057c852b8b80147c11
| 1,781 |
kotlab
|
Apache License 2.0
|
src/Day01.kt
|
ph-pdy
| 572,944,630 | false |
{"Kotlin": 1269}
|
fun main() {
fun part1(input: List<String>): Int =
input.sumCalories().max()
fun part2(input: List<String>): Int =
input.sumCalories().apply { sortDescending() }.take(3).sum()
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 1)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
fun List<String>.sumCalories() =
fold(mutableListOf(0)) { acc, s ->
if (s.isEmpty()) acc.add(0)
else acc[acc.lastIndex] = acc.last() + s.toInt()
acc
}
| 0 |
Kotlin
| 0 | 0 |
0559ae99769dbc20e12c5597c7888eda99b8d989
| 626 |
advent-of-code
|
Apache License 2.0
|
src/day02/Day02.kt
|
schrami8
| 572,631,109 | false |
{"Kotlin": 18696}
|
package day02
import readInput
fun main() {
val precalculated = hashMapOf(
"A X" to 4,
"A Y" to 8,
"A Z" to 3,
"B X" to 1,
"B Y" to 5,
"B Z" to 9,
"C X" to 7,
"C Y" to 2,
"C Z" to 6
)
fun part1(input: List<String>): Int {
return input.sumOf {
precalculated.get(it)!!
}
}
val precalculated2 = hashMapOf(
"A X" to 3,
"A Y" to 4,
"A Z" to 8,
"B X" to 1,
"B Y" to 5,
"B Z" to 9,
"C X" to 2,
"C Y" to 6,
"C Z" to 7
)
fun part2(input: List<String>): Int {
return input.sumOf {
precalculated2.get(it)!!
}
}
// test if implementation meets criteria from the description, like:
//val testInput = readInput("Day01_test")
//check(part1(testInput) == 1)
val input = readInput("day02/Day02")
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
| 0 | 0 |
215f89d7cd894ce58244f27e8f756af28420fc94
| 988 |
advent-of-code-kotlin
|
Apache License 2.0
|
src/main/kotlin/io/array/VerifyIsSorted.kt
|
jffiorillo
| 138,075,067 | false |
{"Kotlin": 434399, "Java": 14529, "Shell": 465}
|
package io.array
import io.utils.runTests
// https://leetcode.com/problems/verifying-an-alien-dictionary/
class VerifyIsSorted {
fun isAlienSorted(words: Array<String>, order: String): Boolean = execute(words, order)
fun execute(words: Array<String>, order: String): Boolean {
val orderMap = order.mapIndexed { index, value -> value to index }.toMap()
words.reduce { acc, item ->
if (orderMap.isNotOrdered(acc, item)) return false
item
}
return true
}
private fun Map<Char, Int>.isNotOrdered(word0: String, word1: String): Boolean = !isOrdered(word0, word1)
private fun Map<Char, Int>.isOrdered(word0: String, word1: String): Boolean {
var index = 0
var found = false
while (index < word0.length && index < word1.length) {
val orderCharAcc = this.getValue(word0[index])
val orderCharItem = this.getValue(word1[index])
if (orderCharAcc < orderCharItem) {
found = true
break
} else if (orderCharAcc == orderCharItem) {
index++
} else {
return false
}
}
if (!found && word0.length > word1.length) {
return false
}
return true
}
}
fun main() {
runTests(listOf(
Triple(arrayOf("apple", "app"), "abcdefghijklmnopqrstuvwxyz", false)
)) { (input, order, value) ->
value to VerifyIsSorted().execute(input, order)
}
}
| 0 |
Kotlin
| 0 | 0 |
f093c2c19cd76c85fab87605ae4a3ea157325d43
| 1,371 |
coding
|
MIT License
|
y2022/src/main/kotlin/adventofcode/y2022/Day21.kt
|
Ruud-Wiegers
| 434,225,587 | false |
{"Kotlin": 503769}
|
package adventofcode.y2022
import adventofcode.io.AdventSolution
object Day21 : AdventSolution(2022, 21, "Monkey Math") {
override fun solvePartOne(input: String): Long {
val instructions = mutableMap(input)
return instructions.getValue("root")()
}
override fun solvePartTwo(input: String): Long {
val instructions = mutableMap(input)
val target = instructions.getValue("hghd")()
return generateSequence(1L to 10_000_000_000_000) { (low, high) ->
val mid = (low + high) / 2
instructions["humn"] = { mid }
val new = instructions.getValue("zhfp")()
if (new > target) mid to high else low to mid
}
.first { it.first + 1 >= it.second }
.second
}
private fun mutableMap(input: String): MutableMap<String, () -> Long> {
val instructions = mutableMapOf<String, () -> Long>()
input.lineSequence().forEach {
val (name, instr) = it.split(": ")
val constant = instr.toLongOrNull()
instructions[name] = if (constant != null) {
{ constant }
} else {
val (lhs, op, rhs) = instr.split(" ")
val operator: (Long, Long) -> Long = when (op) {
"+" -> Long::plus
"-" -> Long::minus
"*" -> Long::times
"/" -> Long::div
else -> throw IllegalArgumentException(op)
}
{ operator(instructions.getValue(lhs)(), instructions.getValue(rhs)()) }
}
}
return instructions
}
}
| 0 |
Kotlin
| 0 | 3 |
fc35e6d5feeabdc18c86aba428abcf23d880c450
| 1,680 |
advent-of-code
|
MIT License
|
games-core/src/main/kotlin/net/zomis/games/dsl/DslSplendor.kt
|
Tejpbit
| 260,966,032 | true |
{"Kotlin": 395303, "Vue": 83692, "JavaScript": 27193, "Java": 17130, "CSS": 3871, "HTML": 1358, "Dockerfile": 228}
|
package net.zomis.games.dsl
data class Player(var chips: Money = Money(), val owned: MutableSet<Card> = mutableSetOf(),
val reserved: MutableSet<Card> = mutableSetOf()) {
fun total(): Money = this.discounts() + this.chips
fun canBuy(card: Card): Boolean = this.total().has(card.costs)
fun buy(card: Card) {
val actualCost = card.costs.minus(this.discounts())
this.chips -= actualCost
this.owned.add(card)
}
fun discounts(): Money {
return this.owned.map { it.discounts }.fold(Money()) { acc, money -> acc + money }
}
}
data class Card(val level: Int, val discounts: Money, val costs: Money, val points: Int) {
// Possible to support multiple discounts on the same card. Because why not!
constructor(level: Int, discount: MoneyType, costs: Money, points: Int):
this(level, Money(discount to 1), costs, points)
}
fun <K, V> Map<K, V>.mergeWith(other: Map<K, V>, merger: (V?, V?) -> V): Map<K, V> {
return (this.keys + other.keys).associateWith {
merger(this[it], other[it])
}
}
enum class MoneyType {
BLACK, WHITE, RED, BLUE, GREEN;
fun toMoney(count: Int): Money {
return Money(mutableMapOf(this to count))
}
}
data class Money(val moneys: MutableMap<MoneyType, Int> = mutableMapOf()) {
// TODO: Add wildcards as a separate field
constructor(vararg money: Pair<MoneyType, Int>) : this(mutableMapOf<MoneyType, Int>(*money))
operator fun plus(other: Money): Money {
val result = moneys.mergeWith(other.moneys) {a, b -> (a ?: 0) + (b ?: 0)}
return Money(result.toMutableMap())
}
fun has(costs: Money): Boolean = costs.moneys.entries.all { it.value <= this.moneys[it.key] ?: 0 }
operator fun minus(other: Money): Money {
val result = moneys.mergeWith(other.moneys) {a, b -> (a ?: 0) - (b ?: 0)}.mapValues {
if (it.value < 0) 0 else it.value
}
return Money(result.toMutableMap())
}
}
data class MoneyChoice(val moneys: List<MoneyType>) {
fun toMoney(): Money {
return Money(moneys.groupBy { it }.mapValues { it.value.size }.toMutableMap())
}
}
fun startingStockForPlayerCount(playerCount: Int): Int {
return 10
}
class SplendorGame(playerCount: Int = 2) {
// TODO: Add nobles
val cardLevels = 1..3
private fun randomType(): MoneyType {
return MoneyType.values().toList().shuffled().first()
}
private fun randomCard(level: Int): Card {
return Card(level, randomType(), Money(randomType() to level * 2), level)
}
val players: List<Player> = (1..playerCount).map { Player() }
val board: MutableList<Card> = mutableListOf()
val deck: MutableList<Card> = cardLevels.flatMap { level ->
(0 until 30).map { randomCard(level) }
}.toMutableList()
var stock: Money = MoneyType.values().fold(Money()) {money, type -> money + type.toMoney(startingStockForPlayerCount(playerCount))}
var currentPlayerIndex: Int = 0
init {
cardLevels.forEach {level ->
(1..4).forEach { _ ->
val card = deck.find { it.level == level }
if (card != null) {
deck.remove(card)
board.add(card)
}
}
}
}
val currentPlayer: Player
get() = this.players[this.currentPlayerIndex]
fun replaceCard(card: Card) {
val index = board.indexOf(card)
if (index < 0) {
throw IllegalArgumentException("Card does not exist on board: $card")
}
val nextCard = deck.firstOrNull { it.level == card.level }
if (nextCard != null) {
board[index] = nextCard
} else {
board.removeAt(index)
}
}
}
class DslSplendor {
val buy = createActionType("buy", Card::class)
val takeMoney = createActionType("takeMoney", MoneyChoice::class)
val reserve = createActionType("reserve", Card::class)
val discardMoney = createActionType("discardMoney", MoneyType::class)
val splendorGame = createGame<SplendorGame>("Splendor") {
setup {
// players(2..4)
init {
SplendorGame()
}
// effect {
// state("cards", game.board)
// }
// replay {
// game.board = state("cards")
// }
}
logic {
singleTarget(buy, {it.board}) { // Is it possible to use API as `buy.singleTarget(game.board)` ?
allowed { it.game.currentPlayer.canBuy(it.parameter) }
effect {
it.game.currentPlayer.buy(it.parameter)
state("nextCard", it.game.replaceCard(it.parameter))
}
// replayEffect {
// it.game.currentPlayer.buy(it.parameter)
// it.game.replaceCard(it.parameter, state("nextCard") as Card)
// }
}
// singleTarget(discardMoney, {MoneyType.values().toList()}) {
// allowed { it.game.currentPlayer.chips.count > 10 }
// effect { it.game.currentPlayer.money -= choice }
// }
// singleTarget(reserve, {it.board}) {
// allowed { it.game.currentPlayer.reserved.size < 3 }
// effect {
// it.game.currentPlayer.reserve(it.parameter)
// state("nextCard", replaceCard(it.parameter))
// }
// replayEffect {
// it.game.currentPlayer.reserve(it.parameter)
// replaceCard(it.parameter, state("nextCard"))
// }
// }
action(takeMoney) {
options {
option(MoneyType.values().asIterable()) { first ->
option(MoneyType.values().asIterable()) {second ->
if (first == second) {
actionParameter(MoneyChoice(listOf(first, second)))
} else {
option(MoneyType.values().asIterable()) {third ->
actionParameter(MoneyChoice(listOf(first, second, third)))
}
}
}
}
}
allowed {
val moneyChosen = it.parameter.toMoney()
if (!it.game.stock.has(moneyChosen)) {
return@allowed false
}
val chosen = it.parameter.moneys
return@allowed when {
chosen.size == 2 -> chosen.distinct().size == 1 && it.game.stock.has(moneyChosen.plus(moneyChosen))
chosen.size == 3 -> chosen.distinct().size == chosen.size
else -> false
}
}
effect {
it.game.stock -= it.parameter.toMoney()
it.game.currentPlayer.chips += it.parameter.toMoney()
}
}
}
fun viewMoney(money: Money): List<Pair<String, Int>> {
return money.moneys.entries.sortedBy { it.key.name }.map { it.key.name to it.value }
}
fun viewCard(card: Card): Map<String, Any?> {
// TODO: Test without this special mapping function. Perhaps it works anyway?
return mapOf(
"level" to card.level,
"discount" to card.discounts,
"costs" to card.costs,
"points" to card.points
)
}
view {
currentPlayer { it.currentPlayerIndex }
// winner { game -> game.winner.takeIf { game.isFinished } }
value("board") {game ->
game.board.map { viewCard(it) }
}
value("stock") {game ->
game.stock
}
value("players") {game ->
game.players.map {
mapOf(
"money" to it.chips,
"cards" to it.owned,
"reserved" to it.reserved.size // TODO: Add possibility for that player to see this card
)
}
}
}
}
}
| 0 | null | 0 | 0 |
cb1cafb4d5ae5c09a9edb336f04ef7cf48ee2714
| 8,421 |
Server2
|
MIT License
|
Contiguous_Array.kt
|
xiekch
| 166,329,519 | false |
{"C++": 165148, "Java": 103273, "Kotlin": 97031, "Go": 40017, "Python": 22302, "TypeScript": 17514, "Swift": 6748, "Rust": 6579, "JavaScript": 4244, "Makefile": 349}
|
import kotlin.math.max
class Solution {
fun findMaxLength(nums: IntArray): Int {
if (nums.size <= 1) return 0
val minIndex = HashMap<Int, Int>()
minIndex[0] = -1
var count = if (nums[0] == 1) 1 else -1
minIndex[count] = 0
var longestLength = 0
for (i in 1..nums.lastIndex) {
count += if (nums[i] == 1) 1 else -1
if (!minIndex.containsKey(count)) minIndex[count] = i
else longestLength = max(longestLength, i - minIndex[count]!!)
}
return longestLength
}
}
fun main() {
val solution = Solution()
val testCases = arrayOf(intArrayOf(1, 0), intArrayOf(1, 0, 1, 0, 1), intArrayOf(1, 1, 0, 1, 0, 1), intArrayOf(1, 1, 1, 1, 0))
for (case in testCases) {
println(solution.findMaxLength(case))
}
}
| 0 |
C++
| 0 | 0 |
eb5b6814e8ba0847f0b36aec9ab63bcf1bbbc134
| 831 |
leetcode
|
MIT License
|
app/src/test/java/com/edgar/movie/demo_study/collections/CollectionFunctionInKotlin.kt
|
edgardeng
| 267,626,303 | false | null |
import org.junit.Test
class CollectionFunctionInKotlin {
@Test
fun main (){
// filter function enables you to filter collections
val numbers = listOf(1, -2, 3, -4, 5, -6) // 1
val positives = numbers.filter { x -> x > 0 } // 2
val negatives = numbers.filter { it < 0 } // 3
println(positives)
println(negatives)
// map extension function enables you to apply a transformation to all elements in a collection.
// val numbers = listOf(1, -2, 3, -4, 5, -6) // 1
val doubled = numbers.map { x -> x * 2 } // 2
val tripled = numbers.map { it * 3 }
println(doubled)
println(tripled)
// any returns true if the collection contains at least one element that matches the given predicate.
val anyNegative = numbers.any { it < 0 } // 2
val anyGT6 = numbers.any { it > 6 }
println(anyNegative)
println(anyGT6 )
// Function all returns true if all elements in collection match the given predicate.
val allEven = numbers.all { it % 2 == 0 } // 2
val allLess6 = numbers.all { it < 6 }
// Function none returns true if there are no elements that match the given predicate in the collection.
val allEven2 = numbers.none { it % 2 == 1 } // 2
val allLess2 = numbers.none { it > 6 }
// find and findLast functions return the first or the last collection element that matches the given predicate. If there are no such elements, functions return null.
val words = listOf("Lets", "find", "something", "in", "collection", "somehow") // 1
val first = words.find { it.startsWith("some") } // 2
val last = words.findLast { it.startsWith("some") } // 3
val nothing = words.find { it.contains("nothing") }
// first, last:These functions return the first and the last element of the collection correspondingly
val firstNum = numbers.first() // 2
val lastNum = numbers.last() // 3
val firstEven = numbers.first { it % 2 == 0 } // 4
val lastOdd = numbers.last { it % 2 != 0 }
// count functions returns either the total number of elements
val totalCount = numbers.count() // 2
val evenCount = numbers.count { it % 2 == 0 }
// Functions associateBy and groupBy build maps from the elements of a collection indexed by the specified key.
// associateBy uses the last suitable element as the value
// groupBy builds a list of all suitable elements and puts it in the value
data class Person(val name: String, val city: String, val phone: String) // 1
val people = listOf( // 2
Person("John", "Boston", "+1-888-123456"),
Person("Sarah", "Munich", "+49-777-789123"),
Person("Svyatoslav", "Saint-Petersburg", "+7-999-456789"),
Person("Vasilisa", "Saint-Petersburg", "+7-999-123456"))
val phoneBook = people.associateBy { it.phone } // 3
val cityBook = people.associateBy(Person::phone, Person::city) // 4
val peopleCities = people.groupBy(Person::city, Person::name) // 5
println("--associateBy ")
println(phoneBook)
println("--associateBy ")
println(cityBook)
println("--groupBy ")
println(peopleCities)
// partition function splits the original collection
val evenOdd = numbers.partition { it % 2 == 0 } // 2 Splits numbers into a Pair of lists with even and odd numbers.
val (positives2, negatives2) = numbers.partition { it > 0 }
println()
println(evenOdd) // ([-2, -4, -6], [1, 3, 5])
println()
println(positives2)
println(negatives2)
// flatMap transforms each element of a collection into an iterable object and builds a single list of the transformation results
val tripled2 = numbers.flatMap { listOf(it, it, it) }
println(numbers.flatMap { listOf(it, it *it) })
// min and max functions
val empty = emptyList<Int>()
println("Numbers: $numbers, min = ${numbers.min()} max = ${numbers.max()}") // 1
println("Empty: $empty, min = ${empty.min()}, max = ${empty.max()}") // For empty collections both functions return null.
// sorted
println("Soroted: ${ numbers.sorted()}")
val inverted = numbers.sortedBy { -it }
val pow = numbers.sortedBy { it*it }
println("Soroted: ${ inverted}")
println("Soroted: ${ pow}")
// Map Element Access
val map = mapOf("key" to 42)
val value1 = map["key"] // 1
val value2 = map["key2"] // 2
val value3: Int = map.getValue("key") // getValue function returns an existing value corresponding to the given key or throws an exception if the key wasn't found. For maps created with withDefault
val mapWithDefault = map.withDefault { k -> k.length } // 设置默认值
val value4 = mapWithDefault.getValue("key2") // 3
try {
map.getValue("anotherKey") // 4
} catch (e: NoSuchElementException) {
println("Message: $e")
}
// zip function merges two given collections into a new collection
val A = listOf("a", "b", "c") // 1
val B = listOf(1, 2) // 1
// zip 不能变长
val resultPairs = A zip B // 2
val resultReduce = A.zip(B) { a, b -> "$a$b" }
val resultlist = A.zip(B) { a, b -> listOf(a,b) }
println("resultPairs: ${resultPairs}, resultReduce: ${resultReduce}, ")
println(resultlist)
//getOrElse provides safe access to elements of a collection.
val list = listOf(0, 10, 20)
println(list.getOrElse(1) { 42 }) // 1
println(list.getOrElse(10) { 42 })
val map3 = mutableMapOf<String, Int?>()
println(map3.getOrElse("x") { 1 }) // 1
map3["x"] = 3
println(map3.getOrElse("x") { 1 }) // 2
map3["x"] = null
println(map3.getOrElse("x") { 1 })
}
}
| 0 |
Kotlin
| 1 | 4 |
d8b3f740d2f564817ac1ffebe000f952cb175361
| 6,576 |
good-kotlin-app
|
MIT License
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.