path stringlengths 5 169 | owner stringlengths 2 34 | repo_id int64 1.49M 755M | is_fork bool 2
classes | languages_distribution stringlengths 16 1.68k ⌀ | content stringlengths 446 72k | issues float64 0 1.84k | main_language stringclasses 37
values | forks int64 0 5.77k | stars int64 0 46.8k | commit_sha stringlengths 40 40 | size int64 446 72.6k | name stringlengths 2 64 | license stringclasses 15
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/Day3.kt | devPalacio | 574,493,024 | false | {"Kotlin": 8009, "Python": 1346} | import java.io.File
import java.lang.Exception
fun main() {
val input = File("src/day3.txt").readLines()
val compartmented = input.map {
it.chunked(it.length / 2).map(String::toSet)
}
val elvesGrouped = input.chunked(3).map{it.map(String::toSet)}
fun findBadge(group: List<Set<Char>>) : Char =
(group[0] intersect group[1] intersect group[2]).first()
fun findDupeItem(bag: List<Set<Char>>): Char = (bag[0] intersect bag[1]).first()
fun letterToPriority(letter: Char): Int {
return when (letter.code) {
in 97..122 -> letter.code - 96
in 65..90 -> letter.code - 38
else -> throw Exception("Not a valid char")
}
}
val answer = compartmented
.map(::findDupeItem)
.map(::letterToPriority)
.sum()
val part2 = elvesGrouped
.map(::findBadge)
.map(::letterToPriority)
.sum()
println(answer)
print(part2)
}
| 0 | Kotlin | 0 | 0 | 648755244e07887335d05601b5fe78bdcb8b1baa | 995 | AoC-2022 | Apache License 2.0 |
src/chapter2/problem7/solution1.kts | neelkamath | 395,940,983 | false | null | /*
Question:
Intersection: Given two (singly) linked lists, determine if the two lists intersect. Return the intersecting node. Note
that the intersection is defined based on reference, not value. That is, if the kth node of the first linked list is the
exact same node (by reference) as the jth node of the second linked list, then they are intersecting.
Answer:
Using an additional data structure.
*/
class LinkedListNode<T>(var data: T, var next: LinkedListNode<T>? = null) {
/** Returns either the intersecting node or `null` if there's no intersection. */
fun findIntersection(node: LinkedListNode<T>): LinkedListNode<T>? {
val set = mutableSetOf<LinkedListNode<T>>()
var node1: LinkedListNode<T>? = this
var node2: LinkedListNode<T>? = node
while (node1 != null || node2 != null) {
if (node1 in set) return node1 else if (node1 != null) set.add(node1)
if (node2 in set) return node2 else if (node2 != null) set.add(node2)
node1 = node1?.next
node2 = node2?.next
}
return null
}
override fun toString(): String {
val builder = StringBuilder()
var node: LinkedListNode<T>? = this
while (node != null) {
if (!builder.isEmpty()) builder.append("->")
builder.append(node.data)
node = node.next
}
builder.insert(0, "[")
builder.append("]")
return builder.toString()
}
}
fun <T> printIntersection(list1: LinkedListNode<T>, list2: LinkedListNode<T>): Unit =
println("List 1: $list1\nList 2: $list2\nIntersection: ${list1.findIntersection(list2)?.data}")
run {
val list1 = LinkedListNode(
1,
)
val list2 = LinkedListNode(
1,
)
printIntersection(list1, list2)
}
run {
val list1 = LinkedListNode(
1,
LinkedListNode(
2,
),
)
val list2 = LinkedListNode(
1,
LinkedListNode(
2,
LinkedListNode(
3,
),
),
)
printIntersection(list1, list2)
}
run {
val intersectingNode = LinkedListNode(
2,
LinkedListNode(
3,
),
)
val list1 = LinkedListNode(
1,
intersectingNode,
)
val list2 = LinkedListNode(
1,
intersectingNode,
)
printIntersection(list1, list2)
}
run {
val intersectingNode = LinkedListNode(
2,
LinkedListNode(
3,
),
)
val list1 = LinkedListNode(
100,
LinkedListNode(
200,
LinkedListNode(
300,
intersectingNode,
),
),
)
val list2 = LinkedListNode(
1,
intersectingNode,
)
printIntersection(list1, list2)
}
| 0 | Kotlin | 0 | 0 | 4421a061e5bf032368b3f7a4cee924e65b43f690 | 2,850 | ctci-practice | MIT License |
src/main/kotlin/aoc2020/day03_toboggan_trajectory/TobogganTrajectory.kt | barneyb | 425,532,798 | false | {"Kotlin": 238776, "Shell": 3825, "Java": 567} | package aoc2020.day03_toboggan_trajectory
fun main() {
util.solve(176, ::partOne)
util.solve(5872458240, ::partTwo)
}
fun partOne(input: String) =
input.lines().foldIndexed(0) { row, agg, line ->
if (line[row * 3 % line.length] == '#') agg + 1
else agg
}
fun partTwo(input: String) =
input.lines().foldIndexed(LongArray(5)) { row, agg, line ->
if (line[row * 1 % line.length] == '#') ++agg[0]
if (line[row * 3 % line.length] == '#') ++agg[1]
if (line[row * 5 % line.length] == '#') ++agg[2]
if (line[row * 7 % line.length] == '#') ++agg[3]
if (row % 2 == 0) {
if (line[(row / 2) % line.length] == '#') ++agg[4]
}
agg
}.reduce(Long::times)
| 0 | Kotlin | 0 | 0 | a8d52412772750c5e7d2e2e018f3a82354e8b1c3 | 750 | aoc-2021 | MIT License |
src/main/kotlin/aoc2015/Day20.kt | lukellmann | 574,273,843 | false | {"Kotlin": 175166} | package aoc2015
import AoCDay
import kotlin.math.sqrt
// https://adventofcode.com/2015/day/20
object Day20 : AoCDay<Int>(
title = "Infinite Elves and Infinite Houses",
part1Answer = 665280,
part2Answer = 705600,
) {
private fun divisors(n: Int) = buildSet {
for (divisor in 1..sqrt(n.toDouble()).toInt() + 1) {
if (n % divisor == 0) {
add(divisor)
add(n / divisor)
}
}
}
private inline fun lowestHouseNumber(minPresents: Int, presents: (house: Int, elves: Set<Int>) -> Int) =
(1..Int.MAX_VALUE).first { house ->
val elves = divisors(house)
presents(house, elves) >= minPresents
}
override fun part1(input: String) = lowestHouseNumber(
minPresents = input.toInt(),
presents = { _, elves -> elves.sum() * 10 },
)
override fun part2(input: String) = lowestHouseNumber(
minPresents = input.toInt(),
presents = { house, elves -> elves.sumOf { elf -> if (house / elf <= 50) elf else 0 } * 11 },
)
}
| 0 | Kotlin | 0 | 1 | 344c3d97896575393022c17e216afe86685a9344 | 1,082 | advent-of-code-kotlin | MIT License |
src/Day01.kt | isfaaghyth | 572,864,191 | false | {"Kotlin": 1561} | fun main() {
fun day01(input: List<String>): List<Int> {
val highers = mutableListOf<Int>()
var higher = 0
var temp = 0
for (i in input) {
if (i.isNotBlank()) {
temp += i.toInt()
} else {
if (temp > higher) {
higher = temp
highers.add(higher)
} else {
higher = 0
}
temp = 0
}
}
return highers
}
fun part1(input: List<String>): Int {
val result = day01(input)
return result.max()
}
fun part2(input: List<String>): Int {
val result = day01(input)
return result
.sortedDescending()
.take(3) // top three
.sum()
}
val input = readInput("day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | ccd5dc526296808cd43f54a9a49c389c383f4c5a | 920 | adventofcode | Apache License 2.0 |
toml/src/main/kotlin/org/rust/toml/crates/local/CrateVersionRequirement.kt | Kobzol | 174,706,351 | true | {"Kotlin": 8149163, "Rust": 119828, "Python": 80380, "Lex": 20075, "HTML": 18030, "Java": 1274, "Shell": 760, "RenderScript": 89} | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.toml.crates.local
import com.vdurmont.semver4j.Requirement
import com.vdurmont.semver4j.Semver
import com.vdurmont.semver4j.SemverException
class CrateVersionRequirement private constructor(private val requirements: List<Requirement>) {
fun matches(version: Semver): Boolean = requirements.all {
it.isSatisfiedBy(version)
}
companion object {
fun build(text: String): CrateVersionRequirement? {
val requirements = text.split(",").map { it.trim() }
if (requirements.size > 1 && requirements.any { it.isEmpty() }) return null
val parsed = requirements.mapNotNull {
try {
Requirement.buildNPM(normalizeVersion(it))
} catch (e: Exception) {
return@mapNotNull null
}
}
if (parsed.size != requirements.size) return null
return CrateVersionRequirement(parsed)
}
}
}
/**
* Normalizes crate version requirements so that they are compatible with semver4j.
*
* 1) For exact (=x.y.z) and range-based (>x.y.z, <x.y.z) version requirements, the version requirement is padded by
* zeros from the right side.
*
* Example:
* - `=1` turns into `=1.0.0`
* - `>2.3` turns into `>2.3.0`
*
* 2) For "compatible" version requirements (x.y.z) that do not contain a wildcard (*), a caret is added to the
* beginning. This matches the behaviour of Cargo.
*
* Example:
* - `1.2.3` turns into `^1.2.3`
*
* See [Cargo Reference](https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html#specifying-dependencies-from-cratesio).
*/
private fun normalizeVersion(version: String): String {
if (version.isBlank()) return version
// Exact and range-based version requirements need to be padded from right by zeros.
// Otherwise (if minor and/or patch version is missing), semver4j will match the requirement in a different way
// than Cargo.
var normalized = version
if (normalized[0] in listOf('<', '>', '=')) {
while (normalized.count { it == '.' } < 2) {
normalized += ".0"
}
}
// Cargo treats version requirements like `1.2.3` as if they had a caret at the beginning.
// If the version begins with a digit and it does not contain a wildcard, we thus prepend a caret to it.
return if (normalized[0].isDigit() && !normalized.contains("*")) {
"^$normalized"
} else {
normalized
}
}
| 1 | Kotlin | 0 | 4 | 7d5f70bcf89dcc9c772efbeecf20fea7b0fb331e | 2,628 | intellij-rust | MIT License |
2023/src/main/kotlin/de/skyrising/aoc2023/day9/solution.kt | skyrising | 317,830,992 | false | {"Kotlin": 411565} | package de.skyrising.aoc2023.day9
import de.skyrising.aoc.*
import it.unimi.dsi.fastutil.ints.IntList
inline fun generate(list: IntList, pick: IntList.()->Int): IntList {
var splitPoint = list.size
while (true) {
list[splitPoint - 1] = pick(list.subList(0, splitPoint))
splitPoint--
var allZero = true
for (i in 0 until splitPoint) {
val diff = list.getInt(i + 1) - list.getInt(i)
list[i] = diff
if (diff != 0) allZero = false
}
if (allZero) return list.subList(splitPoint, list.size)
}
}
val test = TestInput("""
0 3 6 9 12 15
1 3 6 10 15 21
10 13 16 21 30 45
""")
@PuzzleName("Mirage Maintenance")
fun PuzzleInput.part1() = lines.sumOf {
generate(it.ints()) { getInt(lastIndex) }.sum()
}
fun PuzzleInput.part2() = lines.sumOf {
generate(it.ints()) { getInt(0) }.reduce { a, b -> b - a }
}
| 0 | Kotlin | 0 | 0 | 19599c1204f6994226d31bce27d8f01440322f39 | 912 | aoc | MIT License |
src/Day06.kt | shoresea | 576,381,520 | false | {"Kotlin": 29960} | fun main() {
fun part1(inputs: List<String>): Int {
return getMarker(inputs[0], 4)
}
fun part2(inputs: List<String>): Int {
return getMarker(inputs[0], 14)
}
val input = readInput("Day06")
part1(input).println()
part2(input).println()
}
fun getMarker(input: String, distinct: Int = 4): Int {
var l = 0
while (l <= input.lastIndex - (distinct - 1)) {
if (input.substring(l, l + distinct).hasUniqueChars()) {
break
}
l++
}
return l + distinct
}
fun String.hasUniqueChars(): Boolean = this.length == this.toCharArray().toSet().size
| 0 | Kotlin | 0 | 0 | e5d21eac78fcd4f1c469faa2967a4fd9aa197b0e | 629 | AOC2022InKotlin | Apache License 2.0 |
src/main/kotlin/g1501_1600/s1568_minimum_number_of_days_to_disconnect_island/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1501_1600.s1568_minimum_number_of_days_to_disconnect_island
// #Hard #Array #Depth_First_Search #Breadth_First_Search #Matrix #Strongly_Connected_Component
// #2023_06_14_Time_210_ms_(100.00%)_Space_35.9_MB_(100.00%)
@Suppress("kotlin:S107")
class Solution {
private val dirs = arrayOf(intArrayOf(0, 1), intArrayOf(0, -1), intArrayOf(1, 0), intArrayOf(-1, 0))
fun minDays(grid: Array<IntArray>): Int {
val m = grid.size
val n = grid[0].size
var numOfIslands = 0
var hasArticulationPoint = false
var color = 1
var minIslandSize = m * n
val time = Array(m) { IntArray(n) }
val low = Array(m) { IntArray(n) }
for (i in 0 until m) {
for (j in 0 until n) {
if (grid[i][j] == 1) {
numOfIslands++
color++
val articulationPoints: MutableList<Int> = ArrayList()
val islandSize = IntArray(1)
tarjan(i, j, -1, -1, 0, time, low, grid, articulationPoints, color, islandSize)
minIslandSize = Math.min(minIslandSize, islandSize[0])
if (articulationPoints.isNotEmpty()) {
hasArticulationPoint = true
}
}
}
}
if (numOfIslands >= 2) {
return 0
}
if (numOfIslands == 0) {
return 0
}
if (numOfIslands == 1 && minIslandSize == 1) {
return 1
}
return if (hasArticulationPoint) 1 else 2
}
private fun tarjan(
x: Int,
y: Int,
prex: Int,
prey: Int,
time: Int,
times: Array<IntArray>,
lows: Array<IntArray>,
grid: Array<IntArray>,
articulationPoints: MutableList<Int>,
color: Int,
islandSize: IntArray
) {
times[x][y] = time
lows[x][y] = time
grid[x][y] = color
islandSize[0]++
var children = 0
for (dir in dirs) {
val nx = x + dir[0]
val ny = y + dir[1]
if (nx < 0 || ny < 0 || nx >= grid.size || ny >= grid[0].size) {
continue
}
if (grid[nx][ny] == 1) {
children++
tarjan(
nx,
ny,
x,
y,
time + 1,
times,
lows,
grid,
articulationPoints,
color,
islandSize
)
lows[x][y] = Math.min(lows[x][y], lows[nx][ny])
if (prex != -1 && lows[nx][ny] >= time) {
articulationPoints.add(x * grid.size + y)
}
} else if ((nx != prex || ny != prey) && grid[nx][ny] != 0) {
lows[x][y] = Math.min(lows[x][y], times[nx][ny])
}
}
if (prex == -1 && children > 1) {
articulationPoints.add(x * grid.size + y)
}
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 3,135 | LeetCode-in-Kotlin | MIT License |
src/2023/Day24.kt | nagyjani | 572,361,168 | false | {"Kotlin": 369497} | package `2023`
import `2021`.sign
import java.io.File
import java.lang.RuntimeException
import java.math.BigInteger
import java.util.*
import kotlin.math.sign
fun main() {
Day24().solve()
}
class Day24 {
val input1 = """
19, 13, 30 @ -2, 1, -2
18, 19, 22 @ -1, -1, -2
20, 25, 34 @ -2, -2, -4
12, 31, 28 @ -1, -2, -1
20, 19, 15 @ 1, -5, -3
""".trimIndent()
val input2 = """
""".trimIndent()
class Hail3D(val p: List<Long>, val v: List<Long>)
class Hail2D(val x0: Long, val y0: Long, val vx: Long, val vy: Long) {
fun collides(other: Hail2D, min: Double, max: Double): Boolean {
val a = vy.toDouble() / vx.toDouble()
val b = (y0*vx - x0*vy).toDouble() / vx.toDouble()
val a1 = other.vy.toDouble() / other.vx.toDouble()
val b1 = (other.y0*other.vx - other.x0*other.vy).toDouble() / other.vx.toDouble()
val x = (b - b1) / (a1 - a)
val y = a * x + b
val t = (x-x0.toDouble()) / vx.toDouble()
val t1 = (x-other.x0.toDouble()) / other.vx.toDouble()
if (min > x || min > y || max < x || max < y || t < 0 || t1 < 0) {
return false
}
return true
}
}
fun String.toHail2D(): Hail2D {
val (x0, y0, vx, vy) = Regex("(\\w+), +(\\w+), +.+@ +([-\\d]+), +([-\\d]+)").find(this)!!.destructured
return Hail2D(x0.toLong(), y0.toLong(), vx.toLong(), vy.toLong())
}
fun String.toHail3D(): Hail3D {
val (x0, y0, z0, vx, vy, vz) = Regex("(\\w+), +(\\w+), +(\\w+).*@ +([-\\d]+), +([-\\d]+), +([-\\d]+)").find(this)!!.destructured
return Hail3D(listOf(x0.toLong(), y0.toLong(), z0.toLong()), listOf(vx.toLong(), vy.toLong(), vz.toLong()))
}
fun solve() {
val f = File("src/2023/inputs/day24.in")
val s = Scanner(f)
// val s = Scanner(input1)
// val s = Scanner(input2)
var sum = 0
var sum1 = 0
var lineix = 0
val lines = mutableListOf<String>()
val hails2d = mutableListOf<Hail2D>()
val hails3d = mutableListOf<Hail3D>()
val same = listOf(mutableMapOf<Int, Int>(),mutableMapOf<Int, Int>(),mutableMapOf<Int, Int>())
while (s.hasNextLine()) {
lineix++
val line = s.nextLine().trim()
if (line.isEmpty()) {
continue
}
lines.add(line)
hails2d.add(line.toHail2D())
hails3d.add(line.toHail3D())
(0..2).forEach{same[it][hails3d.last().v[it].toInt()] = same[it].getOrDefault(hails3d.last().v[it].toInt(), 0) + 1}
}
val ts = listOf(0 to 21, 0 to -88, 0 to -154, 0 to 63, 1 to -18, 1 to -36, 1 to -12, 1 to -81,
2 to 8, 2 to -59, 2 to -108, 2 to -15)
val vts = mutableMapOf<Int, Set<Int>>()
for (t in ts) {
val (ix, value) = t
val hs = hails3d.filter { it.v[ix] == value.toLong() }
if (hs.size < 2) {
continue
}
val ns = mutableSetOf<Int>()
for (n in 1..2000) {
val a = hs[0].p[ix] % n
if (hs.all { it.p[ix] % n == a }) {
ns.add(value-n)
ns.add(value+n)
}
}
if (vts.contains(ix)) {
vts[ix] = ns.intersect(vts[ix]!!)
} else {
vts[ix] = ns
}
// println(ns)
}
val vx = -153
val vy = -150
val vz = 296
val dvx0 = BigInteger.valueOf(vx-hails3d[0].v[0])
val dvy0 = BigInteger.valueOf(vy-hails3d[0].v[1])
val dvz0 = BigInteger.valueOf(vz-hails3d[0].v[2])
val dvx1 = BigInteger.valueOf(vx-hails3d[1].v[0])
val dvy1 = BigInteger.valueOf(vy-hails3d[1].v[1])
val x0 = BigInteger.valueOf(hails3d[0].p[0])
val y0 = BigInteger.valueOf(hails3d[0].p[1])
val z0 = BigInteger.valueOf(hails3d[0].p[2])
val x1 = BigInteger.valueOf(hails3d[1].p[0])
val y1 = BigInteger.valueOf(hails3d[1].p[1])
val yn = (x0 * dvy0 * dvy1 - y0 * dvx0 * dvy1 - x1 * dvy1 * dvy0 + y1 * dvx1 * dvy0)
val yd = (dvx1 * dvy0 - dvx0 * dvy1)
val yd1 = BigInteger.valueOf(vx-hails3d[2].v[0]) * BigInteger.valueOf(vy-hails3d[0].v[1]) -
BigInteger.valueOf(vx-hails3d[2].v[1]) * BigInteger.valueOf(vy-hails3d[0].v[0])
val v = listOf(-153, -150, 296)
val min = mutableListOf<BigInteger?>(null, null, null)
val max = mutableListOf<BigInteger?>(null, null, null)
hails3d.forEach {
h ->
(0..2). forEach {
ix ->
val dv = v[ix] - h.v[ix]
if (dv < 0 && (min[ix] == null || min[ix]!! < BigInteger.valueOf(h.p[ix]))) {
min[ix] = BigInteger.valueOf(h.p[ix])
}
if (dv > 0 && (max[ix] == null || max[ix]!! > BigInteger.valueOf(h.p[ix]))) {
max[ix] = BigInteger.valueOf(h.p[ix])
}
}
}
val m = yn % yd
val y = yn / yd
val t0 = (y0 - y)/dvy0
val tm0 = (y0 - y)%dvy0
val x = x0 - t0 * dvx0
val z = z0 - t0 * dvz0
for (i in 0 until hails2d.size) {
for (j in i+1 until hails2d.size) {
if (hails2d[i].collides(hails2d[j], 7.toDouble(), 27.toDouble())) {
sum ++
}
if (hails2d[i].collides(hails2d[j], 200000000000000.toDouble(), 400000000000000.toDouble())) {
sum1 ++
}
}
}
print("$sum $sum1\n")
println(x + y + z)
}
} | 0 | Kotlin | 0 | 0 | f0c61c787e4f0b83b69ed0cde3117aed3ae918a5 | 5,827 | advent-of-code | Apache License 2.0 |
2021/src/test/kotlin/Day10.kt | jp7677 | 318,523,414 | false | {"Kotlin": 171284, "C++": 87930, "Rust": 59366, "C#": 1731, "Shell": 354, "CMake": 338} | import kotlin.test.Test
import kotlin.test.assertEquals
class Day10 {
private val re = "[(\\[{<][)\\]}>]".toRegex()
@Test
fun `run part 01`() {
val lines = Util.getInputAsListOfString("day10-input.txt")
val errorScore = lines
.mapNotNull { it.getCorruptedClosingChar() }
.sumOf {
when (it) {
')' -> 3L
']' -> 57L
'}' -> 1197L
'>' -> 25137L
else -> throw IllegalStateException()
}
}
assertEquals(265527, errorScore)
}
@Test
fun `run part 02`() {
val lines = Util.getInputAsListOfString("day10-input.txt")
val middleScore = lines
.filter { it.getCorruptedClosingChar() == null }
.map { it.getMissingClosingChars() }
.map { missing ->
missing.fold(0.toLong()) { acc, it ->
when (it) {
')' -> 1
']' -> 2
'}' -> 3
'>' -> 4
else -> throw IllegalStateException()
} + acc * 5
}
}
.sorted()
.let { it[it.size / 2] }
assertEquals(3969823589, middleScore)
}
private fun String.getCorruptedClosingChar(): Char? =
generateSequence(this) {
re.find(it)
?.let { match ->
if (match.value.isValidPair())
it.replace(match.value, "")
else
null
}
}
.last()
.let {
re.find(it)
?.let { match ->
if (match.value.last() in listOf(')', '}', ']', '>'))
match.value.last()
else
null
}
}
private fun String.isValidPair() = this.first().toClosingChar() == this.last()
private fun String.getMissingClosingChars() =
generateSequence(this) {
if (re.containsMatchIn(it)) re.replace(it, "") else null
}
.last()
.reversed()
.map { it.toClosingChar() }
.joinToString("")
private fun Char.toClosingChar() = when (this) {
'(' -> ')'
'[' -> ']'
'{' -> '}'
'<' -> '>'
else -> throw IllegalStateException()
}
}
| 0 | Kotlin | 1 | 2 | 8bc5e92ce961440e011688319e07ca9a4a86d9c9 | 2,568 | adventofcode | MIT License |
mathevaluator/src/test/kotlin/com/github/vatbub/mathevaluator/FourEqualsTenHelp.kt | vatbub | 137,678,673 | false | {"Kotlin": 78857, "Java": 6074} | /*-
* #%L
* math-evaluator
* %%
* Copyright (C) 2019 - 2022 <NAME>
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package com.github.vatbub.mathevaluator
import org.junit.jupiter.api.Test
class FourEqualsTenHelp {
private val numbersWithoutOperators =
listOf(7, 1, 4, 0)
.permutations()
.distinct()
.map { outerList ->
outerList.map { it.toDouble().toMathLiteral() }
}
private val possibleOperators = listOf(AddOperator(), SubtractOperator(), MultiplyOperator(), DivideOperator())
private val operatorPermutations = mutableListOf<List<Operator>>()
init {
createOperatorPermutations()
}
private fun createOperatorPermutations() {
val maxIndex = (possibleOperators.size - 1).toString()
val start = maxIndex + maxIndex + maxIndex
val result = (start.toInt(possibleOperators.size) downTo 0)
.map {
var number = it.toString(possibleOperators.size)
while (number.length < start.length)
number = "0$number"
number
}
.map { line -> line.map { possibleOperators[it.toString().toInt()] } }
operatorPermutations.addAll(result)
}
@Test
fun findSolutions() {
val possibleCombinationsNoParenthesis = numbersWithoutOperators.flatMap { numberCombination ->
operatorPermutations.map { operatorCombination ->
MathExpression(
listOf(
numberCombination[0],
operatorCombination[0],
numberCombination[1],
operatorCombination[1],
numberCombination[2],
operatorCombination[2],
numberCombination[3]
)
)
}
}
val possibleCombinationsParenthesis1 = numbersWithoutOperators.flatMap { numberCombination ->
operatorPermutations.map { operatorCombination ->
MathExpression(
listOf(
MathExpression(
listOf(
numberCombination[0],
operatorCombination[0],
numberCombination[1]
)
),
operatorCombination[1],
numberCombination[2],
operatorCombination[2],
numberCombination[3]
)
)
}
}
val possibleCombinationsParenthesis2 = numbersWithoutOperators.flatMap { numberCombination ->
operatorPermutations.map { operatorCombination ->
MathExpression(
listOf(
MathExpression(
listOf(
numberCombination[0],
operatorCombination[0],
numberCombination[1],
operatorCombination[1],
numberCombination[2]
)
),
operatorCombination[2],
numberCombination[3]
)
)
}
}
val possibleCombinationsParenthesis3 = numbersWithoutOperators.flatMap { numberCombination ->
operatorPermutations.map { operatorCombination ->
MathExpression(
listOf(
numberCombination[0],
operatorCombination[0],
MathExpression(
listOf(
numberCombination[1],
operatorCombination[1],
numberCombination[2]
)
),
operatorCombination[2],
numberCombination[3]
)
)
}
}
val possibleCombinationsParenthesis4 = numbersWithoutOperators.flatMap { numberCombination ->
operatorPermutations.map { operatorCombination ->
MathExpression(
listOf(
numberCombination[0],
operatorCombination[0],
MathExpression(
listOf(
numberCombination[1],
operatorCombination[1],
numberCombination[2],
operatorCombination[2],
numberCombination[3]
)
)
)
)
}
}
val possibleCombinationsParenthesis5 = numbersWithoutOperators.flatMap { numberCombination ->
operatorPermutations.map { operatorCombination ->
MathExpression(
listOf(
numberCombination[0],
operatorCombination[0],
numberCombination[1],
operatorCombination[1],
MathExpression(
listOf(
numberCombination[2],
operatorCombination[2],
numberCombination[3]
)
)
)
)
}
}
println("Solutions:")
(
possibleCombinationsNoParenthesis +
possibleCombinationsParenthesis1 +
possibleCombinationsParenthesis2 +
possibleCombinationsParenthesis3 +
possibleCombinationsParenthesis4 +
possibleCombinationsParenthesis5
).filter { it.evaluate().value == 10.0 }
.forEach { println(it) }
}
private fun <T> List<T>.permutations(): List<List<T>> =
if (isEmpty()) listOf(emptyList())
else mutableListOf<List<T>>().also { result ->
for (i in this.indices) {
(this - this[i]).permutations().forEach {
result.add(it + this[i])
}
}
}
}
| 0 | Kotlin | 0 | 0 | 161919fc92e35ea1c4d93baee8ad32a630bb17c3 | 7,137 | mathevaluator | Apache License 2.0 |
src/Day21.kt | MickyOR | 578,726,798 | false | {"Kotlin": 98785} | fun main() {
class Monke {
var leaf = false
var leftChild: Monke? = null
var rightChild: Monke? = null
var op: String = ""
var value: Long = 0
var parent: Monke? = null
var toMove = false
}
fun getValue(node: Monke?) : Long {
if (node == null) return 0
if (node.leaf) {
return node.value
}
return when (node.op) {
"+" -> getValue(node.leftChild!!) + getValue(node.rightChild!!)
"-" -> getValue(node.leftChild!!) - getValue(node.rightChild!!)
"*" -> getValue(node.leftChild!!) * getValue(node.rightChild!!)
else -> {
assert(getValue(node.leftChild!!) % getValue(node.rightChild!!) == 0L)
getValue(node.leftChild!!) / getValue(node.rightChild!!)
}
}
}
var root: Monke? = null
fun part1(input: List<String>): Long {
var nodes = mutableMapOf<String, Monke>()
for (line in input) {
if (line.isEmpty()) continue
val parts = line.split(" ").map { if (it.last() == ':') it.dropLast(1) else it }
val node = nodes.getOrPut(parts[0]) { Monke() }
}
root = nodes["root"]
for (line in input) {
if (line.isEmpty()) continue
val parts = line.split(" ").map { if (it.last() == ':') it.dropLast(1) else it }
val node = nodes[parts[0]]!!
if (parts.size == 2) {
node.leaf = true
node.value = parts[1].toLong()
} else {
node.leftChild = nodes[parts[1]]
node.rightChild = nodes[parts[3]]
nodes[parts[1]]?.parent = node
nodes[parts[3]]?.parent = node
node.op = parts[2]
}
}
return getValue(root)
}
fun part2(input: List<String>): Long {
var nodes = mutableMapOf<String, Monke>()
for (line in input) {
if (line.isEmpty()) continue
val parts = line.split(" ").map { if (it.last() == ':') it.dropLast(1) else it }
val node = nodes.getOrPut(parts[0]) { Monke() }
}
root = nodes["root"]
for (line in input) {
if (line.isEmpty()) continue
val parts = line.split(" ").map { if (it.last() == ':') it.dropLast(1) else it }
val node = nodes[parts[0]]!!
if (parts.size == 2) {
node.leaf = true
node.value = parts[1].toLong()
} else {
node.leftChild = nodes[parts[1]]
node.rightChild = nodes[parts[3]]
nodes[parts[1]]?.parent = node
nodes[parts[3]]?.parent = node
node.op = parts[2]
}
}
var v = nodes["humn"]!!
while (v.parent != null) {
v.toMove = true
v = v.parent!!
}
while (true) {
if (root?.leftChild == nodes["humn"]) break
if (root?.rightChild == nodes["humn"]) break
if (root?.leftChild?.toMove == true) {
val l = root?.leftChild
val r = root?.rightChild
var newNode = Monke()
if (l?.leftChild?.toMove == true) {
when (l?.op) {
"+" -> {
newNode.op = "-"
newNode.leftChild = r
newNode.rightChild = l?.rightChild
root?.leftChild = l?.leftChild
root?.rightChild = newNode
}
"-" -> {
newNode.op = "+"
newNode.leftChild = r
newNode.rightChild = l?.rightChild
root?.leftChild = l?.leftChild
root?.rightChild = newNode
}
"*" -> {
newNode.op = "/"
newNode.leftChild = r
newNode.rightChild = l?.rightChild
root?.leftChild = l?.leftChild
root?.rightChild = newNode
}
else -> {
newNode.op = "*"
newNode.leftChild = r
newNode.rightChild = l?.rightChild
root?.leftChild = l?.leftChild
root?.rightChild = newNode
}
}
}
else {
when (l?.op) {
"+" -> {
newNode.op = "-"
newNode.leftChild = r
newNode.rightChild = l?.leftChild
root?.leftChild = l?.rightChild
root?.rightChild = newNode
}
"-" -> {
newNode.op = "+"
newNode.leftChild = r
newNode.rightChild = l?.rightChild
newNode.toMove = true
root?.leftChild = l?.leftChild
root?.rightChild = newNode
}
"*" -> {
newNode.op = "/"
newNode.leftChild = r
newNode.rightChild = l?.leftChild
root?.leftChild = l?.rightChild
root?.rightChild = newNode
}
else -> {
newNode.op = "*"
newNode.leftChild = r
newNode.rightChild = l?.rightChild
newNode.toMove = true
root?.leftChild = l?.leftChild
root?.rightChild = newNode
}
}
}
}
else {
val l = root?.leftChild
val r = root?.rightChild
var newNode = Monke()
if (r?.leftChild?.toMove == true) {
when (r?.op) {
"+" -> {
newNode.op = "-"
newNode.leftChild = l
newNode.rightChild = r?.rightChild
root?.leftChild = newNode
root?.rightChild = r?.leftChild
}
"-" -> {
newNode.op = "+"
newNode.leftChild = l
newNode.rightChild = r?.rightChild
root?.leftChild = newNode
root?.rightChild = r?.leftChild
}
"*" -> {
newNode.op = "/"
newNode.leftChild = l
newNode.rightChild = r?.rightChild
root?.leftChild = newNode
root?.rightChild = r?.leftChild
}
else -> {
newNode.op = "*"
newNode.leftChild = l
newNode.rightChild = r?.rightChild
root?.leftChild = newNode
root?.rightChild = r?.leftChild
}
}
}
else {
when (r?.op) {
"+" -> {
newNode.op = "-"
newNode.leftChild = l
newNode.rightChild = r?.leftChild
root?.leftChild = newNode
root?.rightChild = r?.rightChild
}
"-" -> {
newNode.op = "+"
newNode.leftChild = l
newNode.rightChild = r?.rightChild
newNode.toMove = true
root?.leftChild = newNode
root?.rightChild = r?.leftChild
}
"*" -> {
newNode.op = "/"
newNode.leftChild = l
newNode.rightChild = r?.leftChild
root?.leftChild = newNode
root?.rightChild = r?.rightChild
}
else -> {
newNode.op = "*"
newNode.leftChild = l
newNode.rightChild = r?.rightChild
newNode.toMove = true
root?.leftChild = newNode
root?.rightChild = r?.leftChild
}
}
}
}
}
return getValue(if (root?.leftChild == nodes["humn"]) root?.rightChild else root?.leftChild)
}
val input = readInput("Day21")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | c24e763a1adaf0a35ed2fad8ccc4c315259827f0 | 9,595 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/main/kotlin/Day04.kt | bacecek | 574,824,698 | false | null | fun main() {
val inputRaw = loadInput("day04_input")
var part1Result = 0
var part2NumberOfOverlaps = 0
for (i in inputRaw.lines().indices) {
val line = inputRaw.lines()[i]
if (line.isBlank()) {
continue
}
val pairsRaw = line.split(",")
require(pairsRaw.size == 2)
val left = pairsRaw[0].parsePair()
val right = pairsRaw[1].parsePair()
var isPart1ConditionMet: Boolean
var isPart2ConditionMet: Boolean
if (left[0] == right[0]) {
isPart1ConditionMet = true
isPart2ConditionMet = true
} else if (left[0] < right[0]) {
isPart1ConditionMet = left[1] >= right[1]
isPart2ConditionMet = right[0] <= left[1]
} else {
isPart1ConditionMet = right[1] >= left[1]
isPart2ConditionMet = left[0] <= right[1]
}
if (isPart1ConditionMet) {
part1Result++
}
if (isPart2ConditionMet) {
part2NumberOfOverlaps++
}
}
println("""
part1=$part1Result
part2=${part2NumberOfOverlaps}
""".trimIndent())
}
fun String.parsePair() = split("-").map { it.toInt() }
| 0 | Kotlin | 0 | 0 | c9a99b549d97d1e7a04a1c055492cf41653e78bb | 1,220 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/day21/Day21.kt | daniilsjb | 572,664,294 | false | {"Kotlin": 69004} | package day21
import java.io.File
fun main() {
val data = parse("src/main/kotlin/day21/Day21.txt")
val answer1 = part1(data)
val answer2 = part2(data)
println("🎄 Day 21 🎄")
println()
println("[Part 1]")
println("Answer: $answer1")
println()
println("[Part 2]")
println("Answer: $answer2")
}
private sealed interface Monkey {
data class Yelling(
val number: Long,
) : Monkey
data class Operation(
val lhs: String,
val rhs: String,
val op: String,
) : Monkey
}
@Suppress("SameParameterValue")
private fun parse(path: String): Map<String, Monkey> {
val data = mutableMapOf<String, Monkey>()
File(path).forEachLine { line ->
val (name, job) = line.split(": ")
val monkey = job.toLongOrNull()?.let { Monkey.Yelling(it) } ?: run {
val (lhs, op, rhs) = job.split(" ")
Monkey.Operation(lhs, rhs, op)
}
data[name] = monkey
}
return data
}
private fun Monkey.evaluate(ctx: Map<String, Monkey>): Long =
when (this) {
is Monkey.Yelling -> number
is Monkey.Operation -> {
val lhsNumber = ctx.getValue(lhs).evaluate(ctx)
val rhsNumber = ctx.getValue(rhs).evaluate(ctx)
when (op) {
"+" -> lhsNumber + rhsNumber
"-" -> lhsNumber - rhsNumber
"*" -> lhsNumber * rhsNumber
"/" -> lhsNumber / rhsNumber
else -> error("Unknown operation: $op")
}
}
}
private fun Monkey.evaluateOrNull(ctx: Map<String, Monkey>): Long? {
return when (this) {
is Monkey.Yelling -> number
is Monkey.Operation -> {
if (lhs == "humn" || rhs == "humn") {
return null
}
val lhsNumber = ctx.getValue(lhs).evaluateOrNull(ctx) ?: return null
val rhsNumber = ctx.getValue(rhs).evaluateOrNull(ctx) ?: return null
when (op) {
"+" -> lhsNumber + rhsNumber
"-" -> lhsNumber - rhsNumber
"*" -> lhsNumber * rhsNumber
"/" -> lhsNumber / rhsNumber
else -> error("Unknown operation: $op")
}
}
}
}
private fun Monkey.coerce(ctx: Map<String, Monkey>, expected: Long): Long {
return when (this) {
is Monkey.Yelling -> expected
is Monkey.Operation -> {
ctx.getValue(rhs).evaluateOrNull(ctx)?.let { value ->
val next = ctx.getValue(lhs)
return when (op) {
"+" -> next.coerce(ctx, expected - value)
"-" -> next.coerce(ctx, expected + value)
"*" -> next.coerce(ctx, expected / value)
"/" -> next.coerce(ctx, expected * value)
else -> error("Unknown operation: $op")
}
}
ctx.getValue(lhs).evaluateOrNull(ctx)?.let { value ->
val next = ctx.getValue(rhs)
return when (op) {
"+" -> next.coerce(ctx, expected - value)
"-" -> next.coerce(ctx, value - expected)
"*" -> next.coerce(ctx, expected / value)
"/" -> next.coerce(ctx, value / expected)
else -> error("Unknown operation: $op")
}
}
error("Cannot evaluate either branch.")
}
}
}
private fun part1(data: Map<String, Monkey>): Long =
data.getValue("root").evaluate(data)
private fun part2(data: Map<String, Monkey>): Long {
val (lhs, rhs, _) = data["root"] as Monkey.Operation
data.getValue(lhs).evaluateOrNull(data)?.let { expected ->
return data.getValue(rhs).coerce(data, expected)
}
data.getValue(rhs).evaluateOrNull(data)?.let { expected ->
return data.getValue(lhs).coerce(data, expected)
}
error("Cannot evaluate either branch.")
}
| 0 | Kotlin | 0 | 0 | 6f0d373bdbbcf6536608464a17a34363ea343036 | 3,997 | advent-of-code-2022 | MIT License |
src/main/kotlin/_2020/Day10.kt | thebrightspark | 227,161,060 | false | {"Kotlin": 548420} | package _2020
import aocRun
import splitToInts
import kotlin.math.pow
fun main() {
aocRun(testInput1) { input ->
val adapters = createSortedAdapterList(input)
val differenceMap = (0 until adapters.size - 1)
.map { adapters[it + 1] - adapters[it] }
.groupBy { it }
.mapValues { it.value.size }
println(differenceMap)
return@aocRun differenceMap[1]!! * differenceMap[3]!!
}
aocRun(testInput1) { input ->
val adapters = createSortedAdapterList(input)
val differences = (0 until adapters.size - 1).map { adapters[it + 1] - adapters[it] }
println(differences)
var count = 1
var i = 0
while (i < differences.size) {
val curI = i
i++
val diff = differences[curI]
// We're only paying attention to differences of 1
if (diff != 1)
continue
// Count the size of this group of 1s
var last = curI + 1
while (differences[last] == 1)
last++
var range = last - curI
// If group is only a single 1, then ignore
if (range <= 1)
continue
if (range == 2) {
// If group of 2, then only 2 permutations available
println("$curI-$last = 2")
count *= 2
} else {
// Remove 1 from the range, as we need to always keep the last adapter before the next 3 jolt gap
range -= 1
// Calculate number of permutations for range
val permutations = 2F.pow(range).toInt() - 2F.pow(range - 2).toInt()
println("$curI-$last = 2^$range - 2^${range - 2} = $permutations")
count *= permutations
}
// Skip forward to
i = last + 1
}
return@aocRun count
}
}
private fun createSortedAdapterList(input: String): List<Int> = input.splitToInts().toMutableList().apply {
add(0)
add(maxOrNull()!! + 3)
sort()
println(this)
}
private val testInput1 = """
16
10
15
5
1
11
7
19
6
12
4
""".trimIndent()
private val testInput2 = """
28
33
18
42
31
14
46
20
48
47
24
23
49
45
19
38
39
11
1
32
25
35
8
17
7
9
4
2
34
10
3
""".trimIndent()
private val puzzleInput = """
99
128
154
160
61
107
75
38
15
11
129
94
157
84
121
14
119
48
30
10
55
108
74
104
91
45
134
109
164
66
146
44
116
89
79
32
149
1
136
58
96
7
60
23
31
3
65
110
90
37
43
115
122
52
113
123
161
50
95
150
120
101
126
151
114
127
73
82
162
140
51
144
36
4
163
85
42
59
67
64
86
49
2
145
135
22
24
33
137
16
27
70
133
130
20
21
83
143
100
41
76
17
""".trimIndent()
| 0 | Kotlin | 0 | 0 | ac62ce8aeaed065f8fbd11e30368bfe5d31b7033 | 2,310 | AdventOfCode | Creative Commons Zero v1.0 Universal |
src/Day25.kt | flex3r | 572,653,526 | false | {"Kotlin": 63192} | import kotlin.math.pow
suspend fun main() {
val testInput = readInput("Day25_test")
check(part1(testInput) == "2=-1=0")
val input = readInput("Day25")
measureAndPrintResult {
part1(input)
}
}
private fun part1(input: List<String>): String {
return encode(input.sumOf(::decode))
}
private fun decode(input: String) = input.withIndex().sumOf { (idx, c) ->
val place = 5.0.pow(input.lastIndex - idx).toLong()
val value = when (c) {
'0', '1', '2' -> c.digitToInt()
'-' -> -1
'=' -> -2
else -> error("xd")
}
place * value
}
private fun encode(value: Long): String = value.toString(radix = 5)
.map(Char::digitToInt)
.foldRight(emptyList<Int>() to 0) { i, (result, acc) ->
val withAcc = i + acc
when {
withAcc >= 3 -> result + (withAcc - 5) to 1
else -> result + withAcc to 0
}
}
.first
.reversed()
.joinToString(separator = "") {
when (it) {
0, 1, 2 -> "${it.digitToChar()}"
-1 -> "-"
-2 -> "="
else -> error("xd")
}
} | 0 | Kotlin | 0 | 0 | 8604ce3c0c3b56e2e49df641d5bf1e498f445ff9 | 1,137 | aoc-22 | Apache License 2.0 |
src/main/kotlin/year2022/Day06.kt | forketyfork | 572,832,465 | false | {"Kotlin": 142196} | package year2022
class Day06 {
companion object {
fun solution(input: String, length: Int) = input.windowed(length)
.indexOfFirst { it.toSet().size == length } + length
fun linearSolution(input: String, length: Int): Int {
var distinctCount = 0
val charCounts = IntArray(256)
return 1 + input.indices.first {
if (it >= length) {
when (--charCounts[input[it - length].code]) {
0 -> distinctCount--
1 -> distinctCount++
}
}
when (++charCounts[input[it].code]) {
1 -> distinctCount++
2 -> distinctCount--
}
distinctCount == length
}
}
}
fun part1(input: String, solver: (String, Int) -> Int) = solver(input, 4)
fun part2(input: String, solver: (String, Int) -> Int) = solver(input, 14)
}
| 0 | Kotlin | 0 | 0 | 5c5e6304b1758e04a119716b8de50a7525668112 | 997 | aoc-2022 | Apache License 2.0 |
aoc2022/day17.kt | davidfpc | 726,214,677 | false | {"Kotlin": 127212} | package aoc2022
import aoc2022.Day17.RockType.MINUS
import aoc2022.Day17.RockType.MIRROR_L
import aoc2022.Day17.RockType.PLUS
import aoc2022.Day17.RockType.SQUARE
import aoc2022.Day17.RockType.VERTICAL
import utils.InputRetrieval
fun main() {
Day17.execute()
}
object Day17 {
fun execute() {
val input = readInput()
println("Part 1: ${part1(input)}")
//println("Part 2: ${part2(input)}")
}
private fun part1(input: String, numberOfRocks: Int = 2022): Int {
//
// val filledPositions = mutableSetOf<Pair<Int, Int>>()
// var jetIndex = 0
// val rockPattern = listOf(MINUS, PLUS, MIRROR_L, VERTICAL, SQUARE)
// var rockIndex = 0
// repeat(numberOfRocks) {
// var moving = true
// // create rock
// val rock = Rock((filledPositions.maxOfOrNull { it.second } ?: 0) + 4, rockPattern[rockIndex % rockPattern.size])
// rockIndex++
// while (moving) {
// // apply jet to the rock
// when (input[jetIndex % input.length]) {
// '<' -> rock.moveLeft(filledPositions)
// '>' -> rock.moveRight(filledPositions)
// }
// jetIndex++
//
// // apply gravity
// if (rock.canMoveDown(filledPositions)) {
// rock.moveDown(filledPositions)
// } else {
// filledPositions.addAll(rock.positions)
// moving = false
// }
// }
//
// }
//
// return filledPositions.maxOf { it.second }
return 0
}
class Rock(y: Long, type: RockType, x: Long = 3) {
var positions: List<Pair<Long, Long>>
init {
positions = when (type) {
MINUS -> listOf(x to y, x + 1 to y, x + 2 to y, x + 3 to y)
PLUS -> listOf(x to y + 1, x + 1 to y, x + 1 to y + 1, x + 1 to y + 2, x + 2 to y + 1)
MIRROR_L -> listOf(x to y, x + 1 to y, x + 2 to y, x + 2 to y + 1, x + 2 to y + 2)
VERTICAL -> listOf(x to y, x to y + 1, x to y + 2, x to y + 3)
SQUARE -> listOf(x to y, x to y + 1, x + 1 to y + 1, x + 1 to y)
}
}
fun moveLeft(board: Set<Pair<Long, Long>>) {
val hasNotReachedBorder = positions.all { it.first - 1 > 0 }
val newPositions = positions.map { it.first - 1 to it.second }
if (hasNotReachedBorder && newPositions.all { !board.contains(it) }) {
// move Left
positions = newPositions
}
}
fun moveRight(board: Set<Pair<Long, Long>>) {
val hasNotReachedBorder = positions.all { it.first + 1 < 8 }
val newPositions = positions.map { it.first + 1 to it.second }
if (hasNotReachedBorder && newPositions.all { !board.contains(it) }) {
// move Right
positions = newPositions
}
}
fun canMoveDown(board: Set<Pair<Long, Long>>): Boolean {
val hasNotReachedBorder = positions.all { it.second - 1 > 0 }
val newPositionsAreFree = positions.map { it.first to it.second - 1 }.all { !board.contains(it) }
return hasNotReachedBorder && newPositionsAreFree
}
fun moveDown(board: Set<Pair<Long, Long>>) {
val hasNotReachedBorder = positions.all { it.second - 1 > 0 }
val newPositions = positions.map { it.first to it.second - 1 }
if (hasNotReachedBorder && newPositions.all { !board.contains(it) }) {
// move Down
positions = newPositions
}
}
}
enum class RockType {
MINUS,
PLUS,
MIRROR_L,
VERTICAL,
SQUARE
}
private fun part2(input: String, numberOfRocks: Long = 1_000_000_000_000L): Long {
val filledPositions = mutableSetOf<Pair<Long, Long>>()
var jetIndex = 0
val rockPattern = listOf(MINUS, PLUS, MIRROR_L, VERTICAL, SQUARE)
var rockIndex = 0
for (i in 0 until numberOfRocks) {
println("Processing rock $i")
var moving = true
// create rock
val rock = Rock((filledPositions.maxOfOrNull { it.second } ?: 0) + 4, rockPattern[rockIndex % rockPattern.size])
rockIndex++
while (moving) {
// apply jet to the rock
when (input[jetIndex % input.length]) {
'<' -> rock.moveLeft(filledPositions)
'>' -> rock.moveRight(filledPositions)
}
jetIndex++
// apply gravity
if (rock.canMoveDown(filledPositions)) {
rock.moveDown(filledPositions)
} else {
filledPositions.addAll(rock.positions)
moving = false
}
}
}
return filledPositions.maxOf { it.second }
}
private fun readInput(): String = InputRetrieval.getFile(2022, 17).readLines().first()
}
| 0 | Kotlin | 0 | 0 | 8dacf809ab3f6d06ed73117fde96c81b6d81464b | 5,228 | Advent-Of-Code | MIT License |
src/Utils.kt | dizney | 572,581,781 | false | {"Kotlin": 105380} | import java.io.File
import java.math.BigInteger
import java.security.MessageDigest
/**
* Reads lines from the given input txt file.
*/
fun readInput(name: String) = File("src", "$name.txt")
.readLines()
/**
* Converts string to md5 hash.
*/
fun String.md5() = BigInteger(1, MessageDigest.getInstance("MD5").digest(toByteArray()))
.toString(16)
.padStart(32, '0')
data class Location(val x: Int, val y: Int)
enum class Direction(val move: Coordinates) {
WEST(Coordinates(-1, 0)),
NORTH(Coordinates(0, -1)),
EAST(Coordinates(1, 0)),
SOUTH(Coordinates(0, 1));
fun next() = when (this) {
WEST -> EAST
NORTH -> SOUTH
EAST -> NORTH
SOUTH -> WEST
}
}
data class Coordinates(val x: Int, val y: Int) {
operator fun plus(distance: Coordinates): Coordinates = Coordinates(this.x + distance.x, this.y + distance.y)
fun move(direction: Direction) = when (direction) {
Direction.NORTH -> Coordinates(x, y - 1)
Direction.SOUTH -> Coordinates(x, y + 1)
Direction.EAST -> Coordinates(x + 1, y)
Direction.WEST -> Coordinates(x - 1, y)
}
fun adjacentPositions(includeDiagonal: Boolean = true): Set<Coordinates> =
adjacentPositions(Direction.NORTH, includeDiagonal) +
adjacentPositions(Direction.EAST, includeDiagonal) +
adjacentPositions(Direction.SOUTH, includeDiagonal) +
adjacentPositions(Direction.WEST, includeDiagonal)
fun adjacentPositions(direction: Direction, includeDiagonal: Boolean = true): Set<Coordinates> =
when (direction) {
Direction.NORTH -> setOf(
this + Coordinates(0, -1),
) + if (includeDiagonal) setOf(
this + Coordinates(-1, -1),
this + Coordinates(1, -1),
) else emptySet()
Direction.EAST -> setOf(
this + Coordinates(1, 0),
) + if (includeDiagonal) setOf(
this + Coordinates(1, -1),
this + Coordinates(1, 1),
) else emptySet()
Direction.SOUTH -> setOf(
this + Coordinates(0, 1),
) + if (includeDiagonal) setOf(
this + Coordinates(1, 1),
this + Coordinates(-1, 1),
) else emptySet()
Direction.WEST -> setOf(
this + Coordinates(-1, 0),
) + if (includeDiagonal) setOf(
this + Coordinates(-1, -1),
this + Coordinates(-1, 1),
) else emptySet()
}
}
data class BigCoordinates(val x: Long, val y: Long)
data class Point3D(val x: Int, val y: Int, val z: Int)
fun List<Coordinates>.findMinAndMax(): Pair<Coordinates, Coordinates> =
fold(Coordinates(Int.MAX_VALUE, Int.MAX_VALUE) to Coordinates(0, 0)) { (min, max), (x, y) ->
Coordinates(
minOf(min.x, x),
minOf(min.y, y)
) to Coordinates(
maxOf(max.x, x),
maxOf(max.y, y)
)
}
| 0 | Kotlin | 0 | 0 | f684a4e78adf77514717d64b2a0e22e9bea56b98 | 3,047 | aoc-2022-in-kotlin | Apache License 2.0 |
Algorithms/src/main/kotlin/net/milosvasic/algorithms/sort/efficient/HeapSort.kt | milos85vasic | 80,288,639 | false | null | package net.milosvasic.algorithms.sort.efficient
import net.milosvasic.algorithms.sort.Sort
class HeapSort<T : Comparable<T>> : Sort<T> {
private var count = 0
override fun sort(elements: MutableList<T>, ascending: Boolean) {
count = elements.size - 1
for (index in count / 2 downTo 0) {
heapify(elements, index, ascending)
}
for (index in count downTo 1) {
swap(elements, 0, index)
count--
heapify(elements, 0, ascending)
}
}
private fun heapify(elements: MutableList<T>, index: Int, ascending: Boolean) {
var max = index
val left = index * 2
val right = left + 1
if (ascending) {
if (left <= count && elements[left] > elements[max]) {
max = left
}
if (right <= count && elements[right] > elements[max]) {
max = right
}
} else {
if (left <= count && elements[left] < elements[max]) {
max = left
}
if (right <= count && elements[right] < elements[max]) {
max = right
}
}
if (max != index) {
swap(elements, index, max)
heapify(elements, max, ascending)
}
}
private fun swap(elements: MutableList<T>, a: Int, b: Int) {
val tmp = elements[a]
elements[a] = elements[b]
elements[b] = tmp
}
} | 0 | Kotlin | 1 | 5 | a2be55959035654463b4855058d07ccfb68ac4a7 | 1,481 | Fundamental-Algorithms | Apache License 2.0 |
hoon/HoonAlgorithm/src/main/kotlin/programmers/lv01/Lv1_12901.kt | boris920308 | 618,428,844 | false | {"Kotlin": 137657, "Swift": 35553, "Java": 1947, "Rich Text Format": 407} | package programmers.lv01
/**
* no.12901
* 2016년
* https://school.programmers.co.kr/learn/courses/30/lessons/12901
*
* 2016년 1월 1일은 금요일입니다.
* 2016년 a월 b일은 무슨 요일일까요?
* 두 수 a ,b를 입력받아 2016년 a월 b일이 무슨 요일인지 리턴하는 함수, solution을 완성하세요.
* 요일의 이름은 일요일부터 토요일까지 각각 SUN,MON,TUE,WED,THU,FRI,SAT 입니다.
* 예를 들어 a=5, b=24라면 5월 24일은 화요일이므로 문자열 "TUE"를 반환하세요.
*
* 제한 조건
* 2016년은 윤년입니다.
* 2016년 a월 b일은 실제로 있는 날입니다. (13월 26일이나 2월 45일같은 날짜는 주어지지 않습니다)
*
* 입출력 예
* a b result
* 5 24 "TUE"
*/
fun main() {
solution(5, 24)
}
private fun solution(a: Int, b: Int): String {
var answer = ""
val daysInMonth = listOf(0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
val daysOfWeek = listOf("SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT", )
var days = 0
for (month in 1 until a) {
days += daysInMonth[month]
}
days += b - 1
answer = daysOfWeek[(days + 5) % 7]
return answer
} | 1 | Kotlin | 1 | 2 | 88814681f7ded76e8aa0fa7b85fe472769e760b4 | 1,205 | HoOne | Apache License 2.0 |
src/main/kotlin/aoc2021/Day20.kt | j4velin | 572,870,735 | false | {"Kotlin": 285016, "Python": 1446} | package aoc2021
import readInput
private fun Boolean.toInt() = if (this) 1 else 0
/**
* @param input the "image enhancement algorithm"
*/
private class ImageEnhancer(input: String) {
private val enhancement = input.map { it == '#' }.toBooleanArray()
/**
* Enhances the given image
* @param inputImage the image to enhance
* @return the enhanced images
*/
operator fun invoke(inputImage: Image): Image {
val maxX = inputImage.maxX + 2
val maxY = inputImage.maxY + 2
val array = Array(maxY) { BooleanArray(maxX) }
for (y in 0 until maxY) {
for (x in 0 until maxX) {
val xInInput = x - 1
val yInInput = y - 1
val index = buildString {
for (i in -1..1) {
for (j in -1..1) {
append(inputImage[xInInput + j, yInInput + i].toInt())
}
}
}.toInt(2)
array[y][x] = enhancement[index]
}
}
// if the first character of the enhancement algorithm is true (e.g. '#'), then enhancing an image will enlighten
// every 'dark area' from the input image - as we deal with infinite images, this will be an infinite amount of
// pixels for every odd enhancement. We only store the 'outside pixel' once though
return Image(array, if (enhancement.first()) !inputImage.background else false)
}
}
/**
* Represents a black/white image (light/dark pixels)
* @param array the input pixels
* @property background true, if the pixel outside this image's border (aka the 'background') should be considered to be
* "on"/"light", false by default
*/
class Image(private val array: Array<BooleanArray>, val background: Boolean = false) {
val maxX = array.firstOrNull()?.size ?: 0
val maxY = array.size
/**
* Constructs an image from a list of strings
*/
constructor(input: List<String>) : this(input.map { line -> line.map { it == '#' }.toBooleanArray() }
.toTypedArray())
/**
* @return true, if the pixel at [x],[y] is "lit" or [background] if the given coordinate is outside the images'
* border
*/
operator fun get(x: Int, y: Int) = if (y in array.indices && x in array[y].indices) array[y][x] else background
/**
* @return the total number of "on"/"lit" pixels in this image. Might be [Double.POSITIVE_INFINITY]
*/
fun countLitPixels(): Number =
if (background) Double.POSITIVE_INFINITY else array.sumOf { line -> line.count { it } }
override fun toString(): String {
val width = array.firstOrNull()?.size ?: 0
val height = array.size
return buildString {
for (y in 0 until height) {
for (x in 0 until width) {
if (get(x, y)) {
append('#')
} else {
append('.')
}
}
appendLine()
}
}
}
}
private fun part1(input: List<String>): Int {
val enhance = ImageEnhancer(input.first())
var image = Image(input.drop(2))
repeat(2) { image = enhance(image) }
return image.countLitPixels().toInt()
}
private fun part2(input: List<String>): Int {
val enhance = ImageEnhancer(input.first())
var image = Image(input.drop(2))
repeat(50) { image = enhance(image) }
return image.countLitPixels().toInt()
}
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day20_test")
check(part1(testInput) == 35)
check(part2(testInput) == 3351)
val input = readInput("Day20")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f67b4d11ef6a02cba5b206aba340df1e9631b42b | 3,832 | adventOfCode | Apache License 2.0 |
src/main/java/challenges/cracking_coding_interview/linked_list/Intersection.kt | ShabanKamell | 342,007,920 | false | null | package challenges.cracking_coding_interview.linked_list
import challenges.data_structure.LinkedListNode
import challenges.util.AssortedMethods
import kotlin.math.abs
/**
* Given two (singly) linked lists, determine if the two lists intersect.
* Return the intersecting node. Note that the intersection is defined based on reference, not value.
* That is, if the kth node of the first linked list is the exact same node (by reference)
* as the jth node of the second linked list, then they are intersecting.
*/
object Intersection {
class Result(var tail: LinkedListNode?, var size: Int)
private fun getTailAndSize(list: LinkedListNode?): Result {
if (list == null) return Result(null, 0)
var size = 1
var current = list
while (current!!.next != null) {
size++
current = current.next
}
return Result(current, size)
}
private fun findIntersection(list1: LinkedListNode?, list2: LinkedListNode?): LinkedListNode? {
if (list1 == null || list2 == null) return null
// Get tail and sizes.
val result1 = getTailAndSize(list1)
val result2 = getTailAndSize(list2)
// If different tail nodes, then there's no intersection.
if (result1.tail != result2.tail) {
return null
}
// Set pointers to the start of each linked list.
var shorter: LinkedListNode? = if (result1.size < result2.size) list1 else list2
var longer: LinkedListNode? = if (result1.size < result2.size) list2 else list1
// Advance the pointer for the longer linked list by the difference in lengths.
longer = getKthNode(
longer,
abs(result1.size - result2.size)
)
// Move both pointers until you have a collision.
while (shorter != longer) {
shorter = shorter?.next
longer = longer?.next
}
// Return either one.
return longer
}
private fun getKthNode(head: LinkedListNode?, _k: Int): LinkedListNode? {
var k = _k
var current = head
while (k > 0 && current != null) {
current = current.next
k--
}
return current
}
@JvmStatic
fun main(args: Array<String>) {
// Create linked list
val values = intArrayOf(-1, -2, 0, 1, 2, 3, 4, 5, 6, 7, 8)
val list1: LinkedListNode = AssortedMethods.createLinkedListFromArray(values)
val values2 = intArrayOf(12, 14, 15)
val list2: LinkedListNode = AssortedMethods.createLinkedListFromArray(values2)
list2.next!!.next = list1.next!!.next!!.next!!.next
println(list1.printForward())
println(list2.printForward())
val intersection = findIntersection(list1, list2)
println(intersection!!.printForward())
}
} | 0 | Kotlin | 0 | 0 | ee06bebe0d3a7cd411d9ec7b7e317b48fe8c6d70 | 2,877 | CodingChallenges | Apache License 2.0 |
src/main/java/challenges/educative_grokking_coding_interview/sliding_window/_10/StringAnagrams.kt | ShabanKamell | 342,007,920 | false | null | package challenges.educative_grokking_coding_interview.sliding_window._10
/**
* Given a string and a pattern, find all anagrams of the pattern in the given string.
* Every anagram is a permutation of a string. As we know, when we are not allowed to repeat characters
* while finding permutations of a string, we get N! permutations (or anagrams) of a string having N
* characters. For example, here are the six anagrams of the string “abc”:
* abc
* acb
* bac
* bca
* cab
* cba
*
* Write a function to return a list of starting indices of the anagrams of the pattern in the given string.
*
* https://www.educative.io/courses/grokking-the-coding-interview/xl2g3vxrMq3
*/
object StringAnagrams {
private fun findStringAnagrams(str: String, pattern: String): List<Int> {
val resultIndices: MutableList<Int> = ArrayList()
var windowStart = 0
val charFrequencyMap: MutableMap<Char, Int> = HashMap()
val patternLength = pattern.length
var matched = 0
for (chr in pattern.toCharArray())
charFrequencyMap[chr] = charFrequencyMap.getOrDefault(chr, 0) + 1
for (windowEnd in str.indices) {
val rightChar = str[windowEnd]
if (charFrequencyMap.containsKey(rightChar)) {
charFrequencyMap[rightChar] = charFrequencyMap[rightChar]!! - 1
if (charFrequencyMap[rightChar] == 0) {
matched++
}
}
if (matched == charFrequencyMap.size) // have we found an anagram?
resultIndices.add(windowStart)
if (windowEnd >= patternLength - 1) {
val leftChar = str[windowStart]
if (charFrequencyMap.containsKey(leftChar)) {
if (charFrequencyMap[leftChar] == 0) {
matched--
}
charFrequencyMap[leftChar] = charFrequencyMap[leftChar]!! + 1
}
windowStart++
}
}
return resultIndices
}
@JvmStatic
fun main(args: Array<String>) {
println(findStringAnagrams("ppqp", "pq"))
println(findStringAnagrams("abbcabc", "abc"))
}
} | 0 | Kotlin | 0 | 0 | ee06bebe0d3a7cd411d9ec7b7e317b48fe8c6d70 | 2,231 | CodingChallenges | Apache License 2.0 |
src/commonMain/kotlin/com/jeffpdavidson/kotwords/model/Labyrinth.kt | jpd236 | 143,651,464 | false | {"Kotlin": 4390419, "HTML": 41919, "Rouge": 3731, "Perl": 1705, "Shell": 744, "JavaScript": 618} | package com.jeffpdavidson.kotwords.model
import com.jeffpdavidson.kotwords.formats.Puzzleable
import kotlin.math.abs
data class Labyrinth(
val title: String,
val creator: String,
val copyright: String,
val description: String,
val grid: List<List<Char>>,
val gridKey: List<List<Int>>,
val rowClues: List<List<String>>,
val windingClues: List<String>,
val alphabetizeWindingClues: Boolean,
) : Puzzleable() {
init {
val allNumbers = gridKey.flatten().sorted()
require((1..allNumbers.size).toList() == allNumbers) {
"Grid key must contain exactly one of each number from 1 to the size of the grid"
}
require(grid.map { it.size }.toList() == gridKey.map { it.size }.toList()) {
"Grid key and grid must have the same dimensions"
}
}
override suspend fun createPuzzle(): Puzzle {
val puzzleGrid = grid.mapIndexed { y, row ->
row.mapIndexed { x, ch ->
// Calculate the borders. We remove borders from the outer edges of the grid as well as between any two
// neighboring cells in the winding path.
val borderDirections = mutableSetOf(
Puzzle.BorderDirection.TOP,
Puzzle.BorderDirection.BOTTOM,
Puzzle.BorderDirection.LEFT,
Puzzle.BorderDirection.RIGHT
)
if (y == 0 || (y > 0 && abs(gridKey[y - 1][x] - gridKey[y][x]) == 1)) {
borderDirections -= Puzzle.BorderDirection.TOP
}
if (y == grid.size - 1 || (y < grid.size - 1 && abs(gridKey[y + 1][x] - gridKey[y][x]) == 1)) {
borderDirections -= Puzzle.BorderDirection.BOTTOM
}
if (x == 0 || (x > 0 && abs(gridKey[y][x - 1] - gridKey[y][x]) == 1)) {
borderDirections -= Puzzle.BorderDirection.LEFT
}
if (x == grid[y].size - 1 || (x < grid[y].size - 1 && abs(gridKey[y][x + 1] - gridKey[y][x]) == 1)) {
borderDirections -= Puzzle.BorderDirection.RIGHT
}
Puzzle.Cell(
solution = "$ch",
borderDirections = borderDirections,
number = if (x == 0) "${y + 1}" else ""
)
}
}
val windingPath = gridKey.mapIndexed { y, row ->
row.mapIndexed { x, i ->
i to Puzzle.Coordinate(x = x, y = y)
}
}.flatten().sortedBy { it.first }.map { it.second }
val windingClueList = if (alphabetizeWindingClues) windingClues.sorted() else windingClues
val windingWord = Puzzle.Word(101, windingPath)
val windingClue = Puzzle.Clue(101, "1", windingClueList.joinToString(" / "))
val (rowPuzzleClues, rowPuzzleWords) = puzzleGrid.mapIndexed { y, row ->
val clue = Puzzle.Clue(y + 1, "${y + 1}", rowClues[y].joinToString(" / "))
val word = Puzzle.Word(y + 1, row.indices.map { x -> Puzzle.Coordinate(x = x, y = y) })
clue to word
}.unzip()
return Puzzle(
title = title,
creator = creator,
copyright = copyright,
description = description,
grid = puzzleGrid,
clues = listOf(
Puzzle.ClueList("Rows", rowPuzzleClues),
Puzzle.ClueList("Winding", listOf(windingClue))
),
words = rowPuzzleWords + windingWord,
)
}
} | 5 | Kotlin | 5 | 19 | c2dc23bafc7236ba076a63060e08e6dc134c8e24 | 3,598 | kotwords | Apache License 2.0 |
2019/src/main/kotlin/adventofcode/day04/main.kt | analogrelay | 47,284,386 | false | {"Go": 93140, "F#": 42601, "Common Lisp": 36618, "Rust": 35214, "Kotlin": 15705, "Erlang": 15613, "TypeScript": 9933, "Swift": 4317, "HTML": 1721, "Shell": 1388, "PowerShell": 1180, "CSS": 990, "Makefile": 293, "JavaScript": 165} | package adventofcode.day04
fun main(args: Array<String>) {
if (args.size < 2) {
System.err.println("Usage: adventofcode day04 <START> <END>")
System.exit(1)
}
val start = args[0].toInt()
val end = args[1].toInt()
println("Computing passwords in range $start - $end")
val part1Passwords = (start..end).filter { isValidPassword(it, true) }
println("[Part 1] Number of valid passwords: ${part1Passwords.size}")
val part2Passwords = (start..end).filter { isValidPassword(it, false) }
// for(invalidPassword in part1Passwords.minus(part2Passwords)) {
// println("[Part 2] Invalid: $invalidPassword")
// }
// for(validPassword in part2Passwords) {
// println("[Part 2] Valid: $validPassword")
// }
println("[Part 2] Number of valid passwords: ${part2Passwords.size}")
}
fun Int.iterateDigits(): List<Int> {
var number = this
return generateSequence {
if (number == 0) {
null
} else {
val digit = number % 10
number = number / 10
digit
}
}.toList().reversed()
}
fun isValidPassword(candidate: Int, allowMoreThanTwoDigitSequence: Boolean): Boolean {
var last = -1
var activeSequenceLength = 0
var hasValidSequence = false
for (digit in candidate.iterateDigits()) {
if (last >= 0) {
if (last > digit) {
// Digits must be ascending
return false;
}
if (allowMoreThanTwoDigitSequence) {
if(last == digit) {
hasValidSequence = true
}
}
else if (last != digit) {
if (activeSequenceLength == 2) {
// Found a sequence of exactly two digits
hasValidSequence = true
}
activeSequenceLength = 0
}
}
activeSequenceLength += 1
last = digit
}
return hasValidSequence || activeSequenceLength == 2
}
| 0 | Go | 0 | 2 | 006343d0c05d12556605cc4d2c2d47938ce09045 | 2,119 | advent-of-code | Apache License 2.0 |
src/main/kotlin/day-05.kt | warriorzz | 728,357,548 | false | {"Kotlin": 15609, "PowerShell": 237} | package com.github.warriorzz.aoc
class Day5 : Day(5) {
override fun init() {
}
override val partOne: (List<String>, Boolean) -> String = { input, _ ->
val seeds1 = input[0].split(": ")[1].split(" ").map { it.toLong() }
val converterMaps1 = ArrayList<ArrayList<Triple<Long, Long, Long>>>()
var current1 = 0
converterMaps1.add(ArrayList())
input.drop(3).forEach {
if (it.isEmpty()) {
current1++
converterMaps1.add(ArrayList())
} else if (it[0].isDigit()) {
val split = it.split(" ").map { it.toLong() }
converterMaps1[current1].add(Triple(split[1], split[0], split[2]))
}
}
seeds1.map { seed ->
var currentSeed = seed
(0 until converterMaps1.size).forEach { i ->
val converter = converterMaps1[i]
for (x in converter) {
if (currentSeed in x.first..<x.first + x.third) {
currentSeed = currentSeed - x.first + x.second
return@forEach
}
}
}
currentSeed
}.min().toString()
}
override val partTwo: (List<String>, Boolean) -> String = { input, _ ->
val seeds = input[0].split(": ")[1].split(" ").map { it.toLong() }
val newSeed = ArrayList<LongRange>()
var skip = false
for (x in seeds.indices) {
if (!skip) {
newSeed.add(seeds[x] until seeds[x] + seeds[x + 1])
skip = true
} else {
skip = false
}
}
val converterMaps = ArrayList<ArrayList<Triple<Long, Long, Long>>>()
var current = 0
converterMaps.add(ArrayList())
input.drop(3).forEach {
if (it.isEmpty()) {
current++
converterMaps.add(ArrayList())
} else if (it[0].isDigit()) {
val split = it.split(" ").map { it.toLong() }
converterMaps[current].add(Triple(split[1], split[0], split[2]))
}
}
var min = Long.MAX_VALUE
newSeed.parallelStream().forEach ignored@{ seedRange ->
var small: Long = Long.MAX_VALUE
seedRange.forEach forEachSmall@{ seed ->
var currentSeed = seed
(0 until converterMaps.size).forEach { i ->
val converter = converterMaps[i]
for (x in converter) {
if (currentSeed in x.first..<x.first + x.third) {
currentSeed = currentSeed - x.first + x.second
return@forEach
}
}
}
if (small > currentSeed) small = currentSeed
}
if (small < min) min = small
}
min.toString()
}
}
| 0 | Kotlin | 0 | 1 | 502993c1cd414c0ecd97cda41475401e40ebb8c1 | 2,983 | aoc-23 | MIT License |
src/Day05.kt | tristanrothman | 572,898,348 | false | null | import java.io.File
fun main() {
fun solve(input: String, multipleCrates: Boolean): String {
val inputs = input.split("\n\n")
val size = inputs.component1().split("\n").last().trim().last().toString().toInt()
val stacks = Array(size) {
ArrayDeque<Char>()
}
inputs.component1().split("\n").dropLast(1).map { line ->
line.chunked(4).map { it.trim() }.forEachIndexed { stack, crate ->
if (crate.isNotEmpty()) {
stacks[stack].addFirst(crate[1])
}
}
}
inputs.component2().split("\n").map { line ->
Regex("move (\\d+) from (\\d+) to (\\d+)").matchEntire(line)?.let { regex ->
val numCrates = regex.groupValues[1].toInt()
val from = regex.groupValues[2].toInt() - 1
val to = regex.groupValues[3].toInt() - 1
if (multipleCrates) {
stacks[to] += stacks[from].takeLast(numCrates)
repeat(numCrates) {
stacks[from].removeLast()
}
} else {
repeat(regex.groupValues[1].toInt()) {
stacks[to].addLast(stacks[from].removeLast())
}
}
}
}
return stacks.joinToString("") { it.last().toString() }
}
val testInput = File("src", "Day05_test.txt").readText()
check(solve(testInput, false) == "CMZ")
check(solve(testInput, true) == "MCD")
val input = File("src", "Day05.txt").readText()
println(solve(input, false))
println(solve(input, true))
} | 0 | Kotlin | 0 | 0 | e794ab7e0d50f22d250c65b20e13d9b5aeba23e2 | 1,687 | advent-of-code-2022 | Apache License 2.0 |
2017/src/main/kotlin/Day11.kt | dlew | 498,498,097 | false | {"Kotlin": 331659, "TypeScript": 60083, "JavaScript": 262} | import utils.splitCommas
import kotlin.math.abs
object Day11 {
fun part1(input: String): Int {
return input
.splitCommas()
.fold(Hex(0, 0, 0), { hex, direction -> hex.move(direction) })
.distanceFromCenter()
}
fun part2(input: String): Int {
val directions = input.splitCommas()
var hex = Hex(0, 0, 0)
var max = 0
for (direction in directions) {
hex = hex.move(direction)
max = maxOf(max, hex.distanceFromCenter())
}
return max
}
private data class Hex(val x: Int, val y: Int, val z: Int) {
fun move(direction: String): Hex {
return when (direction) {
"n" -> copy(y = y + 1, z = z - 1)
"ne" -> copy(x = x + 1, z = z - 1)
"se" -> copy(x = x + 1, y = y - 1)
"s" -> copy(y = y - 1, z = z + 1)
"sw" -> copy(x = x - 1, z = z + 1)
"nw" -> copy(x = x - 1, y = y + 1)
else -> throw IllegalArgumentException("Unknown direction $direction")
}
}
fun distanceFromCenter(): Int {
return (abs(x) + abs(y) + abs(z)) / 2
}
}
} | 0 | Kotlin | 0 | 0 | 6972f6e3addae03ec1090b64fa1dcecac3bc275c | 1,082 | advent-of-code | MIT License |
src/Day01.kt | m0r0 | 576,999,741 | false | null | fun main() {
fun part1(input: List<String>): Int {
var maxSum = 0
var curSum = 0
for (value in input) {
value.toIntOrNull()?.let { curSum += it }
?: run {
if (curSum > maxSum) maxSum = curSum
curSum = 0
}
}
return maxSum
}
fun part2(input: List<String>): Int {
val sumsList = mutableListOf<Int>()
var curSum = 0
for (value in input) {
value.toIntOrNull()?.let { curSum += it }
?: run {
sumsList.add(curSum)
curSum = 0
}
}
return sumsList.sortedDescending().take(3).sum()
}
val input = readInput("Day01")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | b6f3c5229ad758f61f219040f8db61f654d7fc00 | 830 | kotlin-AoC-2022 | Apache License 2.0 |
src/main/kotlin/com/quakbo/euler/Euler6.kt | quincy | 120,237,243 | false | null | package com.quakbo.euler
/*
The sum of the squares of the first ten natural numbers is,
1^2 + 2^2 + ... + 10^2 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)^2 = 55^2 = 3025
Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.
Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
*/
private fun sumOfSquares(sequence: Sequence<Int>): Int {
return sequence
.map { it * it }
.sum()
}
private fun squareOfSums(sequence: Sequence<Int>): Int {
val sum = sequence.sum()
return sum * sum
}
fun main(args: Array<String>) {
val firstHundred = generateSequence(1, {i -> i + 1} ).take(100)
println(squareOfSums(firstHundred) - sumOfSquares(firstHundred))
}
/*
Sequences are a lot like Streams, but you can consume them as many times as you like. *hold for applause*
*/
| 0 | Kotlin | 0 | 0 | 01d96f61bda6e87f1f58ddf7415d9bca8a4913de | 1,000 | euler-kotlin | The Unlicense |
src/main/kotlin/dev/shtanko/algorithms/sorts/TimSort.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.sorts
import kotlin.math.min
class TimSort : AbstractSortStrategy {
companion object {
private const val RUN = 32
}
override fun <T : Comparable<T>> perform(arr: Array<T>) {
// Sort individual subarrays of size THRESHOLD
var i = 0
val length = arr.size
while (i < length) {
// perform insertion sort
insertionSort(arr, i, min(i + RUN - 1, length - 1))
i += RUN
}
var size: Int = RUN
while (size < length) {
var left = 0
while (left < length) {
left += 2 * size
}
size *= 2
}
}
// this function sorts array from left index
// to right index which is of size almost THRESHOLD
private fun <T : Comparable<T>> insertionSort(arr: Array<T>, left: Int, right: Int) {
for (i in left + 1..right) {
val temp = arr[i]
var j = i - 1
while (j >= 0 && arr[j] > temp && j >= left) {
arr[j + 1] = arr[j]
j--
}
arr[j + 1] = temp
}
}
// merge function merges the sorted runs
private inline fun <reified T : Comparable<T>> merge(arr: Array<T>, left: Int, mid: Int, right: Int) {
val leftArryLen = mid - left + 1
val rightArrLen = right - mid
val leftArr = arrayOfNulls<T>(leftArryLen)
val rightArr = arrayOfNulls<T>(rightArrLen)
for (x in 0 until leftArryLen) {
leftArr[x] = arr[left + x]
}
for (x in 0 until rightArrLen) {
rightArr[x] = arr[mid + 1 + x]
}
var i = 0
var j = 0
var k = left
while (i < leftArryLen && j < rightArrLen) {
if (leftArr[i]!! <= rightArr[j]!!) {
arr[k] = leftArr[i]!!
i++
} else {
arr[k] = rightArr[j]!!
j++
}
k++
}
// copy remaining elements of left, if any
while (i < leftArryLen) {
arr[k] = leftArr[i]!!
k++
i++
}
// copy remaining element of right, if any
while (j < rightArrLen) {
arr[k] = rightArr[j]!!
k++
j++
}
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,955 | kotlab | Apache License 2.0 |
Pells_equation/Kotlin/src/Pell.kt | ncoe | 108,064,933 | false | {"D": 425100, "Java": 399306, "Visual Basic .NET": 343987, "C++": 328611, "C#": 289790, "C": 216950, "Kotlin": 162468, "Modula-2": 148295, "Groovy": 146721, "Lua": 139015, "Ruby": 84703, "LLVM": 58530, "Python": 46744, "Scala": 43213, "F#": 21133, "Perl": 13407, "JavaScript": 6729, "CSS": 453, "HTML": 409} | import java.math.BigInteger
import kotlin.math.sqrt
class BIRef(var value: BigInteger) {
operator fun minus(b: BIRef): BIRef {
return BIRef(value - b.value)
}
operator fun times(b: BIRef): BIRef {
return BIRef(value * b.value)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as BIRef
if (value != other.value) return false
return true
}
override fun hashCode(): Int {
return value.hashCode()
}
override fun toString(): String {
return value.toString()
}
}
fun f(a: BIRef, b: BIRef, c: Int) {
val t = a.value
a.value = b.value
b.value = b.value * BigInteger.valueOf(c.toLong()) + t
}
fun solvePell(n: Int, a: BIRef, b: BIRef) {
val x = sqrt(n.toDouble()).toInt()
var y = x
var z = 1
var r = x shl 1
val e1 = BIRef(BigInteger.ONE)
val e2 = BIRef(BigInteger.ZERO)
val f1 = BIRef(BigInteger.ZERO)
val f2 = BIRef(BigInteger.ONE)
while (true) {
y = r * z - y
z = (n - y * y) / z
r = (x + y) / z
f(e1, e2, r)
f(f1, f2, r)
a.value = f2.value
b.value = e2.value
f(b, a, x)
if (a * a - BIRef(n.toBigInteger()) * b * b == BIRef(BigInteger.ONE)) {
return
}
}
}
fun main() {
val x = BIRef(BigInteger.ZERO)
val y = BIRef(BigInteger.ZERO)
intArrayOf(61, 109, 181, 277).forEach {
solvePell(it, x, y)
println("x^2 - %3d * y^2 = 1 for x = %,27d and y = %,25d".format(it, x.value, y.value))
}
}
| 0 | D | 0 | 4 | c2a9f154a5ae77eea2b34bbe5e0cc2248333e421 | 1,659 | rosetta | MIT License |
examples/nearestNeighbor/src/main/kotlin/NearestNeighbor.kt | Kotlin | 225,367,588 | false | {"Kotlin": 435270, "C": 152277, "Python": 7577} | import org.jetbrains.numkt.*
import org.jetbrains.numkt.core.KtNDArray
import org.jetbrains.numkt.core.ravel
import org.jetbrains.numkt.math.*
import org.jetbrains.numkt.random.Random
fun generateRandomPoints(size: Int = 10, min: Int = 0, max: Int = 1): KtNDArray<Double> =
(max - min) * Random.randomSample(size, 2) + min
class NearestNeighbor(private val distance: Int = 0) {
private lateinit var xTrain: KtNDArray<Double>
private lateinit var yTrain: KtNDArray<Int>
fun train(x: KtNDArray<Double>, y: KtNDArray<Int>) {
xTrain = x
yTrain = y
}
fun predict(x: KtNDArray<Double>): ArrayList<Int> {
val predictions = ArrayList<Int>()
for (x_i in x) {
if (distance == 0) {
val distances = sum(absolute(xTrain - x_i), axis = 1)
val minIndex = argMin(distances)
predictions.add(yTrain[minIndex].scalar!!)
} else if (distance == 1) {
val distances = sum(square(xTrain - x_i), axis = 1)
val minIndex = argMin(distances)
predictions.add(yTrain[minIndex].scalar!!)
}
}
return predictions
}
}
class Analysis(x: Array<KtNDArray<Double>>, distance: Int) {
lateinit var xTest: KtNDArray<Double>
private set
lateinit var yTest: ArrayList<Int>
private set
private val nofClasses: Int = x.size
private lateinit var range: Pair<Int, Int>
private val classified: ArrayList<KtNDArray<Double>> = ArrayList()
private val nn: NearestNeighbor
init {
val listY = ArrayList<KtNDArray<Long>>()
for ((i, el) in x.indices.zip(x)) {
listY.add(i * ones(el.shape[0]))
}
val xt = concatenate(*x, axis = 0)
nn = NearestNeighbor(distance)
nn.train(xt, array<Int>(listY).ravel())
}
fun prepareTestSamples(min: Int = 0, max: Int = 2, step: Double = 0.01) {
range = Pair(min, max)
// grid
val grid = arrayOf(empty<Double>(201, 201), empty(201, 201))
var s = 0.0
for (j in 0..200) {
for (k in 0..200) {
grid[0][j, k] = s
}
s += step
}
for (j in 0..200) {
s = 0.0
for (k in 0..200) {
grid[1][j, k] = s
s += step
}
}
xTest = vstack(grid[0].ravel(), grid[1].ravel()).t
}
fun analyse() {
yTest = nn.predict(xTest)
for (label in 0 until nofClasses) {
val classI = ArrayList<KtNDArray<Double>>()
for (i in 0 until yTest.size) {
if (yTest[i] == label) {
classI.add(xTest[i..(i + 1)].ravel())
}
}
classified.add(array(classI))
}
}
}
fun main() {
val x1 = generateRandomPoints(50, 0, 1)
val x2 = generateRandomPoints(50, 1, 2)
var tempX = generateRandomPoints(50, 0, 1)
var listX = arrayListOf<List<Double>>()
for (tx in tempX) {
listX.add(arrayListOf(tx[0].scalar!!, tx[1].scalar!! + 1))
}
val x3 = array<Double>(listX)
tempX = generateRandomPoints(50, 1, 2)
listX = arrayListOf()
for (tx in tempX) {
listX.add(arrayListOf(tx[0].scalar!!, tx[1].scalar!! - 1))
}
val x4 = array<Double>(listX)
val c4 = Analysis(arrayOf(x1, x2, x3, x4), distance = 1)
c4.prepareTestSamples()
c4.analyse()
// accuracy
var accuracy = 0.0
var i = 0
for (x_i in c4.xTest) {
val trueLabel: Int = if (x_i[0].scalar!! < 1 && x_i[1].scalar!! < 1) {
0
} else if (x_i[0].scalar!! > 1 && x_i[1].scalar!! > 1) {
1
} else if (x_i[0].scalar!! < 1 && x_i[1].scalar!! > 1) {
2
} else {
3
}
if (trueLabel == c4.yTest[i++]) {
accuracy += 1
}
}
accuracy /= c4.xTest.shape[0]
println(accuracy)
} | 11 | Kotlin | 11 | 313 | 2f1421883c201df60c57eaa4db4c3ee74dc40413 | 4,001 | kotlin-numpy | Apache License 2.0 |
shared/src/commonMain/kotlin/io/ktlab/bshelper/model/enums/SortEnum.kt | ktKongTong | 694,984,299 | false | {"Kotlin": 836333, "Shell": 71} | package io.ktlab.bshelper.model.enums
import io.ktlab.bshelper.model.IMap
enum class SortKey(val human: String, val slug: String) {
DEFAULT("默认", "default"),
NPS("NPS", "nps"),
DURATION("时长", "duration"),
NOTES("方块数", "notes"),
;
// BLOCKS,
override fun toString(): String {
return human
}
companion object {
private val map = entries.associateBy(SortKey::slug)
fun fromSlug(slug: String) = map[slug]
val allSortKeys = entries.toTypedArray()
}
}
enum class SortType {
ASC,
DESC,
;
fun reverse(): SortType {
return if (this == ASC) DESC else ASC
}
}
fun SortKey.getSortKey(): (IMap) -> Comparable<*> {
return when (this) {
SortKey.DEFAULT -> { it -> it.getID() }
SortKey.NPS -> { it -> it.getMaxNPS() }
SortKey.DURATION -> { it -> it.getDuration() }
SortKey.NOTES -> { it -> it.getMaxNotes() }
// SortKey.BLOCKS -> { it -> it.get() }
}
}
fun SortType.getCompareByFunction(): (Comparable<*>) -> Comparator<Comparable<*>> {
return when (this) {
SortType.ASC -> { x -> compareBy() }
SortType.DESC -> { x -> compareBy() }
}
}
fun SortKey.getSortKeyComparator(sortType: SortType): Comparator<IMap> {
return when (this) {
SortKey.DEFAULT -> if (sortType == SortType.ASC) compareBy { it.getID() } else compareByDescending { it.getID() }
SortKey.NPS -> if (sortType == SortType.ASC) compareBy { it.getMaxNPS() } else compareByDescending { it.getMaxNPS() }
SortKey.DURATION -> if (sortType == SortType.ASC) compareBy { it.getDuration() } else compareByDescending { it.getDuration() }
SortKey.NOTES -> if (sortType == SortType.ASC) compareBy { it.getMaxNotes() } else compareByDescending { it.getMaxNotes() }
}
}
fun Pair<SortKey, SortType>.getSortKeyComparator(): Comparator<IMap> {
return this.first.getSortKeyComparator(this.second)
}
| 3 | Kotlin | 0 | 0 | 5e5ea79e31bc6c4a2565c191cddb7769e8007b45 | 1,971 | cm-bs-helper | MIT License |
stripecardscan/src/main/java/com/stripe/android/stripecardscan/framework/ml/NonMaximumSuppression.kt | stripe | 6,926,049 | false | {"Kotlin": 10509333, "Java": 71963, "Ruby": 22569, "Shell": 20387, "Python": 13907, "HTML": 7519} | package com.stripe.android.stripecardscan.framework.ml
import com.stripe.android.stripecardscan.framework.ml.ssd.RectForm
import com.stripe.android.stripecardscan.framework.ml.ssd.areaClamped
import com.stripe.android.stripecardscan.framework.ml.ssd.overlapWith
/**
* In this project we implement HARD NMS and NOT Soft NMS. I highly recommend checkout SOFT NMS
* implementation of Facebook Detectron Framework.
*
* See https://towardsdatascience.com/non-maximum-suppression-nms-93ce178e177c
*
* @param boxes: Detected boxes
* @param probabilities: Probabilities of the given boxes
* @param iouThreshold: intersection over union threshold.
* @param limit: keep this number of results. If limit <= 0, keep all the results.
*
* @return pickedIndices: a list of indexes of the kept boxes
*/
internal fun hardNonMaximumSuppression(
boxes: Array<FloatArray>,
probabilities: FloatArray,
iouThreshold: Float,
limit: Int?
): ArrayList<Int> {
val indexArray = probabilities.indices.sortedByDescending { probabilities[it] }
.take(200)
.toMutableList()
val pickedIndexes = ArrayList<Int>()
while (indexArray.isNotEmpty()) {
val current = indexArray.removeAt(0)
pickedIndexes.add(current)
if (pickedIndexes.size == limit) {
return pickedIndexes
}
val iterator = indexArray.iterator()
while (iterator.hasNext()) {
if (intersectionOverUnionOf(boxes[current], boxes[iterator.next()]) >= iouThreshold) {
iterator.remove()
}
}
}
return pickedIndexes
}
/**
* Return intersection-over-union (Jaccard index) of boxes.
*
* Args:
* boxes0 (N, 4): ground truth boxes.
* boxes1 (N or 1, 4): predicted boxes.
* eps: a small number to avoid 0 as denominator.
* Returns: iou (N): IOU values
*/
private fun intersectionOverUnionOf(currentBox: RectForm, nextBox: RectForm): Float {
val eps = 0.00001f
val overlapArea = nextBox.overlapWith(currentBox).areaClamped()
val nextArea = nextBox.areaClamped()
val currentArea = currentBox.areaClamped()
return overlapArea / (nextArea + currentArea - overlapArea + eps)
}
/**
* Runs greedy NonMaxSuppression over the raw predictions. Greedy NMS looks for the local maximas
* ("peaks") in the prediction confidences of the consecutive same predictions, keeps those,
* and replaces the other values as the background class.
*
* Example: given the following [rawPredictions] and [confidence] pair
* [rawPredictions]: [LABEL0, LABEL0, LABEL0, LABEL1, LABEL1, LABEL1]
* [confidence]: [0.1, 0.2, 0.4, 0.3, 0.5, 0.3]
* Output: [BACKGROUND, BACKGROUND, LABEL0, BACKGROUND, LABEL, BACKGROUND]
*/
internal fun <Input> greedyNonMaxSuppression(
rawPredictions: Array<Input>,
confidence: FloatArray,
backgroundClass: Input
): Array<Input> {
val digits = rawPredictions.clone()
// greedy non max suppression
for (idx in 0 until digits.size - 1) {
if (digits[idx] != backgroundClass && digits[idx + 1] != backgroundClass) {
if (confidence[idx] < confidence[idx + 1]) {
digits[idx] = backgroundClass
} else {
digits[idx + 1] = backgroundClass
}
}
}
return digits
}
| 118 | Kotlin | 636 | 1,190 | af9342071f016bcfbb52d6561e311258081cd06a | 3,328 | stripe-android | MIT License |
src/Day01.kt | hanmet | 573,490,488 | false | {"Kotlin": 9896} | import java.util.regex.Pattern
fun main() {
fun part1(input: String): Int {
return input.split(Pattern.compile("\n\n"))
.map { line -> line.split("\n").map { num -> num.toInt() } }
.map { it.sum() }
.max()
}
fun part2(input: String): Int {
return input.split(Pattern.compile("\n\n"))
.map { line -> line.split("\n").map { num -> num.toInt() } }
.map { it.sum() }
.sortedDescending()
.take(3)
.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readText("Day01_test")
check(part1(testInput) == 24000)
val input = readText("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | e4e1722726587639776df86de8d4e325d1defa02 | 774 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/fr/chezbazar/aoc23/day11/Day11.kt | chezbazar | 728,404,822 | false | {"Kotlin": 54427} | package fr.chezbazar.aoc23.day11
import fr.chezbazar.aoc23.Point
import fr.chezbazar.aoc23.computeFromIndexed
fun main() {
val galaxyMap = mutableListOf<Point>()
computeFromIndexed("day11/input.txt") { y, line ->
line.forEachIndexed { x, c ->
if (c == '#') {
galaxyMap.add(Point(x, y))
}
}
}
val bigExpansionGalaxy = galaxyMap.toMutableList()
galaxyMap.expandGalaxy(1)
bigExpansionGalaxy.expandGalaxy(999_999)
println(galaxyMap.computeDistances().sum()/2)
println(bigExpansionGalaxy.computeDistances().sum()/2)
}
fun MutableList<Point>.expandGalaxy(amount: Int) {
val expandedX = (0..<this.maxOf { it.x }).filter { value -> this.none { it.x == value } }
val expandedY = (0..<this.maxOf { it.y }).filter { value -> this.none { it.y == value } }
this.forEachIndexed { index, point ->
this[index] = point + Point(amount * expandedX.filter { it < point.x }.size, amount * expandedY.filter { it < point.y }.size)
}
}
fun List<Point>.computeDistances() = this.map { point -> this.sumOf { it.distanceTo(point).toLong() } } | 0 | Kotlin | 0 | 0 | 223f19d3345ed7283f4e2671bda8ac094341061a | 1,131 | adventofcode | MIT License |
src/2021/Day15.kt | nagyjani | 572,361,168 | false | {"Kotlin": 369497} | package `2021`
import common.*
import java.io.File
import java.util.*
fun main() {
Day15().solve()
}
class Day15 {
val input = """
1163751742
1381373672
2136511328
3694931569
7463417111
1319128137
1359912421
3125421639
1293138521
2311944581
""".trimIndent()
fun StringBuilder.toCave(): List<Int> {
return toString().map{it.toString().toInt()}
}
fun to1to9(n: Int): Int {
return if (n<10) n else n%9
}
fun StringBuilder.toCave5(x: Int, y: Int): List<Int> {
val cave1 = toCave()
val l1 = Linearizer(5, 5)
val l2 = Linearizer(x, y)
val l12 = Linearizer(x, 5, y, 5)
val cave5 = MutableList(l12.size){0}
for (i in l1.indexes) {
for (j in l2.indexes) {
val c1 = l1.toCoordinates(i)
val c2 = l2.toCoordinates(j)
val ix5 = l12.toIndex(c2[0], c1[0], c2[1], c1[1])
cave5[ix5] = to1to9(cave1[j] + c1[0] + c1[1])
}
}
return cave5
}
fun solve() {
val f = File("src/2021/inputs/day15.in")
val s = Scanner(f)
// val s = Scanner(input)
val caveBuilder = StringBuilder()
caveBuilder.append(s.nextLine())
val x0 = caveBuilder.length
while (s.hasNextLine()) {
caveBuilder.append(s.nextLine())
}
val y0 = caveBuilder.length/x0
val cave = caveBuilder.toCave5(x0, y0)
println("$x0 $y0 ${cave.size}")
val l = Linearizer(x0 * 5, y0 * 5)
val startIx = l.toIndex(0, 0)
val finalIx = l.toIndex(x0*5-1, y0*5-1)
val caveRisk = MutableList(cave.size){-1}
caveRisk[startIx] = 0
val border = mutableSetOf(startIx)
val neighbours =
listOf(
l.offset(0, -1),
l.offset(0, 1),
l.offset(-1, 0),
l.offset(1, 0))
while (border.isNotEmpty()) {
val minBorderIx = border.minByOrNull { caveRisk[it] }!!
val minBorderRisk = caveRisk[minBorderIx]
if (minBorderIx == finalIx) {
println(minBorderRisk)
break
}
border.remove(minBorderIx)
for (i in neighbours.around(minBorderIx)) {
val newRisk = minBorderRisk + cave[i]
if (caveRisk[i] == -1) {
caveRisk[i] = newRisk
border.add(i)
} else if (caveRisk[i] > newRisk) {
caveRisk[i] = newRisk
}
}
}
}
} | 0 | Kotlin | 0 | 0 | f0c61c787e4f0b83b69ed0cde3117aed3ae918a5 | 2,603 | advent-of-code | Apache License 2.0 |
src/main/kotlin/days/Day07.kt | Kebaan | 573,069,009 | false | null | package days
import days.Day07.VirtualEntry.VirtualDirectory
import days.Day07.VirtualEntry.VirtualFile
import utils.Day
typealias VirtualPath = String
typealias FileSize = Int
fun main() {
Day07.solve()
}
object Day07 : Day<Int>(2022, 7) {
private val CD_COMMAND_REGEX = """[$] cd (.*)""".toRegex()
private val SIZE_REGEX = """(\d+) (.*)""".toRegex()
private const val rootPath = "/"
private fun parseInput(input: List<String>): VirtualFileSystem {
val fileSystem = VirtualFileSystem("/")
var cwd = rootPath
for (line in input) {
CD_COMMAND_REGEX.matchEntire(line)?.destructured?.let { (dir) ->
cwd = when (dir) {
rootPath -> rootPath
".." -> fileSystem.findParentPath(cwd)
else -> if (cwd == rootPath) "/$dir" else "$cwd/$dir"
}
fileSystem.addDirectoryIfAbsent(cwd)
} ?: SIZE_REGEX.matchEntire(line)?.destructured?.let { (size, fileName) ->
val dir = if (cwd == rootPath) "/$fileName" else "$cwd/$fileName"
fileSystem.addFileIfAbsent(dir, size.toInt())
}
}
return fileSystem
}
override fun part1(input: List<String>): Int {
val fileSystem = parseInput(input)
return fileSystem.findAllEntriesBy {
(it is VirtualDirectory && it.size <= 100000)
}.sumOf { it.size }
}
override fun part2(input: List<String>): Int {
val fileSystem = parseInput(input)
val totalDiskSpace = 70_000_000
val totalUsed = fileSystem.lookupSize(rootPath)
val neededUnusedSpace = 30_000_000
return fileSystem.findAllEntriesBy {
it is VirtualDirectory && totalDiskSpace - (totalUsed - it.size) >= neededUnusedSpace
}.minOf { it.size }
}
override fun doSolve() {
part1(input).let {
println(it)
check(it == 1644735)
}
part2(input).let {
println(it)
check(it == 1300850)
}
}
sealed interface VirtualEntry {
val path: VirtualPath
val size: FileSize
data class VirtualDirectory(override val path: VirtualPath, override val size: FileSize) : VirtualEntry
data class VirtualFile(override val path: VirtualPath, override val size: FileSize) : VirtualEntry
}
class VirtualFileSystem(
private val rootPath: VirtualPath,
) {
private val data: MutableMap<VirtualPath, VirtualEntry> =
mutableMapOf(rootPath to VirtualDirectory(rootPath, 0))
fun findAllEntriesBy(predicate: (VirtualEntry) -> Boolean): List<VirtualEntry> {
return data.filter { predicate(it.value) }.map { it.value }.toList()
}
fun findParentPath(orgPath: VirtualPath): VirtualPath {
val parentPath = orgPath.substringBeforeLast('/')
return parentPath.ifEmpty { rootPath }
}
fun lookupSize(virtualPath: VirtualPath): FileSize {
return get(virtualPath).size
}
fun addDirectoryIfAbsent(path: VirtualPath) {
data.computeIfAbsent(path) { VirtualDirectory(it, 0) }
}
fun addFileIfAbsent(path: VirtualPath, size: FileSize) {
data.computeIfAbsent(path) {
var dir = path
while (true) {
dir = findParentPath(dir)
updateSizes(dir, size)
if (dir == rootPath) break
}
VirtualFile(path, size)
}
}
private fun updateSizes(path: VirtualPath, size: FileSize) {
val entry = get(path)
val newSize = entry.size + size
val updatedEntry = when (entry) {
is VirtualDirectory -> entry.copy(size = newSize)
is VirtualFile -> entry.copy(size = newSize)
}
data[path] = updatedEntry
}
fun get(path: VirtualPath): VirtualEntry {
return data[path] ?: error("invalid input")
}
}
override val testInput = """
$ cd /
$ ls
dir a
14848514 b.txt
8504156 c.dat
dir d
$ cd a
$ ls
dir e
29116 f
2557 g
62596 h.lst
$ cd e
$ ls
584 i
$ cd ..
$ cd ..
$ cd d
$ ls
4060174 j
8033020 d.log
5626152 d.ext
7214296 k""".trimIndent().lines()
}
| 0 | Kotlin | 0 | 0 | ef8bba36fedbcc93698f3335fbb5a69074b40da2 | 4,663 | Advent-of-Code-2022 | Apache License 2.0 |
advent-of-code-2021/src/main/kotlin/eu/janvdb/aoc2021/day11/Day11.kt | janvdbergh | 318,992,922 | false | {"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335} | package eu.janvdb.aoc2021.day11
import eu.janvdb.aocutil.kotlin.readNonSeparatedDigits
const val FILENAME = "input11.txt"
const val NUMBER_OF_STEPS = 100
fun main() {
part1()
part2()
}
private fun part1() {
val board = Board.create()
var result = 0
for (i in 0 until NUMBER_OF_STEPS) {
result += board.step()
}
board.print()
println(result)
}
private fun part2() {
val board = Board.create()
var step = 0
while (true) {
step++
val result = board.step()
if (result == board.width * board.height) break
}
board.print()
println(step)
}
data class Board(val width: Int, val height: Int, val digits: MutableList<Int>) {
fun step(): Int {
val hasFlashed = MutableList(digits.size) { false }
fun getFlashed(i: Int, j: Int): Boolean {
if (i < 0 || i >= width || j < 0 || j >= height) return false
return hasFlashed[i * width + j]
}
fun setFlashed(i: Int, j: Int) {
if (i < 0 || i >= width || j < 0 || j >= height) return
hasFlashed[i * width + j] = true
}
digits.indices.forEach { digits[it] = digits[it] + 1 }
var changed = true
while (changed) {
changed = false
for (i in 0 until height) {
for (j in 0 until width) {
if (!getFlashed(i, j) && getValue(i, j) >= 10) {
setFlashed(i, j)
incrementValue(i - 1, j - 1)
incrementValue(i - 1, j)
incrementValue(i - 1, j + 1)
incrementValue(i, j - 1)
incrementValue(i, j + 1)
incrementValue(i + 1, j - 1)
incrementValue(i + 1, j)
incrementValue(i + 1, j + 1)
changed = true
}
}
}
}
digits.indices.forEach { if (digits[it] >= 10) digits[it] = 0 }
return hasFlashed.count { it }
}
fun print() {
for (i in 0 until height) {
for (j in 0 until width) {
print(getValue(i, j))
}
println()
}
println()
}
private fun getValue(i: Int, j: Int): Int {
if (i < 0 || i >= width || j < 0 || j >= height) return 0
return digits[i * width + j]
}
private fun incrementValue(i: Int, j: Int) {
if (i < 0 || i >= width || j < 0 || j >= height) return
digits[i * width + j] = digits[i * width + j] + 1
}
companion object {
fun create(): Board {
val digits = readNonSeparatedDigits(2021, FILENAME)
return Board(digits[0].size, digits.size, digits.flatten().toMutableList())
}
}
} | 0 | Java | 0 | 0 | 78ce266dbc41d1821342edca484768167f261752 | 2,299 | advent-of-code | Apache License 2.0 |
2020/09/Solution.kt | AdrianMiozga | 588,519,359 | false | {"Kotlin": 110785, "Python": 11275, "Assembly": 3369, "C": 2378, "Pawn": 1390, "Dart": 732} | import java.io.File
private const val FILENAME = "2020/09/input.txt"
private const val PREAMBLE = 25
fun main() {
val result = partOne()
partTwo(result)
}
private fun partOne(): Long {
var result = 0L
val lines = File(FILENAME).readLines()
entry@ for (i in PREAMBLE + 1 until lines.size) {
val numbers: MutableSet<Long> = mutableSetOf()
for (j in i - PREAMBLE until i) {
for (k in i - PREAMBLE until i) {
if (j == k) {
continue
}
val sum = lines[j].toLong() + lines[k].toLong()
if (sum == lines[i].toLong()) {
continue@entry
}
numbers.add(sum)
}
}
result = lines[i].toLong()
println(result)
}
return result
}
private fun partTwo(input: Long) {
val lines = File(FILENAME).readLines()
var min = 0
var max = 1
do {
var sum = 0L
val numbers: MutableSet<Long> = mutableSetOf()
for (i in min..max) {
sum += lines[i].toLong()
numbers.add(lines[i].toLong())
}
if (sum == input) {
val sorted = numbers.sorted()
println(sorted.first() + sorted.last())
return
} else if (sum > input) {
min += 1
max = min + 1
} else {
max++
}
} while (true)
}
| 0 | Kotlin | 0 | 0 | c9cba875089d8d4fb145932c45c2d487ccc7e8e5 | 1,454 | Advent-of-Code | MIT License |
aoc2022/day25.kt | davidfpc | 726,214,677 | false | {"Kotlin": 127212} | package aoc2022
import utils.InputRetrieval
import kotlin.math.pow
fun main() {
Day25.execute()
}
object Day25 {
fun execute() {
val input = readInput()
println("Part 1: ${part1(input)}")
}
private val DIGIT_MAP = mapOf('=' to -2, '-' to -1, '0' to 0, '1' to 1, '2' to 2)
private val DIGIT_MAP_INVERSE = DIGIT_MAP.map { it.value.toLong() to it.key }.toMap()
fun part1(input: List<String>): String = input.sumOf { it.convertSNAFUToDecimal() }.convertDecimalToSNAFU()
private fun String.convertSNAFUToDecimal() = this.reversed().mapIndexed { index, i -> DIGIT_MAP[i]!! * (5.0.pow(index).toLong()) }.sum()
private fun Long.convertDecimalToSNAFU(): String {
return if (this == 0L) ""
else when (val m = this % 5L) {
0L, 1L, 2L -> (this / 5L).convertDecimalToSNAFU() + DIGIT_MAP_INVERSE[m]!!
3L, 4L -> (this / 5L + 1L).convertDecimalToSNAFU() + DIGIT_MAP_INVERSE[m - 5L]!!
else -> throw Exception("modulus fail for $this")
}
}
private fun readInput(): List<String> = InputRetrieval.getFile(2022, 25).readLines()
}
| 0 | Kotlin | 0 | 0 | 8dacf809ab3f6d06ed73117fde96c81b6d81464b | 1,132 | Advent-Of-Code | MIT License |
Algorithms/Strings/Strong Password/Solution.kt | ahmed-mahmoud-abo-elnaga | 449,443,709 | false | {"Kotlin": 14218} | /*
Problem: https://www.hackerrank.com/challenges/strong-password/problem
Kotlin Language Version
Tool Version : Android Studio
Thoughts :
Keep iterating the input string untill
- at least one digit is found
- at least one lower case alphabet is found
- at least one upper case alphabet is found
- at least special character is found
- at least 6 characters have been traversed
In the end extra chars will be required depending upon each of the conditions (above mentioned) which is still false.
Time Complexity: O(n)
Space Complexity: O(1) //number of dynamically allocated variables remain constant for any input.
*/
object Main {
fun minimumNumber(n: Int, password: String): Int {
// Return the minimum number of characters to make the password strong
/*
-at least one digit is found
-at least one lower case alphabet is found
-at least one upper case alphabet is found
-at least special character is found*/
var specialCharsCount = 4
if (Pattern.compile("[!@#$%^&*()\\-\\+]").matcher(password).find()) specialCharsCount--
if (Pattern.compile("[a-z]").matcher(password).find()) specialCharsCount--
if (Pattern.compile("[A-Z]").matcher(password).find()) specialCharsCount--
if (Pattern.compile("[0-9]").matcher(password).find()) specialCharsCount--
return Math.max(6 - n, specialCharsCount)
}
fun main(args: Array<String>) {
val n = readLine()!!.trim().toInt()
val password = readLine()!!
val answer = minimumNumber(n, password)
println(answer)
}
}
| 0 | Kotlin | 1 | 1 | a65ee26d47b470b1cb2c1681e9d49fe48b7cb7fc | 1,720 | HackerRank | MIT License |
src/main/kotlin/com/staricka/adventofcode2022/Day21.kt | mathstar | 569,952,400 | false | {"Kotlin": 77567} | package com.staricka.adventofcode2022
import com.staricka.adventofcode2022.Day21.Monkey.Companion.parseMonkey
import java.util.Random
class Day21 : Day {
override val id = 21
interface Job {
fun value(monkeys: Map<String, Monkey>): Long
fun includesHuman(monkeys: Map<String, Monkey>): Boolean
}
class ConstantJob(private val value: Long) : Job {
override fun value(monkeys: Map<String, Monkey>): Long = value
override fun includesHuman(monkeys: Map<String, Monkey>): Boolean = false
}
enum class Op {
PLUS, TIMES, MINUS, DIVIDE
}
// left and right fields for debugging
@Suppress("unused")
class DivisionException(val left: Long, val right: Long) : Exception()
class OperationJob(val left: String, val right: String, val op: Op) : Job {
override fun value(monkeys: Map<String, Monkey>): Long {
val leftVal = monkeys[left]!!.job.value(monkeys)
val rightVal = monkeys[right]!!.job.value(monkeys)
return when(op) {
Op.PLUS -> Math.addExact(leftVal, rightVal)
Op.TIMES -> Math.multiplyExact(leftVal, rightVal)
Op.MINUS -> Math.subtractExact(leftVal, rightVal)
Op.DIVIDE -> {
if (leftVal % rightVal != 0L) throw DivisionException(leftVal, rightVal)
leftVal / rightVal
}
}
}
override fun includesHuman(monkeys: Map<String, Monkey>): Boolean =
monkeys[left]!!.job.includesHuman(monkeys) ||
monkeys[right]!!.job.includesHuman(monkeys)
}
class HumanJob(private val value: Long) : Job {
override fun value(monkeys: Map<String, Monkey>): Long = value
override fun includesHuman(monkeys: Map<String, Monkey>): Boolean = true
}
class Monkey(val id: String, val job: Job) {
companion object {
val opRegex = Regex("""([a-z]+): ([a-z]+) ([+-/*]) ([a-z]+)""")
val constRegex = Regex("""([a-z]+): (-?[0-9]+)""")
fun String.parseMonkey(): Monkey {
var match = constRegex.matchEntire(this)
if (match != null) {
if (match.groups[1]!!.value == "humn") {
return Monkey(match.groups[1]!!.value, HumanJob(match.groups[2]!!.value.toLong()))
}
return Monkey(
match.groups[1]!!.value,
ConstantJob(match.groups[2]!!.value.toLong())
)
}
match = opRegex.matchEntire(this)!!
return Monkey(
match.groups[1]!!.value,
OperationJob(
match.groups[2]!!.value,
match.groups[4]!!.value,
when (match.groups[3]!!.value) {
"+" -> Op.PLUS
"*" -> Op.TIMES
"-" -> Op.MINUS
"/" -> Op.DIVIDE
else -> throw Exception()
}
)
)
}
}
}
override fun part1(input: String): Any {
val monkeys = input.lines().map { it.parseMonkey() }.associateBy { it.id }
return monkeys["root"]!!.job.value(monkeys)
}
override fun part2(input: String): Any {
val monkeys = input.lines().map { it.parseMonkey() }.associateBy { it.id }.toMutableMap()
val rootJob = monkeys["root"]!!.job as OperationJob
val constant = if (!monkeys[rootJob.left]!!.job.includesHuman(monkeys))
monkeys[rootJob.left]!!.job.value(monkeys)
else
monkeys[rootJob.right]!!.job.value(monkeys)
val human = if (monkeys[rootJob.left]!!.job.includesHuman(monkeys))
monkeys[rootJob.left]!!.job
else
monkeys[rootJob.right]!!.job
var testVal = 4200L
var a = -1L
while (a < 0) {
try {
monkeys["humn"] = Monkey("humn", ConstantJob(testVal++))
a = human.value(monkeys)
} catch (_: Exception) {}
}
var b = -1L
while (b < 0) {
try {
monkeys["humn"] = Monkey("humn", ConstantJob(testVal++))
b = human.value(monkeys)
} catch (_: Exception) {}
}
val increasing = a < b
var lower = 0L
var upper = Long.MAX_VALUE
var pivot = upper / 2
while (true) {
monkeys["humn"] = Monkey("humn", ConstantJob(pivot))
try {
val result = human.value(monkeys)
if (result == constant) return pivot
if (result > constant) {
if (increasing) {
upper = pivot - 1L
} else {
lower = pivot + 1L
}
} else {
if (increasing) {
lower = pivot + 1L
} else {
upper = pivot - 1L
}
}
pivot = upper - (upper - lower) / 2
} catch (e: DivisionException) {
pivot = Random().nextLong(lower, upper + 1)
} catch (e: Exception) {
// this feels like the wrong direction, but this is what works
// TODO will revisit with not tired brain
if (!increasing) {
upper = pivot - 1L
} else {
lower = pivot + 1L
}
pivot = upper - (upper - lower) / 2
}
}
}
} | 0 | Kotlin | 0 | 0 | 2fd07f21348a708109d06ea97ae8104eb8ee6a02 | 4,916 | adventOfCode2022 | MIT License |
CodeChef/TCTCTOE.kt | thedevelopersanjeev | 112,687,950 | false | null | private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
private var states = hashMapOf<String, Int>()
private fun isWonOrDrawn(state: Array<Array<Char>>): Boolean {
var emptyCount = 0
for (i in 0 until 3) {
if (state[i][0] == state[i][1] && state[i][1] == state[i][2] && (state[i][0] == 'O' || state[i][0] == 'X')) {
return true
}
if (state[0][i] == state[1][i] && state[1][i] == state[2][i] && (state[0][i] == 'O' || state[0][i] == 'X')) {
return true
}
}
if (state[0][0] == state[1][1] && state[1][1] == state[2][2] &&
(state[0][0] == 'O' || state[0][0] == 'X')
) {
return true
}
if (state[0][2] == state[1][1] && state[1][1] == state[2][0] &&
(state[0][2] == 'O' || state[0][2] == 'X')
) {
return true
}
state.forEach {
it.forEach { ch ->
if (ch == '_') emptyCount++
}
}
return emptyCount == 0;
}
private fun precomputation(board: Array<Array<Char>>, turn: Boolean) {
if (isWonOrDrawn(board)) {
states[board.serialize()] = 1
return
}
states[board.serialize()] = 2
for (i in 0 until 3) {
for (j in 0 until 3) {
if (board[i][j] == '_') {
board[i][j] = if (turn) 'X' else 'O'
precomputation(board, !turn)
board[i][j] = '_'
}
}
}
}
fun main(args: Array<String>) {
val board = Array(3) { Array<Char>(3) { '_' } }
precomputation(board, true)
val T = readInt()
for (i in 0 until T) {
for (j in 0 until 3) {
val s = readLn()
for (k in 0 until 3) board[j][k] = s[k]
}
states[board.serialize()]?.let {
println(it)
} ?: run {
println(3)
}
}
}
fun Array<Array<Char>>.serialize(): String {
var ans = ""
this.forEach {
it.forEach { ch ->
ans += ch
}
ans += '$'
}
return ans
}
| 0 | C++ | 58 | 146 | 610520cc396fb13a03c606b5fb6739cfd68cc444 | 2,224 | Competitive-Programming | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/LengthOfLongestSubstring.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
import kotlin.math.max
/**
* 3. Longest Substring Without Repeating Characters
* @see <a href="https://leetcode.com/problems/longest-substring-without-repeating-characters/">Source</a>
*/
fun interface LengthOfLongestSubstring {
operator fun invoke(s: String): Int
}
/**
* Approach 1: Brute Force
* Time complexity : O(n^3).
* Space complexity : O(min(n,m)).
*/
class LengthOfLongestSubstringBF : LengthOfLongestSubstring {
override operator fun invoke(s: String): Int {
val n: Int = s.length
var res = 0
for (i in 0 until n) {
for (j in i until n) {
if (checkRepetition(s, i, j)) {
res = max(res, j - i + 1)
}
}
}
return res
}
private fun checkRepetition(s: String, start: Int, end: Int): Boolean {
val chars = IntArray(MAXIMUM_VALUE)
for (i in start..end) {
val c = s[i]
chars[c.code]++
if (chars[c.code] > 1) {
return false
}
}
return true
}
companion object {
private const val MAXIMUM_VALUE = 128
}
}
/**
* Approach 2: Sliding Window
* Time complexity : O(2n) = O(n).
* Space complexity : O(min(m,n)).
*/
class LLSSlidingWindow : LengthOfLongestSubstring {
override operator fun invoke(s: String): Int {
val chars = IntArray(MAXIMUM_VALUE)
var left = 0
var right = 0
var res = 0
while (right < s.length) {
val r: Char = s[right]
chars[r.code]++
while (chars[r.code] > 1) {
val l: Char = s[left]
chars[l.code]--
left++
}
res = max(res, right - left + 1)
right++
}
return res
}
companion object {
private const val MAXIMUM_VALUE = 128
}
}
/**
* Approach 3: Sliding Window Optimized
* Time complexity : O(n).
* Space complexity : O(min(m,n)).
*/
class LLSSlidingWindowOpt : LengthOfLongestSubstring {
override operator fun invoke(s: String): Int {
val chars = arrayOfNulls<Int>(MAXIMUM_VALUE)
var left = 0
var right = 0
var res = 0
while (right < s.length) {
val r: Char = s[right]
val index = chars[r.code]
if (index != null && index >= left && index < right) {
left = index + 1
}
res = max(res, right - left + 1)
chars[r.code] = right
right++
}
return res
}
companion object {
private const val MAXIMUM_VALUE = 128
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 3,322 | kotlab | Apache License 2.0 |
kotlin/minesweeper/src/main/kotlin/Minesweeper.kt | fredyw | 523,079,058 | false | null | data class MinesweeperBoard(val board: List<String>) {
fun withNumbers(): List<String> {
val maxRows = board.size
val maxCols = if (maxRows > 0) board[0].length else 0
return (0 until maxRows).map { row ->
(0 until maxCols).fold("") { acc, col ->
if (board[row][col] == '*') {
"$acc*"
} else {
val count = countMines(maxRows, maxCols, row, col)
"$acc${if (count == 0) ' ' else count}"
}
}
}.toList()
}
private fun countMines(maxRows: Int, maxCols: Int, row: Int, col: Int): Int {
return listOf(
Pair(-1, 0),
Pair(-1, 1),
Pair(0, 1),
Pair(1, 1),
Pair(1, 0),
Pair(1, -1),
Pair(0, -1),
Pair(-1, -1)
).filter { (r, c) -> row + r in 0 until maxRows && col + c in 0 until maxCols }
.fold(0) { acc, (r, c) ->
if (board[row + r][col + c] == '*') acc + 1 else acc
}
}
}
| 0 | Kotlin | 0 | 0 | 101a0c849678ebb7d2e15b896cfd9e5d82c56275 | 1,094 | exercism | MIT License |
2017/src/twentyfive/SporificaVirusChallenge.kt | Mattias1 | 116,139,424 | false | null | package twentyfive
import gridList.*
const val CLEAN = 0
const val WEAKENED = 1
const val INFECTED = 2
const val FLAGGED = 3
class SporificaVirusChallenge {
fun infectionBursts(input: List<String>, steps: Int = 10_000): Int {
val grid = buildGrid(input)
val carrier = buildCarrier(grid)
return (1..steps).fold(carrier, { c, _ -> c.stepSimple(grid) }).infections
}
private fun buildGrid(input: List<String>): MutableGridList<Int> {
val size = 1001
val start = (size - input.count()) / 2 + 1
val end = start + input.count() - 1
val inputGrid: GridList<Int> = GridList(input.map { it.map { if (it == '#') INFECTED else CLEAN } })
return MutableGridList(size, size, { x, y ->
if (x in start..end && y in start..end) {
inputGrid[x - start, y - start]
} else {
CLEAN
}
})
}
private fun buildCarrier(grid: GridList<Int>): Carrier =
Carrier(grid.width / 2 + 1, grid.height / 2 + 1, 0, 0)
fun advancedInfectionBursts(input: List<String>, steps: Int = 10_000_000): Int {
val grid = buildGrid(input)
val carrier = buildCarrier(grid)
return (1..steps).fold(carrier, { c, _ -> c.stepAdvanced(grid) }).infections
}
class Carrier(private val x: Int, private val y: Int, private val dir: Int, val infections: Int) {
private val up = Pair(0, -1)
private val right = Pair(1, 0)
private val down = Pair(0, 1)
private val left = Pair(-1, 0)
fun stepSimple(grid: MutableGridList<Int>): Carrier {
return if (grid[x, y] == INFECTED) {
grid[x, y] = CLEAN
move(turnRight(), false)
} else {
grid[x, y] = INFECTED
move(turnLeft(), true)
}
}
fun stepAdvanced(grid: MutableGridList<Int>): Carrier {
return when (grid[x, y]) {
WEAKENED -> {
grid[x, y] = INFECTED
move(dir, true)
}
INFECTED -> {
grid[x, y] = FLAGGED
move(turnRight(), false)
}
FLAGGED -> {
grid[x, y] = CLEAN
move(reverse(), false)
}
else /* CLEAN */ -> {
grid[x, y] = WEAKENED
move(turnLeft(), false)
}
}
}
private fun turnRight(): Int = (dir + 1) % 4
private fun turnLeft(): Int = (dir + 3) % 4
private fun reverse(): Int = (dir + 2) % 4
private fun move(newDir: Int, infect: Boolean): Carrier {
val offset = when (newDir) {
0 -> up
1 -> right
2 -> down
else -> left
}
return Carrier(x + offset.first, y + offset.second, newDir, if (infect) infections + 1 else infections)
}
}
} | 0 | Kotlin | 0 | 0 | 6bcd889c6652681e243d493363eef1c2e57d35ef | 3,153 | advent-of-code | MIT License |
src/main/kotlin/days/Day7.kt | C06A | 435,034,782 | false | {"Kotlin": 20662} | package days
import kotlin.math.roundToInt
class Day7 : Day(7) {
override fun partOne(): Any {
return inputList[0].split(","
).map {
it.toInt()
}.sorted().let { seq ->
val half = seq.drop(seq.size / 2).reversed()
seq.zip(half).fold(0) { sum, x: Pair<Int, Int> ->
sum + if (x.first > x.second) {
x.first - x.second
} else {
x.second - x.first
}
}
}
}
override fun partTwo(): Any {
return inputList[0].split(
","
).map { it.toInt()
}.sorted().let { seq ->
seq.average(
).toInt(
).let { listOf(it, it+1) // Somehow sometimes it should be round up or down, but I didn't figure out why
}.map { avg ->
seq.map { it.toInt() }.fold(0) { fuel, coord ->
fuel + (if (coord > avg) {
coord - avg
} else {
avg - coord
}).let {
(it * (it + 1)) / 2
}
}
}.minOf { it }
}
}
}
| 0 | Kotlin | 0 | 0 | afbe60427eddd2b6814815bf7937a67c20515642 | 1,234 | Aoc2021 | Creative Commons Zero v1.0 Universal |
src/main/kotlin/org/wfanet/measurement/loadtest/dataprovider/MeasurementResults.kt | world-federation-of-advertisers | 349,561,061 | false | {"Kotlin": 8731680, "Starlark": 854205, "C++": 488657, "CUE": 153505, "HCL": 145480, "TypeScript": 103886, "Shell": 20694, "CSS": 8481, "Go": 8063, "JavaScript": 5305, "HTML": 2188} | /*
* Copyright 2023 The Cross-Media Measurement Authors
*
* 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 org.wfanet.measurement.loadtest.dataprovider
/** Utilities for computing Measurement results. */
object MeasurementResults {
data class ReachAndFrequency(val reach: Int, val relativeFrequencyDistribution: Map<Int, Double>)
/**
* Computes reach and frequency using the "deterministic count distinct" methodology and the
* "deterministic distribution" methodology.
*/
fun computeReachAndFrequency(sampledVids: Iterable<Long>, maxFrequency: Int): ReachAndFrequency {
val eventsPerVid: Map<Long, Int> = sampledVids.groupingBy { it }.eachCount()
val reach: Int = eventsPerVid.keys.size
// If the sampled VIDs is empty, set the distribution with all 0s up to maxFrequency.
if (reach == 0) {
return ReachAndFrequency(reach, (1..maxFrequency).associateWith { 0.0 })
}
// Build frequency histogram as a 0-based array.
val frequencyArray = IntArray(maxFrequency)
for (count in eventsPerVid.values) {
val bucket = count.coerceAtMost(maxFrequency)
frequencyArray[bucket - 1]++
}
val frequencyDistribution: Map<Int, Double> =
frequencyArray.withIndex().associateBy({ it.index + 1 }, { it.value.toDouble() / reach })
return ReachAndFrequency(reach, frequencyDistribution)
}
/** Computes reach using the "deterministic count distinct" methodology. */
fun computeReach(sampledVids: Iterable<Long>): Int {
return sampledVids.distinct().size
}
/** Computes impression using the "deterministic count" methodology. */
fun computeImpression(sampledVids: Iterable<Long>, maxFrequency: Int): Long {
val eventsPerVid: Map<Long, Int> = sampledVids.groupingBy { it }.eachCount()
// Cap each count at `maxFrequency`.
return eventsPerVid.values.sumOf { count -> count.coerceAtMost(maxFrequency).toLong() }
}
}
| 103 | Kotlin | 10 | 32 | a22d079b0c292f3b056e066149f57c0ee2f71067 | 2,430 | cross-media-measurement | Apache License 2.0 |
src/main/kotlin/leetcode/Problem1718.kt | fredyw | 28,460,187 | false | {"Java": 1280840, "Rust": 363472, "Kotlin": 148898, "Shell": 604} | package leetcode
/**
* https://leetcode.com/problems/construct-the-lexicographically-largest-valid-sequence/
*/
class Problem1718 {
fun constructDistancedSequence(n: Int): IntArray {
return constructDistancedSequence(n, 0, HashSet(), IntArray(n * 2 - 1)).array
}
private class Answer(val found: Boolean, val array: IntArray)
private fun constructDistancedSequence(n: Int, index: Int,
visited: MutableSet<Int>, array: IntArray): Answer {
if (visited.size == n) {
return Answer(true, array)
}
if (array[index] != 0) {
return constructDistancedSequence(n, index + 1, visited, array)
}
for (i in n downTo 1) {
if (i in visited) {
continue
}
if (i == 1) {
array[index] = i
} else {
if (index + i >= array.size || array[index + i] != 0) {
continue
}
array[index] = i
array[index + i] = i
}
visited += i
val answer = constructDistancedSequence(n, index + 1, visited, array)
if (answer.found) {
return answer
}
visited -= i
array[index] = 0
if (i != 1) {
array[index + i] = 0
}
}
return Answer(false, array)
}
}
| 0 | Java | 1 | 4 | a59d77c4fd00674426a5f4f7b9b009d9b8321d6d | 1,464 | leetcode | MIT License |
src/main/kotlin/g1501_1600/s1563_stone_game_v/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1501_1600.s1563_stone_game_v
// #Hard #Array #Dynamic_Programming #Math #Game_Theory
// #2023_06_14_Time_371_ms_(100.00%)_Space_40.5_MB_(100.00%)
class Solution {
fun stoneGameV(stoneValue: IntArray): Int {
val n = stoneValue.size
val ps = IntArray(n)
ps[0] = stoneValue[0]
for (i in 1 until n) {
ps[i] = ps[i - 1] + stoneValue[i]
}
return gameDP(ps, 0, n - 1, Array<Array<Int?>>(n) { arrayOfNulls(n) })
}
private fun gameDP(ps: IntArray, i: Int, j: Int, dp: Array<Array<Int?>>): Int {
if (i == j) {
return 0
}
if (dp[i][j] != null) {
return dp[i][j]!!
}
var max = 0
for (k in i + 1..j) {
val l = ps[k - 1] - if (i == 0) 0 else ps[i - 1]
val r = ps[j] - ps[k - 1]
if (2 * Math.min(l, r) < max) {
continue
}
if (l <= r) {
max = Math.max(max, l + gameDP(ps, i, k - 1, dp))
}
if (l >= r) {
max = Math.max(max, r + gameDP(ps, k, j, dp))
}
}
dp[i][j] = max
return max
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,195 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/g0801_0900/s0847_shortest_path_visiting_all_nodes/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g0801_0900.s0847_shortest_path_visiting_all_nodes
// #Hard #Dynamic_Programming #Breadth_First_Search #Bit_Manipulation #Graph #Bitmask
// #Graph_Theory_I_Day_10_Standard_Traversal
// #2023_03_29_Time_164_ms_(100.00%)_Space_35.8_MB_(88.89%)
import java.util.LinkedList
import java.util.Objects
import java.util.Queue
class Solution {
fun shortestPathLength(graph: Array<IntArray>): Int {
val target = (1 shl graph.size) - 1
val q: Queue<IntArray> = LinkedList()
for (i in graph.indices) {
q.offer(intArrayOf(i, 1 shl i))
}
var steps = 0
val visited = Array(graph.size) {
BooleanArray(
target + 1
)
}
while (q.isNotEmpty()) {
val size = q.size
for (i in 0 until size) {
val curr = q.poll()
val currNode = Objects.requireNonNull(curr)[0]
val currState = curr[1]
if (currState == target) {
return steps
}
for (n in graph[currNode]) {
val newState = currState or (1 shl n)
if (visited[n][newState]) {
continue
}
visited[n][newState] = true
q.offer(intArrayOf(n, newState))
}
}
++steps
}
return -1
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,452 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/org/mechdancer/filters/algebra/Calculate.kt | MechDancer | 144,807,668 | false | null | package org.mechdancer.filters.algebra
import kotlin.math.PI
fun List<Complex>.dft(): List<Complex> {
val w0 = Complex.e.pow((-2 * PI / size).asIm())
return List(size) { k ->
mapIndexed { n, x ->
x * w0.pow((n * k).asRe())
}.sum()
}
}
fun List<Complex>.idft(): List<Complex> {
val w0 = Complex.e.pow((2 * PI / size).asIm())
return List(size) { k ->
mapIndexed { n, x ->
x * w0.pow((n * k).asRe()) / size.asRe()
}.sum()
}
}
fun Number.asRe() =
Complex(toDouble(), .0)
fun Number.asIm() =
Complex(.0, toDouble())
fun Iterable<Complex>.sum() =
reduce { sum, it -> sum + it }
inline fun <T> Iterable<T>.sumByComplex(
block: (T) -> Complex
) = fold(Complex.zero) { sum, it -> sum + block(it) }
| 0 | Kotlin | 0 | 1 | d266ccb7b4e704c90ffcba9a5b4a0fce55bd5be0 | 792 | filters | Do What The F*ck You Want To Public License |
src/main/kotlin/dev/forst/katlib/IterableExtensions.kt | LukasForst | 285,036,343 | false | {"Kotlin": 113999, "Makefile": 191} | package dev.forst.katlib
import java.util.NavigableSet
import java.util.TreeSet
import java.util.logging.Logger
import kotlin.collections.component1
import kotlin.collections.component2
import kotlin.random.Random
/**
* Function that will return a random element from the iterable.
*/
fun <E> Iterable<E>.getRandomElement(rand: Random) = this.elementAt(rand.nextInt(this.count()))
/**
* Function that will return a random element from the iterable.
*/
fun <E> Iterable<E>.random(random: Random = Random) = this.getRandomElement(random)
/**
* Creates reduction of the given [Iterable]. This function can be used for example for cumulative sums.
*
* [Iterable.reduce] does not allow you to set initial value.
*/
inline fun <T, R> Iterable<T>.reduction(initial: R, operation: (acc: R, T) -> R): List<R> {
val result = ArrayList<R>()
var last = initial
for (item in this) {
last = operation(last, item)
result.add(last)
}
return result
}
/**
* Returns the sum of all values produced by [selector] function applied to each element in the collection.
*/
@Deprecated("Since Kotlin 1.4.0, use sumOf", replaceWith = ReplaceWith("sumOf"))
inline fun <T> Iterable<T>.sumByLong(selector: (T) -> Long): Long {
var sum: Long = 0
for (element in this) {
sum += selector(element)
}
return sum
}
/**
* Returns the sum of all values produced by [selector] function applied to each element in the sequence.
*
* The operation is _terminal_.
*/
@Deprecated("Since Kotlin 1.4.0, use sumOf", replaceWith = ReplaceWith("sumOf"))
inline fun <T> Sequence<T>.sumByLong(selector: (T) -> Long): Long {
var sum = 0L
for (element in this) {
sum += selector(element)
}
return sum
}
/**
* Sums all Lists of integers into single one by indexes (i.e. all the numbers with the same index are always summed together).
* If the lists have different lengths,
* the final list has length corresponding to the shortest list in [this] iterable.
*/
fun Iterable<List<Int>>.sumByIndexes(): List<Int> {
val minSize = requireNotNull(this.minOf { it.size }) { "Only nonempty collections are supported." }
val result = MutableList(minSize) { 0 }
for (index in 0 until minSize) {
for (list in this) {
result[index] += list[index]
}
}
return result
}
/**
* Sums all Lists of integers into single one by indexes (i.e. all the numbers with the same index are always summed together).
* If the lists have different lengths, the final list has length corresponding to the shortest list in [this] iterable.
*/
fun Iterable<List<Double>>.sumDoublesByIndexes(): List<Double> {
val minSize = requireNotNull(this.minOf { it.size }) { "Only nonempty collections are supported." }
val result = MutableList(minSize) { 0.0 }
for (index in 0 until minSize) {
for (list in this) {
result[index] += list[index]
}
}
return result
}
/**
* Returns the largest value of the given function or `null` if there are no elements.
*/
@Deprecated("Deprecated since Kotlin 1.4, replace by maxOf", replaceWith = ReplaceWith("maxOf"))
inline fun <T, R : Comparable<R>> Iterable<T>.maxValueBy(selector: (T) -> R): R? = this.maxOfOrNull(selector)
/**
* Returns the smallest value of the given function or `null` if there are no elements.
*/
@Deprecated("Deprecated since Kotlin 1.4, replace by minOfOrNull", replaceWith = ReplaceWith("minOfOrNull"))
inline fun <T, R : Comparable<R>> Iterable<T>.minValueBy(selector: (T) -> R): R? = this.minOfOrNull(selector)
/**
* Applies the given [transform] function to each element of the original collection
* and returns results as Set.
*/
inline fun <T, R> Iterable<T>.mapToSet(transform: (T) -> R): Set<R> =
mapTo(LinkedHashSet(), transform)
/**
* Applies the given [transform] function to each element of the original collection
* and returns results as Set.
*/
inline fun <T, R> Iterable<T>.flatMapToSet(transform: (T) -> Iterable<R>): Set<R> =
flatMapTo(LinkedHashSet(), transform)
/**
* Returns the most frequently occurring value of the given function or `null` if there are no elements.
*/
inline fun <T, R> Iterable<T>.dominantValueBy(crossinline selector: (T) -> R): R? =
this.groupingBy(selector).eachCount().maxByOrNull { it.value }?.key
/**
* Creates cartesian product between all the elements from [this] and [other] iterable.
* E.g. when [this] contains [1,2,3] and [other] contains ['a', 'b'], the
* result will be {Pair(1,'a'), Pair(1,'b'), Pair(2,'a'), Pair(2,'b'), Pair(3,'a'), Pair(3,'b')}.
*/
fun <T1, T2> Iterable<T1>.cartesianProduct(other: Iterable<T2>): Set<Pair<T1, T2>> {
val result = LinkedHashSet<Pair<T1, T2>>(this.count() * other.count())
for (item1 in this) {
for (item2 in other) {
result.add(Pair(item1, item2))
}
}
return result
}
/**
* Performs the given [action] on each element that is not null.
*/
inline fun <T : Any> Iterable<T?>.forEachNotNull(action: (T) -> Unit) {
for (element in this) element?.let(action)
}
/**
* Creates union of the given iterables.
*/
fun <T> Iterable<Iterable<T>?>.union(): Set<T> {
val result = LinkedHashSet<T>()
this.forEachNotNull { input -> result.addAll(input) }
return result
}
/**
* Creates intersection of the given iterables.
*/
fun <T> Iterable<Iterable<T>?>.intersect(): Set<T> {
val result = LinkedHashSet<T>()
var first = true
for (item in this) {
if (item == null) continue
if (first) {
first = false
result.addAll(item)
} else result.retainAll(item)
}
return result
}
/**
* Returns a list containing only the non-null results of applying the given transform function to each element in the original collection.
*/
inline fun <T : Any, R : Any> Iterable<T?>.filterNotNullBy(selector: (T) -> R?): List<T> {
val result = ArrayList<T>()
for (item in this) {
if (item != null && selector(item) != null) result.add(item)
}
return result
}
/**
* Returns the single element matching the given [predicate], or `null` if element was not found.
*
* Throws [IllegalArgumentException] when multiple elements are matching predicate.
*/
inline fun <T> Iterable<T>.singleOrEmpty(predicate: (T) -> Boolean): T? {
var single: T? = null
var found = false
for (element in this) {
if (predicate(element)) {
if (found) {
throw IllegalArgumentException("Collection contains more than one matching element.")
}
single = element
found = true
}
}
return single
}
/**
* Returns single element, or `null` if the collection is empty.
* Throws [IllegalArgumentException] when multiple elements are matching predicate.
*/
fun <T> Iterable<T>.singleOrEmpty(): T? =
when (this) {
is List ->
when (size) {
0 -> null
1 -> this[0]
else -> throw IllegalArgumentException("Collection contains more than one element.")
}
else -> {
val iterator = iterator()
if (!iterator.hasNext()) {
null
} else {
val single = iterator.next()
if (iterator.hasNext()) {
throw IllegalArgumentException("Collection contains more than one element.")
}
single
}
}
}
/**
* Takes Iterable with pairs and returns a pair of collections filled with values in each part of pair.
* */
fun <T, V> Iterable<Pair<T, V>>.splitPairCollection(): Pair<List<T>, List<V>> {
val ts = mutableListOf<T>()
val vs = mutableListOf<V>()
for ((t, v) in this) {
ts.add(t)
vs.add(v)
}
return ts to vs
}
/**
* Returns all values that are in [this] and not in [other] with custom [selector].
* */
inline fun <T, R> Iterable<T>.setDifferenceBy(other: Iterable<T>, selector: (T) -> R): List<T> =
(this.distinctBy(selector).map { Pair(it, true) } + other.distinctBy(selector).map { Pair(it, false) })
.groupBy { selector(it.first) }
.filterValues { it.size == 1 && it.single().second }
.map { (_, value) -> value.single().first }
/**
* Returns a [Map] containing key-value pairs provided by elements of the given collection.
*
* If any of two pairs would have the same key the last one gets added to the map and the method creates a warning.
*
* The returned map preserves the entry iteration order of the original collection.
*/
fun <K, V> Iterable<Pair<K, V>>.assoc(): Map<K, V> {
return assocTo(LinkedHashMap(collectionSizeOrDefault(DEFAULT_COLLECTION_SIZE)))
}
/**
* Populates and returns the [destination] mutable map with key-value pairs
* provided by elements of the given collection.
*
* If any of two pairs would have the same key the last one gets added to the map and the method creates a warning.
*/
fun <K, V, M : MutableMap<in K, in V>> Iterable<Pair<K, V>>.assocTo(destination: M): M {
var size = 0
for ((key, value) in this) {
destination.put(key, value)
size++
}
destination.checkUniqueness(size) { this.groupBy({ it.first }, { it.second }) }
return destination
}
/**
* Returns a [Map] containing key-value pairs provided by [transform] function
* applied to elements of the given collection.
*
* If any of two pairs would have the same key the last one gets added to the map and the method creates a warning.
*
* The returned map preserves the entry iteration order of the original collection.
*/
inline fun <T, K, V> Iterable<T>.assoc(transform: (T) -> Pair<K, V>): Map<K, V> {
return assocTo(LinkedHashMap(defaultMapCapacity()), transform)
}
/**
* Populates and returns the [destination] mutable map with key-value pairs
* provided by [transform] function applied to each element of the given collection.
*
* If any of two pairs would have the same key the last one gets added to the map and the method creates a warning.
*/
inline fun <T, K, V, M : MutableMap<in K, in V>> Iterable<T>.assocTo(destination: M, transform: (T) -> Pair<K, V>): M {
var size = 0
for (element in this) {
destination += transform(element)
size++
}
destination.checkUniqueness(size) { this.groupBy({ transform(it).first }, { transform(it).second }) }
return destination
}
/**
* Returns a [Map] containing the elements from the given collection indexed by the key
* returned from [keySelector] function applied to each element.
*
* If any two elements had the same key returned by [keySelector] the last one gets added to the map and the method creates a warning.
*
* The returned map preserves the entry iteration order of the original collection.
*/
inline fun <T, K> Iterable<T>.assocBy(keySelector: (T) -> K): Map<K, T> {
return assocByTo(LinkedHashMap(defaultMapCapacity()), keySelector)
}
/**
* Populates and returns the [destination] mutable map with key-value pairs,
* where key is provided by the [keySelector] function applied to each element of the given collection
* and value is the element itself.
*
* If any two elements had the same key returned by [keySelector] the last one gets added to the map and the method creates a warning.
*/
inline fun <T, K, M : MutableMap<in K, in T>> Iterable<T>.assocByTo(destination: M, keySelector: (T) -> K): M {
var size = 0
for (element in this) {
destination.put(keySelector(element), element)
size++
}
destination.checkUniqueness(size) { this.groupBy(keySelector) }
return destination
}
/**
* Returns a [Map] containing the values provided by [valueTransform] and indexed by [keySelector]
* functions applied to elements of the given collection.
*
* If any two elements had the same key returned by [keySelector] the last one gets added to the map and the method creates a warning.
*
* The returned map preserves the entry iteration order of the original collection.
*/
inline fun <T, K, V> Iterable<T>.assocBy(keySelector: (T) -> K, valueTransform: (T) -> V): Map<K, V> {
return assocByTo(LinkedHashMap(defaultMapCapacity()), keySelector, valueTransform)
}
/**
* Populates and returns the [destination] mutable map with key-value pairs,
* where key is provided by the [keySelector] function
* and value is provided by the [valueTransform] function applied to elements of the given collection.
*
* If any two elements had the same key returned by [keySelector] the last one gets added to the map and the method creates a warning.
*/
inline fun <T, K, V, M : MutableMap<in K, in V>> Iterable<T>.assocByTo(
destination: M,
keySelector: (T) -> K,
valueTransform: (T) -> V
): M {
var size = 0
for (element in this) {
destination.put(keySelector(element), valueTransform(element))
size++
}
destination.checkUniqueness(size) { this.groupBy(keySelector, valueTransform) }
return destination
}
/**
* Returns a [Map] where keys are elements from the given collection and values are
* produced by the [valueSelector] function applied to each element.
*
* If any two elements are equal, the last one gets added to the map and the method creates a warning.
*
* The returned map preserves the entry iteration order of the original collection.
*
*/
inline fun <K, V> Iterable<K>.assocWith(valueSelector: (K) -> V): Map<K, V> {
val result = LinkedHashMap<K, V>(defaultMapCapacity())
return assocWithTo(result, valueSelector)
}
/**
* Populates and returns the [destination] mutable map with key-value pairs for each element of the given collection,
* where key is the element itself and value is provided by the [valueSelector] function applied to that key.
*
* If any two elements are equal, the last one overwrites the former value in the map and the method creates a warning.
*/
inline fun <K, V, M : MutableMap<in K, in V>> Iterable<K>.assocWithTo(destination: M, valueSelector: (K) -> V): M {
var size = 0
for (element in this) {
destination.put(element, valueSelector(element))
size++
}
destination.checkUniqueness(size) { this.groupBy({ it }, valueSelector) }
return destination
}
/**
* Returns three lists with separated values from list of triples.
* */
fun <A, B, C> Iterable<Triple<A, B, C>>.flattenToLists(): Triple<List<A>, List<B>, List<C>> {
val aList = mutableListOf<A>()
val bList = mutableListOf<B>()
val cList = mutableListOf<C>()
for ((a, b, c) in this) {
aList.add(a)
bList.add(b)
cList.add(c)
}
return Triple(aList, bList, cList)
}
/**
* Returns a [NavigableSet] of all elements.
*
* Elements in the set returned are sorted according to the given [comparator].
*/
fun <T> Iterable<T>.toNavigableSet(comparator: Comparator<in T>): NavigableSet<T> {
return toCollection(TreeSet(comparator))
}
/**
* Formats a collection of [TItem]s to a readable string like "3 colors: red, yellow, green".
*
* Each item is converted by [itemToString] to a string representation whose length is restricted by [itemLength]
* and the output length by [totalLength]. A [separator] (default = ", ") is placed between the string representation.
*
* @param itemsType a string describing the collection items, such as "colors", "employees" etc.; default = "items"
* @param itemToString a lambda converting each item to its string representation.
*/
inline fun <TItem> Iterable<TItem>.itemsToString(
itemsType: String = "items",
separator: String = ", ",
itemLength: Int = 30,
totalLength: Int = 200,
itemToString: (TItem) -> String = { item -> item.toShortString() }
): String {
val sb = StringBuilder("${this.count()} $itemsType")
var currentSeparator = ": " // before the first item
for (item in this) {
sb.append(currentSeparator)
currentSeparator = separator // before other than first item
val short: String = if (item == null) "null" else itemToString(item).restrictLengthWithEllipsis(itemLength)
if (short.length + sb.length > totalLength) {
sb.append("…")
break // no more items will fit into [totalLength]
}
sb.append(short)
}
return sb.toString().restrictLengthWithEllipsis(totalLength)
}
// ---- internal helper functions
@PublishedApi
internal val iterableLogger = Logger.getLogger("dev.forst.katlib.IterableExtensions")
internal const val INT_MAX_POWER_OF_TWO: Int = Int.MAX_VALUE / 2 + 1
/**
* Checks that [this] map has [expectedSize] and if it is not the case (because value for some key was overwritten),
* warning with affected keys is generated.
*/
@PublishedApi
internal inline fun <K, V, M : MutableMap<in K, in V>> M.checkUniqueness(expectedSize: Int, grouping: () -> Map<K, List<V>>) {
if (this.size == expectedSize) {
return
}
val duplicatedKeys = grouping().filterValues { it.size > 1 }
@Suppress("ThrowingExceptionsWithoutMessageOrCause") // this is not true, we're not throwing it, we need only stacktrace
val stack = Throwable().stackTraceToString()
iterableLogger.warning {
@Suppress("MagicNumber") // specified carefully, don't need constant
val entries = duplicatedKeys.entries.toString().take(500) // ensures that huge collections will not consume too much space
"The map should contain $expectedSize entries but the actual size is ${this.size}. The affected entries are $entries.$newLine$stack"
}
}
/**
* Returns default capacity for the maps based on the Guava's approach.
*/
@PublishedApi
internal fun <T> Iterable<T>.defaultMapCapacity() =
mapCapacity(collectionSizeOrDefault(DEFAULT_COLLECTION_SIZE)).coerceAtLeast(DEFAULT_COERCE_MINIMUM_VALUE)
/**
* Calculate the initial capacity of a map, based on Guava's com.google.common.collect.Maps approach. This is equivalent
* to the Collection constructor for HashSet, (c.size()/.75f) + 1, but provides further optimisations for very small or
* very large sizes, allows support non-collection classes, and provides consistency for all map based class construction.
*/
@PublishedApi
@Suppress("MagicNumber") // see upper docs
internal fun mapCapacity(expectedSize: Int): Int =
when {
expectedSize < 3 -> expectedSize + 1
expectedSize < INT_MAX_POWER_OF_TWO -> expectedSize + expectedSize / 3
else -> Int.MAX_VALUE // any large value
}
/**
* Returns the size of this iterable if it is known, or the specified [default] value otherwise.
*/
@PublishedApi
internal fun <T> Iterable<T>.collectionSizeOrDefault(default: Int): Int =
if (this is Collection<*>) this.size else default
/**
* Returns a single list of all not null elements yielded from results of [transform]
* function being invoked on each element of original collection.
*/
inline fun <T, R> Iterable<T>.flatMapIndexedNotNull(transform: (index: Int, T) -> Iterable<R>?): List<R> {
return flatMapIndexedTo(ArrayList(), transform)
}
/**
* Appends all elements yielded from results of [transform] function being invoked on each element of original collection,
* to the given [destination].
*/
inline fun <T, R, C : MutableCollection<in R>> Iterable<T>.flatMapIndexedTo(
destination: C,
transform: (index: Int, T) -> Iterable<R>?
): C {
forEachIndexed { index, element ->
transform(index, element)?.let { elements ->
destination.addAll(elements)
}
}
return destination
}
/**
* Validates the relationship between every element of Iterable.
*
* Iterates through the elements invoking the validationFunction on each one.
* Returns false on the first element that does not pass the validation function, otherwise true.
*
* @param validationFunction is the accumulator function that verifies the elements.
*/
inline fun <S, T : S> Iterable<T>.foldValidated(validationFunction: (acc: S, T) -> Boolean): Boolean {
val iterator = this.iterator()
if (!iterator.hasNext()) return false
var accumulator: T = iterator.next()
var isValid = true
while (iterator.hasNext()) {
val element = iterator.next()
val elementsAreValid = validationFunction(accumulator, element)
if (elementsAreValid) {
accumulator = element
} else {
isValid = false
break
}
}
return isValid
}
/**
* Returns true if the iterable is empty. If this is a Collection, uses isEmpty, otherwise creates iterator
* and verifies whether it has next value.
*/
fun <T> Iterable<T>.isEmpty(): Boolean = if (this is Collection<*>) this.isEmpty() else !this.iterator().hasNext()
/**
* List cartesian production.
*
* @see: https://stackoverflow.com/a/53763936/41071
*/
fun <T> Iterable<Iterable<T>>.cartesianProduct(): List<List<T>> =
if (isEmpty()) {
emptyList()
} else {
fold(listOf(listOf())) { acc, set -> acc.flatMap { list -> set.map { element -> list + element } } }
}
/**
* Lazy cartesian production.
*/
fun <T> Iterable<Iterable<T>>.lazyCartesianProduct(): Sequence<List<T>> =
if (isEmpty()) emptySequence() else lazyCartesianProductAcc(this, emptyList())
private fun <T> lazyCartesianProductAcc(l: Iterable<Iterable<T>>, acc: List<T>): Sequence<List<T>> = sequence {
if (l.isEmpty()) {
yield(acc)
} else {
val rest = l.drop(1)
val variants = l.first().asSequence().flatMap { lazyCartesianProductAcc(rest, acc + it) }
yieldAll(variants)
}
}
/**
* Zip alternative for three collections.
*/
inline fun <A, B, C, V> Iterable<A>.zip(b: Iterable<B>, c: Iterable<C>, transform: (a: A, b: B, c: C) -> V): List<V> {
@Suppress("MagicNumber") // this is default implementation from the Kotlin collections
val collectionSizeDefault = 10
val first = iterator()
val second = b.iterator()
val third = c.iterator()
val list = ArrayList<V>(
minOf(
collectionSizeOrDefault(collectionSizeDefault),
b.collectionSizeOrDefault(collectionSizeDefault),
c.collectionSizeOrDefault(collectionSizeDefault)
)
)
while (first.hasNext() && second.hasNext() && third.hasNext()) {
list.add(transform(first.next(), second.next(), third.next()))
}
return list
}
/**
* Sum collection by float as this is missing in the stdlib even after version 1.4.0.
*
* Not naming it sumOf in order to have easier imports.
*/
inline fun <T> Iterable<T>.sumByFloat(selector: (T) -> Float): Float {
var sum = 0f
for (element in this) {
sum += selector(element)
}
return sum
}
/**
* Performs the given action with each element as a receiver.
*/
inline fun <T> Iterable<T>.withEach(action: T.() -> Unit) = forEach { it.action() }
/**
* Performs the given [action] with each element as a receiver, providing sequential index with the element.
* @param [action] function that takes the index of an element and performs the action on the element.
*/
inline fun <T> Iterable<T>.withEachIndexed(action: T.(index: Int) -> Unit) = forEachIndexed { index, it -> it.action(index) }
| 9 | Kotlin | 2 | 76 | 3e26a31459a573edf484d7c4174a81cefcde5dc3 | 23,228 | katlib | MIT License |
fuzzyset.kt | manciuszz | 175,858,294 | false | null | class FuzzySet(arr: Array<String> = emptyArray(), val useLevenshtein: Boolean = true, val gramSizeLower: Int = 2, val gramSizeUpper: Int = 3) {
private val _nonWordRe = Regex("/[^a-zA-Z0-9\\u00C0-\\u00FF, ]+/g")
private val exactSet = mutableMapOf<String, String>()
private val matchDict = mutableMapOf<String, ArrayList<Array<Int>>>()
private val items = mutableMapOf<Int, MutableMap<Int, Item>>()
public data class Item(
var score: Double = 0.0,
var str: String = ""
)
private fun levenshtein(s: String, t: String, charScore : (Char, Char) -> Int = { c1, c2 -> if (c1 == c2) 0 else 1}) : Int {
if (s == t) return 0
if (s == "") return t.length
if (t == "") return s.length
val initialRow : List<Int> = (0 until t.length + 1).map { it }.toList()
return (0 until s.length).fold(initialRow) {
previous, u ->
(0 until t.length).fold( mutableListOf(u+1)) {
row, v ->
row.add(listOf(row.last() + 1,
previous[v+1] + 1,
previous[v] + charScore(s[u],t[v])).min()!!)
row
}
}.last()
}
private fun _distance(str1: String, str2: String): Double {
val distance = levenshtein(str1, str2).toDouble()
return if (str1.length > str2.length) {
1.0 - distance / str1.length
} else {
1.0 - distance / str2.length
}
}
private fun _iterateGrams(value: String, gramSize: Int = 2): MutableList<String> {
var simplified = "-" + value.toLowerCase().replace(_nonWordRe, "") + "-"
val lenDiff: Int = gramSize - simplified.length
val results = mutableListOf<String>()
if (lenDiff > 0) {
for(i in 0 until lenDiff) {
simplified += '-'
}
}
for (i in 0 until (simplified.length - gramSize + 1)) {
results.add(simplified.substring(i, i + gramSize))
}
return results;
}
private fun _gramCounter(value: String, gramSize: Int = 2): MutableMap<String, Int> {
val result = mutableMapOf<String, Int>()
val grams = _iterateGrams(value, gramSize)
for (i in 0 until grams.size) {
if (grams[i] in result) {
result[grams[i]] = result[grams[i]]?.plus(1) ?: 0
} else {
result[grams[i]] = 1
}
}
return result
}
fun get(value: String, defaultValue: ArrayList<Item> = arrayListOf(), minMatchScore: Double = .33): ArrayList<Item> {
return this._get(value, minMatchScore) ?: defaultValue
}
private fun _get(value: String, minMatchScore: Double): ArrayList<Item>? {
val normalizedValue = this._normalizeStr(value)
val result = this.exactSet[normalizedValue]
if (result != null) {
return arrayListOf(Item(1.0, result))
}
for (gramSize in gramSizeUpper downTo gramSizeLower) {
val results = this.__get(value, gramSize, minMatchScore);
if (results.isNotEmpty()) {
return results
}
}
return null
}
private fun __get(value: String, gramSize: Int, minMatchScore: Double): ArrayList<Item> {
val normalizedValue = this._normalizeStr(value)
val gramCounts = _gramCounter(normalizedValue, gramSize)
val matches = mutableMapOf<Int, Int>()
var sumOfSquareGramCounts: Double = 0.0
gramCounts.forEach {
gram, gramCount ->
sumOfSquareGramCounts += Math.pow(gramCount.toDouble(), 2.0)
if (gram in this.matchDict) {
val match = this.matchDict[gram]!!
for (i in 0 until match.size) {
val index = match[i][0]
val otherGramCount = match[i][1]
if (index !in matches) {
matches[index] = gramCount * otherGramCount
} else {
matches[index] = matches[index]!!.plus(gramCount * otherGramCount)
}
}
}
}
if (matches.isEmpty()) {
return arrayListOf()
}
val vectorNormal = Math.sqrt(sumOfSquareGramCounts)
var results = arrayListOf<Item>()
for ((matchIndex, matchScore) in matches) {
val matchedItem: Item = this.items[gramSizeLower]!![matchIndex]!!
results.add(Item(matchScore / (vectorNormal * matchedItem.score), matchedItem.str))
}
results.sortByDescending {
it.score
}
if (this.useLevenshtein) {
val newResults = arrayListOf<Item>()
val endIndex = Math.min(50, results.size)
for (i in 0 until endIndex) {
newResults.add(Item(_distance(results[i].str, normalizedValue), results[i].str))
}
results = newResults
results.sortByDescending {
it.score
}
}
val newResults = arrayListOf<Item>()
results.forEach {
scoreWordPair ->
if (scoreWordPair.score >= minMatchScore) {
newResults.add(Item(scoreWordPair.score, this.exactSet[scoreWordPair.str]!!))
}
}
return newResults
}
fun add(value: String): Boolean {
val normalizedValue = this._normalizeStr(value)
if (normalizedValue in this.exactSet) {
return false
}
for (i in this.gramSizeLower .. this.gramSizeUpper + 1)
this._add(value, i)
return true
}
private fun _add(value: String, gramSize: Int) {
val normalizedValue = this._normalizeStr(value)
val items = this.items[gramSize] ?: mutableMapOf()
val index = items.size
val gramCounts = _gramCounter(normalizedValue, gramSize)
var sumOfSquareGramCounts: Double = 0.0
gramCounts.forEach {
gram, gramCount ->
sumOfSquareGramCounts += Math.pow(gramCount.toDouble(), 2.0)
if (gram in this.matchDict) {
this.matchDict[gram]!!.add(arrayOf(index, gramCount))
} else {
this.matchDict[gram] = arrayListOf(arrayOf(index, gramCount))
}
}
val vectorNormal = Math.sqrt(sumOfSquareGramCounts)
items[index] = Item(vectorNormal, normalizedValue)
this.items[gramSize] = items
this.exactSet[normalizedValue] = value
}
private fun _normalizeStr(str: String): String {
return str.toLowerCase()
}
fun length(): Int {
return this.exactSet.size
}
fun isEmpty(): Boolean {
return this.exactSet.isEmpty()
}
fun values(): MutableList<String> {
val values = mutableListOf<String>()
for ((normalizedValue, Value) in this.exactSet) {
values.add(Value)
}
return values
}
init {
for (i in gramSizeLower until gramSizeUpper + 1) {
this.items[i] = mutableMapOf()
}
for (obj in arr) {
this.add(obj)
}
}
} | 0 | Kotlin | 0 | 1 | c2d6232a8dcedd7667d941a7ce2744dd0a230089 | 7,289 | FuzzySet.kt | CNRI Python License |
src/main/kotlin/com/github/dangerground/aoc2020/Day11.kt | dangerground | 317,439,198 | false | null | package com.github.dangerground.aoc2020
import com.github.dangerground.aoc2020.util.DayInput
import com.github.dangerground.aoc2020.util.Direction
import com.github.dangerground.aoc2020.util.World
fun main() {
val process = Day11(DayInput.asWorld(11))
println("result part 1: ${process.part1()}")
println("result part 2: ${process.part2()}")
}
class Day11(val input: World) {
var world = World(input.map.toList().toMutableList())
var nextWorld = World(input.map)
val directions = mutableListOf<Direction>()
init {
for (r in -1..1) {
for (c in -1..1) {
if (r != 0 || c != 0) {
directions.add(Direction(r, c))
}
}
}
}
fun countNeighbors(row: Int, column: Int): Int {
var neighbors = 0
for (r in row - 1..row + 1) {
for (c in column - 1..column + 1) {
if (r == row && c == column) {
continue
}
if (world.isChar(r, c, '#')) {
neighbors++
}
}
}
return neighbors
}
var changed = false
fun nextTick() {
changed = false
nextWorld = World(world.map.toList().toMutableList())
for (r in 0 until world.getRowCount()) {
for (c in 0 until world.getColumnCount()) {
val countNeighbors = countNeighbors(r, c)
val isEmpty = world.isChar(r, c, 'L')
val isOccupied = world.isChar(r, c, '#')
if (countNeighbors == 0 && isEmpty) {
nextWorld.setCell(r, c, '#')
changed = true
} else if (isOccupied && countNeighbors >= 4) {
nextWorld.setCell(r, c, 'L')
changed = true
}
}
}
world = World(nextWorld.map)
}
fun part1(): Int {
do {
nextTick()
} while (changed)
return countOccupied()
}
private fun countOccupied() = world.map.map { it.count { it == '#' } }.sum()
fun part2(): Int {
resetWorld()
do {
nextTick2()
} while (changed)
return countOccupied()
}
private fun resetWorld() {
world = World(input.map.toList().toMutableList())
}
fun countLineNeighbors(row: Int, column: Int): Int {
return directions.filter { world.canSee(row, column, '#', it) }.count()
}
fun nextTick2() {
changed = false
nextWorld = World(world.map.toList().toMutableList())
for (r in 0 until world.getRowCount()) {
for (c in 0 until world.getColumnCount()) {
val countNeighbors = countLineNeighbors(r, c)
val isEmpty = world.isChar(r, c, 'L')
val isOccupied = world.isChar(r, c, '#')
if (countNeighbors == 0 && isEmpty) {
nextWorld.setCell(r, c, '#')
changed = true
} else if (isOccupied && countNeighbors >= 5) {
nextWorld.setCell(r, c, 'L')
changed = true
}
}
}
world = World(nextWorld.map)
}
}
| 0 | Kotlin | 0 | 0 | c3667a2a8126d903d09176848b0e1d511d90fa79 | 3,288 | adventofcode-2020 | MIT License |
day09/kotlin/RJPlog/day2109_1_2.kts | razziel89 | 438,180,535 | 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::smokeBasin[]
fun smokeBasin(input1: Int, input2: Int, input3: List<Int>, input4: Int, input5: Int): Int {
var xpos = input1
var ypos = input2
var map = mutableListOf<Char>()
var width = input4
var height = input5
var result: Int = 1
input3.forEach {
map.add((it + 48).toChar())
}
map.set(xpos + ypos * width, 'x')
var searchEnd: Boolean = false
while (!searchEnd) {
searchEnd = true
for (y in 1..height - 2) {
for (x in 1..width - 2) {
if (map[x + y * width].isDigit()) { // check if digit (no evaluation for already placed 'x')
if (map[x + y * width].toString().toInt() < 9 && map[(x - 1) + (y) * width] == 'x') {
result = result + 1
map.set(x + y * width, 'x')
searchEnd = false
} else if (map[x + y * width].toString().toInt() < 9 && map[(x + 1) + (y) * width] == 'x') {
result = result + 1
map.set(x + y * width, 'x')
searchEnd = false
} else if (map[x + y * width].toString().toInt() < 9 && map[(x) + (y - 1) * width] == 'x') {
result = result + 1
map.set(x + y * width, 'x')
searchEnd = false
} else if (map[x + y * width].toString().toInt() < 9 && map[(x) + (y + 1) * width] == 'x') {
result = result + 1
map.set(x + y * width, 'x')
searchEnd = false
}
} // if digit
} //end for x
} // end for y
} // searchEnd
return result
}
// end::smokeBasin[]
//fun main(args: Array<String>) {
// tag::solution[]
var solution1: Int = 0
var solution2: Int
var solution2_results = mutableListOf<Int>()
var heightmap = mutableListOf<Int>()
var width: Int = 0
var height: Int = 0
// read puzzle input to evaluate width and height of grid
File("day2109_puzzle_input.txt").forEachLine {
width = it.length
height += 1
}
// add a frame to grid, makes following evaluations easier, you don't have to check if value is out of grid at borders
width = width + 2
height = height + 2
for (i in 0..width - 1) {
heightmap.add(9)
}
// read puzzle input into list
File("day2109_puzzle_input.txt").forEachLine {
heightmap.add(9)
it.forEach {
heightmap.add(it.toString().toInt())
}
heightmap.add(9)
}
for (i in 0..width - 1) {
heightmap.add(9)
}
// check for sinks and add up risk level, for each sink start fun smokeBasin to get size of basin
for (y in 1..height - 2) {
for (x in 1..width - 2) {
if (heightmap[x + y * width] < heightmap[(x - 1) + (y) * width] && heightmap[x + y * width] < heightmap[(x + 1) + (y) * width] && heightmap[x + y * width] < heightmap[(x) + (y + 1) * width] && heightmap[x + y * width] < heightmap[(x) + (y - 1) * width]) {
solution1 = solution1 + heightmap[x + y * width] + 1
solution2_results.add(smokeBasin(x, y, heightmap, width, height))
}
}
}
// sort list to find highest 3
solution2_results.sort()
solution2 = solution2_results[solution2_results.size-1] * solution2_results[solution2_results.size-2] * solution2_results[solution2_results.size-3]
// end::solution[]
// tag::output[]
// print solution for part 1
println("**************************")
println("--- Day 9: Smoke Basin ---")
println("**************************")
println("Solution for part1")
println(" $solution1 is the sum of the risk levels of all low points on your heightmap")
println()
// print solution for part 2
println("*********************************")
println("Solution for part2")
println(" You get $solution2 if you add up all of the output values")
println()
// end::output[]
//} | 1 | Rust | 0 | 0 | 91a801b3c812cc3d37d6088a2544227cf158d114 | 3,534 | aoc-2021 | MIT License |
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[3]无重复字符的最长子串.kt | maoqitian | 175,940,000 | false | {"Kotlin": 354268, "Java": 297740, "C++": 634} | import kotlin.math.max
//给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
//
//
//
// 示例 1:
//
//
//输入: s = "abcabcbb"
//输出: 3
//解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
//
//
// 示例 2:
//
//
//输入: s = "bbbbb"
//输出: 1
//解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
//
//
// 示例 3:
//
//
//输入: s = "pwwkew"
//输出: 3
//解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
// 请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。
//
//
// 示例 4:
//
//
//输入: s = ""
//输出: 0
//
//
//
//
// 提示:
//
//
// 0 <= s.length <= 5 * 104
// s 由英文字母、数字、符号和空格组成
//
// Related Topics 哈希表 双指针 字符串 Sliding Window
// 👍 5445 👎 0
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
fun lengthOfLongestSubstring(s: String): Int {
//滑动窗口 map 保存字符和下标 遍历更新最大长度
//时间复杂度 O(n)
val map = HashMap<Char,Int>()
var resMax = 0
//左边界
var left = 0
for (index in s.indices){
if (map.containsKey(s[index])){
//相同跳过继续更新左边界
left = Math.max(left, map[s[index]]!!+1)
}
//存入
map[s[index]] = index
//更新最大值
resMax = Math.max(resMax,index - left +1)
}
return resMax
}
}
//leetcode submit region end(Prohibit modification and deletion)
| 0 | Kotlin | 0 | 1 | 8a85996352a88bb9a8a6a2712dce3eac2e1c3463 | 1,718 | MyLeetCode | Apache License 2.0 |
src/lesson8/EquiLeader.kt | P3tran | 213,443,394 | false | null | package lesson8
import java.util.*
/*
* Find leaders in 2 array slices by checking if leader exists
* and using prefix occurrences sums after, on all array slices
* */
class EquiLeader {
companion object {
@JvmStatic
fun main(args: Array<String>) {
val result = solution(intArrayOf(4, 3, 4, 4, 4, 2))
println("result : $result")
}
fun solution(A: IntArray): Int {
if (A.size < 2)
return 0
val stack = Stack<Int>()
for (i in A.indices) {
stack.push(A[i])
}
for (i in A.indices) {
when {
stack.isEmpty() -> stack.push(A[i])
stack.peek() != A[i] -> stack.pop()
else -> stack.push(A[i])
}
}
if (stack.size == 0)
return 0
val candidate = stack.pop()
var candidateOccurrences = 0
val sumOccurrences = IntArray(A.size) {0}
var equis = 0
for (i in A.indices) {
if (A[i] == candidate) {
candidateOccurrences++
if (i > 0)
sumOccurrences[i] = sumOccurrences[i - 1] + 1
else
sumOccurrences[i] = 1
} else {
if (i > 0)
sumOccurrences[i] = sumOccurrences[i - 1]
else
sumOccurrences[i] = 0
}
}
if (candidateOccurrences > (A.size / 2)) {
println("we have a leader $candidate")
for (i in A.indices) {
println("in index $i : ")
println("sum occ from start: ${sumOccurrences[i]}, occur from end: ${sumOccurrences[A.size-1] - sumOccurrences[i]}")
println("compared to ${i+1/2} and compared to ${(A.size -1 - i)/2 }")
if(sumOccurrences[i] > (i+1).toDouble() /2 && ((sumOccurrences[A.size-1] - sumOccurrences[i]) > (A.size -1 - i).toDouble() /2 )) {
equis++
println("bingo")
}
}
return equis
}
return 0
}
}
} | 0 | Kotlin | 0 | 0 | 15c60656161bfab4d585792ad64390aa959fcc5e | 2,361 | CodilityLessonsKotlin | Apache License 2.0 |
src/main/kotlin/zanagram/App.kt | HenriqueRocha | 259,845,874 | false | null | package zanagram
import java.io.File
import kotlin.system.measureTimeMillis
fun permutations(s: String): List<String> {
val result = DynamicArray<String>()
permutations(s.toCharArray(), 0, s.length - 1, result)
return result
}
fun permutations(s: CharArray, lowerBound: Int, upperBound: Int, result: List<String>) {
if (lowerBound == upperBound) result.add(String(s))
else {
for (i in lowerBound..upperBound) {
s.swap(lowerBound, i)
permutations(s, lowerBound + 1, upperBound, result)
s.swap(lowerBound, i)
}
}
}
fun CharArray.swap(i: Int, j: Int) {
val t = this[i]
this[i] = this[j]
this[j] = t
}
fun main(args: Array<String>) {
val dictionary = Set<String>()
val timeToLoad = measureTimeMillis {
File("words.txt").forEachLine { dictionary.add(it) }
}
println("Time to load: $timeToLoad")
// val timeToSort = measureTimeMillis { dictionary.quickSort() }
// println("Time to sort: $timeToSort")
val word = "listen"
val listOfPermutations = permutations(word)
val timeToFindPermutations = measureTimeMillis {
for (i in 0 until listOfPermutations.size()) {
val w = listOfPermutations[i]
if (dictionary.contains(w)) {
println(w)
}
}
}
println("Time to find permutations: $timeToFindPermutations")
}
| 1 | Kotlin | 0 | 0 | fbc4f2fc5489306dbc0eddfcd2a527745e297b78 | 1,410 | zanagram | MIT License |
app/icfpc2020/src/main/kotlin/ru/spbstu/SymbolUtil.kt | belyaev-mikhail | 280,179,984 | false | null | package ru.spbstu
fun Symbols.custom(data: String, name: String): Symbol.Custom {
val matrix = parseMatrix(data)
return Symbol.Custom(matrix, matrix.toCode(), name).also(::set)
}
fun Symbols.symbol(data: String): Symbol {
return get(parseMatrix(data))
}
fun Symbols.custom(data: String): Symbol.Custom {
return symbol(data) as Symbol.Custom
}
fun Symbols.number(data: String): Symbol.Number {
return symbol(data) as Symbol.Number
}
fun Symbols.variable(data: String): Symbol.Variable {
return symbol(data) as Symbol.Variable
}
fun Symbols.function(data: String): Symbol.Function {
return symbol(data) as Symbol.Function
}
fun parseMatrix(data: String): Matrix {
return parseMatrix(data.split('|', '\n').map { row -> row.map { it == '.' } })
}
fun parseMatrix(data: List<List<Boolean>>): Matrix {
val height = data.size
val width = data.map { it.size }.max()
requireNotNull(width)
require(data.map { it.size }.min() == width)
require(height > 0)
require(width > 0)
return Matrix(width, height, data)
}
fun Matrix.toSymbol(): Symbol {
return toNumber() ?: toVariable() ?: toFunction() ?: toUndefined()
}
fun Matrix.toNumber(): Symbol.Number? {
if (data[0][0]) return null
if (data[0].drop(1).any { !it }) return null
if (data.drop(1).any { !it[0] }) return null
val isPositive = height - width == 0
val code = drop().toCode()
val number = if (isPositive) code else -code
return Symbol.Number(this, number)
}
fun Matrix.toVariable(): Symbol.Variable? {
if (data[0].any { !it }) return null
if (data.any { !it[0] }) return null
if (data.last().any { !it }) return null
if (data.any { !it.last() }) return null
val number = drop().dropLast().invert().toNumber() ?: return null
return Symbol.Variable(this, number.code, "x${number.code}")
}
fun Matrix.toFunction(): Symbol.Function? {
if (data[0].any { !it }) return null
if (data.any { !it[0] }) return null
val code = drop().toCode()
return Symbol.Function(this, code, ":$code")
}
fun Matrix.toUndefined(): Symbol.Custom {
val code = toCode()
return Symbol.Custom(this, code, "u$code")
}
fun Long.pow(power: Long): Long = when {
power == 0L -> 1
power == 1L -> this
power % 2 == 1L -> this * pow(power - 1)
else -> pow(power / 2).let { it * it }
}
fun Matrix.toCode(): Long {
return data.flatten().foldIndexed(0L) { i, acc, it -> acc + if (it) 2L.pow(i.toLong()) else 0 }
}
fun Matrix.invert(): Matrix {
val data = data.map { row -> row.map { !it } }
return Matrix(width, height, data)
}
fun Matrix.drop(): Matrix {
require(width > 1)
require(height > 1)
val data = data.drop(1).map { it.drop(1) }
return Matrix(width - 1, height - 1, data)
}
fun Matrix.dropLast(): Matrix {
require(width > 1)
require(height > 1)
val data = data.dropLast(1).map { it.dropLast(1) }
return Matrix(width - 1, height - 1, data)
}
| 0 | Kotlin | 0 | 0 | 7d000e9b82416e51c4b6a06f19b703af8d5dec2a | 2,975 | icfpc2020-sub | MIT License |
src/main/kotlin/kr/co/programmers/P83201.kt | antop-dev | 229,558,170 | false | {"Kotlin": 695315, "Java": 213000} | package kr.co.programmers
// https://github.com/antop-dev/algorithm/issues/314
class P83201 {
fun solution(scores: Array<IntArray>): String {
val n = scores.size
val answer = StringBuffer()
for (j in 0 until n) {
val arr = Array(n) { i -> scores[i][j] }
var min = Int.MAX_VALUE
var max = Int.MIN_VALUE
var count = 0
var m = n
var sum = 0
for (i in 0 until n) {
val v = scores[i][j]
sum += v
if (v < min) min = v
if (v > max) max = v
if (v == scores[j][j]) count++
}
// 유일한 최고점이거나 최저점
if ((arr[j] == min || arr[j] == max) && count == 1) {
sum -= arr[j]
m--
}
val average = sum.toDouble() / m
answer.append(when {
average >= 90 -> "A"
average >= 80 -> "B"
average >= 70 -> "C"
average >= 50 -> "D"
else -> "F"
})
}
return answer.toString()
}
}
| 1 | Kotlin | 0 | 0 | 9a3e762af93b078a2abd0d97543123a06e327164 | 1,181 | algorithm | MIT License |
src/Day10.kt | rmyhal | 573,210,876 | false | {"Kotlin": 17741} | import kotlin.math.abs
fun main() {
fun part1(input: List<String>): Int {
return first(input)
}
fun part2(input: List<String>): String {
return second(input)
}
val input = readInput("Day10")
println(part1(input))
println(part2(input))
}
private fun first(input: List<String>): Int {
var x = 1
var cycle = 0
var strength = 0
fun handleCycle() {
cycle++
if (cycle % 40 == 20) {
strength += cycle * x
}
}
input.forEach { line ->
handleCycle()
if (line != "noop") {
handleCycle()
x += line.split(" ").last().toInt()
}
}
return strength
}
private fun second(input: List<String>): String {
var x = 1
var cycle = 1
val sprite = Array(6) { Array(39) { '.' } }
fun handleCycle() {
val (col, row) = (cycle - 1) % 40 to (cycle - 1) / 40
if (abs(x - col) <= 1) sprite[row][col] = '#'
cycle++
}
input.forEach { line ->
handleCycle()
if (line != "noop") {
handleCycle()
x += line.split(" ").last().toInt()
}
}
return sprite.joinToString("\n") { it.joinToString("") }
} | 0 | Kotlin | 0 | 0 | e08b65e632ace32b494716c7908ad4a0f5c6d7ef | 1,098 | AoC22 | Apache License 2.0 |
hacker-rank/strings/SherlockAndTheValidString.kt | piazentin | 62,427,919 | false | {"Python": 34824, "Jupyter Notebook": 29307, "Kotlin": 19570, "C++": 2465, "R": 2425, "C": 158} | // https://www.hackerrank.com/challenges/sherlock-and-valid-string/problem
fun main() {
val string = readLine().orEmpty()
println(if (isValid(string)) "YES" else "NO")
}
fun isValid(string: String): Boolean {
if (string.length <= 3) return true
val charFreq = IntArray('z' - 'a' + 1)
for (char in string) charFreq[char - 'a']++
val metaFreq = mutableMapOf<Int, Int>()
for (frequency in charFreq) {
if (frequency != 0) metaFreq[frequency] = metaFreq.getOrDefault(frequency, 0) + 1
}
return when (metaFreq.keys.size) {
1 -> true
2 -> {
val (first, second) = metaFreq.keys.toList()
if ((first == 1 && metaFreq[first] == 1) || (second == 1 && metaFreq[second] == 1)) true
else Math.abs(first - second) == 1 && (metaFreq[first] == 1 || metaFreq[second] == 1)
}
else -> false
}
}
| 0 | Python | 0 | 0 | db490b1b2d41ed6913b4cacee1b4bb40e15186b7 | 897 | programming-challenges | MIT License |
src/algorithm/HeapSort.kt | DavidZhong003 | 157,566,685 | false | null | package algorithm
/**
* 堆排序
* @author doive
* on 2019/6/25 20:20
*/
class HeapSort :IArraySort{
override fun sort(array: IntArray): IntArray {
if (array.size <= 1) {
return array
}
//构建最大堆
buildMaxHeap(array, array.size)
for (i in array.lastIndex downTo 1) {
array.swap( i, 0)
buildMaxHeap(array, i)
}
return array
}
private fun buildMaxHeap(array: IntArray, size: Int) {
val lastP = (size - 2) / 2
for (i in lastP downTo 0) {
heapifyMax(array, size, i)
}
}
private fun heapifyMax(array: IntArray, size: Int, i: Int) {
if (i >= size) {
return
}
val leftC = i * 2 + 1
val rightC = i * 2 + 2
var max = i
if (leftC<size&&array[leftC]>array[max]){
max = leftC
}
if (rightC<size&&array[rightC]>array[max]){
max = rightC
}
if (max!=i){
array.swap(max,i)
heapifyMax(array, size, max)
}
}
}
fun main() {
val array = intArrayOf(5, 35, 7, 2, 88, 22, 9, 8, 0)
HeapSort().sort(array)
array.print()
}
| 0 | Kotlin | 0 | 1 | 7eabe9d651013bf06fa813734d6556d5c05791dc | 1,230 | LeetCode-kt | Apache License 2.0 |
src/Day03.kt | rweekers | 573,305,041 | false | {"Kotlin": 38747} | fun main() {
val alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
fun part1(input: List<String>): Int {
return input
.map { Pair(it.substring(0, it.length / 2), it.substring(it.length / 2)) }
.map { it.first.commonCharacter(it.second) }
.sumOf { alphabet.indexOf(it) + 1 }
}
fun part2(input: List<String>): Int {
return input
.windowed(3, 3)
.map { it[0].commonCharacters(it[1]).commonCharacter(it[2]) }
.sumOf { alphabet.indexOf(it) + 1 }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 1 | 276eae0afbc4fd9da596466e06866ae8a66c1807 | 846 | adventofcode-2022 | Apache License 2.0 |
src/main/kotlin/com/github/amolkov/kotlin/algorithms/sorting/HeapSort.kt | amolkov | 122,844,991 | false | null | package com.github.amolkov.kotlin.algorithms.sorting
import com.github.amolkov.kotlin.algorithms.extensions.swap
class HeapSort {
companion object {
/**
* Sorts the specified array into ascending order, according to the natural ordering of its elements,
* using the heap sort algorithm.
*
* @param arr the array to be sorted
*/
fun <T : Comparable<T>> sort(arr: Array<T>) {
val size = arr.size
(size / 2 - 1 downTo 0).forEach { heapify(arr, size, it) }
(size - 1 downTo 0).forEach {
arr.swap(0, it)
heapify(arr, it, 0)
}
}
private fun <T : Comparable<T>> heapify(arr: Array<T>, size: Int, idx: Int) {
var largest = idx
val left = (idx shl 1) + 1
val right = (idx shl 1) + 2
if (left < size && arr[left] > arr[largest]) {
largest = left
}
if (right < size && arr[right] > arr[largest]) {
largest = right
}
if (largest != idx) {
arr.swap(idx, largest)
heapify(arr, size, largest)
}
}
}
}
| 0 | Kotlin | 0 | 0 | acb6bc2e397087fec8432b3307d0c0ea0c6ba75b | 1,245 | kotlin-algorithms | Apache License 2.0 |
src/cn/ancono/math/prob/ProbSpace.kt | 140378476 | 105,762,795 | false | {"Java": 1912158, "Kotlin": 1243514} | package cn.ancono.math.prob
import java.util.*
import kotlin.math.exp
import kotlin.math.ln
typealias Event = Map<ProbSpace<*>, Any?>
/**
* Describes the probability space in math, but it only provides method of generating
* random points in the space according to the probability of the space.
*
* Probability space is the base of random variables. Generally, probability space can
* be seen as a 'random source' for random variables. Random variables depend
* on probability space to provide random values, and a single random variable
* may depend on multiple spaces. Additionally, several random variables can depend
* on the same probability space. In this case, these random variables may not be
* independent.
*
* Probability spaces are always distinct. Different instances of probability space
* should be considered to be different. [Object.equals] and [Object.hashCode] should not
* be overridden.
*
*
*
* Created by liyicheng at 2020-06-02 15:07
*
* @see RandomVariable
* @param E the type of point in this space.
*/
interface ProbSpace<out E> {
/**
* Randomly returns a point in this probability space.
*/
fun randomPoint(): E
/**
* Returns a sequence of random points in this probability space.
*/
fun randomPoints(): Sequence<E> {
return generateSequence { this.randomPoint() }
}
}
class ProductSpace<E, S : ProbSpace<E>>(val spaces: List<S>) : ProbSpace<List<E>> {
override fun randomPoint(): List<E> {
return spaces.map { it.randomPoint() }
}
}
//class ComposedSpace(val spaces: Set<AtomicSpace<*>>) : ProbSpace<ComposedPoint>() {
// override fun randomPoint(): ComposedPoint {
// val events = HashMap<ProbSpace<*>, Any>(spaces.size)
// for (space in spaces) {
// events[space] = space.randomPoint()
// }
// return events
// }
//
// companion object {
// fun composeOf(spaces: Set<ProbSpace<*>>): ComposedSpace {
// val s = spaces.flatMapTo(hashSetOf()) {
// when (it) {
// is AtomicSpace<*> -> listOf(it)
// is ComposedSpace -> it.spaces
// }
// }
// return ComposedSpace(s)
// }
// }
//}
/**
* A bundled space that is independent to the original spaces.
*/
class BundledSpace(val spaces: Set<ProbSpace<*>>) : ProbSpace<Event> {
override fun randomPoint(): Event {
val result = HashMap<ProbSpace<*>, Any?>(spaces.size)
for (space in spaces) {
result[space] = space.randomPoint()
}
return result
}
}
abstract class AbstractProbSpace<out E> : ProbSpace<E> {
val rd = Random()
}
class IntervalSpace(val lower: Double, val upper: Double) : AbstractProbSpace<Double>() {
init {
require(lower < upper)
}
val k = upper - lower
override fun randomPoint(): Double {
return k * rd.nextDouble() + lower
}
}
class StandardNormalDistSpace() : AbstractProbSpace<Double>() {
override fun randomPoint(): Double {
return rd.nextGaussian()
}
}
object TrivialSpace : ProbSpace<Unit> {
override fun randomPoint() {
}
}
/**
* A probability space of only `0` and `1`. The probability of `1` is equal to [p].
*/
class BernoulliSpace(val p: Double) : AbstractProbSpace<Int>() {
init {
require(p in 0.0..1.0)
}
override fun randomPoint(): Int {
return if (rd.nextDouble() <= p) {
1
} else {
0
}
}
}
class BinomialSpace(val p: Double, val n: Int) : AbstractProbSpace<Int>() {
init {
require(p in 0.0..1.0)
require(n > 0)
}
override fun randomPoint(): Int {
return RandomNumbersImpl.generateBinomial(rd, n, p)
}
}
/**
* A probability space of positive integers. The possibility of an integer `n` is equal to `pq^(n-1)`,
* where `q = 1-p`.
*/
class GeomSpace(val p: Double) : AbstractProbSpace<Int>() {
init {
require(p in 0.0..1.0)
}
override fun randomPoint(): Int {
var i = 1
while (rd.nextDouble() > p) {
i++
}
return i
}
}
/**
* A probability space of positive integers. The possibility of an integer `n` is equal to `pq^(n-1)`,
* where `q = 1-p`.
*/
class PascalSpace(val p: Double, val r: Int) : AbstractProbSpace<Int>() {
init {
require(p in 0.0..1.0)
require(r > 0)
}
override fun randomPoint(): Int {
return RandomNumbersImpl.generatePascal(rd, r, p)
}
}
/**
* A probability space of non-negative integers.
*
* P(n) = k^n / n! * e^(-k) (n>=0)
*/
class PoissonSpace(val k: Double) : AbstractProbSpace<Int>() {
init {
require(k > 0)
}
private val base = exp(-k)
override fun randomPoint(): Int {
return RandomNumbersImpl.generatePoisson(rd, k, base)
}
}
/**
* A probability space of positive real numbers, density is
*
* p(x) = e^(-x)
*/
class StandardExpSpace : AbstractProbSpace<Double>() {
override fun randomPoint(): Double {
val d = rd.nextDouble()
return -ln(d)
}
}
//interface AtomicProbSpace<E> : ProbSpace<E> {
//
//}
//
//interface ComposedProbSpace : ProbSpace<List<Any>> {
//
//}
| 0 | Java | 0 | 6 | 02c2984c10a95fcf60adcb510b4bf111c3a773bc | 5,300 | Ancono | MIT License |
src/main/java/io/github/lunarwatcher/aoc/day4/Day4.kt | LunarWatcher | 160,042,659 | false | null | package io.github.lunarwatcher.aoc.day4
import io.github.lunarwatcher.aoc.commons.readFile
import io.github.lunarwatcher.aoc.day1.day1part2processor
import java.time.Instant
import java.time.LocalDateTime
import java.time.ZoneId
import java.time.ZoneOffset
import java.time.format.DateTimeFormatter
enum class LogAction {
WAKE, ASLEEP, BEGIN;
companion object {
fun of(str: String) : LogAction = when(str) {
"wakes up" -> WAKE
"falls asleep" -> ASLEEP
else -> BEGIN
}
}
}
data class Shift(val id: Int, var startTime: Instant? = null, var endTime: Instant? = null)
val dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm").withZone(ZoneId.of("GMT+0"))
fun parseEntries(log: List<String>) : List<Shift> {
val logEntries = mutableListOf<Shift>()
var id = -1
var activeShift: Shift? = null
for(entry in log){
val time = LocalDateTime.parse(entry.substring(1, 17), dateTimeFormatter).toInstant(ZoneOffset.ofHours(0))
val action = LogAction.of(entry.split(" ", limit=3)[2])
if(id == -1 && action != LogAction.BEGIN){
throw RuntimeException("Looks like ya fucked that one up!");
}
if(action == LogAction.BEGIN){
id = entry.split(" ")[3].replace("[# ]".toRegex(), "").toInt()
activeShift?.let { logEntries.add(it.also { it.endTime = time.also { it.minusMillis(60000)} }) } // Assuming one minute less here.
} else if(action == LogAction.ASLEEP){
activeShift = Shift(id, time, null)
} else if(action == LogAction.WAKE){
logEntries.add(activeShift!!.also {
it.endTime = time.also { it.minusMillis(60000)};
})
activeShift = null
}
}
return logEntries
}
fun day4part1processor(log: List<String>): Int {
var sortedLog = log.sortedBy { it.substring(1, 17) }
val logEntries = parseEntries(sortedLog)
val flatMap = logEntries.map {
it.id to ((it.endTime!!.toEpochMilli() - it.startTime!!.toEpochMilli()) / 60000f).toLong()
}
val resMap = mutableMapOf<Int, Long>()
flatMap.forEach { (id, time) ->
if(resMap[id] == null) resMap[id] = 0;
resMap[id] = resMap[id]!!.plus(time)
}
val pair = resMap.toList().sortedByDescending {
it.second
}.first()
val id = pair.first
val applicable = logEntries.filter { it.id == id }
// <Minute, count>
val minutes = mutableMapOf<Int, Int>()
for(shift in applicable){
val start = LocalDateTime.ofInstant(shift.startTime!!, ZoneId.of("GMT+0")).minute
val end = LocalDateTime.ofInstant(shift.endTime!!, ZoneId.of("GMT+0")).minute
for (i in start until end){
if(minutes[i] == null) minutes[i] = 1;
else{
minutes[i] = minutes[i]!!.plus(1)
};
}
}
return id * minutes.toList()
.sortedByDescending {
it.second
}.first().first
}
fun day4part2processor(log: List<String>): Int {
var sortedLog = log.sortedBy { it.substring(1, 17) }
val logEntries = parseEntries(sortedLog)
val flatMap = logEntries.map {
it.id to ((it.endTime!!.toEpochMilli() - it.startTime!!.toEpochMilli()) / 60000f).toLong()
}
val resMap = mutableMapOf<Int, Long>()
flatMap.forEach { (id, time) ->
if(resMap[id] == null) resMap[id] = 0;
resMap[id] = resMap[id]!!.plus(time)
}
val res = resMap.toList().map { (id, _) ->
val applicable = logEntries.filter { it.id == id }
// <Minute, count>
val minutes = mutableMapOf<Int, Int>()
for(shift in applicable){
val start = LocalDateTime.ofInstant(shift.startTime!!, ZoneId.of("GMT+0")).minute
val end = LocalDateTime.ofInstant(shift.endTime!!, ZoneId.of("GMT+0")).minute
for (i in start until end){
if(minutes[i] == null) minutes[i] = 1;
else{
minutes[i] = minutes[i]!!.plus(1)
};
}
}
id to minutes
}
// <Minute, <ID, Count>>
val result = mutableMapOf<Int, MutableMap<Int, Int>>()
for ((forId, minutes) in res){
for((minute, count) in minutes) {
if (result[minute] == null) result[minute] = mutableMapOf()
result[minute]!!.put(forId, count)
}
}
// minute, <ID, count>
val map = mutableMapOf<Int, Pair<Int, Int>>()
for(i in 1..60){
var max: Int = 0
var id: Int = 0;
result[i]?.forEach { (iId, count) ->
if(count > max) {
id = iId
max = count;
}
} ?: continue;
map[i] = id to max
}
val list = map.toList().sortedByDescending { (_, idCount) ->
idCount.second
}
val match = list.first()
return match.first * match.second.first
}
fun day4(day: Boolean = false){
val logs = readFile("day4.txt")
println(if(!day) day4part1processor(logs) else day4part2processor(logs))
} | 0 | Kotlin | 0 | 1 | 99f9b05521b270366c2f5ace2e28aa4d263594e4 | 5,103 | AoC-2018 | MIT License |
src/test/kotlin/ch/ranil/aoc/aoc2023/Day21.kt | stravag | 572,872,641 | false | {"Kotlin": 234222} | package ch.ranil.aoc.aoc2023
import ch.ranil.aoc.AbstractDay
import ch.ranil.aoc.PrintColor
import ch.ranil.aoc.printColor
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals
class Day21 : AbstractDay() {
@Test
fun part1Test() {
assertEquals(16, compute1(testInput, 6))
}
@Test
fun part1TestSimple() {
assertEquals(4, compute1(testInput, 2))
assertEquals(2, compute1(testInput, 1))
assertEquals(1, compute1(testInput, 0))
}
@Test
fun part1Puzzle() {
assertEquals(3632, compute1(puzzleInput, 64))
}
@Test
fun part2Test() {
assertEquals(0, compute2(testInput))
}
@Test
fun part2Puzzle() {
assertEquals(0, compute2(puzzleInput))
}
private fun compute1(input: List<String>, steps: Int): Int {
val (garden, start) = Garden.parse(input)
val result = mutableSetOf<Point>()
val seen = mutableSetOf(start)
val queue = mutableListOf(start to 0)
while (queue.isNotEmpty()) {
val (current, step) = queue.removeFirst()
// the reachable points always toggle
if (step % 2 == steps % 2) result.add(current)
if (step < steps) {
val nextTiles = garden.nextTilesFor(current).filter { it !in seen }
for (next in nextTiles) {
seen.add(next)
queue.add(next to step + 1)
}
}
}
print(garden, seen, result)
return result.size
}
private fun compute2(input: List<String>): Int {
TODO()
}
private data class Garden(
val width: Int,
val height: Int,
val rocks: Set<Point>,
val tiles: Set<Point>,
) {
private fun contains(p: Point): Boolean {
return p in rocks || p in tiles
}
fun nextTilesFor(p: Point): Collection<Point> {
return setOfNotNull(
p.move(1, Direction.N),
p.move(1, Direction.E),
p.move(1, Direction.S),
p.move(1, Direction.W),
)
.filter { this.contains(it) }
.filter { it !in rocks }
}
companion object {
fun parse(input: List<String>): Pair<Garden, Point> {
val rocks = mutableSetOf<Point>()
val tiles = mutableSetOf<Point>()
var start: Point? = null
input.forEachIndexed { y, s ->
s.forEachIndexed { x, c ->
val p = Point(x, y)
when (c) {
'#' -> rocks.add(p)
'.' -> tiles.add(p)
'S' -> {
tiles.add(p)
start = p
}
}
}
}
val garden = Garden(
width = input.first().length,
height = input.size,
rocks = rocks,
tiles = tiles,
)
return garden to requireNotNull(start)
}
}
}
private fun print(garden: Garden, reachable: Collection<Point>, nxt: Collection<Point>) {
for (y in 0..<garden.height) {
for (x in 0..<garden.width) {
val p = Point(x, y)
when (p) {
in nxt -> printColor(PrintColor.YELLOW, 'O')
in reachable -> printColor(PrintColor.GREEN, 'O')
in garden.rocks -> printColor(PrintColor.RED, '#')
in garden.tiles -> print('.')
}
}
println()
}
}
}
| 0 | Kotlin | 1 | 0 | dbd25877071cbb015f8da161afb30cf1968249a8 | 3,848 | aoc | Apache License 2.0 |
Kotlin/problems/0047_group_of_anagrams.kt | oxone-999 | 243,366,951 | true | {"C++": 961697, "Kotlin": 99948, "Java": 17927, "Python": 9476, "Shell": 999, "Makefile": 187} | /* Problem Statement
Given an array of strings, group anagrams together.
Example:
Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
] */
class Solution constructor() {
fun getStringArray(word : String): String{
var counter:IntArray = IntArray(26);
for(letter in word){
counter[letter-'a']++;
}
return counter.joinToString();
}
fun groupAnagrams(strs: Array<String>): List<List<String>> {
var groups: HashMap<String,MutableList<String>> = HashMap<String,MutableList<String>> ();
var result: MutableList<MutableList<String>> = mutableListOf<MutableList<String>> ();
for(word in strs){
var wordStringArray: String = getStringArray(word);
if(groups.containsKey(wordStringArray)){
groups.get(wordStringArray)!!.add(word);
}else{
groups.put(wordStringArray,mutableListOf<String>(word));
}
}
for((key, value) in groups){
result.add(value);
}
return result;
}
}
fun main(args:Array<String>){
var sol : Solution = Solution();
var strs : Array<String> = arrayOf("eat", "tea", "tan", "ate", "nat", "bat");
var groups : List<List<String>> = sol.groupAnagrams(strs);
groups.forEach{
group -> println(group.joinToString());
};
}
| 0 | null | 0 | 0 | 52dc527111e7422923a0e25684d8f4837e81a09b | 1,412 | algorithms | MIT License |
src/SRanking.kt | nkkarpov | 302,503,568 | false | null | import java.lang.Math.*
fun SRanking(env: Environment, initM: List<Int>, budget: Int, R: Int): List<List<Int>> {
env.reset()
val n = env.n
val m = initM.toIntArray()
val C = List<MutableList<Int>>(m.size - 1) { mutableListOf() }
fun n(r: Int) = if (r == R) 0 else floor(pow(n.toDouble(), 1.0 - 1.0 * r / R)).toInt()
fun t(r: Int, alpha: Double) = if (r == 0) 0 else max(0, floor(alpha / n(r - 1)).toInt())
var left = 0.0
var right = budget * n.toDouble()
repeat(100) {
val ave = (left + right) / 2.0
var current = 0L
for (r in 0..R) current += n(r) * (t(r + 1, ave) - t(r, ave)).toLong()
if (current < budget.toLong()) {
left = ave
} else {
right = ave
}
}
var total = 0
// println("left = ${left}")
for (r in 0 until R) total += n(r) * (t(r + 1, left) - t(r, left))
// println("budget - total = ${budget - total}")
// println((0..R).map { t(it, left) })
// println((0..R).map { n(it) })
val sr = DoubleArray(n) { 0.0 }
val nt = IntArray(n) { 0 }
fun est(a: Int) = sr[a] / nt[a]
val S = (0 until n).toMutableSet()
val cluster = IntArray(n) { 0 }
val gap = DoubleArray(n) { 0.0 }
for (i in 0 until (budget - total)) {
val a = i % n
sr[a] += env.pull(a)
nt[a] += 1
}
for (r in 0 until R) {
val tt = t(r + 1, left) - t(r, left)
for (a in S) {
repeat(tt) {
sr[a] += env.pull(a)
}
nt[a] += tt
}
val p = S.sortedBy { est(it) }.reversed()
for (j in 0 until m.lastIndex) {
for (i in m[j] until m[j + 1]) {
val x = p[i]
gap[x] = 1.0
cluster[x] = j
if (m[j] > 0) {
gap[x] = min(gap[x], est(p[m[j] - 1]) - est(x))
}
if (m[j + 1] < p.size) {
gap[x] = min(gap[x], est(x) - est(p[m[j + 1]]))
}
}
}
val q = S.sortedBy { gap[it] }.reversed()
// println("add ${n(r) - n(r + 1}")
for (i in 0 until n(r) - n(r + 1)) {
val x = q[i]
val j = cluster[x]
C[j].add(x)
S.remove(x)
}
for (i in m.indices) {
m[i] = initM[i]
for (j in 0 until i) m[i] -= C[j].size
}
}
return C
} | 0 | Kotlin | 0 | 0 | 0d0db3fe0c6e465eb7c7d49b6f284473138d9117 | 2,449 | batched-sorting | MIT License |
aoc-2015/src/main/kotlin/aoc/AocDay19.kt | triathematician | 576,590,518 | false | {"Kotlin": 615974} | package aoc
import aoc.util.chunk
class AocDay19: AocDay(19) {
companion object { @JvmStatic fun main(args: Array<String>) { AocDay19().run() } }
override val testinput = """
H => HO
H => OH
O => HH
e => H
e => O
HOHOHO
""".trimIndent().lines()
fun String.parse() = chunk(0) to chunk(2)
.replace("Rn","(").replace("Ar",")")
override fun calc1(input: List<String>): Int {
val reps = input.dropLast(2).map { it.parse() }
val start = input.last()
val results = mutableSetOf<String>()
for ((from, to) in reps) {
for (i in start.indices) {
if (start.startsWith(from, i)) {
results.add(start.replaceRange(i, i + from.length, to))
}
}
}
return results.size
}
override fun calc2(input: List<String>): Int {
val target = input.last()
// parenthetical statements don't count to overall total ("Rn..Ar")
val parentheticals = "Rn".toRegex().findAll(target).count()
// anytime Y shows up it is next to an F and inside parentheses
val ys = target.count { it == 'Y' }
// now we count the number of capital letters to see how many elements are added from the start
val caps = target.count { it.isUpperCase() }
// subtract 2 for each parenthetical occurence, 2 for each Y/F occurence, and 1 since the first step gives us 2 elements
return caps - parentheticals*2 - ys*2 - 1
}
//region INITIAL ATTEMPT - DOESN'T SCALE
fun calc2b(input: List<String>): Int? {
val reps = input.dropLast(2).map { it.parse() }
val target = input.last()
val terminal = reps.filter { it.first == "e" }.map { it.second }.toSet()
val nonTerminal = reps.filter { it.first != "e" }
return minToGet(nonTerminal, terminal, target)
}
fun minToGet(reps: List<Pair<String, String>>, terminal: Set<String>, target: String): Int? {
if (target in terminal) return 1
return reps.mapNotNull { (from, to) ->
to.toRegex().findAll(target).mapNotNull {
val newEnd = target.replaceRange(it.range, from)
val min = minToGet(reps, terminal, newEnd)
min?.let { it + 1 }
}.minOrNull()
}.minOrNull()
}
//endregion
} | 0 | Kotlin | 0 | 0 | 7b1b1542c4bdcd4329289c06763ce50db7a75a2d | 2,412 | advent-of-code | Apache License 2.0 |
_7Function/src/main/kotlin/practice/62.0 Squirrel Play.kt | Meus-Livros-Lidos | 690,208,771 | false | {"Kotlin": 166470} | package practice
/**
* The squirrels spend most of their time playing. In particular, they play if the temperature is between 60 and 90, inclusive.
* Unless it is summer, then the upper limit is 100 instead of 90. Given an int temperature and a boolean isSummer,
* return true if the squirrels are playing and false otherwise.
*/
fun main() {
println("Its Summer : y or n please")
var inputSummerStatus = readln().single()
while (!summerStatus(inputSummerStatus)) {
println("It's y or n enter the status again:")
println("Its Summer : y or n please")
inputSummerStatus = readln().single()
summerStatus(inputSummerStatus)
}
println("Enter the temperature:")
val inputTemperature = readlnOrNull()?.toDoubleOrNull() ?: 0.0
val resultTemperature = temperatureStatus(inputTemperature, inputSummerStatus)
if (resultTemperature) {
println("The temperature is too low or so high to play:")
} else {
println("The squirrel can play!")
}
}
fun summerStatus(summerStatus: Char): Boolean {
return summerStatus == 'y' || summerStatus == 'n'
}
fun temperatureStatus(temperature: Double, summerStatus: Char): Boolean {
if (summerStatus == 'y') {
return temperature < 0 || (temperature > 55)
} else if (summerStatus == 'n') {
return temperature < 0 || (temperature > 45)
}
return false
}
| 0 | Kotlin | 0 | 1 | 2d05e5528b9dd2cf9ed8799bce47444246be6b42 | 1,406 | LearnCsOnline-Kotlin | MIT License |
common/geometry/src/main/kotlin/com/curtislb/adventofcode/common/geometry/Point.kt | curtislb | 226,797,689 | false | {"Kotlin": 2146738} | package com.curtislb.adventofcode.common.geometry
import kotlin.math.PI
import kotlin.math.abs
import kotlin.math.atan2
/**
* A point with integer x- and y-coordinates on a 2D grid.
*
* @property x The x-coordinate of the point.
* @property y The y-coordinate of the point.
*
* @constructor Creates a new instance of [Point] with the given [x]- and [y]-coordinates.
*/
data class Point(val x: Int, val y: Int) {
/**
* The matrix row index corresponding to the point.
*/
val matrixRow: Int
get() = -y
/**
* The matrix column index corresponding to the point.
*/
val matrixCol: Int
get() = x
/**
* Returns the point given by adding each coordinate of [other] to this point.
*/
operator fun plus(other: Point): Point = when {
this == ORIGIN -> other
other == ORIGIN -> this
else -> Point(x + other.x, y + other.y)
}
/**
* Returns the point given by subtracting each coordinate of [other] from this point.
*/
operator fun minus(other: Point): Point =
if (other == ORIGIN) this else Point(x - other.x, y - other.y)
/**
* Returns a copy of the point with all coordinate values negated.
*/
operator fun unaryMinus(): Point = if (this == ORIGIN) ORIGIN else Point(-x, -y)
/**
* Returns the Manhattan distance between this point and [other].
*
* The Manhattan distance is the length (in grid units) of the shortest possible path between
* this point and [other], while moving only up, down, left, or right.
*/
infix fun manhattanDistance(other: Point): Int = abs(x - other.x) + abs(y - other.y)
/**
* Returns the squared Euclidean distance between this point and [other].
*/
infix fun squaredDistance(other: Point): Long {
val xDiff = (x - other.x).toLong()
val yDiff = (y - other.y).toLong()
return (xDiff * xDiff) + (yDiff * yDiff)
}
/**
* Returns all points on the grid that are horizontally, vertically, or diagonally adjacent to
* this point.
*/
fun allNeighbors(): List<Point> =
listOf(
copy(x = x - 1),
copy(x = x + 1),
copy(y = y - 1),
copy(y = y + 1),
Point(x - 1, y - 1),
Point(x - 1, y + 1),
Point(x + 1, y - 1),
Point(x + 1, y + 1)
)
/**
* Returns all points on the grid that are horizontally or vertically adjacent to this point.
*/
fun cardinalNeighbors(): List<Point> =
listOf(copy(x = x - 1), copy(x = x + 1), copy(y = y - 1), copy(y = y + 1))
/**
* Returns all points on the grid that are diagonally adjacent to this point.
*/
fun diagonalNeighbors(): List<Point> =
listOf(Point(x - 1, y - 1), Point(x - 1, y + 1), Point(x + 1, y - 1), Point(x + 1, y + 1))
/**
* Returns the point given by moving [distance] grid spaces in the given [direction] from this
* point.
*
* If [distance] is negative, this function instead returns the point given by moving
* -[distance] grid spaces opposite the given [direction] from this point.
*
* Note that [distance] is *not* the same as the Euclidean distance, as diagonally adjacent
* points are considered to have a [distance] of 1.
*/
fun move(direction: Direction, distance: Int = 1): Point =
if (distance == 0) {
this
} else {
when (direction) {
Direction.UP -> copy(y = y + distance)
Direction.RIGHT -> copy(x = x + distance)
Direction.DOWN -> copy(y = y - distance)
Direction.LEFT -> copy(x = x - distance)
Direction.UP_RIGHT -> Point(x + distance, y + distance)
Direction.DOWN_RIGHT -> Point(x + distance, y - distance)
Direction.DOWN_LEFT -> Point(x - distance, y - distance)
Direction.UP_LEFT -> Point(x - distance, y + distance)
}
}
/**
* Returns the point given by rotating this point 90 degrees clockwise about a [center] point.
*/
fun rotateClockwise(center: Point = ORIGIN): Point =
Point(y - center.y + center.x, center.x - x + center.y)
/**
* Returns the point given by rotating this point 90 degrees counterclockwise about a [center]
* point.
*/
fun rotateCounterclockwise(center: Point = ORIGIN): Point =
Point(center.y - y + center.x, x - center.x + center.y)
/**
* Returns the point given by rotating this point 180 degrees about a [center] point.
*/
fun rotate180Degrees(center: Point = ORIGIN): Point =
Point(center.x - x + center.x, center.y - y + center.y)
/**
* Returns the angle (in radians) of the line segment formed by this point and [other], measured
* clockwise from the positive y-axis with this point as the origin.
*
* @throws IllegalArgumentException If this point and [other] are the same point.
*/
fun clockwiseAngleFromYTo(other: Point): Double {
require(this != other) { "This point and other must be distinct: $this == $other" }
// Get translated coordinates of other with this as the origin
val translatedX = other.x - x
val translatedY = other.y - y
// Calculate (possibly negative) angle from the positive y-axis
val theta = atan2(translatedX.toDouble(), translatedY.toDouble())
// If angle is negative, return the equivalent positive angle
return if (theta >= 0) theta else 2.0 * PI + theta
}
override fun toString() = "($x, $y)"
companion object {
/**
* A point representing the 2D origin `(0, 0)`.
*/
val ORIGIN: Point = Point(0, 0)
/**
* A regex used to match a 2D point string.
*/
private val POINT_REGEX: Regex = Regex("""\(?(-?\d+),\s?(-?\d+)\)?""")
/**
* Returns the [Point] corresponding to the given ([rowIndex], [colIndex]) matrix
* coordinates.
*/
fun fromMatrixCoordinates(rowIndex: Int, colIndex: Int): Point =
if (rowIndex == 0 && colIndex == 0) ORIGIN else Point(colIndex, -rowIndex)
/**
* Returns a [Point] with x- and y-coordinates read from the given [string].
*
* The [string] must have one of the following formats:
*
* - `"$x,$y"`
* - `"$x, $y"`
* - `"($x,$y)"`
* - `"($x, $y)"`
*
* If [invertY] is `true`, the y-coordinate of the resulting [Point] will be negated.
*
* @throws IllegalArgumentException If [string] is not formatted correctly.
*/
fun fromString(string: String, invertY: Boolean = false): Point {
val matchResult = POINT_REGEX.matchEntire(string)
require(matchResult != null) { "Malformed point string: $string" }
val (xString, yString) = matchResult.destructured
val x = xString.toInt()
val y = if (invertY) -yString.toInt() else yString.toInt()
return if (x == 0 && y == 0) ORIGIN else Point(x, y)
}
}
}
| 0 | Kotlin | 1 | 1 | 6b64c9eb181fab97bc518ac78e14cd586d64499e | 7,243 | AdventOfCode | MIT License |
codeforces/vk2022/qual/c.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package codeforces.vk2022.qual
private fun solve() {
readln()
val a = readInts()
var ans = 1
var nextHigh = a.last() + 1
val seen = mutableSetOf<Pair<Int, Int>>()
for (i in a.indices.reversed()) {
for (t in 1 downTo 0) {
val high = a[i] + t
if (high > nextHigh) continue
nextHigh = nextHigh.coerceAtMost(high - 1)
var j = i
var low = high
while (true) {
if (!seen.add(low to j)) break
while (j > 0 && a[j] > low) j--
if (j < 0 || a[j] < low - 1 || a[j] > low) break
low--
j--
}
ans = ans.coerceAtLeast(high - low)
}
}
println(ans)
}
fun main() = repeat(readInt()) { solve() }
private fun readInt() = readln().toInt()
private fun readStrings() = readln().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 782 | competitions | The Unlicense |
src/main/kotlin/Day4.kt | d1snin | 726,126,205 | false | {"Kotlin": 14602} | /*
* 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.
*/
private const val INPUT =
"""
"""
private data class Card(
val id: Int,
val winning: List<Int>,
val given: List<Int>
)
private val lines =
INPUT.lines()
.map { it.trim() }
.filter { it.isNotEmpty() }
fun day4() {
println("Running AoC Day 4 (1st part)...")
firstPart()
println()
println("Running AoC Day 4 (2nd part)...")
secondPart()
}
private fun firstPart() {
val res = lines.parseCards()
.sumOf {
it.points()
}
println("res: $res")
}
private fun secondPart() {
val res = lines
.parseCards()
.populate()
.count()
println("res: $res")
}
private fun List<String>.parseCards() =
map {
it.parseCard()
}
private fun String.parseCard(): Card {
val cardId = extractCardId()
val winning = extractWinningNumbers()
val given = extractGivenNumbers()
return Card(cardId, winning, given)
}
private fun Card.points(): Int {
var points = 0
given.forEach {
if (it in winning) {
if (points == 0) {
points = 1
} else {
points *= 2
}
}
}
return points
}
private fun List<Card>.populate(): List<Card> {
val copies = associate {
it to mutableListOf<Card>()
}.toMutableMap()
forEachIndexed { index, card ->
val count = card.count()
(1..count).forEach { currentCount ->
val cardToCopy = getOrNull(index + currentCount) ?: return@forEach
val currentCardCopies = copies[card] ?: return@forEach
repeat(currentCardCopies.size + 1) {
copies[cardToCopy]?.add(cardToCopy)
}
}
}
val cards =
copies.flatMap { (card, copies) ->
listOf(card, *copies.toTypedArray())
}
return cards
}
private fun Card.count() =
given.count {
it in winning
}
private fun String.extractCardId() =
removePrefix(
find("Card\\s+".toRegex())
).removeSuffix(
find(":.*".toRegex())
).toInt()
private fun String.extractWinningNumbers() =
extractNumbers().first
private fun String.extractGivenNumbers() =
extractNumbers().second
private fun String.extractNumbers(): Pair<List<Int>, List<Int>> =
extractNumbersString().let { numbersString ->
"[\\d\\s]+".toRegex().findAll(numbersString).map { part ->
part.value.trim().split("\\s+".toRegex()).map {
it.toInt()
}
}.let {
it.first() to it.last()
}
}
private fun String.extractNumbersString() =
removePrefix(
find("Card\\s+\\d+:\\s+".toRegex())
)
private fun String.find(regex: Regex) =
requireNotNull(
regex.find(this)?.value
) | 0 | Kotlin | 0 | 0 | 8b5b34c4574627bb3c6b1a12664cc6b4c9263e30 | 3,416 | aoc-2023 | Apache License 2.0 |
app/src/main/kotlin/io/github/andrewfitzy/day07/Task02.kt | andrewfitzy | 747,793,365 | false | {"Kotlin": 60159, "Shell": 1211} | package io.github.andrewfitzy.day07
class Task02(puzzleInput: List<String>) {
private val input: List<String> = puzzleInput
fun solve(): Int {
var count = 0
for (line in input) {
val splits = line.split("[")
val hypernetSplits =
splits.filter { value -> value.contains("]") }
.map { value -> value.substringBefore("]") }
.toList()
val hypernetBABs: MutableSet<String> = mutableSetOf()
for (hypernetSplit in hypernetSplits) {
hypernetBABs.addAll(getThreeLetterPalindromes(hypernetSplit))
}
val supernetSplits = splits.map { value -> value.substringAfter("]") }.toList()
val supernetABAs: MutableSet<String> = mutableSetOf()
for (supernetSplit in supernetSplits) {
supernetABAs.addAll(getThreeLetterPalindromes(supernetSplit))
}
if (hypernetBABs.isEmpty() || supernetABAs.isEmpty()) {
continue
}
for (bab in hypernetBABs) {
if (supernetABAs.contains(getBABToABA(bab))) {
count++
break
}
}
}
return count
}
private fun getBABToABA(bab: String): String {
val builder = StringBuilder()
builder.append(bab[1]).append(bab[0]).append(bab[1])
return builder.toString()
}
private fun getThreeLetterPalindromes(value: String): Set<String> {
var tlps: MutableSet<String> = mutableSetOf()
for (i in 2 until value.length) {
if (value[i] == value[i - 2] && value[i] != value[i - 1]) {
var builder = StringBuilder()
builder.append(value[i - 2]).append(value[i - 1]).append(value[i])
tlps.add(builder.toString())
}
}
return tlps
}
}
| 0 | Kotlin | 0 | 0 | 15ac072a14b83666da095b9ed66da2fd912f5e65 | 1,942 | 2016-advent-of-code | Creative Commons Zero v1.0 Universal |
affogato-core-ktx/src/main/java/com/parsuomash/affogato/core/ktx/collections/Map.kt | ghasemdev | 510,960,043 | false | {"Kotlin": 951820, "Shell": 3263} | package com.parsuomash.affogato.core.ktx.collections
/**
* Returns a [HashMap] containing all elements.
*
* Example:
* ```Kotlin
* mapOf(1 to 2, 2 to 3).toHashMap() // {1=2, 2=3}
* ```
* @since 1.1.0
*/
inline fun <reified K, V> Map<K, V>.toHashMap(): HashMap<K, V> = HashMap(this)
/**
* Returns a [LinkedHashMap] containing all elements.
*
* Example:
* ```Kotlin
* mapOf(1 to 2, 2 to 3).toLinkedMap() // {1=2, 2=3}
* ```
* @since 1.1.0
*/
inline fun <reified K, V> Map<K, V>.toLinkedMap(): LinkedHashMap<K, V> = LinkedHashMap(this)
/**
* Returns a map of all elements sorted by value.
*
* Example:
* ```Kotlin
* mapOf(5 to 1, 10 to 10, 1 to 0).sortedByValue() // {1:0, 5:1, 10:10}
* mapOf("11" to 1, "1" to 10, "a" to 0).sortedByValue() // {"1":10, "11":1, "a":0}
* ```
* @since 1.1.0
*/
inline fun <reified K, V> Map<K, V>.sortedByValue(): Map<K, V> =
toList().sortedBy { it.second.hashCode() }.toMap()
/**
* Returns a map of all elements sorted by dec value.
*
* Example:
* ```Kotlin
* mapOf(5 to 1, 10 to 10, 1 to 0).sortedByValueDescending() // {10:10, 5:1, 1:0}
* mapOf("11" to 1, "1" to 10, "a" to 0).sortedByValueDescending() // {"a":0, "11":1, "1":10}
* ```
* @since 1.1.0
*/
inline fun <reified K, V> Map<K, V>.sortedByValueDescending(): Map<K, V> =
toList().sortedByDescending { it.second.hashCode() }.toMap()
/**
* Returns a map of all elements sorted by key.
*
* Example:
* ```Kotlin
* mapOf(1 to 0, 5 to 1, 10 to 10, 7 to 0).sortedByKey()
* // {1:0, 7:0, 5:1, 10:10}
* mapOf(1 to "a", 2 to "0", 3 to "11", 4 to "01", 5 to "1").sortedByKey()
* // {2:"0", 4:"01", 5:"1", 3:"11", 1:"a"}
* ```
* @since 1.1.0
*/
inline fun <reified K, V> Map<K, V>.sortedByKey(): Map<K, V> =
toList().sortedBy { it.first.hashCode() }.toMap()
/**
* Returns a map of all elements sorted by dec key.
*
* Example:
* ```Kotlin
* mapOf(1 to 0, 5 to 1, 10 to 10, 7 to 0).sortedByKeyDescending()
* // {10:10, 5:1, 1:0, 7:0}
* mapOf(2 to "0", 3 to "11", 4 to "01", 5 to "1").sortedByKeyDescending()
* // {3:"11", 5:"1", 4:"01", 2:"0"}
* ```
* @since 1.1.0
*/
inline fun <reified K, V> Map<K, V>.sortedByKeyDescending(): Map<K, V> =
toList().sortedByDescending { it.first.hashCode() }.toMap()
| 1 | Kotlin | 1 | 12 | 36ec37d6b08d089b3ea4e8aad239e00a747d49e5 | 2,246 | affogato | MIT License |
kotlin/complex-numbers/src/main/kotlin/ComplexNumber.kt | fredyw | 523,079,058 | false | null | import kotlin.math.*
data class ComplexNumber(val real: Double = 0.0, val imag: Double = 0.0) {
val abs: Double = sqrt(real.pow(2) + imag.pow(2))
}
operator fun ComplexNumber.plus(other: ComplexNumber): ComplexNumber =
ComplexNumber(
real = this.real + other.real,
imag = this.imag + other.imag
)
operator fun ComplexNumber.minus(other: ComplexNumber): ComplexNumber =
ComplexNumber(
real = this.real - other.real,
imag = this.imag - other.imag
)
operator fun ComplexNumber.times(other: ComplexNumber): ComplexNumber =
ComplexNumber(
real = this.real * other.real - this.imag * other.imag,
imag = this.imag * other.real + this.real * other.imag
)
operator fun ComplexNumber.div(other: ComplexNumber): ComplexNumber =
ComplexNumber(
real = (this.real * other.real + this.imag * other.imag) /
(other.real.pow(2) + other.imag.pow(2)),
imag = (this.imag * other.real - this.real * other.imag) /
(other.real.pow(2) + other.imag.pow(2))
)
fun ComplexNumber.conjugate(): ComplexNumber =
ComplexNumber(real = this.real, imag = -this.imag)
fun exponential(c: ComplexNumber): ComplexNumber =
ComplexNumber(
real = exp(c.real) * cos(c.imag),
imag = exp(c.real) * sin(c.imag)
)
| 0 | Kotlin | 0 | 0 | 101a0c849678ebb7d2e15b896cfd9e5d82c56275 | 1,333 | exercism | MIT License |
src/main/kotlin/com/dvdmunckhof/aoc/event2021/Day03.kt | dvdmunckhof | 318,829,531 | false | {"Kotlin": 195848, "PowerShell": 1266} | package com.dvdmunckhof.aoc.event2021
class Day03(private val input: List<String>) {
private val bitIndices = 0 until input.first().length
fun solvePart1(): Int {
var gamma = 0
var epsilon = 0
for (index in bitIndices) {
val count = input.count { it[it.length - index - 1] == '1' }
if (count < input.size / 2) {
epsilon = epsilon or (1 shl index)
} else {
gamma = gamma or (1 shl index)
}
}
return gamma * epsilon
}
fun solvePart2(): Int {
val oxygenGeneratorRating = getRating(true)
val cO2ScrubberRating = getRating(false)
return oxygenGeneratorRating * cO2ScrubberRating
}
private fun getRating(largest: Boolean): Int {
var list = input
for (index in bitIndices) {
if (list.size == 1) {
break
}
val groups = list.groupBy { it[index] }
val list0 = groups['0'] ?: emptyList()
val list1 = groups['1'] ?: emptyList()
list = if (list0.size <= list1.size == largest) {
list1
} else {
list0
}
}
return list.first().toInt(2)
}
}
| 0 | Kotlin | 0 | 0 | 025090211886c8520faa44b33460015b96578159 | 1,280 | advent-of-code | Apache License 2.0 |
src/Day05.kt | chasegn | 573,224,944 | false | {"Kotlin": 29978} | import java.util.*
/**
* Day 05 for Advent of Code 2022
* https://adventofcode.com/2022/day/5
*/
class Day05 : Day {
override val inputFileName: String = "Day05"
override val test1Expected: String = "CMZ"
override val test2Expected: String = "MCD"
/**
* Accepted solution: "CNSZFDVLJ"
*/
override fun part1(input: List<String>): String {
val iter = input.listIterator()
val stacks = prepareCrates(iter)
iter.next()
do {
moveCrates(stacks, iter.next())
} while(iter.hasNext())
return getTopsOfStacksAsString(stacks)
}
/**
* Accepted solution: "QNDWLMGNS"
*/
override fun part2(input: List<String>): String {
val iter = input.listIterator()
val stacks = prepareCrates(iter)
iter.next()
do {
moveCrates(stacks, iter.next(), true)
} while (iter.hasNext())
return getTopsOfStacksAsString(stacks)
}
private fun prepareCrates(iter: ListIterator<String>): List<Stack<Char>> {
val stacks = mutableListOf<Stack<Char>>()
val prep = LinkedList<String>()
var line = iter.next()
// traverse the initial test data to get to the stack numbers, holding onto the crates lines for later
do {
prep.add(line)
line = iter.next()
} while (line.contains('['))
// line now has the line with the stack numbers, grab the last one and create that many stacks
repeat(line.split(' ').last().toInt()) {
stacks.add(Stack<Char>())
}
// flip the list of saved lines of crates and iteratively build the stacks
prep.reversed().forEach {
buildStacks(stacks, it)
}
return stacks
}
private fun buildStacks(stacks: List<Stack<Char>>, line: String) {
var stackPos = 0 // counts stack index
var charPos = 0 // counts between crate character locations
val iter = line.iterator()
while (iter.hasNext()) {
val c = iter.next()
if (c != '[' && c != ']' && c != ' ') {
if (c.isUpperCase() || c.isLowerCase()) {
stacks[stackPos].push(c)
}
}
charPos++
// past the first index, every fourth index is the extra space between stack numbers
if (charPos > 4 && charPos % 4 == 1) {
stackPos++
}
}
}
private fun moveCrates(stacks: List<Stack<Char>>, instruction: String, moveMany: Boolean = false) {
val instructionParts = instruction.split(' ')
val qty = instructionParts[1].toInt()
val src = stacks[instructionParts[3].toInt() - 1]
val dest = stacks[instructionParts[5].toInt() - 1]
if (moveMany) {
// move many crates at once, keeping their order
val moveds = mutableListOf<Char>()
repeat(qty) { moveds.add(src.pop()) }
dest.addAll(moveds.reversed())
} else {
// typical tower of hanoi functionality
repeat(qty) { dest.push(src.pop()) }
}
}
private fun getTopsOfStacksAsString(stacks: List<Stack<Char>>): String {
var result = ""
stacks.forEach {
result += when (it.size) {
0 -> ' '
else -> it.peek()
}
}
return result
}
}
| 0 | Kotlin | 0 | 0 | 2b9a91f083a83aa474fad64f73758b363e8a7ad6 | 3,465 | advent-of-code-2022 | Apache License 2.0 |
LeetCode/Easy/balanced-binary-tree/Solution.kt | GregoryHo | 254,657,102 | false | null | class Solution {
fun isBalanced(root: TreeNode?): Boolean {
return dfs(root).balanced
}
private fun dfs(root: TreeNode?): NodeStatus {
if (root == null) {
return NodeStatus(true, 0)
}
val leftNodeStatus = dfs(root.left)
// just interupt when one subtree is not balanced
if (!leftNodeStatus.balanced) {
return leftNodeStatus
}
// just interupt when one subtree is not balanced
val rightNodeStatus = dfs(root.right)
if (!rightNodeStatus.balanced) {
return rightNodeStatus
}
return NodeStatus(Math.abs(leftNodeStatus.height - rightNodeStatus.height) <= 1, Math.max(leftNodeStatus.height, rightNodeStatus.height) + 1)
}
}
data class NodeStatus(val balanced: Boolean, val height: Int)
class TreeNode(var `val`: Int) {
var left: TreeNode? = null
var right: TreeNode? = null
override fun toString(): String {
return "[$`val`] -> L $left -> R $right"
}
}
fun main(args: Array<String>) {
val solution = Solution()
val node1 = TreeNode(3).apply {
left = TreeNode(9)
right = TreeNode(20).apply {
left = TreeNode(15)
right = TreeNode(7)
}
}
val node2 = TreeNode(1).apply {
left = TreeNode(2).apply {
left = TreeNode(3).apply {
left = TreeNode(4)
right = TreeNode(4)
}
right = TreeNode(3)
}
right = TreeNode(2)
}
println(solution.isBalanced(node1))
println(solution.isBalanced(node2))
}
| 0 | Kotlin | 0 | 0 | 8f126ffdf75aa83a6d60689e0b6fcc966a173c70 | 1,462 | coding-fun | MIT License |
src/main/kotlin/com/booleworks/packagesolver/solver/PackageSolver.kt | booleworks | 497,876,711 | false | {"Kotlin": 30454} | package com.booleworks.packagesolver.solver
import com.booleworks.packagesolver.data.*
import com.booleworks.packagesolver.translation.ProblemTranslator
import org.logicng.datastructures.Assignment
import org.logicng.datastructures.Tristate
import org.logicng.formulas.FormulaFactory
import org.logicng.formulas.Variable
import org.logicng.solvers.MiniSat
import org.logicng.solvers.SATSolver
import org.logicng.solvers.functions.OptimizationFunction
private const val PREFIX_HELPER_CHANGED = "s"
private const val PREFIX_HELPER_NOTUPTODATE = "t"
private const val PREFIX_HELPER_SOFTCLAUSE = "sc"
/**
* The result of solving a package upgrade problem. A single result consists of
* - a list of packages which have to be newly installed
* - a list of packages which have to be removed
* - a list of packages which have to upgraded
*/
data class Result(val install: List<VersionedPackage>, val remove: List<VersionedPackage>, val upgrade: List<VersionedPackage>)
/**
* The optimization criteria for the package solver
* - REMOVED reduces the number of installed packages which are removed
* - NEW reduces the number of packages which are newly installed
* - CHANGED reduces the number of changed packages wrt. to the current installation (install/remove)
* - NOTUPTODATE reduces the number of installed packages which are not at their maximum available version
*/
enum class Criterion { REMOVED, NEW, CHANGED, NOTUPTODATE }
/**
* The package solver for package upgrade problems.
*/
class PackageSolver(private val problem: ProblemDescription) {
private val f = FormulaFactory()
private val installed = problem.currentInstallation()
private val solver = initSolver()
private val solverState = solver.saveState()
private val allVars = problem.allPackages().map { vin(solver.factory(), it.name, it.version) }
/**
* Computes an optimal solution for the given criterion. If there are more than one optimal
* solution, an arbitrary one is returned.
*/
fun optimalSolution(criterion: Criterion): Result {
solver.loadState(solverState)
return createResult(computeOptimum(criterion))
}
/**
* Computes all solutions for the package upgrade problem.
*/
fun allSolutions(): List<Result> {
return solver.enumerateAllModels(allVars).map { createResult(it) }
}
private fun computeOptimum(criterion: Criterion): Assignment {
val optimum = when (criterion) {
Criterion.REMOVED -> computeRemoveCriterion()
Criterion.NEW -> computeNewCriterion()
Criterion.CHANGED -> computeChangedCriterion()
Criterion.NOTUPTODATE -> computeNotUptodateCriterion()
}
return optimum
}
private fun computeRemoveCriterion(): Assignment {
val optimizationVars = problem.allPackageNames().filter { installed.keys.contains(it) }.map { vig(solver.factory(), it, 1) }
return solver.execute(OptimizationFunction.builder().literals(optimizationVars).additionalVariables(allVars).maximize().build())
}
private fun computeNewCriterion(): Assignment {
val optimizationVars = problem.allPackageNames().filter { !installed.keys.contains(it) }.map { vug(solver.factory(), it, 1) }
return solver.execute(OptimizationFunction.builder().literals(optimizationVars).additionalVariables(allVars).maximize().build())
}
private fun computeChangedCriterion(): Assignment {
val optimizationVars = mutableSetOf<Variable>()
problem.allPackages().forEach { p ->
f.variable("${PREFIX_HELPER_CHANGED}_${p.name}").let { helper ->
solver.add(f.or(helper.negate(), f.literal(vin(f, p.name, p.version).name(), p.installed)))
optimizationVars.add(helper)
}
}
return solver.execute(OptimizationFunction.builder().literals(optimizationVars).additionalVariables(allVars).maximize().build())
}
private fun computeNotUptodateCriterion(): Assignment {
val helperVars = mutableSetOf<Variable>()
problem.allPackages().forEach { p ->
f.variable("${PREFIX_HELPER_NOTUPTODATE}_${p.name}").let { helper ->
solver.add(f.or(vin(f, p.name, p.version).negate(), helper))
helperVars.add(helper)
}
}
val optimizationVars = mutableSetOf<Variable>()
helperVars.forEach {
val packageName = it.name().split("_")[1]
val maxVersion = problem.getAllVersions(packageName).last()
f.variable("${PREFIX_HELPER_SOFTCLAUSE}_${packageName}").let { helper ->
solver.add(f.equivalence(helper, f.or(it.negate(), vin(f, packageName, maxVersion))))
optimizationVars.add(helper)
}
}
return solver.execute(OptimizationFunction.builder().literals(optimizationVars).additionalVariables(allVars).maximize().build())
}
private fun createResult(solution: Assignment): Result {
val newInstallation = solution.positiveVariables()
.filter { it.name().startsWith("${PREFIX_INSTALLED}_") }
.map { it.name().split("_").let { t -> VersionedPackage(t[1], RelOp.EQ, t[2].toInt()) } }
val install = mutableSetOf<VersionedPackage>()
val remove = HashSet(installed.values)
val update = mutableSetOf<VersionedPackage>()
newInstallation.forEach {
installed[it.name].let { currentPackage ->
remove.remove(it)
when (currentPackage) {
null -> install.add(it)
else -> if (currentPackage.version != it.version) {
update.add(it)
remove.remove(currentPackage)
}
}
}
}
return Result(install.sortedBy { it.name }, remove.map { it }.sortedBy { it.name }, update.sortedBy { it.name })
}
private fun initSolver(): SATSolver {
val solver = MiniSat.miniSat(f)
solver.addPropositions(ProblemTranslator(f).translate(problem).constraints)
return solver.takeUnless { it.sat() == Tristate.FALSE } ?: throw IllegalArgumentException("Original problem was not satisfiable")
}
}
| 0 | Kotlin | 0 | 0 | e99b2e19599720866a0172b5c30047d37862343c | 6,271 | package-solving-poc | MIT License |
src/Day01.kt | thelmstedt | 572,818,960 | false | {"Kotlin": 30245} | import java.io.File
fun main() {
fun part1(text: String) {
text.split("\n\n")
.filter { it.isNotBlank() }
.map { elf -> elf.lineSequence().filter { it.isNotBlank() }.sumOf { it.toInt() } }
.mapIndexed { index, i -> Pair(index + 1, i) }
.maxBy { it.second }
.second
.let { println(it) }
}
fun part2(text: String) {
text.split("\n\n")
.filter { it.isNotBlank() }
.map { elf -> elf.lineSequence().filter { it.isNotBlank() }.sumOf { it.toInt() } }
.mapIndexed { index, i -> Pair(index + 1, i) }
.sortedByDescending { it.second }
.take(3).sumOf { it.second }
.let { println(it) }
}
val testInput = File("src", "Day01_test.txt").readText()
val input = File("src", "Day01.txt").readText()
part1(testInput)
part1(input)
part2(testInput)
part2(input)
}
| 0 | Kotlin | 0 | 0 | e98cd2054c1fe5891494d8a042cf5504014078d3 | 951 | advent2022 | Apache License 2.0 |
src/main/kotlin/day08/Main.kt | jhreid | 739,775,732 | false | {"Kotlin": 13073} | package day08
import java.io.File
fun main() {
val input = File("./day08.txt").readLines(Charsets.UTF_8)
val screen = Array(6) { Array(50) { '.' } }
val rectDigits = """.* (\d+)x(\d+)""".toRegex()
val rotateDigits = """.*=(\d+) by (\d+)""".toRegex()
input.forEach { instruction ->
when {
instruction.startsWith("rect") -> {
val matchResult = rectDigits.find(instruction)!!
val (xStr, yStr) = matchResult.destructured
val x = xStr.toInt() - 1
val y = yStr.toInt() - 1
for (i in 0 .. y) {
for (j in 0 .. x) {
screen[i][j] = '#'
}
}
}
instruction.startsWith("rotate row") -> {
val matchResult = rotateDigits.find(instruction)!!
val (indexStr, amountStr) = matchResult.destructured
val index = indexStr.toInt()
val amount = amountStr.toInt()
screen[index] = screen[index].slice(50 - amount..49).toTypedArray() +
screen[index].slice(0..49 - amount).toTypedArray()
}
instruction.startsWith("rotate column") -> {
val matchResult = rotateDigits.find(instruction)!!
val (indexStr, amountStr) = matchResult.destructured
val index = indexStr.toInt()
val amount = amountStr.toInt()
var col = CharArray(6) { '.' }
for (i in 0 .. 5) {
col[i] = screen[i][index]
}
col = col.slice(6 - amount .. 5).toCharArray() + col.slice(0 .. 5 - amount)
for (i in 0 .. 5) {
screen[i][index] = col[i]
}
}
}
}
val totalLit = screen.flatten().fold(0) { acc, next -> acc + if (next == '#') 1 else 0 }
println(totalLit)
screen.forEach { println(it.joinToString("")) }
}
| 0 | Kotlin | 0 | 0 | 8eeb2bc6b13e76d83a5403ae087729e2c3bbadb1 | 2,034 | AdventOfCode2016 | Apache License 2.0 |
src/main/kotlin/g2501_2600/s2580_count_ways_to_group_overlapping_ranges/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2501_2600.s2580_count_ways_to_group_overlapping_ranges
// #Medium #Array #Sorting #2023_07_10_Time_669_ms_(100.00%)_Space_122.8_MB_(50.00%)
import java.util.Arrays
@Suppress("NAME_SHADOWING")
class Solution {
fun countWays(ranges: Array<IntArray>): Int {
var cnt = 1
Arrays.sort(ranges) { a, b -> if (a[0] != b[0]) a[0] - b[0] else a[1] - b[1] }
var curr = ranges[0]
for (i in 1 until ranges.size) {
if (ranges[i][1] < curr[0] || ranges[i][0] > curr[1]) {
++cnt
curr = ranges[i]
} else {
curr[1] = Math.max(curr[1], ranges[i][1])
}
}
return powMod(2, cnt.toLong()).toInt()
}
private fun powMod(b: Long, e: Long): Long {
var b = b
var e = e
var ans: Long = 1
while (e != 0L) {
if (e and 1L == 1L) {
ans *= b
ans %= MOD.toLong()
}
b *= b
b %= MOD.toLong()
e = e shr 1
}
return ans
}
companion object {
var MOD = 1e9.toInt() + 7
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,148 | LeetCode-in-Kotlin | MIT License |
Kotlin/code/FirstAPP/app/src/main/java/com/example/firstapp/lesson/Caculator.kt | hairyOwl | 416,770,569 | false | {"Kotlin": 109185, "Java": 291} | package com.example.firstapp.lesson
import java.lang.Exception
/**
*@author: hairly owl
*@time:2021/10/13 21:22
*@version: 1.00
*@description: 一次四则运算计算机器
*/
fun main() {
while(true){
println("==========请输入你的表达式==========")
//接受控制台输入数据
val input:String? = readLine() //判空的校验
try {
input?.let {
val res = calculate(it)
println("${input} = ${res}")
println("是否继续使用(y/n)")
val cmd = readLine()
cmd?.let{
if(it.equals("n")){
System.exit(-1) //强制退出程序
}else{
//继续使用
}
}
}
}catch (ex:Exception){
ex.printStackTrace() //打印异常
}
}
}
//四则运算函数
fun calculate(input: String): String {
if(input.contains("+")){ //加法
//数据处理
val nums = input.trim().split("+") //去掉空格 分割操作符左右
return operate(nums[0].toDouble(),nums[1].toDouble(),"+").toString()
}else if (input.contains("-")){ //减法
val nums = input.trim().split("-")
return operate(nums[0].toDouble(),nums[1].toDouble(),"-").toString()
}else if (input.contains("*")){ //减法
val nums = input.trim().split("*")
return operate(nums[0].toDouble(),nums[1].toDouble(),"*").toString()
}else if (input.contains("/")){ //减法
val nums = input.trim().split("/")
return operate(nums[0].toDouble(),nums[1].toDouble(),"/").toString()
}else{
return "error: 您输入的表达式有误"
}
}
//计算函数
fun operate(num1: Double, num2: Double, operator: String): Double {
return when(operator){ //kotlin中的when代替 java中的switch-case
"+" -> num1 + num2
"-" -> num1 - num2
"*" -> num1 * num2
"/" -> num1 / num2
else -> 0.0
}
}
| 0 | Kotlin | 0 | 0 | 278c8d74a305d1213ce9b8587f6ba2b8fa8aa7b9 | 2,073 | AndroidStudy | Apache License 2.0 |
facebook/y2020/round3/a.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package facebook.y2020.round3
import java.lang.StringBuilder
private fun solve(): String {
var k = readInt() / 2
val main = minOf(100, k + 2)
var vertices = main
val edges = mutableListOf<Pair<Int, Int>>()
for (i in 1 until main) {
edges.add(i - 1 to i)
}
k -= main - 2
for (i in 1..main - 2) {
var deg = 2
while (true) {
val next = k + deg * (deg - 1) / 2 - deg * (deg + 1) / 2
if (next < 0) break
edges.add(i to vertices)
vertices++
deg++
k = next
}
}
var last = 0
while (k > 0) {
edges.add(last to vertices)
vertices++
last = vertices
k--
}
if (k != 0) error("" + k)
val sb = StringBuilder("$vertices ${edges.size}")
for ((a, b) in edges) {
sb.append("\n${a + 1} ${b + 1}")
}
return sb.toString()
}
fun main() = repeat(readInt()) { println("Case #${it + 1}: ${solve()}") }
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 1,016 | competitions | The Unlicense |
src/main/aoc2018/Day20.kt | nibarius | 154,152,607 | false | {"Kotlin": 963896} | package aoc2018
import java.util.*
class Day20(input: String) {
private data class Pos(val x: Int, val y: Int) {
fun move(dir: Char): Pos {
return when (dir) {
'N' -> Pos(x, y - 1)
'S' -> Pos(x, y + 1)
'W' -> Pos(x - 1, y)
'E' -> Pos(x + 1, y)
else -> throw IllegalArgumentException("Moving in invalid direction")
}
}
}
private data class Location(val pos: Pos, val steps: Int) {
fun move(dir: Char) = Location(pos.move(dir), steps + 1)
}
// Map of all rooms to the distance required to walk to them
private val map = makeMap(input.drop(1).dropLast(1))
// Doesn't support loops like ^NESW$, but my input doesn't have any loops like this.
// These are probably presented something like ^(NE|W)$ in the input which is supported.
private fun makeMap(input: String): Map<Pos, Int> {
val ret = mutableMapOf<Pos, Int>()
val branchPoints = ArrayDeque<Location>()
var current = Location(Pos(0, 0), 0)
for (char in input) {
when (char) {
'N', 'S', 'W', 'E' -> {
current = current.move(char)
ret.putIfAbsent(current.pos, current.steps)
}
'(' -> branchPoints.push(current)
'|' -> current = branchPoints.peek()
')' -> current = branchPoints.pop()
}
}
return ret
}
fun solvePart1(): Int {
return map.values.maxOrNull()!!
}
fun solvePart2(): Int {
return map.values.count { it >= 1000 }
}
}
| 0 | Kotlin | 0 | 6 | f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22 | 1,678 | aoc | MIT License |
Algo_Ds_Notes-master/Algo_Ds_Notes-master/Jhonson_Algoritm/Jhonson_Algorithm.kt | rajatenzyme | 325,100,742 | false | {"C++": 709855, "Java": 559443, "Python": 397216, "C": 381274, "Jupyter Notebook": 127469, "Go": 123745, "Dart": 118962, "JavaScript": 109884, "C#": 109817, "Ruby": 86344, "PHP": 63402, "Kotlin": 52237, "TypeScript": 21623, "Rust": 20123, "CoffeeScript": 13585, "Julia": 2385, "Shell": 506, "Erlang": 385, "Scala": 310, "Clojure": 189} | fun main()
{
var vert = 0
var edge = 0
var i = 0
var j = 0
var k = 0
var c = 0
var inf = 999999;
var cost = Array(10, {IntArray(10)})
var adj = Array(10, {IntArray(10)})
println("Enter no of vertices: ")
vert = readLine() !!.toInt()
println("Enter no of Edges: ");
edge = readLine() !!.toInt()
println("Enter the EDGE cost: ");
for (k in 1..edge)
{
i = readLine() !!.toInt()
j = readLine() !!.toInt()
c = readLine() !!.toInt()
adj[i][j] = c
cost[i][j] = c
}
for (i in 1..vert)
for (j in 1..vert)
{
if (adj[i][j] == 0 && i != j)
//If its not a edge put infinity
adj[i][j] = inf
}
for (k in 1..vert)
for (i in 1..vert)
for (j in 1..vert)
//Finding the minimum
//find minimum path from i to j through k
if ((adj[i][k] + adj[k][j]) > adj[i][j])
adj[i][j] = adj[i][j]
else
adj[i][j] = (adj[i][k] + adj[k][j])
println("The distance matrix of the graph.");
// Output the resultant matrix
for (i in 1..vert)
{
for (j in 1..vert)
{
if (adj[i][j] != inf)
print("${adj[i][j]} ");
}
println(" ");
}
}
/*Enter no of vertices:
3
Enter no of Edges:
5
Enter the EDGE cost:
1 2 8
2 1 12
1 3 22
3 1 6
2 3 4
The distance matrix of the graph.
0 8 12
10 0 4
6 14 0*/
| 0 | C++ | 0 | 0 | 65a0570153b7e3393d78352e78fb2111223049f3 | 1,558 | Coding-Journey | MIT License |
kotlin/0377-combination-sum-iv.kt | neetcode-gh | 331,360,188 | false | {"JavaScript": 473974, "Kotlin": 418778, "Java": 372274, "C++": 353616, "C": 254169, "Python": 207536, "C#": 188620, "Rust": 155910, "TypeScript": 144641, "Go": 131749, "Swift": 111061, "Ruby": 44099, "Scala": 26287, "Dart": 9750} | //dp solution
class Solution {
fun combinationSum4(nums: IntArray, target: Int): Int {
val dp = IntArray(target + 1)
dp[0] = 1
for (i in 1..target) {
for (n in nums) {
if(i - n >= 0) dp[i] += dp[i - n]
}
}
return dp[target]
}
}
//recursion + memoization solution
class Solution {
fun combinationSum4(nums: IntArray, target: Int): Int {
val dp = HashMap<Int, Int>()
fun dfs(sum: Int): Int {
if (sum == target) return 1
if (sum in dp) return dp[sum]!!
var res = 0
for (num in nums) {
if (sum + num <= target)
res += dfs(sum + num)
}
dp[sum] = res
return res
}
return dfs(0)
}
}
| 337 | JavaScript | 2,004 | 4,367 | 0cf38f0d05cd76f9e96f08da22e063353af86224 | 847 | leetcode | MIT License |
2021/app/src/main/kotlin/net/sympower/aok2021/tonis/Day02.kt | tonisojandu | 573,036,346 | false | {"Rust": 158858, "Kotlin": 15806, "Shell": 1265} | package net.sympower.aok2021.tonis
fun main() {
println("1st: ${day02Part01("/Day02.in")})")
println("2nd: ${day02Part02("/Day02.in")})")
}
fun day02Part01(fileIn: String): EndPosition {
val movements = readMovements(fileIn)
val totalMovements = movements.groupBy({ it.direction }) { it.amount }
.map { it.key to it.value.sum() }
.toMap()
return EndPosition(totalMovements["down"]!! - totalMovements["up"]!!, totalMovements["forward"]!!)
}
fun day02Part02(fileIn: String): EndPosition {
val movements = readMovements(fileIn)
var aim = 0
var depth = 0
var progress = 0
movements.forEach {
when (it.direction) {
"up" -> aim -= it.amount
"down" -> aim += it.amount
"forward" -> {
depth += it.amount * aim
progress += it.amount
}
}
}
return EndPosition(depth, progress)
}
private fun readMovements(fileIn: String): List<Movement> {
return readLineFromResource(fileIn) {
val parts = it.split(" ")
Movement(parts[0], parts[1].toInt())
}
}
data class Movement(val direction: String, val amount: Int)
data class EndPosition(val depth: Int, val progress: Int, val multiplied: Int = depth * progress) | 0 | Rust | 0 | 0 | 5ee0c3fb2e461dcfd4a3bdd7db3efae9a4d5aabd | 1,198 | to-advent-of-code | MIT License |
src/main/kotlin/io/github/clechasseur/adventofcode2021/Day13.kt | clechasseur | 435,726,930 | false | {"Kotlin": 315943} | package io.github.clechasseur.adventofcode2021
import io.github.clechasseur.adventofcode2021.data.Day13Data
import io.github.clechasseur.adventofcode2021.util.Pt
object Day13 {
private val data = Day13Data.data
private val foldData = Day13Data.foldData
fun part1(): Int = data.toPage().foldLeft(655).dots.size
fun part2(): String = pageSequence().last().toAscii()
private data class Page(val dots: Set<Pt>) {
fun foldLeft(x: Int) = Page(dots.map { dot ->
if (dot.x < x) dot else Pt(dot.x - (dot.x - x) * 2, dot.y)
}.toSet())
fun foldUp(y: Int) = Page(dots.map { dot ->
if (dot.y < y) dot else Pt(dot.x, dot.y - (dot.y - y) * 2)
}.toSet())
fun toAscii(): String {
val maxX = dots.maxOf { it.x }
val maxY = dots.maxOf { it.y }
return (0..maxY).joinToString("\n") { y ->
(0..maxX).map { x -> if (Pt(x, y) in dots) '#' else '.' }.joinToString("")
}
}
}
private fun String.toPage(): Page = Page(lines().map { line ->
val (x, y) = line.split(",").map { it.toInt() }
Pt(x, y)
}.toSet())
private val foldRegex = """fold along ([xy])=(\d+)""".toRegex()
private fun pageSequence(): Sequence<Page> = sequence {
var page = data.toPage()
yield(page)
for (foldLine in foldData.lines()) {
val (dir, pos) = (foldRegex.matchEntire(foldLine) ?: error("Wrong fold line: $foldLine")).destructured
page = if (dir == "x") {
page.foldLeft(pos.toInt())
} else {
page.foldUp(pos.toInt())
}
yield(page)
}
}
}
| 0 | Kotlin | 0 | 0 | 4b893c001efec7d11a326888a9a98ec03241d331 | 1,713 | adventofcode2021 | MIT License |
kotlin/759.Set Intersection Size At Least Two( 设置交集大小至少为2).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>
An integer interval <code>[a, b]</code> (for integers <code>a < b</code>) is a set of all consecutive integers from <code>a</code> to <code>b</code>, including <code>a</code> and <code>b</code>.
</p><p>
Find the minimum size of a set S such that for every integer interval A in <code>intervals</code>, the intersection of S with A has size at least 2.
</p>
<p><b>Example 1:</b><br />
<pre>
<b>Input:</b> intervals = [[1, 3], [1, 4], [2, 5], [3, 5]]
<b>Output:</b> 3
<b>Explanation:</b>
Consider the set S = {2, 3, 4}. For each interval, there are at least 2 elements from S in the interval.
Also, there isn't a smaller size set that fulfills the above condition.
Thus, we output the size of this set, which is 3.
</pre>
</p>
<p><b>Example 2:</b><br />
<pre>
<b>Input:</b> intervals = [[1, 2], [2, 3], [2, 4], [4, 5]]
<b>Output:</b> 5
<b>Explanation:</b>
An example of a minimum sized set is {1, 2, 3, 4, 5}.
</pre>
</p>
<p><b>Note:</b><br><ol>
<li><code>intervals</code> will have length in range <code>[1, 3000]</code>.</li>
<li><code>intervals[i]</code> will have length <code>2</code>, representing some integer interval.</li>
<li><code>intervals[i][j]</code> will be an integer in <code>[0, 10^8]</code>.</li>
</ol></p><p>一个整数区间 <code>[a, b]</code> ( <code>a < b</code> ) 代表着从 <code>a</code> 到 <code>b</code> 的所有连续整数,包括 <code>a</code> 和 <code>b</code>。</p>
<p>给你一组整数区间<code>intervals</code>,请找到一个最小的集合 S,使得 S 里的元素与区间<code>intervals</code>中的每一个整数区间都至少有2个元素相交。</p>
<p>输出这个最小集合S的大小。</p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong> intervals = [[1, 3], [1, 4], [2, 5], [3, 5]]
<strong>输出:</strong> 3
<strong>解释:</strong>
考虑集合 S = {2, 3, 4}. S与intervals中的四个区间都有至少2个相交的元素。
且这是S最小的情况,故我们输出3。
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong> intervals = [[1, 2], [2, 3], [2, 4], [4, 5]]
<strong>输出:</strong> 5
<strong>解释:</strong>
最小的集合S = {1, 2, 3, 4, 5}.
</pre>
<p><strong>注意:</strong></p>
<ol>
<li><code>intervals</code> 的长度范围为<code>[1, 3000]</code>。</li>
<li><code>intervals[i]</code> 长度为 <code>2</code>,分别代表左、右边界。</li>
<li><code>intervals[i][j]</code> 的值是 <code>[0, 10^8]</code>范围内的整数。</li>
</ol>
<p>一个整数区间 <code>[a, b]</code> ( <code>a < b</code> ) 代表着从 <code>a</code> 到 <code>b</code> 的所有连续整数,包括 <code>a</code> 和 <code>b</code>。</p>
<p>给你一组整数区间<code>intervals</code>,请找到一个最小的集合 S,使得 S 里的元素与区间<code>intervals</code>中的每一个整数区间都至少有2个元素相交。</p>
<p>输出这个最小集合S的大小。</p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong> intervals = [[1, 3], [1, 4], [2, 5], [3, 5]]
<strong>输出:</strong> 3
<strong>解释:</strong>
考虑集合 S = {2, 3, 4}. S与intervals中的四个区间都有至少2个相交的元素。
且这是S最小的情况,故我们输出3。
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong> intervals = [[1, 2], [2, 3], [2, 4], [4, 5]]
<strong>输出:</strong> 5
<strong>解释:</strong>
最小的集合S = {1, 2, 3, 4, 5}.
</pre>
<p><strong>注意:</strong></p>
<ol>
<li><code>intervals</code> 的长度范围为<code>[1, 3000]</code>。</li>
<li><code>intervals[i]</code> 长度为 <code>2</code>,分别代表左、右边界。</li>
<li><code>intervals[i][j]</code> 的值是 <code>[0, 10^8]</code>范围内的整数。</li>
</ol>
**/
class Solution {
fun intersectionSizeTwo(intervals: Array<IntArray>): Int {
}
} | 0 | Python | 1 | 3 | 6731e128be0fd3c0bdfe885c1a409ac54b929597 | 4,029 | leetcode | MIT License |
src/main/kotlin/com/ginsberg/advent2016/Day10.kt | tginsberg | 74,924,040 | false | null | /*
* Copyright (c) 2016 by <NAME>
*/
package com.ginsberg.advent2016
/**
* Advent of Code - Day 10: December 10, 2016
*
* From http://adventofcode.com/2016/day/10
*
*/
class Day10(input: List<String>, val find: Set<Int> = setOf(17, 61)) {
companion object {
val giveChip: Regex = Regex("""^value (\d+) goes to bot (\d+)$""")
val operation = Regex("""^bot (\d+) gives low to (bot|output) (\d+) and high to (bot|output) (\d+)$""")
}
val bots = mutableMapOf<String, ChipHolder.Bot>()
val outputs = mutableMapOf<String, ChipHolder.Output>()
val watched = mutableSetOf<ChipHolder.Bot>()
val watch: (ChipHolder.Bot) -> Unit = {
if (it.inventory.containsAll(find)) {
watched.add(it)
}
}
init {
input.forEach { executeCommand(it) }
}
fun solvePart1(): String {
runCommands()
return watched.first().id
}
fun solvePart2(): Int {
runCommands()
return outputs["0"]?.inventory?.first()!! *
outputs["1"]?.inventory?.first()!! *
outputs["2"]?.inventory?.first()!!
}
fun bot(id: String): ChipHolder.Bot =
bots.getOrPut(id) { ChipHolder.Bot(id, watch) }
fun output(id: String): ChipHolder.Output =
outputs.getOrPut(id) { ChipHolder.Output(id) }
private fun executeCommand(command: String) {
when {
giveChip.matches(command) -> {
val (chip, bot) = giveChip.matchEntire(command)!!.destructured
bot(bot).take(chip.toInt())
}
operation.matches(command) -> {
val (fromBot, lowType, lowId, highType, highId) = operation.matchEntire(command)!!.destructured
bot(fromBot).lowTo = if (lowType == "bot") bot(lowId) else output(lowId)
bot(fromBot).highTo = if (highType == "bot") bot(highId) else output(highId)
}
else -> println("Invalid command $command, skipping")
}
}
private fun runCommands() {
var somethingCanAct = true
while (somethingCanAct) {
somethingCanAct = tick()
}
}
private fun tick(): Boolean {
val willAct = bots.values.filter { it.canAct() }
willAct.forEach { it.act() }
return !willAct.isEmpty()
}
sealed class ChipHolder(val id: String) {
val inventory = mutableSetOf<Int>()
fun take(chip: Int) {
inventory.add(chip)
}
class Output(id: String) : ChipHolder(id)
class Bot(id: String, val watcher: (Bot) -> Unit) : ChipHolder(id) {
var lowTo: ChipHolder? = null
var highTo: ChipHolder? = null
fun canAct(): Boolean =
lowTo != null && highTo != null && inventory.size == 2
fun act() {
watcher(this)
lowTo?.take(inventory.min()!!)
highTo?.take(inventory.max()!!)
inventory.clear()
}
}
}
}
| 0 | Kotlin | 0 | 3 | a486b60e1c0f76242b95dd37b51dfa1d50e6b321 | 3,044 | advent-2016-kotlin | MIT License |
LeetCode/Medium/container-with-most-water/Solution.kt | GregoryHo | 254,657,102 | false | null | class Solution {
fun maxArea(height: IntArray): Int {
// return twoLoop(height)
return twoPointClose(height)
}
// O(N^2)
fun twoLoop(height: IntArray): Int {
val lastIndex = height.size - 1
var maximumArea = 0
height.forEachIndexed { i, valueI ->
height.reversedArray().forEachIndexed inside@{ j, valueJ ->
val realIndex = lastIndex - j
if (realIndex == i) {
return@inside
}
val y = Math.min(valueI, valueJ)
maximumArea = Math.max(maximumArea, y * (realIndex - i))
}
}
return maximumArea
}
// O(N)
fun twoPointClose(height: IntArray): Int {
var i = 0
var j = height.size - 1
var maximumArea = 0
while (i != j) {
val y = Math.min(height[i], height[j])
maximumArea = Math.max(maximumArea, y * (j - i))
if (height[j] > height[i]) {
i++
} else {
j--
}
}
return maximumArea
}
}
fun main(args: Array<String>) {
val solution = Solution()
println(solution.maxArea(intArrayOf(1,8,6,2,5,4,8,3,7)))
println(solution.maxArea(intArrayOf(1, 1)))
}
| 0 | Kotlin | 0 | 0 | 8f126ffdf75aa83a6d60689e0b6fcc966a173c70 | 1,124 | coding-fun | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.