path stringlengths 5 169 | owner stringlengths 2 34 | repo_id int64 1.49M 755M | is_fork bool 2 classes | languages_distribution stringlengths 16 1.68k ⌀ | content stringlengths 446 72k | issues float64 0 1.84k | main_language stringclasses 37 values | forks int64 0 5.77k | stars int64 0 46.8k | commit_sha stringlengths 40 40 | size int64 446 72.6k | name stringlengths 2 64 | license stringclasses 15 values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/main/kotlin/math/Vec4.kt | spookyGh0st | 197,557,690 | false | null | package math
import kotlin.math.sqrt
data class Vec4(var x: Double = 0.0, var y: Double = 0.0, var z: Double = 0.0,var w: Double = 0.0){
constructor(x: Number, y: Number, z: Number, t: Number): this(x.toDouble(), y.toDouble(), z.toDouble(), t.toDouble())
val length
get() = sqrt(x * x + y * y + z * z + w * w)
/**
* Normalise the vector to length 1
*/
fun normalize(){
val l = 1.0/ sqrt(x * x + y * y + z * z + w*w)
x*=l; y*= l; z*=l; w*= l
}
fun toVec2(): Vec2 {
return Vec2(x,y)
}
fun toVec3(): Vec3 {
return Vec3(x,y,z)
}
operator fun plus(vec4: Vec4): Vec4 {
return Vec4(x + vec4.x, y + vec4.y, z + vec4.z, w + vec4.w)
}
operator fun minus(vec4: Vec4): Vec4 {
return Vec4(x - vec4.x, y - vec4.y, z - vec4.z, w -vec4.w)
}
operator fun times(fac: Double): Vec4 {
return Vec4(x * fac, y * fac, z * fac, w*fac)
}
operator fun times(fac: Int): Vec4 {
return Vec4(x * fac, y * fac, z * fac, w*fac)
}
operator fun div(fact: Double): Vec4 {
val xfact = 1.0/ fact
return Vec4(x * xfact, y * xfact, z * xfact, w*fact)
}
operator fun div(fact: Int): Vec4 {
val xfact = 1.0/ fact
return Vec4(x * xfact, y * xfact, z * xfact, w*fact)
}
operator fun get(index: Int) = when(index){
0 -> x; 1 -> y; 2 -> z; 3 -> w
else -> throw IndexOutOfBoundsException()
}
operator fun set(index: Int, value: Double) = when(index){
0 -> x = value; 1 -> y = value; 2 -> z = value; 3 -> w = value
else -> throw IndexOutOfBoundsException()
}
operator fun times(mat4: Mat4): Vec4 =
Vec4(
x=x*mat4.x.x + y*mat4.y.x + z* mat4.z.x + w * mat4.w.x,
y=x*mat4.x.y + y*mat4.y.y + z* mat4.z.y + w * mat4.w.y,
z=x*mat4.x.z + y*mat4.y.z + z* mat4.z.z + w * mat4.w.z,
w=x*mat4.x.w + y*mat4.y.w + z* mat4.z.w + w * mat4.w.w,
)
fun toList(): List<Double> =
listOf(x,y,z,w)
operator fun times(vec4: Vec4): Vec4 {
return Vec4(
vec4.x * x,
vec4.y * y,
vec4.z * z,
vec4.w * w,
)
}
}
| 3 | Kotlin | 9 | 19 | 0ba55cb3d9abb3a9e57e8cef6c7eb0234c4f116a | 2,239 | beatwalls | MIT License |
app/src/y2021/day02/Day02Dive.kt | henningBunk | 432,858,990 | false | {"Kotlin": 124495} | package y2021.day02
import common.Answers
import common.AocSolution
import common.annotations.AoCPuzzle
import java.security.InvalidKeyException
fun main(args: Array<String>) {
Day02Dive().solveThem()
}
@AoCPuzzle(2021, 2)
class Day02Dive : AocSolution {
override val answers = Answers(samplePart1 = 150, samplePart2 = 900, part1 = 1670340, part2 = 1954293920)
override fun solvePart1(input: List<String>): Int = input
.map {
it
.split(" ")
.let { (direction, value) -> Pair(direction, value.toInt()) }
}
.groupBy(
keySelector = {
when (it.first) {
"forward" -> "forward"
else -> "depth"
}
},
valueTransform = {
when (it.first) {
"up" -> -it.second
else -> it.second
}
}
)
.mapValues { it.value.sum() }
.values
.fold(1) { acc, value -> acc * value }
override fun solvePart2(input: List<String>): Int = input
.map {
it
.split(" ")
.let { (direction, value) -> Command(direction, value.toInt()) }
}
.fold(Position(0, 0, 0)) { position, command ->
when (command.direction) {
"down" -> position.aim += command.amount
"up" -> position.aim -= command.amount
"forward" -> {
position.horizontal += command.amount
position.depth += command.amount * position.aim
}
else -> throw InvalidKeyException("${command.direction} is not a known command")
}
position
}
.let { it.horizontal * it.depth }
class Position(var horizontal: Int, var depth: Int, var aim: Int)
data class Command(val direction: String, val amount: Int)
} | 0 | Kotlin | 0 | 0 | 94235f97c436f434561a09272642911c5588560d | 1,972 | advent-of-code-2021 | Apache License 2.0 |
src/test/kotlin/aoc2020/OperationOrderTest.kt | komu | 113,825,414 | false | {"Kotlin": 395919} | package komu.adventofcode.aoc2020
import komu.adventofcode.utils.nonEmptyLines
import komu.adventofcode.utils.readTestInput
import komu.adventofcode.utils.sumByLong
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals
class OperationOrderTest {
@Test
fun `example 1`() {
assertEquals(71, operationOrder1("1 + 2 * 3 + 4 * 5 + 6"))
assertEquals(51, operationOrder1("1 + (2 * 3) + (4 * (5 + 6))"))
assertEquals(26, operationOrder1("2 * 3 + (4 * 5)"))
assertEquals(437, operationOrder1("5 + (8 * 3 + 9 + 3 * 4 * 3)"))
assertEquals(12240, operationOrder1("5 * 9 * (7 * 3 * 3 + 9 * 3 + (8 + 6 * 4))"))
assertEquals(13632, operationOrder1("((2 + 4 * 9) * (6 + 9 * 8 + 6) + 6) + 2 + 4 * 2"))
}
@Test
fun `example 2`() {
assertEquals(231, operationOrder2("1 + 2 * 3 + 4 * 5 + 6"))
assertEquals(51, operationOrder2("1 + (2 * 3) + (4 * (5 + 6))"))
assertEquals(46, operationOrder2("2 * 3 + (4 * 5)"))
assertEquals(1445, operationOrder2("5 + (8 * 3 + 9 + 3 * 4 * 3)"))
assertEquals(669060, operationOrder2("5 * 9 * (7 * 3 * 3 + 9 * 3 + (8 + 6 * 4))"))
assertEquals(23340, operationOrder2("((2 + 4 * 9) * (6 + 9 * 8 + 6) + 6) + 2 + 4 * 2"))
}
@Test
fun `part 1`() {
assertEquals(98621258158412, readTestInput("/2020/OperationOrder.txt").nonEmptyLines().sumByLong { operationOrder1(it) })
}
@Test
fun `part 2`() {
assertEquals(241216538527890, readTestInput("/2020/OperationOrder.txt").nonEmptyLines().sumByLong { operationOrder2(it) })
}
}
| 0 | Kotlin | 0 | 0 | 8e135f80d65d15dbbee5d2749cccbe098a1bc5d8 | 1,606 | advent-of-code | MIT License |
src/Day02.kt | Daan-Gunnink | 572,614,830 | false | {"Kotlin": 8595} | class Day02 : AdventOfCode(15, 12) {
private fun calculateScoreFromMap(input: List<String>, map: Map<String, Int>): Int {
var totalScore = 0
input.forEach {
totalScore += map[it] ?: 0
}
return totalScore
}
override fun part1(input: List<String>): Int {
return calculateScoreFromMap(
input,
mapOf(
Pair("A X", 4),
Pair("A Y", 8),
Pair("A Z", 3),
Pair("B X", 1),
Pair("B Y", 5),
Pair("B Z", 9),
Pair("C X", 7),
Pair("C Y", 2),
Pair("C Z", 6),
)
)
}
override fun part2(input: List<String>): Int {
return calculateScoreFromMap(
input,
mapOf(
Pair("A X", 3),
Pair("A Y", 4),
Pair("A Z", 8),
Pair("B X", 1),
Pair("B Y", 5),
Pair("B Z", 9),
Pair("C X", 2),
Pair("C Y", 6),
Pair("C Z", 7),
))
}
}
| 0 | Kotlin | 0 | 0 | 15a89224f332faaed34fc2d000c00fbefe1a3c08 | 1,305 | advent-of-code-2022 | Apache License 2.0 |
bench/algorithm/merkletrees/1.kt | turururu | 509,064,681 | true | {"C#": 227864, "Rust": 189855, "Common Lisp": 142537, "Java": 56110, "C": 54246, "Go": 49634, "Python": 44672, "Zig": 43293, "Kotlin": 42632, "OCaml": 36915, "Julia": 35976, "TypeScript": 35314, "Dart": 35048, "Chapel": 33907, "Crystal": 33602, "C++": 33006, "Nim": 28654, "JavaScript": 26793, "Vue": 24821, "Haxe": 23695, "D": 22887, "V": 22090, "Swift": 20955, "Racket": 20474, "Fortran": 19285, "Ruby": 18347, "Lua": 8189, "Pony": 7246, "Elixir": 6620, "Shell": 6240, "Perl": 5588, "Hack": 4541, "Raku": 4441, "PHP": 3343, "Haskell": 2823, "SCSS": 503, "HTML": 53} | import kotlin.math.*
const val MinDepth = 4
fun main(args: Array<String>) {
val maxDepth = if (args.size > 0) max(args[0].toInt(), MinDepth + 2) else 10
val stretchDepth = maxDepth + 1
val stretchTree = Node.create(stretchDepth)
stretchTree.calHash()
println(
"stretch tree of depth ${stretchDepth}\t root hash: ${stretchTree.getHash()} check: ${stretchTree.check()}"
)
val longLivedTree = Node.create(maxDepth)
val nResults = (maxDepth - MinDepth) / 2 + 1
for (i in 0..nResults - 1) {
val depth = i * 2 + MinDepth
val n = 1.shl(maxDepth - depth + MinDepth)
var sum = 0L
for (j in 1..n) {
val tree = Node.create(depth)
tree.calHash()
sum += tree.getHash()
}
println("${n}\t trees of depth ${depth}\t root hash sum: ${sum}")
}
longLivedTree.calHash()
println(
"long lived tree of depth ${maxDepth}\t root hash: ${longLivedTree.getHash()} check: ${longLivedTree.check()}"
)
}
class Node(val value: Long?, val left: Node?, val right: Node?) {
var hash: Long? = null
fun check(): Boolean {
if (hash != null) {
if (value != null) {
return true
}
if (left != null && right != null) {
return left.check() && right.check()
}
return false
} else {
return false
}
}
fun calHash() {
if (hash == null) {
if (value != null) {
hash = value
} else if (left != null && right != null) {
left.calHash()
right.calHash()
hash = left.getHash() + right.getHash()
}
}
}
fun getHash(): Long {
if (hash != null) {
return hash!!
} else {
return -1
}
}
companion object {
fun create(n: Int): Node {
if (n == 0) {
return Node(1, null, null)
}
val d = n - 1
return Node(null, Node.create(d), Node.create(d))
}
}
}
| 0 | C# | 0 | 0 | f72b031708c92f9814b8427b0dd08cb058aa6234 | 2,166 | Programming-Language-Benchmarks | MIT License |
Rationals_Board/Rationals/Task/src/rationals/Racional.kt | EdmundoSanchezM | 354,481,310 | false | null | package rationals
import java.lang.IllegalArgumentException
import java.math.BigInteger
import java.util.*
class Rational(numerator: BigInteger, denominator: BigInteger) : Comparable<Rational> {
companion object {
val ZERO = Rational(BigInteger.ZERO, BigInteger.ONE)
}
private val numerator: BigInteger
private val denominator: BigInteger
constructor(numerator: Int) : this(numerator.toBigInteger(), BigInteger.ONE)
constructor(numerator: Long) : this(numerator.toBigInteger(), BigInteger.ONE)
constructor(numerator: BigInteger) : this(numerator, BigInteger.ONE)
init {
if (denominator == BigInteger.ZERO) {
throw IllegalArgumentException()
}
val (num, den) = normalize(numerator, denominator)
this.numerator = num
this.denominator = den
}
private fun normalize(numerator: BigInteger, denominator: BigInteger): Pair<BigInteger, BigInteger> {
val gcd = numerator.gcd(denominator)
val sign = denominator.signum().toBigInteger()
var num = numerator / (gcd * sign)
var den = denominator / (gcd * sign)
return Pair(num, den)
}
private fun lcm(numerator: BigInteger, denominator: BigInteger): BigInteger {
val num = numerator.abs()
val den = denominator.abs()
return num * (den / num.gcd(den))
}
operator fun unaryMinus() : Rational = Rational(-numerator, denominator)
private fun negate() : Rational = unaryMinus()
operator fun minus(rational: Rational) : Rational {
return this.plus(rational.negate())
}
operator fun plus(rational: Rational) : Rational {
if (this == ZERO) return rational
if (rational == ZERO) return this
val f = this.numerator.gcd(rational.numerator)
val g = this.denominator.gcd(rational.denominator)
val num = f * ((this.numerator / f) * (rational.denominator / g) + (rational.numerator / f) * (this.denominator / g))
val den = lcm(this.denominator, rational.denominator)
return Rational(num, den)
}
operator fun times(rational: Rational) : Rational {
val c = Rational(this.numerator, rational.denominator)
val d = Rational(rational.numerator, this.denominator)
return Rational(c.numerator * d.numerator, c.denominator * d.denominator)
}
operator fun div (rational: Rational) : Rational {
return this.times(rational.reciprocal())
}
private fun reciprocal() : Rational {
return Rational(denominator, numerator)
}
override fun toString(): String {
return if (denominator == BigInteger.ONE) "$numerator" else "$numerator/$denominator"
}
override fun hashCode(): Int {
return Objects.hash(numerator, denominator)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || javaClass != other.javaClass) return false
return compareTo(other as Rational) == 0
}
override fun compareTo(other: Rational): Int {
val lhs = this.numerator * other.denominator
val rhs = this.denominator * other.numerator
return lhs.compareTo(rhs)
}
}
infix fun Int.divBy(denominator: Int) : Rational = Rational(this) / Rational(denominator)
infix fun Long.divBy(denominator: Long) : Rational = Rational(this) / Rational(denominator)
infix fun BigInteger.divBy(denominator: BigInteger) : Rational = Rational(this) / Rational(denominator)
fun String.toRational() : Rational {
val args = this.split("/");
return if (args.size == 1) {
Rational(args[0].toBigInteger())
} else {
Rational(args[0].toBigInteger(), args[1].toBigInteger())
}
} | 0 | Kotlin | 0 | 0 | a671a9b35eeae1f56ee1ad448347d9df5e583c9d | 3,749 | Kotlin-for-Java-Developers | MIT License |
core/matchers/src/main/kotlin/au/com/dius/pact/core/matchers/RequestMatching.kt | zmot | 336,870,141 | true | {"Groovy": 937121, "Kotlin": 725937, "Java": 707835, "Scala": 96345, "Clojure": 7519, "ANTLR": 7005, "Dockerfile": 582} | package au.com.dius.pact.core.matchers
import au.com.dius.pact.core.model.Interaction
import au.com.dius.pact.core.model.Request
import au.com.dius.pact.core.model.RequestResponseInteraction
import au.com.dius.pact.core.model.Response
import mu.KLogging
sealed class RequestMatch {
private val score: Int
get() {
return when (this) {
is FullRequestMatch -> this.calculateScore()
is PartialRequestMatch -> this.calculateScore()
else -> 0
}
}
/**
* Take the first total match, or merge partial matches, or take the best available.
*/
fun merge(other: RequestMatch): RequestMatch = when {
this is FullRequestMatch && other is FullRequestMatch -> if (this.score >= other.score) this
else other
this is FullRequestMatch -> this
other is FullRequestMatch -> other
this is PartialRequestMatch && other is PartialRequestMatch -> if (this.score >= other.score) this
else other
this is PartialRequestMatch -> this
else -> other
}
}
data class FullRequestMatch(val interaction: Interaction, val result: RequestMatchResult) : RequestMatch() {
fun calculateScore() = result.calculateScore()
}
data class PartialRequestMatch(val problems: Map<Interaction, RequestMatchResult>) : RequestMatch() {
fun description(): String {
var s = ""
for (problem in problems) {
s += problem.key.description + ":\n"
for (mismatch in problem.value.mismatches) {
s += " " + mismatch.description() + "\n"
}
}
return s
}
fun calculateScore() = problems.values.map { it.calculateScore() }.max() ?: 0
}
object RequestMismatch : RequestMatch()
class RequestMatching(private val expectedInteractions: List<RequestResponseInteraction>) {
fun matchInteraction(actual: Request): RequestMatch {
val matches = expectedInteractions.map { compareRequest(it, actual) }
return if (matches.isEmpty())
RequestMismatch
else
matches.reduce { acc, match -> acc.merge(match) }
}
fun findResponse(actual: Request): Response? {
val match = matchInteraction(actual)
return when (match) {
is FullRequestMatch -> (match.interaction as RequestResponseInteraction).response
else -> null
}
}
companion object : KLogging() {
var allowUnexpectedKeys = false
private fun decideRequestMatch(expected: RequestResponseInteraction, result: RequestMatchResult) =
when {
result.matchedOk() -> FullRequestMatch(expected, result)
result.matchedMethodAndPath() -> PartialRequestMatch(mapOf(expected to result))
else -> RequestMismatch
}
fun compareRequest(expected: RequestResponseInteraction, actual: Request): RequestMatch {
val mismatches = requestMismatches(expected.request, actual)
logger.debug { "Request mismatch: $mismatches" }
return decideRequestMatch(expected, mismatches)
}
@JvmStatic
fun requestMismatches(expected: Request, actual: Request): RequestMatchResult {
logger.debug { "comparing to expected request: \n$expected" }
return RequestMatchResult(Matching.matchMethod(expected.method, actual.method),
Matching.matchPath(expected, actual),
Matching.matchQuery(expected, actual),
Matching.matchCookie(expected.cookie(), actual.cookie()),
Matching.matchRequestHeaders(expected, actual),
Matching.matchBody(expected, actual, allowUnexpectedKeys))
}
}
}
| 0 | Groovy | 0 | 0 | e5c867ad52d4bc6965f01ce6f1f6d3af06400283 | 3,484 | pact-jvm | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/CombinationIterator.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2020 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import java.util.Stack
interface CombinationIterator {
fun next(): String
fun hasNext(): Boolean
}
class CombinationIteratorImpl(characters: String, combinationLength: Int) : CombinationIterator {
private val st = Stack<Char>()
private val ch2Idx = hashMapOf<Char, Int>()
private var result = ""
private val str = characters
private val combLength = combinationLength
init {
createCombination(characters, combinationLength)
}
override fun next(): String {
val currResult = result
var idx = str.length - 1
while (st.isNotEmpty() && ch2Idx[st.peek()] == idx) {
st.pop()
idx--
result = result.substring(0, result.length - 1)
}
if (st.isEmpty()) return currResult
idx = ch2Idx[st.pop()] ?: 0
result = result.substring(0, result.length - 1)
while (st.size != combLength) {
val temp = str[++idx]
result += temp
st.push(temp)
}
return currResult
}
override fun hasNext(): Boolean = st.isNotEmpty()
private fun createCombination(characters: String, combinationLength: Int) {
for (ch in characters) {
st.push(ch)
result += ch
if (st.size == combinationLength) break
}
var idx = 0
for (ch in characters) {
ch2Idx[ch] = idx++
}
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,075 | kotlab | Apache License 2.0 |
src/main/kotlin/com/colinodell/advent2016/Day24.kt | colinodell | 495,627,767 | false | {"Kotlin": 80872} | package com.colinodell.advent2016
class Day24(input: List<String>) {
private val layout = input.toGrid()
private val requiredLocations = layout.filter { it.value.isDigit() }.keys
private val start = layout.filter { it.value == '0' }.keys.first()
fun solvePart1() = solve { state: State -> state.seen.containsAll(requiredLocations) }
fun solvePart2() = solve { state: State -> state.seen.containsAll(requiredLocations) && state.pos == start }
private fun solve(reachedGoal: (State) -> Boolean) =
AStar(State(start, setOf(start)), reachedGoal, { state: State -> state.generateNextMoves(layout) }).distance
private data class State(val pos: Vector2, val seen: Set<Vector2> = emptySet()) {
fun generateNextMoves(layout: Grid<Char>) =
pos.neighbors().associateWith { layout[it] }.filter { it.value != '#' && it.value != null }.map {
if (it.value?.isDigit() == true) {
State(it.key, seen.plus(it.key))
} else {
State(it.key, seen)
}
}.asSequence()
}
}
| 0 | Kotlin | 0 | 0 | 8a387ddc60025a74ace8d4bc874310f4fbee1b65 | 1,110 | advent-2016 | Apache License 2.0 |
2023/18/Solution.kt | AdrianMiozga | 588,519,359 | false | {"Kotlin": 110785, "Python": 11275, "Assembly": 3369, "C": 2378, "Pawn": 1390, "Dart": 732} | import java.io.File
import java.util.*
private const val FILENAME = "2023/18/input.txt"
private const val GROUND = '.'
private const val TRENCH = '#'
private data class Position(var x: Int, var y: Int)
fun main() {
partOne()
}
private fun partOne() {
val file = File(FILENAME).readLines()
val array: MutableList<MutableList<Char>> =
mutableListOf(mutableListOf(GROUND))
val position = Position(0, 0)
for (line in file) {
val (direction, length) = Regex("""(\w) (\d+) \(#\w+\)""").matchEntire(
line
)!!.destructured
for (i in 0 until length.toInt()) {
when (direction) {
"R" -> position.x++
"L" -> position.x--
"U" -> position.y--
"D" -> position.y++
}
// Grow right
if (position.x >= array[0].size) {
for (row in array) {
row.addLast(GROUND)
}
}
// Grow left
if (position.x < 0) {
for (row in array) {
row.addFirst(GROUND)
}
position.x = 0
}
// Grow down
if (position.y >= array.size) {
array.addLast(MutableList(array[0].size) { GROUND })
}
// Grow up
if (position.y < 0) {
array.addFirst(MutableList(array[0].size) { GROUND })
position.y = 0
}
array[position.y][position.x] = TRENCH
}
}
// floodFill(array, Pair(1, 1))
floodFill(array, Pair(151, 1))
val count = array.sumOf { it.count { char -> char == TRENCH } }
println(count)
}
private fun floodFill(
array: MutableList<MutableList<Char>>, initialPosition: Pair<Int, Int>
) {
val stack = Stack<Pair<Int, Int>>()
stack.push(Pair(initialPosition.first, initialPosition.second))
while (stack.isNotEmpty()) {
val current = stack.pop()
val x = current.first
val y = current.second
if (x < 0 || y < 0) {
continue
}
if (y >= array.size || x >= array[0].size) {
continue
}
if (array[y][x] == TRENCH) {
continue
}
array[y][x] = TRENCH
stack.push(Pair(x + 1, y))
stack.push(Pair(x - 1, y))
stack.push(Pair(x, y + 1))
stack.push(Pair(x, y - 1))
}
}
| 0 | Kotlin | 0 | 0 | c9cba875089d8d4fb145932c45c2d487ccc7e8e5 | 2,486 | Advent-of-Code | MIT License |
src/year2021/day06/Day06.kt | fadi426 | 433,496,346 | false | {"Kotlin": 44622} | package year2021.day01.day06
import util.assertTrue
import util.read2021DayInput
fun main() {
fun calcLanternFishDensity(input: List<Int>, days: Int): Long {
var fishDensityList = (0..9).map { n -> input.count { n == it } }.map { it.toLong() }
for (i in 1..days) {
fishDensityList = mutableListOf(
fishDensityList[1],
fishDensityList[2],
fishDensityList[3],
fishDensityList[4],
fishDensityList[5],
fishDensityList[6],
fishDensityList[7] + fishDensityList[0],
fishDensityList[8],
fishDensityList[0]
)
}
return fishDensityList.sum()
}
val input = read2021DayInput("Day06.txt").first().split(",").map { it.toInt() }
fun task01() = calcLanternFishDensity(input, 80)
fun task02() = calcLanternFishDensity(input, 256)
assertTrue(task01().toInt() == 360761)
assertTrue(task02() == 1632779838045)
}
| 0 | Kotlin | 0 | 0 | acf8b6db03edd5ff72ee8cbde0372113824833b6 | 1,024 | advent-of-code-kotlin-template | Apache License 2.0 |
src/main/java/hes/nonogram/Puzzle.kt | Hes-Siemelink | 689,215,071 | false | {"Kotlin": 32733} | package hes.nonogram
/**
* Nonogram puzzle state.
*
* Cells are mutable; hints are read-only.
*/
data class Puzzle(
private val rowHints: List<Hints>,
private val columnHints: List<Hints>,
private val cells: List<Cell> = mutableListOf()
) {
private val width: Int = columnHints.size
private val height: Int = rowHints.size
val rows: List<Line>
val columns: List<Line>
init {
// Initialize with empty cells if we are not copying
if (cells.isEmpty() && cells is MutableList) {
for (i in 1..width * height) {
cells.add(Cell())
}
}
rows = rowHints.mapIndexed { index, hints -> Line(row(index), hints) }
columns = columnHints.mapIndexed { index, hints -> Line(column(index), hints) }
}
private fun row(index: Int): List<Cell> {
return cells.subList(index * width, (index + 1) * width)
}
private fun column(index: Int): List<Cell> {
val cellColumn = mutableListOf<Cell>()
for (row in 0 until height) {
cellColumn.add(cells[width * row + index])
}
return cellColumn
}
fun cell(row: Int, column: Int): Cell {
return rows[row].cells[column]
}
fun isSolved(): Boolean = rows.all { it.isSolved() } && columns.all { it.isSolved() }
fun copy(): Puzzle {
val cellsCopy = cells.map { it.copy() }
return Puzzle(rowHints, columnHints, cellsCopy)
}
override fun toString(): String {
return buildString {
columns.forEach {
append(it.hints)
append(" ")
}
append("\n")
rows.forEach {
for (char in it.toString().toCharArray()) {
append(char)
append(' ')
}
append(" ")
append(it.hints)
append('\n')
}
}
}
fun print() {
rows.forEach {
println(it.cells.asString().replace(".", " ").replace("-", "· ").replace("*", "██"))
}
}
}
typealias Hints = List<Int>
typealias LineState = List<State>
class PuzzleSpec(
val rowHints: MutableList<Hints> = mutableListOf(),
val columnHints: MutableList<Hints> = mutableListOf()
) {
fun row(vararg hints: Int) {
rowHints.add(hints.asList())
}
fun column(vararg hints: Int) {
columnHints.add(hints.asList())
}
fun toPuzzle(rowHints: List<Hints>, columnHints: List<Hints>): Puzzle {
return Puzzle(rowHints, columnHints)
}
}
fun nonogram(init: PuzzleSpec.() -> Unit): Puzzle {
val spec = PuzzleSpec()
spec.init()
return spec.toPuzzle(spec.rowHints, spec.columnHints)
}
fun interface PuzzleSolver {
fun solve(puzzle: Puzzle): Puzzle?
}
| 0 | Kotlin | 0 | 0 | 7b96e50eb2973e4e2a906cf20af743909f0ebc8d | 2,842 | Nonogram | MIT License |
src/Day01.kt | chrisjwirth | 573,098,264 | false | {"Kotlin": 28380} | fun main() {
fun part1(input: List<String>): Int {
var maxWeight = 0
var currentWeight = 0
input.forEach {
if (it.isNotBlank()) {
currentWeight += it.toInt()
} else {
maxWeight = maxOf(maxWeight, currentWeight)
currentWeight = 0
}
}
return maxOf(maxWeight, currentWeight)
}
fun part2(input: List<String>): Int {
val allWeights = mutableListOf<Int>()
var currentWeight = 0
input.forEach {
if (it.isNotBlank()) {
currentWeight += it.toInt()
} else {
allWeights.add(currentWeight)
currentWeight = 0
}
}
if (currentWeight != 0) allWeights.add(currentWeight)
return allWeights.sortedDescending().subList(0, 3).sum()
}
// Test
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
// Final
val input = readInput("Day01")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | d8b1f2a0d0f579dd23fa1dc1f7b156f728152c2d | 1,123 | AdventOfCode2022 | Apache License 2.0 |
src/main/kotlin/day10/Day10.kt | daniilsjb | 572,664,294 | false | {"Kotlin": 69004} | package day10
import java.io.File
fun main() {
val data = parse("src/main/kotlin/day10/Day10.txt")
val answer1 = part1(data)
val answer2 = part2(data)
println("🎄 Day 10 🎄")
println()
println("[Part 1]")
println("Answer: $answer1")
println()
println("[Part 2]")
println("Answer:\n$answer2")
}
@Suppress("SameParameterValue")
private fun parse(path: String): List<String> =
File(path).readLines()
private fun List<String>.execute(onCycle: (x: Int, cycle: Int) -> Unit) {
var x = 1
var cycle = 0
for (instruction in this) {
val tokens = instruction.split(" ")
when (tokens[0]) {
"noop" -> onCycle(x, ++cycle)
"addx" -> {
onCycle(x, ++cycle)
onCycle(x, ++cycle)
x += tokens[1].toInt()
}
}
}
}
private fun part1(program: List<String>): Int {
var result = 0
program.execute { x, cycle ->
if ((cycle - 20) % 40 == 0) {
result += x * cycle;
}
}
return result
}
private fun part2(program: List<String>): String {
val (w, h) = 40 to 6
val crt = Array(h) { Array(w) { '.' } }
program.execute { x, cycle ->
val col = (cycle - 1) % w
if (x - 1 <= col && col <= x + 1) {
val row = (cycle - 1) / w
crt[row][col] = '#'
}
}
return crt.asIterable()
.joinToString(separator = "\n") { line ->
line.joinToString(separator = "")
}
}
| 0 | Kotlin | 0 | 0 | 6f0d373bdbbcf6536608464a17a34363ea343036 | 1,539 | advent-of-code-2022 | MIT License |
src/leetcodeProblem/leetcode/editor/en/RemoveLinkedListElements.kt | faniabdullah | 382,893,751 | false | null | //Given the head of a linked list and an integer val, remove all the nodes of
//the linked list that has Node.val == val, and return the new head.
//
//
// Example 1:
//
//
//Input: head = [1,2,6,3,4,5,6], val = 6
//Output: [1,2,3,4,5]
//
//
// Example 2:
//
//
//Input: head = [], val = 1
//Output: []
//
//
// Example 3:
//
//
//Input: head = [7,7,7,7], val = 7
//Output: []
//
//
//
// Constraints:
//
//
// The number of nodes in the list is in the range [0, 10⁴].
// 1 <= Node.val <= 50
// 0 <= val <= 50
//
// Related Topics Linked List Recursion 👍 3859 👎 140
package leetcodeProblem.leetcode.editor.en
class RemoveLinkedListElements {
fun solution() {
}
//below code will be used for submission to leetcode (using plugin of course)
//leetcode submit region begin(Prohibit modification and deletion)
/**
* Example:
* var li = ListNode(5)
* var v = li.`val`
* Definition for singly-linked list.
* class ListNode(var `val`: Int) {
* var next: ListNode? = null
* }
*/
class Solution {
fun removeElements(head: ListNode?, `val`: Int): ListNode? {
var current = head
var result = head
var next = ListNode(0)
next.next = result
while (current != null) {
if (current.`val` == 6) {
result?.next = result?.next?.next
}
result = result?.next
current = current.next
}
return next.next
}
}
class ListNode(var `val`: Int) {
var next: ListNode? = null
}
//leetcode submit region end(Prohibit modification and deletion)
}
fun main() {}
| 0 | Kotlin | 0 | 6 | ecf14fe132824e944818fda1123f1c7796c30532 | 1,736 | dsa-kotlin | MIT License |
src/Day03.kt | BerkkanB | 573,764,177 | false | {"Kotlin": 1868} | fun main(){
val testInput = readTestInput("Day03_test")
val actualInput = readInput("Day03")
val score = calculateScore(testInput)
println("The score of given rucksacks is: $score")
}
fun calculateScore(list: List<String>): Int {
var sum = 0
list.forEach {
sum += it.pointOfSameItem()
}
return sum
}
fun String.pointOfSameItem(): Int {
val length = this.length
for (i in 0 until length/2){
for (j in length/2 until length){
if (this[i] == this[j]){
return this[i].findItemPoint()
}
}
}
return 0
}
fun Char.findItemPoint(): Int {
return if (this in 'a'..'z') this.code.minus(96)
else this.code.minus(38)
}
| 0 | Kotlin | 0 | 1 | b7a2d163f19545b668df2731b720759089f191bf | 729 | adventOfCode | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MaxWidthOfVerticalArea.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import kotlin.math.max
/**
* 1637. Widest Vertical Area Between Two Points Containing No Points
* @see <a href="https://leetcode.com/problems/widest-vertical-area-between-two-points-containing-no-points">Source</a>
*/
fun interface MaxWidthOfVerticalArea {
operator fun invoke(points: Array<IntArray>): Int
}
class MaxWidthOfVerticalAreaSort : MaxWidthOfVerticalArea {
override fun invoke(points: Array<IntArray>): Int {
points.sortWith(compareBy { it[0] })
var ans = 0
for (i in 1 until points.size) {
ans = max(ans, points[i][0] - points[i - 1][0])
}
return ans
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,281 | kotlab | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/RecoverFromPreorder.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import dev.shtanko.algorithms.DECIMAL
import java.util.Stack
/**
* 1028. Recover a Tree From Preorder Traversal
* @see <a href="https://leetcode.com/problems/recover-a-tree-from-preorder-traversal/">Source</a>
*/
fun interface RecoverFromPreorder {
operator fun invoke(traversal: String): TreeNode?
}
class RecoverFromPreorderIterative : RecoverFromPreorder {
override operator fun invoke(traversal: String): TreeNode? {
var level: Int
var value: Int
val stack: Stack<TreeNode> = Stack()
var i = 0
while (i < traversal.length) {
level = 0
while (traversal[i] == '-') {
level++
i++
}
value = 0
while (i < traversal.length && traversal[i] != '-') {
value = value * DECIMAL + (traversal[i] - '0')
i++
}
while (stack.size > level) {
stack.pop()
}
val node = TreeNode(value)
if (stack.isNotEmpty()) {
if (stack.peek().left == null) {
stack.peek().left = node
} else {
stack.peek().right = node
}
}
stack.add(node)
}
while (stack.size > 1) {
stack.pop()
}
return stack.pop()
}
}
class RecoverFromPreorderRecursive : RecoverFromPreorder {
var i = 0
override operator fun invoke(traversal: String): TreeNode? {
return helper(traversal, -1)
}
private fun helper(s: String, pLevel: Int): TreeNode? {
if (i >= s.length) {
return null
}
var count = 0
var j: Int = i
while (!Character.isDigit(s[j])) {
j++
count++
}
return if (count == pLevel + 1) {
val start = j
while (j < s.length && Character.isDigit(s[j])) {
j++
}
val value = s.substring(start, j).toInt()
i = j
val node = TreeNode(value)
node.left = helper(s, count)
node.right = helper(s, count)
node
} else {
null
}
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,897 | kotlab | Apache License 2.0 |
src/Day02.kt | JaydenPease | 574,590,496 | false | {"Kotlin": 11645} | fun main() {
// fun part1(input: List<String>): Int {
// return input.size
// }
//
// fun part2(input: List<String>): Int {
// return input.size
// }
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
//println(Day02_part1(testInput))
//println(Day02_part2(testInput))
val input = readInput("Day02")
//println(Day02_part1(input))
println(Day02_part2(input))
}
fun Day02_part1(input : List<String>) : Int {
var totalScore:Int = 0
var currentRoundScore: Int = 0
var opponentHand: Int = 0
var myHand: Int = 0
for(i in input.indices) {
when {
input[i].indexOf("A") > -1 -> opponentHand = 1
input[i].indexOf("B") > -1 -> opponentHand = 2
input[i].indexOf("C") > -1 -> opponentHand = 3
}
when {
input[i].indexOf("X") > -1 -> myHand = 1
input[i].indexOf("Y") > -1 -> myHand = 2
input[i].indexOf("Z") > -1 -> myHand = 3
}
if(opponentHand == myHand) {
currentRoundScore = myHand + 3
}
else if(myHand - opponentHand == 1 || myHand - opponentHand == -2) {
currentRoundScore = myHand + 6
}
else if(myHand - opponentHand == -1 || myHand - opponentHand == 2) {
currentRoundScore = myHand + 0
}
totalScore += currentRoundScore
currentRoundScore = 0
}
return totalScore
}
fun Day02_part2(input : List<String>) : Int {
var totalScore:Int = 0
var currentRoundScore: Int = 0
var opponentHand: Int = 0
var myHand: Int = 0
for(i in input.indices) {
when {
input[i].indexOf("A") > -1 -> opponentHand = 1
input[i].indexOf("B") > -1 -> opponentHand = 2
input[i].indexOf("C") > -1 -> opponentHand = 3
}
when {
input[i].indexOf("X") > -1 -> {
myHand = opponentHand - 1
}
input[i].indexOf("Y") > -1 -> {
myHand = opponentHand
currentRoundScore += 3
}
input[i].indexOf("Z") > -1 -> {
myHand = opponentHand + 1
currentRoundScore += 6
}
}
when {
myHand == 0 -> myHand = 3
myHand == 4 -> myHand = 1
}
totalScore += currentRoundScore + myHand
currentRoundScore = 0
}
return totalScore
} | 0 | Kotlin | 0 | 0 | 0a5fa22b3653c4b44a716927e2293fc4b2ed9eb7 | 2,654 | AdventOfCode-2022 | Apache License 2.0 |
app/src/main/kotlin/day02/Day02.kt | meli-w | 433,710,859 | false | {"Kotlin": 52501} | package day02
import common.InputRepo
import common.readSessionCookie
import common.solve
import java.lang.IllegalStateException
fun main(args: Array<String>) {
val day = 2
val input = InputRepo(args.readSessionCookie()).get(day = day)
solve(day, input, ::solveDay02Part1, ::solveDay02Part2)
}
fun solveDay02Part1(input: List<String>): Int {
val pair: List<Pair<String, Int>> = convertInputData(input)
var horizontal = 0
var depth = 0
pair.forEach { (direction, i) ->
when(direction){
"forward" -> horizontal += i
"down" -> depth += i
"up" -> depth -= i
else -> throw IllegalStateException("Unknown direction")
}
}
return horizontal * depth
}
fun solveDay02Part2(input: List<String>): Int {
val pair: List<Pair<String, Int>> = convertInputData(input)
var horizontal = 0
var depth = 0
var aim = 0
pair.forEach { (direction, i) ->
when(direction){
"forward" -> {
horizontal += i
depth += aim * i
}
"down" -> aim += i
"up" -> aim -= i
else -> throw IllegalStateException("Unknown direction")
}
}
return horizontal * depth
}
private fun convertInputData(input: List<String>) = input.map {
it
.replace("(\\w+) (\\d+)".toRegex(), "\$1 \$2")
.split(" ")
.let { i ->
Pair(i.first(), i.last().toInt())
}
}
| 0 | Kotlin | 0 | 1 | f3b96c831d6c8e21de1ac866cf9c64aaae2e5ea1 | 1,495 | AoC-2021 | Apache License 2.0 |
src/year2022/day17/Day17.kt | kingdongus | 573,014,376 | false | {"Kotlin": 100767} | package year2022.day17
import Point2D
import readInputFileByYearAndDay
import readTestFileByYearAndDay
val shapes = mapOf(
0 to setOf(Point2D(0, 0), Point2D(1, 0), Point2D(2, 0), Point2D(3, 0)), // plank
1 to setOf(Point2D(1, 0), Point2D(0, 1), Point2D(1, 1), Point2D(2, 1), Point2D(1, 2)), // cross
2 to setOf(Point2D(0, 0), Point2D(1, 0), Point2D(2, 0), Point2D(2, 1), Point2D(2, 2)), // inverse L
3 to setOf(Point2D(0, 0), Point2D(0, 1), Point2D(0, 2), Point2D(0, 3)), // stick
4 to setOf(Point2D(0, 0), Point2D(0, 1), Point2D(1, 0), Point2D(1, 1)) // block
)
infix fun Set<*>.containsAny(other: Set<*>): Boolean = other.any { this.contains(it) }
// 2 from left, "3 free rows" from top
val spawnOffset = Point2D(2, 4)
fun spawnRock(id: Int, top: Int): Set<Point2D> =
shapes[id]!!.map { it + spawnOffset }.map { it + Point2D(0, top) }.toSet()
fun moveLeft(points: Set<Point2D>): Set<Point2D> =
if (points.any { it.x == 0 }) points // on left edge
else points.map { Point2D(it.x - 1, it.y) }.toSet()
fun moveRight(points: Set<Point2D>): Set<Point2D> =
if (points.any { it.x == 6 }) points // on right edge
else points.map { Point2D(it.x + 1, it.y) }.toSet()
fun moveDown(points: Set<Point2D>): Set<Point2D> = points.map { Point2D(it.x, it.y - 1) }.toSet()
fun moveUp(points: Set<Point2D>): Set<Point2D> = points.map { Point2D(it.x, it.y + 1) }.toSet()
fun topRowsNormalized(rocks: Set<Point2D>, offset: Int): Set<Point2D> {
val maxY = rocks.maxOf { it.y }
return rocks.filter { it.y >= maxY - offset }.map { Point2D(it.x, maxY - it.y) }.toSet()
}
data class MemoryItem(val rocks: Set<Point2D>, val steamIndex: Int, val shapeIndex: Int)
fun calculateHighestColumn(input: List<String>, numRocks: Long): Long {
val steam = input.first()
val placedRocks = (0..6).map { Point2D(it, 0) }.toMutableSet() // bottom row
var top = 0
var idxSteam = 0
var idxRock = 0
var totalRocksCalculated = 0L
var addedTop = 0L
val memory = mutableMapOf<MemoryItem, Pair<Int, Int>>()
while (totalRocksCalculated < numRocks) {
var rock = spawnRock(idxRock % 5, top)
// get pushed -> fall down
var settled = false
while (!settled) {
// get pushed
when (steam[idxSteam % steam.length]) {
'>' -> {
rock = moveRight(rock)
val collided = placedRocks containsAny rock
if (collided) rock = moveLeft(rock)
}
'<' -> {
rock = moveLeft(rock)
val collided = placedRocks containsAny rock
if (collided) rock = moveRight(rock)
}
else -> throw IllegalStateException("que pasa")
}
// fall down
rock = moveDown(rock)
val collided = placedRocks containsAny rock
if (collided) {
// undo, then move to placedRocks
rock = moveUp(rock)
placedRocks.addAll(rock)
top = placedRocks.maxOf { it.y }
val memoryItem = MemoryItem(topRowsNormalized(placedRocks, 40), idxSteam % steam.length, idxRock % 5)
if (memory.containsKey(memoryItem)) {
// found cycle
val (oldIdxRock, oldTop) = memory[memoryItem]!!
val deltaTop = top - oldTop
val deltaRocks = idxRock - oldIdxRock
// this is how often we add the repeating pattern "on top"
val repetitions = (numRocks - totalRocksCalculated) / deltaTop
addedTop += repetitions * deltaTop
// skip ahead - once we find a pattern, we insert it as often as possible, then skip ahead to the end
// and calc what is missing
totalRocksCalculated += repetitions * deltaRocks
}
memory[memoryItem] = idxRock to top
settled = true
}
idxSteam += 1
}
idxRock += 1
totalRocksCalculated += 1
}
return top.toLong() + addedTop
}
fun main() {
val testInput = readTestFileByYearAndDay(2022, 17)
check(calculateHighestColumn(testInput, 2022) == 3068L)
check(calculateHighestColumn(testInput, 1_000_000_000_000) == 1514285714288L)
val input = readInputFileByYearAndDay(2022, 17)
println(calculateHighestColumn(input, 2022))
println(calculateHighestColumn(input, 1_000_000_000_000))
}
| 0 | Kotlin | 0 | 0 | aa8da2591310beb4a0d2eef81ad2417ff0341384 | 4,597 | advent-of-code-kotlin | Apache License 2.0 |
src/main/kotlin/day14/day14.kt | corneil | 572,437,852 | false | {"Kotlin": 93311, "Shell": 595} | package day14
import main.utils.measureAndPrint
import main.utils.scanInts
import utils.Coord
import utils.readFile
import utils.readLines
import utils.separator
import kotlin.math.max
import kotlin.math.min
enum class Substance(val c: Char) {
AIR('.'),
ROCK('#'),
SAND('o')
}
enum class Direction {
STOP,
NONE,
DOWN,
LEFT,
RIGHT,
ABYSS
}
object Depth {
private val depth = ThreadLocal.withInitial { 0 }
var maxDepth = 0
fun enter() {
depth.set(depth.get() + 1)
maxDepth = max(maxDepth, depth.get())
}
fun exit() {
depth.set(depth.get() - 1)
}
}
fun main() {
val test = readLines(
"""498,4 -> 498,6 -> 496,6
503,4 -> 502,4 -> 502,9 -> 494,9"""
)
val input = readFile("day14")
open class Grid(val cells: MutableMap<Coord, Substance> = mutableMapOf()) : MutableMap<Coord, Substance> by cells {
open val maxX: Int get() = cells.keys.maxOf { it.x }
open val minX: Int get() = cells.keys.minOf { it.x }
open val maxY: Int get() = cells.keys.maxOf { it.y }
open val minY: Int = 0
open fun stretch() {}
fun countSand() = cells.values.count { it == Substance.SAND }
open fun isInGrid(pos: Coord): Boolean = pos.x in minX..maxX
&& pos.y in minY..maxY
fun getSubStance(pos: Coord) = getOrDefault(pos, Substance.AIR)
fun isAir(pos: Coord) = getSubStance(pos) == Substance.AIR
fun isTarget(pos: Coord) = isInGrid(pos) && isAir(pos)
fun canDrop(pos: Coord): Pair<Coord, Direction> {
Depth.enter()
try {
if (!isInGrid(pos.left()) || !isInGrid(pos.right())) {
return Pair(pos, Direction.ABYSS)
}
if (isInGrid(pos.bottom())) {
if (isTarget(pos.bottom())) {
return canDrop(pos.bottom())
} else {
if (isTarget(pos.bottom().left())) {
return canDrop(pos.bottom().left())
} else if (isTarget(pos.bottom().right())) {
return canDrop(pos.bottom().right())
}
if (isTarget(pos)) {
return Pair(pos, Direction.DOWN)
}
}
}
return Pair(pos, Direction.STOP)
} finally {
Depth.exit()
}
}
fun print(entry: Coord?) {
val zX = maxX
val aX = minX
val zY = maxY
val aY = minY
for (y in aY..zY) {
for (x in aX..zX) {
val pos = Coord(x, y)
if (entry != null && pos == entry) {
print('+')
} else {
print(getOrDefault(pos, Substance.AIR).c)
}
}
println()
}
}
}
class InfiniteGird(cells: MutableMap<Coord, Substance>, val level: Int) : Grid(cells) {
override val maxY: Int get() = level
override fun get(key: Coord): Substance? {
if (key.y == level) {
return Substance.ROCK
}
return super.get(key)
}
override fun getOrDefault(key: Coord, defaultValue: Substance): Substance {
if (key.y == level) {
return Substance.ROCK
}
return super.getOrDefault(key, defaultValue)
}
override fun isInGrid(pos: Coord): Boolean = pos.y <= level
override fun stretch() {
val zX = (cells.keys.filter { it.y < level }.maxOfOrNull { it.x } ?: maxX) + 1
val aX = (cells.keys.filter { it.y < level }.minOfOrNull { it.x } ?: minX) - 1
for (x in aX..zX) {
val pos = Coord(x, level)
if (!containsKey(pos)) {
cells[pos] = Substance.ROCK
}
}
}
}
fun loadStructure(lines: List<String>): Grid {
val grid = mutableMapOf<Coord, Substance>()
val scans = lines.map {
it.scanInts()
.windowed(2, 2)
.map { line -> Coord(line[0], line[1]) }
}
scans.forEach { scan ->
scan.windowed(2)
.forEach { pair ->
check(pair.size == 2)
val prev = pair[0]
val curr = pair[1]
val diff = curr - prev
check((diff.x == 0 && diff.y != 0) || (diff.x != 0 && diff.y == 0)) { "Expected one 0 in $diff" }
if (diff.y == 0) {
for (x in min(curr.x, prev.x)..max(curr.x, prev.x)) {
val pos = Coord(x, curr.y)
if (!grid.containsKey(pos)) {
grid[pos] = Substance.ROCK
}
}
} else {
for (y in min(curr.y, prev.y)..max(curr.y, prev.y)) {
val pos = Coord(curr.x, y)
if (!grid.containsKey(pos)) {
grid[pos] = Substance.ROCK
}
}
}
}
}
return Grid(grid)
}
fun isStop(direction: Direction) = direction == Direction.STOP
|| direction == Direction.NONE
|| direction == Direction.ABYSS
fun dropSand(grid: Grid, entry: Coord): Pair<Coord, Boolean> {
val drop = grid.canDrop(entry)
if (drop.second == Direction.ABYSS) {
return Pair(drop.first, false)
}
return Pair(drop.first, !isStop(drop.second))
}
fun simulateSand(grid: Grid, start: Coord, print: Boolean): Int {
do {
val result = dropSand(grid, start)
if (result.second) {
grid[result.first] = Substance.SAND
}
} while (result.second)
return grid.countSand()
}
fun calcSand(input: List<String>, print: Boolean): Int {
val grid = loadStructure(input)
val entry = Coord(500, 0)
if(print) {
grid.print(entry)
}
simulateSand(grid, entry, print)
if(print) {
grid.print(entry)
}
return grid.countSand()
}
fun calcInfiniteSand(input: List<String>, print: Boolean): Int {
val grid = loadStructure(input)
val entry = Coord(500, 0)
val infiniteGrid = InfiniteGird(grid.toMutableMap(), grid.maxY + 2)
if (print) {
grid.print(entry)
}
infiniteGrid.stretch()
val sand = simulateSand(infiniteGrid, entry, print)
if (print) {
infiniteGrid.print(null)
}
return sand
}
fun part1() {
val testResult = calcSand(test, false)
println("Part 1 Test Answer = $testResult")
check(testResult == 24) { "Expected 24 not $testResult" }
val result = measureAndPrint("Test 1 Time: ") {
calcSand(input, false)
}
println("Part 1 Answer = $result")
}
fun part2() {
val testResult = calcInfiniteSand(test, false)
println("Part 2 Test Answer = $testResult")
check(testResult == 93) { "Expected 93 not $testResult" }
val result = measureAndPrint("Test 2 Time: ") {
calcInfiniteSand(input, false)
}
println("Part 2 Answer = $result")
check(result == 22499) { "Expected 22499 not $result" }
}
println("Day - 14")
part1()
part2()
}
| 0 | Kotlin | 0 | 0 | dd79aed1ecc65654cdaa9bc419d44043aee244b2 | 6,642 | aoc-2022-in-kotlin | Apache License 2.0 |
Problems/Algorithms/1268. Search Suggestions System/SearchSuggestionsSystem.kt | xuedong | 189,745,542 | false | {"Kotlin": 332182, "Java": 294218, "Python": 237866, "C++": 97190, "Rust": 82753, "Go": 37320, "JavaScript": 12030, "Ruby": 3367, "C": 3121, "C#": 3117, "Swift": 2876, "Scala": 2868, "TypeScript": 2134, "Shell": 149, "Elixir": 130, "Racket": 107, "Erlang": 96, "Dart": 65} | class Solution {
fun suggestedProducts(products: Array<String>, searchWord: String): List<List<String>> {
products.sort()
val n = products.size
var start = 0
val results: MutableList<MutableList<String>> = mutableListOf()
var prefix = StringBuilder()
for (ch in searchWord) {
prefix.append(ch)
val curr = lowerBound(products, start, prefix.toString())
val m = prefix.length
results.add(mutableListOf())
for (i in curr..minOf(curr+3, n)-1) {
if (products[i].length < m || products[i].substring(0, m) != prefix.toString()) {
break
}
results.get(results.size-1).add(products[i])
}
start = curr
}
return results
}
private fun lowerBound(products: Array<String>, start: Int, word: String): Int {
var left = start
var right = products.size
while (left < right) {
val mid = left + (right - left) / 2
if (products[mid] >= word) {
right = mid
} else {
left = mid + 1
}
}
return left
}
}
| 0 | Kotlin | 0 | 1 | 5e919965b43917eeee15e4bff12a0b6bea4fd0e7 | 1,350 | leet-code | MIT License |
src/Day11.kt | RobvanderMost-TomTom | 572,005,233 | false | {"Kotlin": 47682} | import java.math.BigInteger
import kotlin.math.floor
fun BigInteger.divisibleBy(value: Int) = this % value.toBigInteger() == BigInteger.ZERO
class Monkey(
val items: MutableList<BigInteger>,
private val operation: (old: BigInteger) -> BigInteger,
val divider: Int,
private val trueMonkey: Int,
private val falseMonkey: Int,
var itemsInspected: Long = 0,
) {
fun inspectItems() =
items
.map(operation)
.map { BigInteger.valueOf(floor(it.toDouble() / 3).toLong()) }
.map {
if (it.divisibleBy(divider)) {
ThrowTo(it, trueMonkey)
} else {
ThrowTo(it, falseMonkey)
}
}
.also {
itemsInspected += it.size
items.clear()
}
fun inspectItemsVeryWorried() =
items
.map(operation)
.map {
if (it.divisibleBy(divider)) {
ThrowTo(it, trueMonkey)
} else {
ThrowTo(it, falseMonkey)
}
}
.also {
itemsInspected += it.size
items.clear()
}
}
data class ThrowTo(
val item: BigInteger,
val monkey: Int
)
fun main() {
fun bigIntegerListOf(vararg integers: Int) =
integers.map { BigInteger.valueOf(it.toLong()) }.toMutableList()
fun Int.toBigInteger() = BigInteger.valueOf(toLong())
fun testMonkeys() =
listOf(
Monkey(bigIntegerListOf(79, 98),
{ old -> old * 19.toBigInteger() },
23, 2, 3
),
Monkey(bigIntegerListOf(54, 65, 75, 74),
{ old -> old + 6.toBigInteger() },
19, 2, 0
),
Monkey(bigIntegerListOf(79, 60, 97),
{ old -> old * old },
13, 1, 3
),
Monkey(bigIntegerListOf(74),
{ old -> old + 3.toBigInteger() },
17, 0, 1
),
)
fun monkeys() =
listOf(
Monkey(bigIntegerListOf(89, 84, 88, 78, 70),
{ old -> old * 5.toBigInteger()},
7, 6, 7
),
Monkey(bigIntegerListOf(76, 62, 61, 54, 69, 60, 85),
{ old -> old + 1.toBigInteger() },
17, 0, 6
),
Monkey(bigIntegerListOf(83, 89, 53),
{ old -> old + 8.toBigInteger() },
11, 5, 3
),
Monkey(bigIntegerListOf(95, 94, 85, 57),
{ old -> old + 4.toBigInteger() },
13, 0, 1
),
Monkey(bigIntegerListOf(82, 98),
{ old -> old + 7.toBigInteger() },
19, 5, 2
),
Monkey(bigIntegerListOf(69),
{ old -> old + 2.toBigInteger() },
2, 1, 3
),
Monkey(bigIntegerListOf(82, 70, 58, 87, 59, 99, 92, 65),
{ old -> old * 11.toBigInteger() },
5, 7, 4
),
Monkey(bigIntegerListOf(91, 53, 96, 98, 68, 82),
{ old -> old * old },
3, 4, 2
),
)
fun part1(input: List<Monkey>): Long {
(1..20).forEach { _ ->
input
.forEach { monkey ->
monkey.inspectItems()
.forEach { item ->
input[item.monkey].items.add(item.item)
}
}
input.forEachIndexed { index, monkey ->
// println("Monkey $index: ${monkey.items}")
}
}
return input.map { it.itemsInspected }
.sorted()
.takeLast(2)
.reduce { acc, i -> acc * i }
}
fun part2(input: List<Monkey>): Long {
val reduceMod = input.map { it.divider }.reduce { a, b -> a * b }
(1..10000).forEach { _ ->
input
.forEach { monkey ->
monkey.inspectItemsVeryWorried()
.forEach { item ->
input[item.monkey].items.add(item.item % reduceMod.toBigInteger())
}
}
input
.forEach { check(it.itemsInspected > 0) }
}
return input.map { it.itemsInspected }
.sorted()
.takeLast(2)
.also {
println("Top items: $it")
}
.reduce { acc, i -> acc * i }
}
// test if implementation meets criteria from the description, like:
println("================ TEST 1 ==============")
check(part1(testMonkeys()) == 10605L)
println("================ TEST 2 ==============")
check(part2(testMonkeys()) == 2713310158L)
println("================ REAL 1 ==============")
// println(part1(monkeys()))
check(part1(monkeys()) == 55930L)
println("================ REAL 2 ==============")
println(part2(monkeys()))
}
| 5 | Kotlin | 0 | 0 | b7143bceddae5744d24590e2fe330f4e4ba6d81c | 5,130 | advent-of-code-2022 | Apache License 2.0 |
Chapter06/KotlinCollectionsApi.kt | PacktPublishing | 131,798,556 | false | null | package quickstartguide.kotlin.chapter5
fun filterEvensThenSquare(numbers: Collection<Int>) {
val result: List<String> = numbers.filter { n -> n % 2 == 0 }
.map { n -> n * n }
.sorted()
.takeWhile { n -> n < 1000 }
.map { n -> n.toString() }
}
// FILTERING
fun drop() {
val numbers = listOf(1, 2, 3, 4, 5)
val dropped = numbers.drop(2)
}
fun filter() {
val numbers = listOf(1, 2, 3, 4, 5)
val smallerThan3 = numbers.filter { n -> n < 3 }
}
fun filterNot() {
val numbers = listOf(1, 2, 3, 4, 5)
val largerThan3 = numbers.filterNot { n -> n < 3 }
}
fun take() {
val numbers = listOf(1, 2, 3, 4, 5)
val first2 = numbers.take(2)
}
// AGGREGATE
fun any() {
val numbers = listOf(1, 2, 3, 4, 5)
val hasEvens = numbers.any { n -> n % 2 == 0 }
}
fun all() {
val numbers = listOf(1, 2, 3, 4, 5)
val allEven = numbers.all { n -> n % 2 == 0 }
}
fun count() {
val numbers = listOf(1, 2, 3, 4, 5)
val evenCount = numbers.count { n -> n % 2 == 0 }
}
fun forEach() {
val numbers = listOf(1, 2, 3, 4, 5)
numbers.forEach { n -> println(n) }
}
fun max() {
val numbers = listOf(1, 2, 3, 4, 5)
val max = numbers.max()
}
fun min() {
val numbers = listOf(1, 2, 3, 4, 5)
val min = numbers.min()
}
fun sum() {
val numbers = listOf(1, 2, 3, 4, 5)
val sum = numbers.sum()
}
// TRANSFORMING
fun map() {
val numbers = listOf(1, 2, 3, 4, 5)
val strings = numbers.map { n -> n.toString() }
}
fun flatMap() {
val numbers = listOf(1, 2, 3, 4, 5)
val multiplesOf10 = numbers.flatMap { n -> listOf(n, n * 10) }
}
fun groupBy() {
val strings = listOf("abc", "ade", "bce", "bef")
val groupped = strings.groupBy { s -> s[0] }
}
fun associateBy() {
val numbers = listOf(1, 2, 3, 4, 5)
val groupped = numbers.associateBy { n -> n.toString() }
}
// ITEMS
fun contains() {
val numbers = listOf(1, 2, 3, 4, 5)
val contains10 = numbers.contains(10)
}
fun first() {
val numbers = listOf(1, 2, 3, 4, 5)
val firstEven = numbers.first { n -> n % 2 == 0 }
}
fun firstOrNull() {
val numbers = listOf(1, 2, 3, 4, 5)
val firstLargerThan10 = numbers.firstOrNull { n -> n > 10 }
}
fun last() {
val numbers = listOf(1, 2, 3, 4, 5)
val lastEven = numbers.last { n -> n % 2 == 0 }
}
fun lastOrNull() {
val numbers = listOf(1, 2, 3, 4, 5)
val lastLargerThan10 = numbers.lastOrNull { n -> n > 10 }
}
fun single() {
val numbers = listOf(1, 2, 3, 4, 5)
val number5 = numbers.single { n -> n > 4 }
}
fun singleOrNull() {
val numbers = listOf(1, 2, 3, 4, 5)
val smallerThan1 = numbers.singleOrNull { n -> n < 1 }
}
// SORTING
fun reversed() {
val numbers = listOf(1, 2, 3, 4, 5)
val reversed = numbers.reversed()
}
fun sorted() {
val numbers = listOf(2, 1, 5, 3, 4)
val sorted = numbers.sorted()
}
fun sortedDescending() {
val numbers = listOf(2, 1, 5, 3, 4)
val sortedDesc = numbers.sortedDescending()
}
| 1 | Kotlin | 8 | 9 | 5c781d2da36e8cb3407b8448c5cbff207fe34592 | 3,026 | Kotlin-Quick-Start-Guide | MIT License |
src/test/kotlin/adventofcode/day18/Day18.kt | jwcarman | 573,183,719 | false | {"Kotlin": 183494} | /*
* Copyright (c) 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package adventofcode.day18
import adventofcode.util.geom.solid.Point3D
import adventofcode.util.graph.Graphs
import adventofcode.util.readAsString
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
class Day18 {
@Test
fun example1() {
assertThat(calculatePart1(readAsString("day18-example.txt"))).isEqualTo(64)
}
@Test
fun part1() {
assertThat(calculatePart1(readAsString("day18.txt"))).isEqualTo(3390)
}
@Test
fun example2() {
assertThat(calculatePart2(readAsString("day18-example.txt"))).isEqualTo(58)
}
@Test
fun part2() {
assertThat(calculatePart2(readAsString("day18.txt"))).isEqualTo(2058)
}
fun calculatePart1(input: String): Int {
val points = parsePoints(input)
return points.sumOf { it.neighbors().filter { n -> n !in points }.size }
}
private fun parsePoints(input: String) = input.lines()
.map { it.split(',') }
.map { Point3D(it[0].toInt(), it[1].toInt(), it[2].toInt()) }
fun calculatePart2(input: String): Int {
val points = parsePoints(input)
val xBounds = (points.minOf { it.x } - 1)..(points.maxOf { it.x } + 1)
val yBounds = (points.minOf { it.y } - 1)..(points.maxOf { it.y } + 1)
val zBounds = (points.minOf { it.z } - 1)..(points.maxOf { it.z } + 1)
val air = mutableSetOf<Point3D>()
xBounds.forEach { x ->
yBounds.forEach { y ->
zBounds.forEach { z ->
val point = Point3D(x, y, z)
if (point !in points) {
air.add(point)
}
}
}
}
val validNeighbors = cluster(air).filter { cluster ->
cluster.any {
it.x == xBounds.first ||
it.x == xBounds.last ||
it.y == yBounds.first ||
it.y == yBounds.last ||
it.z == zBounds.first ||
it.z == zBounds.last
}
}
.flatten()
.toSet()
return points.flatMap { it.neighbors() }.count { it in validNeighbors }
}
private fun cluster(original:Set<Point3D>):List<Set<Point3D>> {
val queue = mutableListOf<Point3D>()
val clusters = mutableListOf<Set<Point3D>>()
queue.addAll(original)
while(queue.isNotEmpty()) {
val point = queue.removeFirst()
val reachable = Graphs.reachable(point) { it.neighbors().filter { n -> n in original } }
queue.removeAll(reachable)
clusters.add(reachable)
}
return clusters
}
} | 0 | Kotlin | 0 | 0 | d6be890aa20c4b9478a23fced3bcbabbc60c32e0 | 3,338 | adventofcode2022 | Apache License 2.0 |
src/Day02.kt | uzorov | 576,933,382 | false | {"Kotlin": 6068} | import java.io.File
import java.util.*
fun main() {
fun getPoints(guideString: String):Int {
when (guideString) {
"A X" -> return 3
"B X" -> return 1
"C X" -> return 2
"A Y" -> return 4
"B Y" -> return 5
"C Y" -> return 6
"A Z" -> return 8
"B Z" -> return 9
"C Z" -> return 7
}
return -1
}
fun parseInput(input: String) : List<String>{
return input.split("\n").map { it }
}
fun part1(input: String): Int {
val scoreArr = parseInput(input).map { getPoints(it) }
return scoreArr.sum()
}
// fun part2(input: List<String>): Int {
// return
//}
// test if implementation meets criteria from the description, like:
//val testInput = readInput("Day01_test")
//check(part1(testInput) == 1)
val input = File("src/day2input.txt").readText()
part1(input).println()
}
//part2(input).println()
| 0 | Kotlin | 0 | 0 | be4ec026f6114f2fa7ae7ebd9b55af9215de8e7b | 968 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day01.kt | Longtainbin | 573,466,419 | false | {"Kotlin": 22711} | import java.util.PriorityQueue
import kotlin.math.max
fun main() {
val input = readInput("inputDay01")
fun part1(input: List<String>): Int {
val caloriesList = mutableListOf<Int>()
var maxCalories = 0
for (str in input) {
if (str.isEmpty()) {
val curElfCalories = caloriesList.sum()
maxCalories = max(maxCalories, curElfCalories)
caloriesList.clear()
} else {
caloriesList.add(str.toInt())
}
}
return maxCalories
}
fun part2(input: List<String>): Int {
val caloriesList = mutableListOf<Int>()
val minHead = PriorityQueue<Int>(3)
for (str in input) {
if (str.isEmpty()) {
val curElfCalories = caloriesList.sum()
caloriesList.clear()
minHead.add(curElfCalories)
if (minHead.size > 3) {
minHead.poll()
}
} else {
caloriesList.add(str.toInt())
}
}
return minHead.sum()
}
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 48ef88b2e131ba2a5b17ab80a0bf6a641e46891b | 1,156 | advent-of-code-2022 | Apache License 2.0 |
partiql-lang/src/main/kotlin/org/partiql/lang/graph/Graph.kt | partiql | 186,474,394 | false | {"Kotlin": 6425423, "HTML": 103438, "ANTLR": 34368, "Inno Setup": 3838, "Java": 1949, "Shell": 748} | package org.partiql.lang.graph
import org.partiql.lang.eval.ExprValue
/** This is an "external" interface to a graph data value,
* providing functionality needed for a pattern-matching processor.
* The intent is to come up with something that can be implemented by different "platforms"
* in different ways.
* There are only minimal assumptions about the underlying implementation of
* graph nodes and edges: they must provide access to labels and payloads
* and the == equality must distinguish and equate them properly.
* In particular, there is no node-edge-node "pointer" navigation.
* The graph's structure is exposed only through the "scan" functions for getting
* adjacent nodes and edges satisfying certain criteria.
*
* TODO:
* - Expand "criteria" beyond label specs, to include predicates ("prefilters"),
* perhaps as call-back lambdas.
* - Instead of returning results as [List]s, consider something lazy/streaming, perhaps [Sequence].
*/
interface Graph {
interface Elem {
val labels: Set<String>
val payload: ExprValue
}
interface Node : Elem
interface Edge : Elem
interface EdgeDirected : Edge
interface EdgeUndir : Edge
/** Get all the nodes conforming to a label specification. */
fun scanNodes(spec: LabelSpec): List<Node>
/** Get undirected edges (and their adjacent nodes) whose labels satisfy the given specifications.
* Spec Triple(x, _, y) can be used to compute both patterns (x)~(y) and (y)~(x).
* An undirected edge a---b is matched twice, returning x=a, y=b and x=b, y=a.
*/
fun scanUndir(spec: Triple<LabelSpec, LabelSpec, LabelSpec>): List<Triple<Node, EdgeUndir, Node>>
/** Get directed edges (and their adjacent nodes) whose labels satisfy the given specifications,
* when the requested direction *agrees* with the one at which an edge is defined.
* Edge a --> b matches spec Triple(a, _, b), aka a `--)` b or b `(--` a,
* and gets returned as Triple(a, _ , b). */
fun scanDirectedStraight(spec: Triple<LabelSpec, LabelSpec, LabelSpec>): List<Triple<Node, EdgeDirected, Node>>
/** Get directed edges (and their adjacent nodes) whose labels satisfy the given specifications,
* when the requested direction is *opposite* to the one at which an edge is defined.
* Edge a --> b matches spec Triple(b, _, a), aka b `--)` a or a `(--` b,
* and gets returned as Triple(b, _ , a). */
fun scanDirectedFlipped(spec: Triple<LabelSpec, LabelSpec, LabelSpec>): List<Triple<Node, EdgeDirected, Node>>
/** Get directed edges without regard for the direction at which they point.
* Spec Triple(x, _, y) can be used to compute both patterns (x)<->(y) and (y)<->(x).
* A directed edge a --> b is matched twice, returning x=a, y=b and x=b, y=a.
*
* The result of this method can be obtained by combining results of
* [scanDirectedStraight] and [scanDirectedFlipped],
* but [scanDirectedBlunt] is meant to be implemented with one pass over the data.
*/
fun scanDirectedBlunt(spec: Triple<LabelSpec, LabelSpec, LabelSpec>): List<Triple<Node, EdgeDirected, Node>>
}
/** Label specifications for selecting graph elements (nodes or edges)
* based on labels at them.
*/
sealed class LabelSpec {
/** A graph element (node or edge) matches when its label set contains [name]. */
data class Name(val name: String) : LabelSpec()
/** A graph element matches as long as it has a label. */
object Wildcard : LabelSpec()
// TODO: more LabelSpec features: alternation, negation, string patterns, ...
}
| 269 | Kotlin | 60 | 530 | e894fad711bc4126d1022f62d7545b64f5e6bfc8 | 3,644 | partiql-lang-kotlin | Apache License 2.0 |
src/Day11.kt | acrab | 573,191,416 | false | {"Kotlin": 52968} | import com.google.common.truth.Truth.assertThat
import java.math.BigInteger
class Monkey(
val id: String,
startingItems: List<Int>,
private val inspectOperation: (BigInteger) -> BigInteger,
private val testValue: BigInteger,
private val onTrue: String,
private val onFalse: String,
private val debug: Boolean
) {
private val heldItems: Array<BigInteger> = Array(40) { BigInteger.ZERO }
private var itemCount = 0
init {
if (debug) {
println("Init")
}
startingItems.forEach { giveItem(it.toBigInteger()) }
if (debug) {
printHoldings()
}
}
var totalInspections: Long = 0
private set
private fun giveItem(item: BigInteger) {
heldItems[itemCount] = item
itemCount++
if (debug) {
println("$id given $item, now has $itemCount items")
}
}
fun printHoldings() {
if (debug) {
println("$id holding $itemCount items: ${heldItems.take(itemCount).joinToString()}")
}
}
private fun inspectPart1(item: Int) = inspectOperation(heldItems[item]) / BigInteger.valueOf(3)
private fun takeTurn(monkeys: Map<String, Monkey>, inspection: (Int) -> BigInteger) {
if (debug) {
println("----")
}
for (i in 0 until itemCount) {
totalInspections++
val newValue = inspection(i)
if ((newValue % testValue) == BigInteger.ZERO) {
monkeys[onTrue]?.giveItem(newValue)
} else {
monkeys[onFalse]?.giveItem(newValue)
}
}
if (debug) {
println("----")
}
itemCount = 0
}
fun takePart1Turn(monkeys: Map<String, Monkey>) {
takeTurn(monkeys, ::inspectPart1)
}
}
fun String.toOperation(): (BigInteger) -> BigInteger {
val (operation, operand) = split(" ")
if (operand == "old") {
if (operation == "*") {
return { x -> x * x }
} else {
return { x -> x + x }
}
} else {
val parsedOperand = operand.toBigInteger()
if (operation == "*") {
return { x -> x * parsedOperand }
} else {
return { x -> x + parsedOperand }
}
}
}
fun parseMonkeys(input: List<String>, debug: Boolean): Map<String, Monkey> {
val monkeys = mutableMapOf<String, Monkey>()
with(input.iterator()) {
while (hasNext()) {
val id = next().split(" ")[1].removeSuffix(":")
val startingItems = next().removePrefix(" Starting items: ").split(", ").map { it.toInt() }
val operation = next().removePrefix(" Operation: new = old ").toOperation()
val test = next().removePrefix(" Test: divisible by ").toBigInteger()
val trueTarget = next().removePrefix(" If true: throw to monkey ")
val falseTarget = next().removePrefix(" If false: throw to monkey ")
monkeys[id] = Monkey(id, startingItems, operation, test, trueTarget, falseTarget, debug)
//Skip blank lines between monkeys
if (hasNext()) {
next()
}
}
}
if (debug) {
println("Parsed ${monkeys.values.size} monkeys")
}
return monkeys
}
fun main() {
fun calculateMonkeyBusiness(monkeys: Map<String, Monkey>) =
monkeys.values.map { it.totalInspections }.sortedDescending().take(2).fold(1L) { acc, i -> acc * i }
fun part1(input: List<String>, debug: Boolean): Long {
val monkeys = parseMonkeys(input, debug)
repeat(20) {
monkeys.values.sortedBy { it.id }.forEach {
it.takePart1Turn(monkeys)
}
if (debug) {
println("-------------------------------------")
monkeys.values.sortedBy { it.id }.forEach {
it.printHoldings()
}
println("-------------------------------------")
}
}
return calculateMonkeyBusiness(monkeys)
}
val testInput = readInput("Day11_test")
assertThat(part1(testInput, true)).isEqualTo(10605L)
val input = readInput("Day11")
println(part1(input, false))
} | 0 | Kotlin | 0 | 0 | 0be1409ceea72963f596e702327c5a875aca305c | 4,280 | aoc-2022 | Apache License 2.0 |
app/src/main/kotlin/solution/Solution2454.kt | likexx | 559,794,763 | false | {"Kotlin": 136661} | package solution
import solution.annotation.Leetcode
class Solution2454 {
@Leetcode(2454)
class Solution {
// inspired by https://leetcode.com/problems/next-greater-element-iv/discuss/2756668/JavaC%2B%2BPython-One-Pass-Stack-Solution-O(n)
fun secondGreaterElement(nums: IntArray): IntArray {
val result = IntArray(nums.size) {-1}
val s1 = mutableListOf<Int>()
val s2 = mutableListOf<Int>()
val temp = mutableListOf<Int>()
for ((i,n) in nums.withIndex()) {
while (s2.size>0 && nums[s2.last()]<n) {
val j = s2.last()
s2.removeAt(s2.size-1)
result[j]=n
}
while (s1.size>0 && nums[s1.last()]<n) {
val j = s1.last()
s1.removeAt(s1.size-1)
temp.add(j)
}
while (temp.size>0) {
val j = temp.last()
temp.removeAt(temp.size-1)
s2.add(j)
}
s1.add(i)
}
return result
}
fun secondGreaterElementOriginal(nums: IntArray): IntArray {
val next = IntArray(nums.size) { -1 }
val maxes = IntArray(nums.size) { -1 }
maxes[maxes.size-1]=nums[maxes.size-1]
for (i in nums.size-2 downTo 0) {
if (nums[i]==nums[i+1]) {
next[i]=next[i+1]
maxes[i]=maxes[i+1]
continue
}
maxes[i] = kotlin.math.max(maxes[i+1], nums[i])
var j = i+1
while (j<nums.size && j!=-1) {
if (nums[j]>nums[i]) {
next[i]=j
break
}
j=next[j]
}
}
// println(next.toList())
// println(maxes.toList())
val result = IntArray(nums.size) { -1 }
for (i in 0..nums.size-1) {
if (i>0 && nums[i-1]==nums[i]) {
result[i]=result[i-1]
continue
}
var j=next[i]
if (j==-1) {
continue
}
for (k in j+1..nums.size-1) {
if (maxes[k]<=nums[i]) {
break
}
if (nums[k]>nums[i]) {
result[i]=nums[k]
break
}
}
}
return result
}
fun secondGreaterElementNaive(nums: IntArray): IntArray {
val result = IntArray(nums.size) { -1 }
for (i in 0..nums.size-1) {
var count=0
for (j in i+1..nums.size-1) {
if (nums[j]>nums[i]) {
count+=1
}
if (count==2) {
result[i]=nums[j]
break
}
}
}
return result
}
}
} | 0 | Kotlin | 0 | 0 | 376352562faf8131172e7630ab4e6501fabb3002 | 3,236 | leetcode-kotlin | MIT License |
src/main/kotlin/de/niemeyer/aoc2022/Day20.kt | stefanniemeyer | 572,897,543 | false | {"Kotlin": 175820, "Shell": 133} | /**
* Advent of Code 2022, Day 20: Grove Positioning System
* Problem Description: https://adventofcode.com/2022/day/20
*/
package de.niemeyer.aoc2022
import de.niemeyer.aoc.utils.Resources.resourceAsListOfLong
import de.niemeyer.aoc.utils.getClassName
import kotlin.math.absoluteValue
fun main() {
fun parseInput(input: List<Long>, decryptionKey: Long = 1L): List<LinkedList> {
val result = mutableListOf<LinkedList>()
val firstValue = input.first() * decryptionKey
val head = LinkedList(firstValue)
result.add(head)
var tail = head
input.drop(1).forEach { value ->
tail = tail.addAfter(value * decryptionKey)
result.add(tail)
}
head.previous = tail
tail.next = head
return result.toList()
}
fun solve(input: List<Long>, rounds: Int = 1, decryptionKey: Long = 1): Long {
val encFile = parseInput(input, decryptionKey)
var zero: LinkedList? = null
val numNumbers = input.size
repeat(rounds) {
encFile.forEach { current ->
if (current.value == 0L) {
zero = current
}
current.move((current.value % (numNumbers - 1)).toInt())
}
}
require(zero != null)
val e1000 = zero!![1000 % numNumbers].value
val e2000 = zero!![2000 % numNumbers].value
val e3000 = zero!![3000 % numNumbers].value
return e1000 + e2000 + e3000
}
fun part1(input: List<Long>): Long =
solve(input)
fun part2(input: List<Long>): Long =
solve(input, 10,811_589_153L)
val name = getClassName()
val testInput = resourceAsListOfLong(fileName = "${name}_test.txt")
val puzzleInput = resourceAsListOfLong(fileName = "${name}.txt")
check(part1(testInput) == 3L)
val puzzleResultPart1 = part1(puzzleInput)
println(puzzleResultPart1)
check(puzzleResultPart1 == 1_591L)
check(part2(testInput) == 1_623_178_306L)
val puzzleResultPart2 = part2(puzzleInput)
println(puzzleResultPart2)
check(puzzleResultPart2 == 14_579_387_544_492L)
}
data class LinkedList(val value: Long, var previous: LinkedList? = null, var next: LinkedList? = null)
fun LinkedList.addAfter(value: Long): LinkedList {
val next = this.next
val newNode = LinkedList(value, this, next)
this.next = newNode
next?.previous = newNode
return newNode
}
fun LinkedList.move(relativePos: Int) {
if (relativePos == 0) return // nothing to do
val next = this.next
val previous = this.previous
// relink old neighbors
previous?.next = next
next?.previous = previous
var target = this
repeat(relativePos.absoluteValue) {
target = if (relativePos < 0) target.previous!! else target.next!!
}
if (relativePos > 0) {
this.next = target.next
this.previous = target
// relink new neighbors
target.next?.previous = this
target.next = this
} else {
this.next = target
this.previous = target.previous
// relink new neighbors
target.previous?.next = this
target.previous = this
}
}
operator fun LinkedList.get(relativePos: Int): LinkedList {
var current = this
repeat(relativePos.absoluteValue) {
current = if (relativePos < 0) current.previous!! else current.next!!
}
return current
}
@Suppress("unused")
fun LinkedList.printBottomLeft() {
var current = this
var count = 10
do {
print("${current.value}, ")
current = current.next!!
} while (count-- >= 0 && current != this)
println()
}
| 0 | Kotlin | 0 | 0 | ed762a391d63d345df5d142aa623bff34b794511 | 3,684 | AoC-2022 | Apache License 2.0 |
src/commonMain/kotlin/advent2020/day02/Day02Puzzle.kt | jakubgwozdz | 312,526,719 | false | null | package advent2020.day02
internal data class ParsedLine(val number1: Int, val number2: Int, val char: Char, val password: String)
val regexp by lazy { """(\d+)-(\d+) (\w): (\w*)""".toRegex() }
internal fun parse(line: String): ParsedLine {
val (g1, g2, g3, g4) = regexp.matchEntire(line)?.destructured
?: error("line `$line` does not match `$regexp`")
return ParsedLine(g1.toInt(), g2.toInt(), g3.single(), g4)
}
fun part1(input: String): String {
val passwords = input.trim().lines().map { parse(it) }
val result = passwords
.count { it.password.count { c -> c == it.char } in it.number1..it.number2 }
return result.toString()
}
fun part2(input: String): String {
val passwords = input.trim().lines().map { parse(it) }
val result = passwords
.count { (it.password[it.number1 - 1] == it.char) xor (it.password[it.number2 - 1] == it.char) }
return result.toString()
}
| 0 | Kotlin | 0 | 2 | e233824109515fc4a667ad03e32de630d936838e | 927 | advent-of-code-2020 | MIT License |
src/pl/shockah/aoc/y2019/Day3.kt | Shockah | 159,919,224 | false | null | package pl.shockah.aoc.y2019
import pl.shockah.aoc.AdventTask
import pl.shockah.unikorn.geom.polygon.Polygon
import pl.shockah.unikorn.math.MutableVector2
import pl.shockah.unikorn.math.Vector2
import kotlin.math.abs
class Day3: AdventTask<Pair<Polygon, Polygon>, Int, Int>(2019, 3) {
enum class Direction(
val symbol: Char,
val x: Int,
val y: Int
) {
Right('R', 1, 0),
Up('U', 0, -1),
Left('L', -1, 0),
Down('D', 0, 1);
companion object {
val bySymbol = values().associateBy { it.symbol }
}
}
override fun parseInput(rawInput: String): Pair<Polygon, Polygon> {
val lines = rawInput.lines().take(2)
fun parsePolygon(line: String): Polygon {
var x = 0
var y = 0
val polygon = Polygon()
polygon.points += MutableVector2(0.0, 0.0)
for (entry in line.split(",")) {
val direction = Direction.bySymbol[entry[0]]!!
val length = entry.drop(1).toInt()
x += direction.x * length
y += direction.y * length
polygon.points += MutableVector2(x.toDouble(), y.toDouble())
}
return polygon
}
return parsePolygon(lines[0]) to parsePolygon(lines[1])
}
enum class Mode {
ManhattanDistance, Delay
}
private fun task(input: Pair<Polygon, Polygon>, mode: Mode): Int {
val lines = input.first.lines to input.second.lines
val intersections = mutableListOf<Pair<Vector2, Int>>()
var length1 = 0
for (line1 in lines.first) {
var length2 = 0
for (line2 in lines.second) {
(line1 intersect line2)?.let {
val delay = length1 + length2 + (it - line1.point1).length.toInt() + (it - line2.point1).length.toInt()
intersections += it to delay
}
length2 += line2.perimeter.toInt()
}
length1 += line1.perimeter.toInt()
}
return when (mode) {
Mode.ManhattanDistance -> intersections.minOf { (abs(it.first.x) + abs(it.first.y)).toInt() }
Mode.Delay -> intersections.minOf { it.second }
}
}
override fun part1(input: Pair<Polygon, Polygon>): Int {
return task(input, Mode.ManhattanDistance)
}
override fun part2(input: Pair<Polygon, Polygon>): Int {
return task(input, Mode.Delay)
}
// TODO: tests
} | 0 | Kotlin | 0 | 0 | 9abb1e3db1cad329cfe1e3d6deae2d6b7456c785 | 2,119 | Advent-of-Code | Apache License 2.0 |
src/main/kotlin/aoc22/Day16.kt | tom-power | 573,330,992 | false | {"Kotlin": 254717, "Shell": 1026} | package aoc22
import aoc22.Day16Domain.Mountain
import aoc22.Day16Domain.Valve
import aoc22.Day16Domain.valvesToVisit
import aoc22.Day16Parser.toValves
import aoc22.Day16Solution.part1Day16
import aoc22.Day16Solution.part2Day16
import com.github.shiguruikai.combinatoricskt.combinations
import common.Year22
object Day16: Year22 {
fun List<String>.part1(): Int = part1Day16()
fun List<String>.part2(): Int = part2Day16()
}
object Day16Solution {
fun List<String>.part1Day16(): Int =
toValves()
.associateBy { it.name }
.let { Mountain(valveMap = it, minutes = 30).pressureReleased() }
fun List<String>.part2Day16(): Int =
toValves()
.associateBy { it.name }
.let {
it.valvesToVisit()
.combinations(it.valvesToVisit().size / 2)
.maxOf { halfTheValvesToVisit ->
fun pressureReleasedFor(valvesToVisit: Set<String>) =
Mountain(
valveMap = it,
minutes = 26
).pressureReleased(valvesToVisit)
listOf(
halfTheValvesToVisit.toSet(),
it.valvesToVisit() - halfTheValvesToVisit.toSet()
).sumOf(::pressureReleasedFor)
}
}
}
object Day16Domain {
fun ValveMap.valvesToVisit() = filter { it.value.flowRate > 0 }.keys
class Mountain(
private val valveMap: Map<String, Valve>,
private val minutes: Int,
) {
fun pressureReleased(valvesToVisit: Set<String> = valveMap.valvesToVisit()): Int =
PressureReleased(
valveMap = valveMap,
valvesToVisit = valvesToVisit,
minutes = minutes,
shortestDistanceMap = ShortestDistances(valveMap).invoke()
).invoke()
}
private class PressureReleased(
private val valveMap: Map<String, Valve>,
private val valvesToVisit: Set<String>,
private val minutes: Int,
private val shortestDistanceMap: ShortestDistanceMap
) : () -> Int {
override fun invoke() = initialState().sumOfFlowsOverShortest()
private fun initialState() =
TraverseState(
current = valveMap.getValue("AA"),
remainingMinutes = minutes,
remainingValves = valvesToVisit,
finalFlow = 0,
)
private class TraverseState(
val current: Valve,
val remainingMinutes: Int,
val remainingValves: Set<String>,
val finalFlow: Int,
)
private fun TraverseState.sumOfFlowsOverShortest(): Int =
currentFlow() +
(remainingValves
.filter { next -> shortestDistanceTo(next) < remainingMinutes }
.map { next -> nextState(next).sumOfFlowsOverShortest() }
.maxOrNull()
?: 0)
private fun TraverseState.currentFlow() = remainingMinutes * current.flowRate
private fun TraverseState.nextState(next: String) =
TraverseState(
current = valveMap.getValue(next),
remainingMinutes = remainingMinutes - 1 - shortestDistanceTo(next),
remainingValves = remainingValves - next,
finalFlow = finalFlow
)
private fun TraverseState.shortestDistanceTo(other: String) = shortestDistanceMap[current.name]!![other]!!
}
private class ShortestDistances(
private val valveMap: Map<String, Valve>,
) : () -> ShortestDistanceMap {
override fun invoke(): ShortestDistanceMap = valveMap.keys.associateWith { shortestDistancesFrom(it) }
private fun shortestDistancesFrom(valve: String): MutableMap<String, Int> {
val shortestDistances =
mutableMapOf<String, Int>()
.withDefault { Int.MAX_VALUE }
.apply { put(valve, 0) }
fun visitNext(valve: String) {
val nextDistance = shortestDistances[valve]!! + 1
valveMap[valve]!!.otherValves
.forEach { nextValve ->
if (nextDistance < shortestDistances.getValue(nextValve)) {
shortestDistances[nextValve] = nextDistance
visitNext(nextValve)
}
}
}
visitNext(valve)
return shortestDistances
}
}
data class Valve(
val name: String,
val flowRate: Int,
val otherValves: List<String>,
)
}
private typealias ShortestDistanceMap = Map<String, Map<String, Int>>
private typealias ValveMap = Map<String, Valve>
object Day16Parser {
fun List<String>.toValves(): List<Valve> =
map { line ->
line.replace("Valve ", "")
.replace(" has flow rate=", ";")
.replace(" tunnels lead to valves ", "")
.replace(" tunnel leads to valve ", "")
.split(";")
.let {
Valve(
name = it[0],
flowRate = it[1].toInt(),
otherValves = it[2].split(", ")
)
}
}
}
| 0 | Kotlin | 0 | 0 | baccc7ff572540fc7d5551eaa59d6a1466a08f56 | 5,503 | aoc | Apache License 2.0 |
src/main/kotlin/aoc/Day1.kt | dtsaryov | 573,392,550 | false | {"Kotlin": 28947} | package aoc
/**
* [AoC 2022: Day 1](https://adventofcode.com/2022/day/1)
*/
fun findMaxCalories(): Int {
val input = readInput("day1.txt") ?: return -1
var max = 0
processSums(input) { sum ->
if (sum > max) max = sum
}
return max
}
fun findSumOfTop3Calories(): Int {
val input = readInput("day1.txt") ?: return -1
val top3 = Top3()
processSums(input, top3::add)
return top3.getValues().fold(0, Int::plus)
}
private class Top3 {
private val values = arrayOf(-1, -1, -1)
fun add(n: Int) {
var minIdx = 0
for (i in 1..2)
if (values[i] < values[minIdx]) minIdx = i
if (values[minIdx] < n)
values[minIdx] = n
}
fun getValues() = values
}
private fun processSums(input: List<String>, processor: (Int) -> Unit) {
var current = 0
for (line in input) {
if (line.isEmpty()) {
processor(current)
current = 0
} else {
current += line.toInt()
}
}
} | 0 | Kotlin | 0 | 0 | 549f255f18b35e5f52ebcd030476993e31185ad3 | 1,028 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/pl/mrugacz95/aoc/day10/day10.kt | mrugacz95 | 317,354,321 | false | null | package pl.mrugacz95.aoc.day10
fun part1(joltages: List<Int>): Int {
val differences = joltages.sorted().windowed(2, 1).map { it[1] - it[0] }.groupingBy { it }.eachCount()
return differences[1]!! * differences[3]!!
}
val cache = HashMap<Int, Long>()
fun findPermutations(startIndex: Int, list: List<Int>): Long {
cache[startIndex]?.let {
return it
}
if (startIndex == list.size - 1) {
return 1
}
val first = list[startIndex]
var count = 0L
for (i in startIndex + 1 until list.size) {
val nextValue = list[i]
if (nextValue - first <= 3) {
count += findPermutations(i, list)
} else {
break
}
}
cache[startIndex] = count
return count
}
fun main() {
val joltages = {}::class.java.getResource("/day10.in")
.readText()
.split("\n")
.map { it.toInt() }
.sorted()
.toMutableList()
joltages.add(0, 0)
joltages.add(joltages.size, joltages.maxOrNull()!! + 3)
println("Answer part 1: ${part1(joltages)}")
println("Answer part 2: ${findPermutations(0, joltages)}")
} | 0 | Kotlin | 0 | 1 | a2f7674a8f81f16cd693854d9f564b52ce6aaaaf | 1,138 | advent-of-code-2020 | Do What The F*ck You Want To Public License |
advent/src/test/kotlin/org/elwaxoro/advent/y2021/Dec17.kt | elwaxoro | 328,044,882 | false | {"Kotlin": 376774} | package org.elwaxoro.advent.y2021
import org.elwaxoro.advent.Coord
import org.elwaxoro.advent.PuzzleDayTester
import org.elwaxoro.advent.contains
/**
* Trick Shot
*/
class Dec17 : PuzzleDayTester(17, 2021) {
override fun part1(): Any = parse().sprayAndPray().flatten().maxOf { it.pos.y }
override fun part2(): Any = parse().sprayAndPray().size
/**
* Shoot a shit ton of probes out there and see what hits the target
* Returns each successful flight
*/
private fun Pair<Coord, Coord>.sprayAndPray(): List<List<Probe>> =
(1..second.x).mapNotNull { xVel ->
(first.y..100).mapNotNull { yVel ->
Probe(Coord(), xVel, yVel).probulate(this)
}
}.flatten()
private data class Probe(val pos: Coord, val velX: Int, val velY: Int) {
/**
* Move the probe and update the velocity
*/
fun iterate(): Probe = Probe(pos.add(velX, velY), (velX - 1).takeUnless { velX <= 0 } ?: 0, velY - 1)
/**
* Track the probe through all iterations until it either hits the target (return path) or falls out of bounds (return null)
*/
tailrec fun probulate(target: Pair<Coord, Coord>, track: List<Probe> = listOf(this)): List<Probe>? =
if (target.contains(track.last().pos)) {
track
} else if (track.last().pos.x >= target.second.x || track.last().pos.y <= target.first.y) {
null
} else {
probulate(target, track.plus(track.last().iterate()))
}
}
private fun parse() = load().single().replace("target area: x=", "").replace(" y=", "").split(",").let { (xs, ys) ->
val xs2 = xs.split("..")
val ys2 = ys.split("..")
Coord(xs2[0].toInt(), ys2[0].toInt(), 'T') to Coord(xs2[1].toInt(), ys2[1].toInt(), 'T')
}
}
| 0 | Kotlin | 4 | 0 | 1718f2d675f637b97c54631cb869165167bc713c | 1,873 | advent-of-code | MIT License |
Problems/Algorithms/547. Number of Provinces/NumberOfProvinces.kt | xuedong | 189,745,542 | false | {"Kotlin": 332182, "Java": 294218, "Python": 237866, "C++": 97190, "Rust": 82753, "Go": 37320, "JavaScript": 12030, "Ruby": 3367, "C": 3121, "C#": 3117, "Swift": 2876, "Scala": 2868, "TypeScript": 2134, "Shell": 149, "Elixir": 130, "Racket": 107, "Erlang": 96, "Dart": 65} | class Solution {
fun findCircleNum(isConnected: Array<IntArray>?): Int {
if (isConnected == null || isConnected.size == 0) {
return 0
}
val n = isConnected.size
val uf = UnionFind(n)
for (i in 0..n-1) {
for (j in 0..n-1) {
if (isConnected[i][j] == 1) {
uf.union(i, j)
}
}
}
return uf.getCount()
}
private class UnionFind(size: Int) {
private val root = IntArray(size) {i -> i}
private val rank = IntArray(size) {i -> 1}
private var count = size
fun find(x: Int): Int {
if (x == root[x]) {
return x
}
root[x] = find(root[x])
return root[x]
}
fun union(x: Int, y: Int): Unit {
val rootX = find(x)
val rootY = find(y)
if (rootX != rootY) {
if (rank[rootX] > rank[rootY]) {
root[rootY] = rootX
} else if (rank[rootX] < rank[rootY]) {
root[rootX] = rootY
} else {
root[rootY] = rootX
rank[rootX] += 1
}
count--
}
}
fun getCount(): Int {
return count
}
}
}
| 0 | Kotlin | 0 | 1 | 5e919965b43917eeee15e4bff12a0b6bea4fd0e7 | 1,434 | leet-code | MIT License |
src/2022/Day11.kt | nagyjani | 572,361,168 | false | {"Kotlin": 369497} | package `2022`
import java.io.File
import java.math.BigInteger
import java.util.*
fun main() {
Day11().solve()
}
class Day11 {
val input1 = """
Monkey 0:
Starting items: 79, 98
Operation: new = old * 19
Test: divisible by 23
If true: throw to monkey 2
If false: throw to monkey 3
Monkey 1:
Starting items: 54, 65, 75, 74
Operation: new = old + 6
Test: divisible by 19
If true: throw to monkey 2
If false: throw to monkey 0
Monkey 2:
Starting items: 79, 60, 97
Operation: new = old * old
Test: divisible by 13
If true: throw to monkey 1
If false: throw to monkey 3
Monkey 3:
Starting items: 74
Operation: new = old + 3
Test: divisible by 17
If true: throw to monkey 0
If false: throw to monkey 1
""".trimIndent()
val input2 = """
""".trimIndent()
enum class Op {
ADD, MUL, SQUARE
}
class Operation(val op: Op, val other: BigInteger) {
fun apply(item: BigInteger): BigInteger {
if (op == Op.MUL) {
return item.multiply(other)
} else if (op == Op.SQUARE) {
return item.multiply(item)
}
return item.add(other)
}
}
class Test(val n: BigInteger) {
fun test(k: BigInteger): Boolean {
return k.mod(n) == BigInteger.ZERO
}
}
data class Throw(val monkey: Int, val items: MutableList<BigInteger> = mutableListOf()) {
fun add(item: BigInteger) {
items.add(item)
}
}
class Monkey(val test: Test, val operation: Operation, val toMonkeys: List<Int>) {
val items = mutableListOf<BigInteger>()
var inspectNum = 0L
fun add(stuff: List<BigInteger>) {
items.addAll(stuff)
}
fun throws(mod: BigInteger? = null): List<Throw> {
val r = toMonkeys.map{Throw(it)}
items.forEach {
val w =
if (mod == null) {
operation.apply(it).div(BigInteger("3"))
} else {
operation.apply(it).mod(mod)
}
++inspectNum
if (test.test(w)) {
r[0].add(w)
} else {
r[1].add(w)
}
}
items.removeAll{true}
return r
}
}
fun solve() {
val f = File("src/2022/inputs/day11.in")
val s = Scanner(f)
// val s = Scanner(input1)
val monkeys = mutableListOf<Monkey>()
var mod = BigInteger.ONE
while (s.hasNextLine()) {
var line = s.nextLine().trim()
if (line.isEmpty()) {
continue
}
if (!line.startsWith("Monkey")) {
throw RuntimeException()
}
line = s.nextLine().trim()
if (!line.startsWith("Starting items: ")) {
throw RuntimeException()
}
var rest = line.substring(16)
val items = rest.split(", ").map{it.toBigInteger()}
line = s.nextLine().trim()
if (!line.startsWith("Operation: new = old ")) {
throw RuntimeException()
}
val opChar = line[21]
rest = line.substring(23)
val operation =
if (rest == "old") {
Operation(Op.SQUARE, BigInteger.ONE)
} else if (opChar == '*') {
Operation(Op.MUL, rest.toBigInteger())
} else if (opChar == '+') {
Operation(Op.ADD, rest.toBigInteger())
} else {
throw RuntimeException()
}
line = s.nextLine().trim()
if (!line.startsWith("Test: divisible by ")) {
throw RuntimeException()
}
rest = line.substring(19)
val d = rest.toBigInteger()
mod = mod.times(d)
line = s.nextLine().trim()
if (!line.startsWith("If true: throw to monkey ")) {
throw RuntimeException()
}
rest = line.substring(25)
val m1 = rest.toInt()
line = s.nextLine().trim()
if (!line.startsWith("If false: throw to monkey ")) {
throw RuntimeException()
}
rest = line.substring(26)
val m2 = rest.toInt()
val monkey = Monkey(Test(d), operation, listOf(m1, m2))
monkey.add(items)
monkeys.add(monkey)
// println("")
}
// for (i in 1..20) {
// for (m in monkeys) {
// val t = m.throws()
// t.map { monkeys[it.monkey].add(it.items) }
// }
// }
//
// // [23, 63, 198, 241, 256, 385, 421, 433]
// val sortedInspectNums = monkeys.map { it.inspectNum }.sorted()
for (i in 1..10000) {
for (m in monkeys) {
val t = m.throws(mod)
t.map { monkeys[it.monkey].add(it.items) }
}
}
// [23, 63, 198, 241, 256, 385, 421, 433]
val sortedInspectNums = monkeys.map { it.inspectNum }.sortedDescending()
println("${sortedInspectNums[0] * sortedInspectNums[1]}")
}
}
| 0 | Kotlin | 0 | 0 | f0c61c787e4f0b83b69ed0cde3117aed3ae918a5 | 5,387 | advent-of-code | Apache License 2.0 |
src/Day14.kt | greg-burgoon | 573,074,283 | false | {"Kotlin": 120556} | fun main() {
class Point (x: Int, y: Int) {
val x = x
val y = y
}
fun drawLine(grid: MutableList<MutableList<Char>>, firstPoint: Point, secondPoint: Point) {
val isVerticalLine = firstPoint.x == secondPoint.x
if (isVerticalLine) {
var maxY = Math.max(firstPoint.y, secondPoint.y)
var minY = Math.min(firstPoint.y, secondPoint.y)
for(i in minY .. maxY){
grid[i][firstPoint.x] = '#'
}
} else {
var maxX = Math.max(firstPoint.x, secondPoint.x)
var minX = Math.min(firstPoint.x, secondPoint.x)
for(i in minX .. maxX){
grid[firstPoint.y][i] = '#'
}
}
}
fun simulateSand(grid: MutableList<MutableList<Char>>, sandLocation: Point): Int {
var isTrackingUnit = true
var currentSandPosition = sandLocation
var sandUnits = 1
while(true){
//launch new Sand?
if (isTrackingUnit) {
if (currentSandPosition.y + 1 >= grid.size) {
break
}
if (grid[currentSandPosition.y+1][currentSandPosition.x] == '.') {
currentSandPosition = Point(currentSandPosition.x, currentSandPosition.y+1)
} else if (currentSandPosition.x - 1 >= 0 && grid[currentSandPosition.y+1][currentSandPosition.x-1] == '.') {
currentSandPosition = Point(currentSandPosition.x - 1, currentSandPosition.y + 1)
} else if (currentSandPosition.x + 1 < grid[0].size && grid[currentSandPosition.y+1][currentSandPosition.x+1] == '.') {
currentSandPosition = Point( currentSandPosition.x + 1, currentSandPosition.y + 1)
} else {
if (currentSandPosition.x - 1 < 0) {
break
} else if (currentSandPosition.x + 1 >= grid[0].size) {
break
}
if (grid[currentSandPosition.y][currentSandPosition.x] == 'O') {
break
}
grid[currentSandPosition.y][currentSandPosition.x] = 'O'
isTrackingUnit = false
}
} else {
isTrackingUnit = true
currentSandPosition = sandLocation
sandUnits++
}
}
return sandUnits-1
}
fun getAllPointsFromInput(input: String): MutableList<Point> {
var points = input.split("\n")
.flatMap {
it.split(" -> ").map {
var pair = it.split(",")
Point(pair[0].toInt(), pair[1].toInt())
}
}.toMutableList()
return points
}
fun createGridFromMinAndMax(
minY: Int,
maxY: Int,
minX: Int,
maxX: Int
): MutableList<MutableList<Char>> {
var grid = mutableListOf<MutableList<Char>>()
for (y in minY..maxY) {
grid.add(mutableListOf<Char>())
for (x in minX..maxX) {
grid[y].add('.')
}
}
return grid
}
fun createRocks(
rockLines: List<List<Point>>,
grid: MutableList<MutableList<Char>>
) {
rockLines.forEach {
it.windowed(2, 1) { pairs ->
var firstPoint = pairs[0]
var secondPoint = pairs[1]
drawLine(grid, firstPoint, secondPoint)
}
}
}
fun part1(input: String): Int {
var points = getAllPointsFromInput(input)
var minX = points.minOf { it.x }
var transform = 0 - minX
var maxX = points.maxOf { it.x } + transform
minX = 0
var minY = 0
var maxY = points.maxOf { it.y }
var grid = createGridFromMinAndMax(minY, maxY, minX, maxX)
var rockLines = input.split("\n")
.map {
it.split(" -> ").map {
var pair = it.split(",")
Point(pair[0].toInt()+transform, pair[1].toInt())
}
}
createRocks(rockLines, grid)
var sandLocation = Point(500+transform, 0)
var numberOfSandUnits = simulateSand(grid, sandLocation)
return numberOfSandUnits
}
fun part2(input: String): Int {
var points = getAllPointsFromInput(input)
var minX = points.minOf { it.x }
var maxX = points.maxOf { it.x }
var minY = 0
var maxY = points.maxOf { it.y }
var floorLeft = Point (minX - maxY, maxY + 2)
var floorRight = Point (maxX + maxY, maxY + 2)
var transform = 0 - floorLeft.x
maxX = floorRight.x + transform
minX = 0
var grid = createGridFromMinAndMax(minY, floorRight.y, minX, maxX)
var rockLines = input.split("\n")
.map {
it.split(" -> ").map {
var pair = it.split(",")
Point(pair[0].toInt()+transform, pair[1].toInt())
}
}.toMutableList()
var transformedFloorLeft = Point(floorLeft.x +transform, floorLeft.y)
var transformedFloorRight = Point(floorRight.x + transform, floorRight.y)
rockLines.add(listOf(transformedFloorLeft, transformedFloorRight))
createRocks(rockLines, grid)
var sandLocation = Point(500+transform, 0)
return simulateSand(grid, sandLocation)
}
val testInput = readInput("Day14_test")
val output = part1(testInput)
check(output == 24)
val outputTwo = part2(testInput)
check(outputTwo == 93)
val input = readInput("Day14")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 74f10b93d3bad72fa0fc276b503bfa9f01ac0e35 | 5,808 | aoc-kotlin | Apache License 2.0 |
src/main/kotlin/day9/Day9.kt | Mee42 | 433,459,856 | false | {"Kotlin": 42703, "Java": 824} | package dev.mee42.day9
import dev.mee42.*
val test = """
2199943210
3987894921
9856789892
8767896789
9899965678
""".trimIndent()
fun <T> T.println(name: String? = null): T {
if(name == null) println(this)
else System.out.println("$name: $this")
return this
}
fun main() {
val inputRaw = if(1 == 0) test.trim() else input(day = 9, year = 2021)
val input = Array2D.from(inputRaw.trim().split("\n").map { it.map(::id) })
.map { c -> "$c".toInt() }
// the size of a basin is trivial to find
fun sizeOfBasin(pos: Coords2D, filled: Array2D<Boolean>, captureAbove: Int): Int {
if(!filled.isInBound(pos)) return 0
val value = input[pos]
if(filled[pos] || value < captureAbove || value == 9) return 0
filled[pos] = true
return CARDINAL_OFFSETS.sumOf { off ->
sizeOfBasin(pos + off, filled, value)
} + 1
}
input.map { value, coords ->
for (off in CARDINAL_OFFSETS) {
val around = input.getOrNull(coords + off) ?: continue
if (around <= value) return@map null
}
return@map coords
}
.toList()
.filterNotNull()
.println("Lowest points")
.also { println("Part 1:" + it.sumOf { pos -> input[pos] }) }
.map { pos -> sizeOfBasin(pos, input.map { _ -> false }, 0) } // list of basin sizes
.sortedDescending()
.take(3)
.product()
.println("Solution")
} | 0 | Kotlin | 0 | 0 | db64748abc7ae6a92b4efa8ef864e9bb55a3b741 | 1,466 | aoc-2021 | MIT License |
src/Day09_part2.kt | jmorozov | 573,077,620 | false | {"Kotlin": 31919} | import kotlin.math.absoluteValue
fun main() {
val inputData = readInput("Day09")
part2(inputData)
}
private fun part2(inputData: List<String>) {
val visitedByTail = mutableSetOf<Point>()
val startPoint = Point.start()
var state = MutableList(ROPE_LENGTH) { _ -> startPoint }
for (line in inputData) {
val (direction, steps) = parseMovement(line) ?: continue
state = when (direction) {
"L" -> goLeft(state, visitedByTail, steps)
"R" -> goRight(state, visitedByTail, steps)
"U" -> goUp(state, visitedByTail, steps)
"D" -> goDown(state, visitedByTail, steps)
else -> state
}
println("STATE: $state")
}
println("Positions, which the tail of the rope visit at least once: ${visitedByTail.size}")
}
private const val ROPE_LENGTH = 10
private fun goLeft(rope: MutableList<Point>, visitedByTail: MutableSet<Point>, steps: Int): MutableList<Point> {
var currentState = rope
repeat(steps) {
val newState = mutableListOf<Point>()
var head = currentState.first().left()
newState.add(head)
for ((idx, tail) in currentState.withIndex()) {
if (idx == 0) continue
val newTail = if (idx == 1) goLeft(head, tail) else nextMove(head, tail)
newState.add(newTail)
head = newTail
}
currentState = newState
visitedByTail.add(newState.last())
}
return currentState
}
private fun goLeft(head: Point, tail: Point): Point {
if (noNeedHorizontalMoving(head, tail)) {
return tail
}
return if (head.y == tail.y) {
tail.left()
} else {
if (head.y > tail.y) {
tail.up().left()
} else {
tail.down().left()
}
}
}
private fun noNeedHorizontalMoving(head: Point, tail: Point): Boolean = (tail.x - head.x).absoluteValue <= 1
private fun goRight(rope: MutableList<Point>, visitedByTail: MutableSet<Point>, steps: Int): MutableList<Point> {
var currentState = rope
repeat(steps) {
val newState = mutableListOf<Point>()
var head = currentState.first().right()
newState.add(head)
for ((idx, tail) in currentState.withIndex()) {
if (idx == 0) continue
val newTail = if (idx == 1) goRight(head, tail) else nextMove(head, tail)
newState.add(newTail)
head = newTail
}
currentState = newState
visitedByTail.add(newState.last())
}
return currentState
}
private fun goRight(head: Point, tail: Point): Point {
if (noNeedHorizontalMoving(head, tail)) {
return tail
}
return if (head.y == tail.y) {
tail.right()
} else {
if (head.y > tail.y) {
tail.up().right()
} else {
tail.down().right()
}
}
}
private fun goUp(rope: MutableList<Point>, visitedByTail: MutableSet<Point>, steps: Int): MutableList<Point> {
var currentState = rope
repeat(steps) {
val newState = mutableListOf<Point>()
var head = currentState.first().up()
newState.add(head)
for ((idx, tail) in currentState.withIndex()) {
if (idx == 0) continue
val newTail = if (idx == 1) goUp(head, tail) else nextMove(head, tail)
newState.add(newTail)
head = newTail
}
currentState = newState
visitedByTail.add(newState.last())
}
return currentState
}
private fun goUp(head: Point, tail: Point): Point {
if (noNeedVerticalMoving(head, tail)) {
return tail
}
return if (head.x == tail.x) {
tail.up()
} else {
if (head.x > tail.x) {
tail.right().up()
} else {
tail.left().up()
}
}
}
private fun noNeedVerticalMoving(head: Point, tail: Point): Boolean = (tail.y - head.y).absoluteValue <= 1
private fun goDown(rope: MutableList<Point>, visitedByTail: MutableSet<Point>, steps: Int): MutableList<Point> {
var currentState = rope
repeat(steps) {
val newState = mutableListOf<Point>()
var head = currentState.first().down()
newState.add(head)
for ((idx, tail) in currentState.withIndex()) {
if (idx == 0) continue
val newTail = if (idx == 1) goDown(head, tail) else nextMove(head, tail)
newState.add(newTail)
head = newTail
}
currentState = newState
visitedByTail.add(newState.last())
}
return currentState
}
private fun goDown(head: Point, tail: Point): Point {
if ((tail.y - head.y).absoluteValue <= 1) {
return tail
}
return if (head.x == tail.x) {
tail.down()
} else {
if (head.x > tail.x) {
tail.right().down()
} else {
tail.left().down()
}
}
}
private fun nextMove(head: Point, tail: Point): Point {
return when {
tail.y - head.y > 1 -> goDown(head, tail)
head.y - tail.y > 1 -> goUp(head, tail)
head.x - tail.x > 1 -> goRight(head, tail)
tail.x - head.x > 1 -> goLeft(head, tail)
else -> tail
}
} | 0 | Kotlin | 0 | 0 | 480a98838949dbc7b5b7e84acf24f30db644f7b7 | 5,234 | aoc-2022-in-kotlin | Apache License 2.0 |
src/com/mrxyx/algorithm/LFU.kt | Mrxyx | 366,778,189 | false | null | package com.mrxyx.algorithm
class LFU (capacity: Int){
// key 到 val 的映射,我们后文称为 KV 表
private var keyToVal: HashMap<Int, Int> = HashMap()
// key 到 freq 的映射,我们后文称为 KF 表
private var keyToFreq: HashMap<Int, Int> = HashMap()
// freq 到 key 列表的映射,我们后文称为 FK 表
var freqToKeys: HashMap<Int, LinkedHashSet<Int>> = HashMap()
// 记录最小的频次
private var minFreq = 0
// 记录 LFU 缓存的最大容量
private var cap = 0
init{
cap = capacity
minFreq = 0
}
operator fun get(key: Int): Int {
if (!(keyToVal.containsKey(key))) {
return -1
}
// 增加 key 对应的 freq
increaseFreq(key)
return keyToVal[key]!!
}
fun put(key: Int, `val`: Int) {
if (cap <= 0) return
/* 若 key 已存在,修改对应的 val 即可 */
if (keyToVal.containsKey(key)) {
keyToVal[key] = `val`
// key 对应的 freq 加一
increaseFreq(key)
return
}
/* key 不存在,需要插入 */
/* 容量已满的话需要淘汰一个 freq 最小的 key */
if (cap <= keyToVal.size) {
removeMinFreqKey()
}
/* 插入 key 和 val,对应的 freq 为 1 */
// 插入 KV 表
keyToVal[key] = `val`
// 插入 KF 表
keyToFreq[key] = 1
// 插入 FK 表
freqToKeys.putIfAbsent(1, LinkedHashSet())
freqToKeys[1]!!.add(key)
// 插入新 key 后最小的 freq 肯定是 1
minFreq = 1
}
private fun removeMinFreqKey() {
// freq 最小的 key 列表
val keyList = freqToKeys[minFreq]
// 其中最先被插入的那个 key 就是该被淘汰的 key
val deletedKey = keyList!!.iterator().next()
/* 更新 FK 表 */
keyList.remove(deletedKey)
if (keyList.isEmpty()) {
freqToKeys.remove(minFreq)
}
/* 更新 KV 表 */
keyToVal.remove(deletedKey)
/* 更新 KF 表 */
keyToFreq.remove(deletedKey)
}
private fun increaseFreq(key: Int) {
val freq = keyToFreq[key]!!
/* 更新 KF 表 */keyToFreq[key] = freq + 1
/* 更新 FK 表 */
// 将 key 从 freq 对应的列表中删除
freqToKeys[freq]!!.remove(key)
// 将 key 加入 freq + 1 对应的列表中
freqToKeys.putIfAbsent(freq + 1, LinkedHashSet())
freqToKeys[freq + 1]!!.add(key)
// 如果 freq 对应的列表空了,移除这个 freq
if (freqToKeys[freq]!!.isEmpty()) {
freqToKeys.remove(freq)
// 如果这个 freq 恰好是 minFreq,更新 minFreq
if (freq == minFreq) {
minFreq++
}
}
}
} | 0 | Kotlin | 0 | 0 | b81b357440e3458bd065017d17d6f69320b025bf | 2,888 | algorithm-test | The Unlicense |
src/main/java/dev/haenara/mailprogramming/solution/y2020/m03/d29/Solution200329.kt | HaenaraShin | 226,032,186 | false | null | package dev.haenara.mailprogramming.solution.y2020.m03.d29
import dev.haenara.mailprogramming.solution.Solution
/**
* 매일프로그래밍 2020. 03. 29
* 순환 정수 배열이 주어졌을 때, 합이 최대가 되는 부분 배열을 구하시오.
*
* Input: [2, 1, -5, 4, -3, 1, -3, 4, -1]
* Output: 부분 배열 [4, -1, 2, 1], 합 6
* Input: [-3, 1, -3, 4, -1, 2, 1, -5, 4]
* Output: 부분 배열 [4, -1, 2, 1], 합 6
*
* 풀이 :
* 입력배열이 2번 반복되는 배열이라 가정하고 2월 9일 문제와 동일하게 풀 수 있다.
* 단 양수만 있을 경우 전체 배열의 길이를 넘어갈 수 있으므로 입력 길이보다 길면 자른다.
*/
class Solution200329 : Solution<Array<Int>, Array<Int>>{
override fun solution(input: Array<Int>): Array<Int> {
val doubleInput = intArrayOf(*input.toIntArray(), *input.toIntArray())
var biggestArrayList = arrayListOf<Int>()
var currentArrayList = arrayListOf<Int>()
var lastArrayList = arrayListOf<Int>()
var biggestSum = if (input.isNotEmpty()) { input[0] } else { 0 }
var lastSum = 0
var currentSum = 0
var isLastPositive = 0
doubleInput.forEach {
// 예외적으로 음수만 나오는 경우에는 개별로 최대값인지 비교한다.
if (biggestSum < 0 && it > biggestSum) {
biggestArrayList.add(it)
biggestSum = it
}
// 양수 또는 음수의 연속인지, 아니면 부호가 바뀐 것인지 비교한다.
// 이전까지의 값을 isLastPositive에 저장하고 현재 값과 곱하여 양수면 부호가 같고 음수면 부호가 다른 것이다.
if (isLastPositive * it >= 0) {
// 양수든 음수든 일단 연속된다면 임시 합계를 누적한다.
currentArrayList.add(it)
currentSum += it
} else {
// 부호가 바뀌었다면 양수였다가 음수로 나온건지, 음수였다가 양수가 나온건지 비교한다.
if (it < 0) {
// 양수였다가 음수가 된 경우
lastSum = currentSum // 앞으로 나올 음수의 합과 이전에 나왔던 양수의 합을 비교해야 하므로 일단 저장해둔다.
lastArrayList = currentArrayList.clone() as ArrayList<Int>
if (biggestSum < currentSum) { // 앞으로 양수가 안나올 수도 있으므로 현재시점에서 최대 합계보다 큰 양수의 합인지 비교한다.
biggestSum = currentSum
biggestArrayList = currentArrayList.clone() as ArrayList<Int>
}
currentSum = it // 앞으로 나올 음수 누적 합계를 위해 현재 합계를 갱신
currentArrayList.clear()
currentArrayList.add(it)
} else {
// 음수였다가 양수가 된 경우
if (currentSum + lastSum > 0) { // 이전 양수합계가 음수합계보다 크다면
currentSum += (lastSum + it) // 양수합계와 음수합계를 합쳐서 하나의 작은 양수로 취급하여 누적 계산을 이어간다.
lastArrayList.forEachIndexed { index, element ->
currentArrayList.add(index, element)
}
currentArrayList.add(it)
} else { // 이전 양수합계가 작아서 더이상 의미가 없다면
currentSum = it // 앞으로 새로운 양수 누적 합계를 위해 현재 합계를 갱신
currentArrayList = arrayListOf(it)
}
}
}
// 0인 경우는 부호 판단에서 생략한다.
if (it != 0) {
isLastPositive = it
}
}
val answser = if (currentSum < 0) { // 최종적으로 음수 합계로 끝난 경우는 비교할 필요가 없다.
biggestArrayList.toTypedArray()
} else if (biggestSum <= currentSum) { // 최종합계가 여태까지의 합계최댓값보다 크다면 갱신
currentArrayList.toTypedArray()
} else {
biggestArrayList.toTypedArray()
}
return if (answser.size > input.size) {
answser.copyOfRange(0, answser.size)
} else {
answser
}
}
} | 0 | Kotlin | 0 | 7 | b5e50907b8a7af5db2055a99461bff9cc0268293 | 4,576 | MailProgramming | MIT License |
common/geometry/src/main/kotlin/com/curtislb/adventofcode/common/geometry/Direction.kt | curtislb | 226,797,689 | false | {"Kotlin": 2146738} | package com.curtislb.adventofcode.common.geometry
import com.curtislb.adventofcode.common.collection.getCyclic
/**
* A valid direction in a two-dimensional grid.
*
* @property clockwiseIndex The index of the direction in clockwise order, starting with [UP].
*/
enum class Direction(private val clockwiseIndex: Int) {
/**
* The direction of positive y.
*/
UP(clockwiseIndex = 0),
/**
* The direction of positive x and y.
*/
UP_RIGHT(clockwiseIndex = 1),
/**
* The direction of positive x.
*/
RIGHT(clockwiseIndex = 2),
/**
* The direction of positive x and negative y.
*/
DOWN_RIGHT(clockwiseIndex = 3),
/**
* The direction of negative y.
*/
DOWN(clockwiseIndex = 4),
/**
* The direction of negative x and y.
*/
DOWN_LEFT(clockwiseIndex = 5),
/**
* The direction of negative x.
*/
LEFT(clockwiseIndex = 6),
/**
* The direction of negative x and positive y.
*/
UP_LEFT(clockwiseIndex = 7);
/**
* Returns `true` if the direction is horizontal.
*/
fun isHorizontal(): Boolean = this == RIGHT || this == LEFT
/**
* Returns `true` if the direction is vertical.
*/
fun isVertical(): Boolean = this == UP || this == DOWN
/**
* Returns `true` if the direction is diagonal.
*/
fun isDiagonal(): Boolean = when (this) {
UP, RIGHT, DOWN, LEFT -> false
UP_RIGHT, DOWN_RIGHT, DOWN_LEFT, UP_LEFT -> true
}
/**
* Returns the direction given by turning 180 degrees from this one.
*/
fun reverse(): Direction =
clockwiseOrder.getCyclic(clockwiseIndex + RotationAngle.DEGREES_180.turnCount)
/**
* Returns the direction given by turning a given [angle] counterclockwise from this one.
*/
fun turnLeft(angle: RotationAngle = RotationAngle.DEGREES_90): Direction =
clockwiseOrder.getCyclic(clockwiseIndex - angle.turnCount)
/**
* Returns the direction given by turning a given [angle] clockwise from this one.
*/
fun turnRight(angle: RotationAngle = RotationAngle.DEGREES_90): Direction =
clockwiseOrder.getCyclic(clockwiseIndex + angle.turnCount)
companion object {
/**
* A list of all directions in clockwise order, starting with [UP].
*/
private val clockwiseOrder: List<Direction> = entries.sortedBy { it.clockwiseIndex }
/**
* Returns an array of all cardinal directions.
*/
fun cardinalValues(): Array<Direction> = arrayOf(UP, RIGHT, DOWN, LEFT)
/**
* Returns the cardinal direction corresponding to [char].
*
* @throws IllegalArgumentException If [char] has no corresponding direction.
*/
fun fromChar(char: Char): Direction = when (char) {
'U', 'u' -> UP
'R', 'r' -> RIGHT
'D', 'd' -> DOWN
'L', 'l' -> LEFT
else -> throw IllegalArgumentException("No direction for char: $char")
}
}
}
| 0 | Kotlin | 1 | 1 | 6b64c9eb181fab97bc518ac78e14cd586d64499e | 3,084 | AdventOfCode | MIT License |
client/PathFinder/app/src/main/java/com/dijkstra/pathfinder/util/KalmanFilter3D.kt | PathFinder-SSAFY | 643,691,193 | false | null | package com.dijkstra.pathfinder.util
class KalmanFilter3D(
initialState: List<Double>,
initialCovariance: List<List<Double>>
) {
private var state = initialState
private var covariance = initialCovariance
private val processNoise = listOf(
listOf(0.1, 0.0, 0.0),
listOf(0.0, 0.1, 0.0),
listOf(0.0, 0.0, 0.1)
)
fun update(measurement: List<Double>, measurementNoise: List<Double>): List<Double> {
val kalmanGain = calculateKalmanGain(measurementNoise)
val innovation = measurement.zip(state) { m, s -> m - s }
state = state.zip(
kalmanGain.map { row ->
row.zip(innovation) { x, y ->
x * y
}.sum()
}
).map { it.first + it.second }
covariance = updateCovariance(kalmanGain)
return state
}
private fun calculateKalmanGain(measurementNoise: List<Double>): List<List<Double>> {
val sum = covariance.zip(processNoise) { a, b -> a.zip(b) { x, y -> x + y } }
val sumDiagonal = sum.indices.map { sum[it][it] }
val noisePlusSumDiagonal = measurementNoise.zip(sumDiagonal) { x, y -> x + y }
return covariance.map { row -> row.zip(noisePlusSumDiagonal) { x, y -> x / y } }
}
private fun updateCovariance(kalmanGain: List<List<Double>>): List<List<Double>> {
val gainTimesCovariance =
kalmanGain.map { row -> row.zip(covariance) { x, col -> x * col.sum() } }
val identityMinusGain = gainTimesCovariance.indices.map { i ->
gainTimesCovariance[i].mapIndexed { j, value -> if (i == j) 1.0 - value else -value }
}
return identityMinusGain.map { row -> row.zip(covariance) { x, col -> x * col.sum() } }
}
}
| 1 | Kotlin | 3 | 1 | 57e9a94594ff2e3561e62b6c5c9db63cfa4ef203 | 1,777 | PathFinder | Apache License 2.0 |
2021/src/main/kotlin/aoc2021/day14/Day14.kt | dkhawk | 433,915,140 | false | {"Kotlin": 170350} | package aoc2021.day14
import kotlin.system.measureTimeMillis
import utils.Input
@OptIn(ExperimentalStdlibApi::class)
class Day14 {
companion object {
fun run() {
val time1 = measureTimeMillis {
Day14().part1()
}
println("millis: $time1")
measureTimeMillis {
Day14().part2()
}.also {
println("millis: $it")
}
}
}
val sample = """
NNCB
CH -> B
HH -> N
CB -> H
NH -> C
HB -> C
HC -> B
HN -> C
NN -> C
BH -> H
NC -> B
NB -> B
BN -> B
BB -> N
BC -> B
CC -> N
CN -> C""".trimIndent().split("\n").filter { it.isNotBlank() }
private fun getInput(useRealInput: Boolean): Pair<String, Map<String, String>> {
val input = if (useRealInput) {
Input.readAsLines("14")
} else {
sample
}
val template = input.take(1).first()
val rules = input.drop(1).map { line ->
line.split(" -> ").let {
it.first() to it.last()
}
}.toMap()
return template to rules
}
private fun part1() {
val (template, rules) = getInput(useRealInput = true)
var poly = template
repeat(10) {
poly = poly.windowed(2, 1) { pair ->
pair.first() + rules[pair]!!
}.joinToString("") + template.last()
}
val counts = poly.groupingBy { it }.eachCount()
val answer = counts.maxOf { it.value }.toLong() - counts.minOf { it.value }.toLong()
println(answer)
}
private fun part2() {
val (template, rules) = getInput(useRealInput = true)
var counts = rules.keys.map { it to 0L }.toMap().toMutableMap()
template.windowed(2, 1) { pair ->
val key = pair.toString()
counts[key] = counts.getOrDefault(key, 0) + 1
}
repeat(40) {
val newCounts = mutableMapOf<String, Long>()
counts.keys.map { key ->
val c = rules[key]!!
val v = counts[key]!!
val key1 = key.first() + c
newCounts[key1] = newCounts.getOrDefault(key1, 0) + v
val key2 = c + key.last()
newCounts[key2] = newCounts.getOrDefault(key2, 0) + v
}
counts = newCounts
}
val elementCounts = mutableMapOf<Char, Long>()
counts.forEach { (t, u) ->
elementCounts[t.first()] = elementCounts.getOrDefault(t.first(), 0) + u
elementCounts[t.last()] = elementCounts.getOrDefault(t.last(), 0) + u
}
elementCounts[template.last()] = elementCounts.getOrDefault(template.last(), 0) + 1
val sorted = elementCounts.toList().sortedBy { it.second }
val answer = sorted.last().second / 2 - sorted.first().second / 2
println(answer)
}
}
| 0 | Kotlin | 0 | 0 | 64870a6a42038acc777bee375110d2374e35d567 | 2,647 | advent-of-code | MIT License |
aoc-2017/src/main/kotlin/nl/jstege/adventofcode/aoc2017/days/Day15.kt | JStege1206 | 92,714,900 | false | null | package nl.jstege.adventofcode.aoc2017.days
import nl.jstege.adventofcode.aoccommon.days.Day
/**
*
* @author <NAME>
*/
class Day15 : Day(title = "Dueling Generators") {
private companion object Configuration {
private const val MASK = 0xFFFFL
private const val DIVISOR = 2147483647
private const val FACTOR_A = 16807L
private const val FACTOR_B = 48271L
private const val FIRST_ITERATIONS = 40_000_000
private const val SECOND_ITERATIONS = 5_000_000
private const val SECOND_MULTIPLES_A = 4L
private const val SECOND_MULTIPLES_B = 8L
}
override fun first(input: Sequence<String>): Any {
return input
.map { it.split(" ") }
.map { (_, _, _, _, init) -> init.toLong() }
.toList()
.let { (a, b) -> Generator(a, FACTOR_A) to Generator(b, FACTOR_B) }
.let { (a, b) ->
(0 until FIRST_ITERATIONS).count { a.next() and MASK == b.next() and MASK }
}
}
override fun second(input: Sequence<String>): Any {
return input
.map { it.split(" ") }
.map { (_, _, _, _, init) -> init.toLong() }
.toList()
.let { (a, b) -> Generator(a, FACTOR_A) to Generator(b, FACTOR_B) }
.let { (a, b) ->
(0 until SECOND_ITERATIONS).count {
a.next(SECOND_MULTIPLES_A) and MASK == b.next(SECOND_MULTIPLES_B) and MASK
}
}
}
private class Generator(init: Long, val factor: Long) {
var current = init
fun next(multiples: Long = 1): Long {
do {
current = (current * factor % DIVISOR)
} while (current % multiples != 0L)
return current
}
}
}
| 0 | Kotlin | 0 | 0 | d48f7f98c4c5c59e2a2dfff42a68ac2a78b1e025 | 1,819 | AdventOfCode | MIT License |
src/main/kotlin/utils/Math.kt | sssemil | 268,084,789 | false | null | package utils
val fastLookupFactorial = hashMapOf<Long, Long>()
fun factorialNaive(n: Long): Long {
if (n <= 1) return 1
return n * factorialNaive(n - 1)
}
fun factorialDynamic(n: Long): Long {
if (n <= 1) return 1
if (!fastLookupFactorial.containsKey(n)) {
fastLookupFactorial[n] = n * factorialDynamic(n - 1)
}
return fastLookupFactorial[n]!!
}
fun factorial(n: Long): Rational = Rational(factorialDynamic(n), 1)
// broken for large values
fun binom0(n: Long, k: Long): Rational {
check(k in 0..n && n >= 0)
if ((n == k) || (k == 0L)) return Rational(1, 1)
return Rational(factorial(n), (factorial(k) * factorial(n - k)))
}
fun binom1(n: Long, k: Long): Rational {
check(k in 0..n && n >= 0)
if ((n == k) || (k == 0L)) return Rational(1, 1)
return binom1(n - 1, k - 1) + binom1(n - 1, k)
}
fun binom(n: Long, k: Long) = binom1(n, k)
/**
* Partial derangements.
*
* [https://en.wikipedia.org/wiki/Rencontres_numbers]
*
*/
fun rencontresNumber(n: Long, m: Long): Rational {
val a = Rational(factorial(n), factorial(m))
val sum = (0..n - m).map { k ->
if (k % 2 == 0L) {
Rational(1, factorial(k))
} else {
Rational(-1, factorial(k))
}
}.sum()
return a*sum
} | 0 | Kotlin | 0 | 0 | 02d951b90e0225bb1fa36f706b19deee827e0d89 | 1,289 | math_playground | MIT License |
src/main/kotlin/kt/kotlinalgs/app/sorting/KMessedArraySort.ws.kts | sjaindl | 384,471,324 | false | null | // https://www.pramp.com/challenge/XdMZJgZoAnFXqwjJwnBZ
// https://www.bezkoder.com/kotlin-priority-queue/
package kt.kotlinalgs.app.sorting
import java.util.*
println("test")
val sorted = sortKMessesArray(
intArrayOf(1, 4, 5, 2, 3, 7, 8, 6, 10, 9), 2
)
val minComparator: Comparator<Int> = compareBy<Int> {
it
}//.reversed()
val maxComparator: Comparator<Int> = compareBy<Int> {
-it
}//.reversed()
val minSorted = intArrayOf(1, 4, 5, 2, 3, 7, 8, 6, 10, 9).sortedWith(minComparator)
minSorted.forEach {
println(it)
}
val maxSorted = intArrayOf(1, 4, 5, 2, 3, 7, 8, 6, 10, 9).sortedWith(maxComparator)
maxSorted.forEach {
println(it)
}
sorted.forEach {
println(it)
}
class MinIntComparator : Comparator<Int> {
override fun compare(p0: Int, p1: Int): Int {
return p0 - p1
}
}
class MaxIntComparator : Comparator<Int> {
override fun compare(p0: Int, p1: Int): Int {
return p0 - p1
}
}
fun sortKMessesArray(array: IntArray, k: Int): IntArray {
//val array = array2.reversedArray()
if (array.isEmpty() || k <= 0 || k >= array.size) return array
val output = IntArray(array.size) { 0 }
var outputIndex = 0
val comparator: Comparator<Int> = compareBy<Int> {
it
}.reversed()
//val pq = PriorityQueue<Int>(8, comparator)
//val pq = PriorityQueue<Int>()
//val pq = PriorityQueue<Int>(11, MaxIntComparator().reversed())
val pq = PriorityQueue<Int>(11, MinIntComparator())
for (num in 0 until k + 1) {
pq.add(array.get(num))
}
for (index in k + 1 until array.size) {
val min = pq.poll()
output[outputIndex] = min
outputIndex++
pq.add(array[index])
}
while (!pq.isEmpty()) {
val min = pq.poll()
output[outputIndex] = min
outputIndex++
}
return output
} | 0 | Java | 0 | 0 | e7ae2fcd1ce8dffabecfedb893cb04ccd9bf8ba0 | 1,857 | KotlinAlgs | MIT License |
src/aoc2022/Day10.kt | anitakar | 576,901,981 | false | {"Kotlin": 124382} | package aoc2022
import println
import readInput
fun main() {
fun part1(input: List<String>): Int {
var s20: Int? = null
var s60: Int? = null
var s100: Int? = null
var s140: Int? = null
var s180: Int? = null
var s220: Int? = null
var curCycle = 1
var register = 1
for (line in input) {
var toAdd = 0
if (line == "noop") {
curCycle += 1
} else {
toAdd = line.substring(5).toInt()
curCycle += 2
}
if (curCycle == 20) {
register += toAdd
s20 = 20 * register
} else if (curCycle == 21) {
s20 = 20 * register
register += toAdd
} else if (curCycle == 60) {
register += toAdd
s60 = 60 * register
} else if (curCycle == 61) {
s60 = 60 * register
register += toAdd
} else if (curCycle == 100) {
register += toAdd
s100 = 100 * register
} else if (curCycle == 101) {
s100 = 100 * register
register += toAdd
} else if (curCycle == 140) {
register += toAdd
s140 = 140 * register
} else if (curCycle == 141) {
s140 = 140 * register
register += toAdd
} else if (curCycle == 180) {
register += toAdd
s180 = 180 * register
} else if (curCycle == 181) {
s180 = 180 * register
register += toAdd
} else if (curCycle == 220) {
register += toAdd
s220 = 220 * register
} else if (curCycle == 221) {
s220 = 220 * register
register += toAdd
} else {
register += toAdd
}
}
return s20!! + s60!! + s100!! + s140!! + s180!! + s220!!
}
fun part2(input: List<String>): Array<CharArray> {
val matrix = Array(6) { CharArray(40) }
val sprite = mutableSetOf(0, 1, 2)
var curCycle = 0
var register = 1
for (line in input) {
var toAdd = 0
if (line == "noop") {
if (sprite.contains(curCycle % 40)) {
matrix[curCycle / 40][curCycle % 40] = '#'
} else {
matrix[curCycle / 40][curCycle % 40] = '.'
}
curCycle += 1
} else {
toAdd = line.substring(5).toInt()
if (sprite.contains(curCycle % 40)) {
matrix[curCycle / 40][curCycle % 40] = '#'
} else {
matrix[curCycle / 40][curCycle % 40] = '.'
}
curCycle += 1
if (sprite.contains(curCycle % 40)) {
matrix[curCycle / 40][curCycle % 40] = '#'
} else {
matrix[curCycle / 40][curCycle % 40] = '.'
}
curCycle += 1
register += toAdd
sprite.clear()
sprite.add(register - 1);
sprite.add(register);
sprite.add(register + 1);
}
}
return matrix
}
fun printMatrix(matrix: Array<CharArray>) {
for (line in matrix) {
println(String(line))
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day10_test")
check(part1(testInput) == 13140)
printMatrix(part2(testInput))
val input = readInput("Day10")
part1(input).println()
printMatrix(part2(input))
}
| 0 | Kotlin | 0 | 1 | 50998a75d9582d4f5a77b829a9e5d4b88f4f2fcf | 3,842 | advent-of-code-kotlin | Apache License 2.0 |
2020/src/main/kotlin/sh/weller/adventofcode/twentytwenty/Day2.kt | Guruth | 328,467,380 | false | {"Kotlin": 188298, "Rust": 13289, "Elixir": 1833} | package sh.weller.adventofcode.twentytwenty
fun List<String>.validatePasswords(validationType: ValidationType): Int =
this.map {
val criteria = it.getCriteria()
val password = it.getPassword()
return@map when (validationType) {
ValidationType.COUNT -> password.validateByCount(criteria)
ValidationType.POSITION -> password.validateByPosition(criteria)
}
}.count { it }
enum class ValidationType {
COUNT, POSITION
}
private fun String.getCriteria(): Triple<Int, Int, Char> {
val criteriaPart = this.substringBefore(':', "")
val lowerBound = criteriaPart.substringBefore('-', "").toInt()
val upperBound = criteriaPart.substringAfter('-', "").substringBefore(" ", "").toInt()
val validationChar = criteriaPart.substringAfter(' ', "").first()
assert(lowerBound > 0) { "lowerBound not valid" }
assert(upperBound > 0 && upperBound >= lowerBound) { "upperBound not valid" }
assert(validationChar.isLetter()) { "validationChar not valid" }
return Triple(lowerBound, upperBound, validationChar)
}
private fun String.getPassword(): String {
val password = this.substringAfter(':', "")
assert(password.isNotBlank()) { "password not valid" }
return password
}
private fun String.validateByCount(criteria: Triple<Int, Int, Char>): Boolean {
val groupedChars = this.groupBy { it }
val numOfCriteriaChar = groupedChars[criteria.third]?.count()
return numOfCriteriaChar != null && numOfCriteriaChar >= criteria.first && numOfCriteriaChar <= criteria.second
}
private fun String.validateByPosition(criteria: Triple<Int, Int, Char>): Boolean {
return !((this[criteria.first] == criteria.third) && (this[criteria.second] == criteria.third)) && ((this[criteria.first] == criteria.third) || (this[criteria.second] == criteria.third))
} | 0 | Kotlin | 0 | 0 | 69ac07025ce520cdf285b0faa5131ee5962bd69b | 1,851 | AdventOfCode | MIT License |
src/y2022/Day05.kt | Yg0R2 | 433,731,745 | false | null | package y2022
import DayX
import y2022.Day05.Procedure.Companion.getRearrangementProcedure
import y2022.Day05.Stack.Companion.getInitialStack
class Day05 : DayX<String>("CMZ", "MCD") {
override fun part1(input: List<String>): String {
val stack = input.getInitialStack()
val rearrangementProcedure = input.getRearrangementProcedure()
rearrangementProcedure.forEach {
stack.rearrangeOneCraterAtOnce(it)
}
return stack.getLastCrates()
.joinToString("")
}
override fun part2(input: List<String>): String {
val stack = input.getInitialStack()
val rearrangementProcedure = input.getRearrangementProcedure()
rearrangementProcedure.forEach {
stack.rearrangeMultipleCraterAtOnce(it)
}
return stack.getLastCrates()
.joinToString("")
}
private class Procedure(
line: String
) {
val amount: Int
val from: Int
val to: Int
init {
line.replace(PROCEDURE_REGEX, "\$1$DELIMITER\$2$DELIMITER\$3")
.split(DELIMITER)
.let {
amount = it[0].toInt()
from = it[1].toInt()
to = it[2].toInt()
}
}
override fun toString(): String =
"move $amount from $from to $to"
companion object {
private const val DELIMITER = " "
private val PROCEDURE_REGEX = Regex("move ([0-9]+) from ([0-9]+) to ([0-9]+)")
fun List<String>.getRearrangementProcedure(): List<Procedure> =
subList(indexOfFirst { it.isEmpty() } + 1, size)
.map { Procedure(it) }
}
}
private class Stack(
stackInput: List<List<String>>,
) {
private val stackMap: MutableMap<Int, MutableList<Char>> = mutableMapOf()
init {
for (row: Int in stackInput.size - 1 downTo 0) {
for (column: Int in 0 until stackInput[row].size) {
if (stackMap[column] == null) {
stackMap[column] = mutableListOf()
}
with(stackInput[row][column].elementAt(1)) {
if (this != ' ') {
stackMap[column]!!.add(this)
}
}
}
}
}
fun getLastCrates(): List<Char> =
stackMap.values
.map { it.last() }
fun rearrangeMultipleCraterAtOnce(procedure: Procedure) {
stackMap[procedure.from - 1]!!
.removeLast(procedure.amount)
.let { stackMap[procedure.to - 1]!!.addAll(it) }
}
fun rearrangeOneCraterAtOnce(procedure: Procedure) {
stackMap[procedure.from - 1]!!
.removeLast(procedure.amount)
.asReversed()
.let { stackMap[procedure.to - 1]!!.addAll(it) }
}
override fun toString(): String = stackMap.toString()
companion object {
fun List<String>.getInitialStack(): Stack =
take(indexOfFirst { it.isEmpty() } - 1)
.map { it.windowed(3, 4) }
.let { Stack(it) }
private fun <T> MutableList<T>.removeLast(n: Int): List<T> {
val elements = takeLast(n)
repeat(n) {
this.removeLastOrNull()
}
return elements
.toMutableList()
}
}
}
}
| 0 | Kotlin | 0 | 0 | d88df7529665b65617334d84b87762bd3ead1323 | 3,644 | advent-of-code | Apache License 2.0 |
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[1018]可被 5 整除的二进制前缀.kt | maoqitian | 175,940,000 | false | {"Kotlin": 354268, "Java": 297740, "C++": 634} | //给定由若干 0 和 1 组成的数组 A。我们定义 N_i:从 A[0] 到 A[i] 的第 i 个子数组被解释为一个二进制数(从最高有效位到最低有效位)。
//
//
// 返回布尔值列表 answer,只有当 N_i 可以被 5 整除时,答案 answer[i] 为 true,否则为 false。
//
//
//
// 示例 1:
//
// 输入:[0,1,1]
//输出:[true,false,false]
//解释:
//输入数字为 0, 01, 011;也就是十进制中的 0, 1, 3 。只有第一个数可以被 5 整除,因此 answer[0] 为真。
//
//
// 示例 2:
//
// 输入:[1,1,1]
//输出:[false,false,false]
//
//
// 示例 3:
//
// 输入:[0,1,1,1,1,1]
//输出:[true,false,false,false,true,false]
//
//
// 示例 4:
//
// 输入:[1,1,1,0,1]
//输出:[false,false,false,false,false]
//
//
//
//
// 提示:
//
//
// 1 <= A.length <= 30000
// A[i] 为 0 或 1
//
// Related Topics 数组
// 👍 99 👎 0
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
fun prefixesDivBy5(A: IntArray): BooleanArray {
//只要获取个位数 看是否符合 5 的取余
//时间复杂度 O(n)
var res = BooleanArray(A.size)
var num = 0
for ((index,value) in A.withIndex()){
num = num shl 1
num += value
num %= 10
res[index] = num % 5 == 0
}
return res
}
}
//leetcode submit region end(Prohibit modification and deletion)
| 0 | Kotlin | 0 | 1 | 8a85996352a88bb9a8a6a2712dce3eac2e1c3463 | 1,482 | MyLeetCode | Apache License 2.0 |
src/main/kotlin/mkuhn/aoc/util/Utils.kt | mtkuhn | 572,236,871 | false | {"Kotlin": 53161} | package mkuhn.aoc.util
import java.io.File
fun readInput(name: String) = File("src/main/resources/", "$name.txt")
.readLines()
fun readTestInput(name: String) = File("src/test/resources/", "$name.txt")
.readLines()
fun String.splitToPair(separator: Char) = this.substringBefore(separator) to this.substringAfter(separator)
fun <T> List<T>.splitList(separator: T): List<List<T>> =
this.fold(mutableListOf(mutableListOf<T>())) { acc, a ->
if (a == separator) acc += mutableListOf<T>()
else acc.last() += a
acc
}
fun <T> Collection<Collection<T>>.intersectAll(): Set<T> =
this.fold(this.first().toSet()) { acc, e -> acc intersect e.toSet() }
fun <T> List<List<T>>.transpose(filterCondition: (T) -> Boolean = { true }): MutableList<MutableList<T>> =
mutableListOf<MutableList<T>>().apply {
repeat(this@transpose.first().size) { this += mutableListOf<T>() }
this@transpose.forEach { r ->
r.forEachIndexed { i, c ->
if(filterCondition(c)) { this[i] += c }
}
}
}
inline fun <T> Iterable<T>.takeWhileInclusive(predicate: (T) -> Boolean): List<T> {
val list = ArrayList<T>()
for (item in this) {
list.add(item)
if (!predicate(item))
break
}
return list
}
fun Int.progressBetween(i: Int) = IntProgression.fromClosedRange(this, i, if(this > i) -1 else 1)
//stolen shamelessly from Todd
infix fun IntRange.fullyOverlaps(other: IntRange): Boolean =
first <= other.first && last >= other.last
infix fun IntRange.overlaps(other: IntRange): Boolean =
first <= other.last && other.first <= last
infix fun LongRange.fullyOverlaps(other: LongRange): Boolean =
first <= other.first && last >= other.last
infix fun LongRange.overlaps(other: LongRange): Boolean =
first <= other.last && other.first <= last
| 0 | Kotlin | 0 | 1 | 89138e33bb269f8e0ef99a4be2c029065b69bc5c | 1,874 | advent-of-code-2022 | Apache License 2.0 |
the-ray-tracer-challenge/src/main/kotlin/io/github/ocirne/ray/challenge/tuples/Tuple.kt | ocirne | 379,563,605 | false | null | package io.github.ocirne.ray.challenge.tuples
import kotlin.math.sqrt
import io.github.ocirne.ray.challenge.math.equalsDelta
open class Tuple(val x: Double, val y: Double, val z: Double, val w: Double) {
constructor(x: Int, y: Int, z: Int, w: Int) : this(x.toDouble(), y.toDouble(), z.toDouble(), w.toDouble())
fun isPoint(): Boolean {
return w.equalsDelta(1.0)
}
fun isVector(): Boolean {
return w.equalsDelta(0.0)
}
fun ensureVector(): Vector {
return Tuple(x, y, z, 0.0)
}
override fun toString(): String {
return "tuple[$x $y $z $w]"
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other?.javaClass != javaClass) return false
other as Tuple
return x.equalsDelta(other.x) &&
y.equalsDelta(other.y) &&
z.equalsDelta(other.z) &&
w.equalsDelta(other.w)
}
operator fun plus(t: Tuple): Tuple {
return Tuple(x + t.x, y + t.y, z + t.z, w + t.w)
}
operator fun minus(t: Tuple): Tuple {
return Tuple(x - t.x, y - t.y, z - t.z, w - t.w)
}
operator fun unaryMinus(): Tuple {
return Tuple(-x, -y, -z, -w)
}
operator fun times(s: Double): Tuple {
return Tuple(x * s, y * s, z * s, w * s)
}
operator fun times(s: Int): Tuple {
return this * s.toDouble()
}
operator fun div(s: Double): Tuple {
return Tuple(x / s, y / s, z / s, w / s)
}
operator fun div(s: Int): Tuple {
return this / s.toDouble()
}
fun magnitude(): Double {
return sqrt(x * x + y * y + z * z + w * w)
}
fun normalize(): Tuple {
return Tuple(x, y, z, w) / magnitude()
}
fun dot(b: Tuple): Double {
return x * b.x + y * b.y + z * b.z + w * b.w
}
fun cross(b: Tuple): Tuple {
return vector(
y * b.z - z * b.y,
z * b.x - x * b.z,
x * b.y - y * b.x
)
}
fun reflect(normal: Tuple): Tuple {
return this - normal * 2 * dot(normal)
}
}
fun point(x: Double, y: Double, z: Double): Tuple {
return Tuple(x, y, z, 1.0)
}
fun point(x: Int, y: Int, z: Int): Tuple {
return Tuple(x, y, z, 1)
}
fun vector(x: Double, y: Double, z: Double): Tuple {
return Tuple(x, y, z, 0.0)
}
fun vector(x: Int, y: Int, z: Int): Tuple {
return Tuple(x, y, z, 0)
}
typealias Point = Tuple
typealias Vector = Tuple
| 0 | Kotlin | 0 | 0 | 5075b417be18fd07f61f5182e0381fd283319c66 | 2,503 | ray | The Unlicense |
src/main/kotlin/util/Cell.kt | vovarova | 726,012,901 | false | {"Kotlin": 48551} | package util
import java.util.stream.IntStream
data class Cell(val row: Int, val column: Int) {
fun down(): Cell = Cell(row + 1, column)
fun up(): Cell = Cell(row - 1, column)
fun left(): Cell = Cell(row, column - 1)
fun right(): Cell = Cell(row, column + 1)
fun toPair() = Pair(row, column)
}
interface GridConfig<T> {
fun valid(cell: Cell): Boolean
fun value(cell: Cell): T
fun addValue(cell: Cell, value: T)
}
data class GridCell<T>(val cell: Cell, private val config: GridConfig<T>) {
var value
get() = config.value(cell)
set(value) = config.addValue(cell, value)
fun up(): GridCell<T> = GridCell(cell.up(), config)
fun down(): GridCell<T> = GridCell(cell.down(), config)
fun left(): GridCell<T> = GridCell(cell.left(), config)
fun right(): GridCell<T> = GridCell(cell.right(), config)
fun valid(): Boolean = config.valid(cell)
fun straightNeighbours(): List<GridCell<T>> = listOf(up(), down(), left(), right()).filter { it.valid() }
fun diagonalNeighbours(): List<GridCell<T>> =
listOf(up().left(), up().right(), down().right(), down().left()).filter { it.valid() }
fun neighbours(): List<GridCell<T>> = straightNeighbours() + diagonalNeighbours()
override fun toString(): String {
return "(row:${cell.row},column:${cell.column},value:${value})"
}
}
class Matrix<T>(val matrixGrid: Array<Array<T>>) : Iterable<GridCell<T>> {
inner class Config : GridConfig<T> {
override fun valid(cell: Cell): Boolean {
return cell.row >= 0
&& cell.row < matrixGrid.size
&& cell.column >= 0
&& cell.column < matrixGrid[0].size
}
override fun value(cell: Cell): T {
return matrixGrid[cell.row][cell.column]
}
override fun addValue(cell: Cell, value: T) {
matrixGrid[cell.row][cell.column] = value
}
}
private val config = Config()
fun cell(row: Int, column: Int): GridCell<T> = GridCell(Cell(row, column), config)
override fun iterator(): Iterator<GridCell<T>> {
return IntStream.range(0, matrixGrid.size).mapToObj { i -> i }.flatMap { row ->
IntStream.range(0, matrixGrid[0].size).mapToObj { column ->
GridCell(Cell(row, column), config)
}
}.iterator()
}
fun column(column: Int): List<GridCell<T>> {
return IntStream.range(0, matrixGrid.size).mapToObj { i -> i }.map { row ->
GridCell(Cell(row, column), config)
}.toList()
}
fun firstRow(): List<GridCell<T>> {
return row(0)
}
fun lastRow(): List<GridCell<T>> {
return row(matrixGrid.size - 1)
}
fun firstColumn(): List<GridCell<T>> {
return column(0)
}
fun lastColumn(): List<GridCell<T>> {
return column(matrixGrid[0].size - 1)
}
fun rows(): List<List<GridCell<T>>> {
return IntStream.range(0, matrixGrid.size).mapToObj { row(it) }.toList()
}
fun columns(): List<List<GridCell<T>>> {
return IntStream.range(0, matrixGrid[0].size).mapToObj { column(it) }.toList()
}
fun row(row: Int): List<GridCell<T>> {
return IntStream.range(0, matrixGrid[0].size).mapToObj { i -> i }.map { column ->
GridCell(Cell(row, column), config)
}.toList()
}
companion object {
inline fun <reified T> fromList(value: List<List<T>>): Matrix<T> {
return Matrix(value.map { it.toTypedArray() }.toTypedArray())
}
}
} | 0 | Kotlin | 0 | 0 | 77df1de2a663def33b6f261c87238c17bbf0c1c3 | 3,593 | adventofcode_2023 | Creative Commons Zero v1.0 Universal |
src/main/kotlin/days/Day15.kt | andilau | 429,206,599 | false | {"Kotlin": 113274} | package days
import days.Day15.Block.*
import days.Point.Companion.ORIGIN
@AdventOfCodePuzzle(
name = "Oxygen System",
url = "https://adventofcode.com/2019/day/15",
date = Date(day = 15, year = 2019)
)
class Day15(input: LongArray) : Puzzle {
private val computer = CompleteIntCodeComputer(input)
private val map = mutableMapOf(ORIGIN to SPACE).exploreMap()
private val locationOxygen = map.entries.first { it.value == OXYGEN }.key
init {
map.mapAsString(WALL, Block::symbol)
// .also { println(it) }
}
override fun partOne(): Int = map
.allowedLocations()
.findPath(ORIGIN, locationOxygen)
.lastIndex
override fun partTwo(): Int = map
.allowedLocations()
.findPath(locationOxygen)
.lastIndex
private fun Map<Point, Block>.allowedLocations() =
mapValues {
when (it.value) {
WALL -> false
SPACE, OXYGEN, HERE -> true
}
}
private fun MutableMap<Point, Block>.exploreMap(here: Point = ORIGIN): MutableMap<Point, Block> {
here.neighbors()
.filter { it !in this }
.forEach { to ->
val direction = direction(to - here)
val statusCode = computer.process(direction)
val block = Block.from(statusCode)
this[to] = block
when (block) {
SPACE, OXYGEN -> {
exploreMap(to)
// go back
val back = direction(here - to)
computer.process(back)
}
else -> {}
}
}
return this
}
enum class Block(val id: Int, val symbol: Char) {
WALL(0, '#'),
SPACE(1, ' '),
OXYGEN(2, 'O'),
HERE(3, 'X');
companion object {
fun from(id: Int) = values()
.firstOrNull { it.id == id }
?: error("Invalid block id: $id")
}
}
private fun CompleteIntCodeComputer.process(direction: Int): Int {
input = direction.toLong()
run()
return output.toInt()
}
// north (1), south (2), west (3), and east (4)
private fun direction(movement: Point): Int =
when (movement) {
ORIGIN.up() -> 1
ORIGIN.down() -> 2
ORIGIN.left() -> 3
ORIGIN.right() -> 4
else -> throw IllegalArgumentException("Unknown direction: $movement")
}
} | 2 | Kotlin | 0 | 0 | f51493490f9a0f5650d46bd6083a50d701ed1eb1 | 2,588 | advent-of-code-2019 | Creative Commons Zero v1.0 Universal |
challenges/hacker-rank/kotlin/src/main/kotlin/com/raphaelnegrisoli/hackerrank/sorting/MergeSortCountingInversions.kt | rbatista | 36,197,840 | false | {"Scala": 34929, "Kotlin": 23388} | /**
* https://www.hackerrank.com/challenges/ctci-merge-sort/
*/
package com.raphaelnegrisoli.hackerrank.sorting
import java.lang.StringBuilder
fun countInversions(arr: Array<Int>): Long {
return mergeSort(arr, Array(arr.size) { 0 }, 0, arr.size - 1)
}
fun mergeSort(arr: Array<Int>, temp: Array<Int>, begin: Int, endIncluded: Int): Long {
if (begin >= endIncluded) {
return 0
}
val middle = (begin + endIncluded) / 2
var swaps = mergeSort(arr, temp, begin, middle)
swaps += mergeSort(arr, temp, middle + 1, endIncluded)
return swaps + mergeHalves(arr, temp, begin, endIncluded)
}
fun mergeHalves(arr: Array<Int>, temp: Array<Int>, begin: Int, endIncluded: Int): Long {
val middle = (begin + endIncluded) / 2
var left = begin
var right = middle + 1
var index = begin
var swaps = 0L
while (left <= middle && right <= endIncluded) {
if (arr[left] <= arr[right]) {
temp[index] = arr[left]
left++
} else {
temp[index] = arr[right]
swaps += right - index
right++
}
index++
}
while (left <= middle) {
temp[index++] = arr[left++]
}
while (right <= endIncluded) {
temp[index++] = arr[right++]
}
System.arraycopy(temp, begin, arr, begin, endIncluded - begin + 1)
return swaps
}
fun main(args: Array<String>) {
val datasets = readLine()!!.trim().toInt()
val out = StringBuilder()
for (i in 0 until datasets) {
val elements = readLine()!!.trim().toInt()
val arr = readLine()!!.trim().split(" ").map { it.toInt() }.toTypedArray()
out.append(countInversions(arr)).append("\n")
}
println(out)
} | 2 | Scala | 0 | 0 | f1267e5d9da0bd5f6538b9c88aca652d9eb2b96c | 1,755 | algorithms | MIT License |
src/main/aoc2016/Day11.kt | nibarius | 154,152,607 | false | {"Kotlin": 963896} | package aoc2016
import kotlin.math.abs
class Day11(input: List<String>) {
// First approach used separate classes for Generators and Microchips with their positions
// and names. But that got messy and cumbersome when moving items and when checking for
// equivalent states. Just one list of Ints representing the positions of all the items
// made everything much simpler.
// items: generator1, chip1, generator2, chip2, etc
data class State(val elevatorPosition: Int, val items: List<Int>, val steps: Int) {
// Essential optimization: It doesn't matter which microchip/generator pair is moved
// Example: With Chip A + Generator A and Chip B + Generator B on floor 3
// it doesn't matter if the A pair is brought to floor 4 first or if
// pair B is moved first. Both approaches will require the same amount of
// moves to get both to floor 4. Do comparisons against a state where
// the order of the pairs doesn't matter.
fun getEquivalentState(): Int {
var i = 0
var ret = "E$elevatorPosition "
val l = mutableListOf<Pair<Int, Int>>()
while (i < items.size) {
l.add(Pair(items[i], items[i + 1]))
i += 2
}
l.sortWith(compareBy({ it.first }, { it.second }))
for (p in l) {
ret += "(${p.first},${p.second}) "
}
return ret.hashCode()
}
fun isWin() = items.all { it == 4 }
fun isLose(items: List<Int>): Boolean {
val floorsWithGenerators = items.filterIndexed { index, _ -> index % 2 == 0 }
var i = 0
while (i < items.size) {
if (items[i] != items[i + 1] && floorsWithGenerators.contains(items[i + 1])) {
// there is a chip without it's generator on same floor and there is (another)
// generator on the same floor
return true
}
i += 2
}
return false
}
// minor optimization: elevator never need to go down below the lowest floor with an item
fun elevatorCanMoveTo(floor: Int): Boolean {
return floor >= items.minOrNull()!! && floor <= 4 && abs(elevatorPosition - floor) == 1
}
}
private val initialState = parseInput(input)
private val alreadyChecked = mutableSetOf<Int>()
private fun parseInput(input: List<String>): State {
val generatorList = mutableListOf<Pair<String, Int>>()
val microchipList = mutableListOf<Pair<String, Int>>()
input.forEachIndexed { index, description ->
val floor = index + 1
description.split(",", " and").forEach {
when {
it.contains("generator") -> {
val generator = it.substringBefore(" generator").substringAfterLast(" ")
generatorList.add(Pair(generator, floor))
}
it.contains("microchip") -> {
val microchip = it.substringBefore("-compatible").substringAfterLast(" ")
microchipList.add(Pair(microchip, floor))
}
}
}
}
generatorList.sortBy { it.first }
microchipList.sortBy { it.first }
val items = mutableListOf<Int>()
for (i in 0 until generatorList.size) {
items.add(generatorList[i].second)
items.add(microchipList[i].second)
}
return State(1, items, 0)
}
private fun enqueueOneMoveFor(state: State, dir: Int, toCheck: MutableList<State>, alreadyChecked: MutableSet<Int>, vararg itemsToMove: Int): Boolean {
val toFloor = state.elevatorPosition + dir
if (!state.elevatorCanMoveTo(toFloor)) {
return false
}
val newItems = state.items.toMutableList()
for (item in itemsToMove) {
newItems[item] = toFloor
}
if (state.isLose(newItems)) {
return false
}
val newState = State(toFloor, newItems, state.steps + 1)
// Optimization: Don't enqueue a state that is already in the queue, or an item that has
// previously been checked.
val stateIsAlreadyQueued = toCheck.any { it.getEquivalentState() == newState.getEquivalentState() }
val stateHasAlreadyBeenChecked = alreadyChecked.contains(newState.getEquivalentState())
if (!stateHasAlreadyBeenChecked && !stateIsAlreadyQueued) {
toCheck.add(newState)
}
return true
}
private fun enqueueAllPossibleMovesFor(state: State, toCheck: MutableList<State>, alreadyChecked: MutableSet<Int>) {
val movableItems = mutableListOf<Int>()
state.items.forEachIndexed { index, itemFloor ->
if (itemFloor == state.elevatorPosition) {
movableItems.add(index)
}
}
//make all combos of movable items for moving two items at a time
val itemPairs = mutableListOf<List<Int>>()
for (first in 0 until movableItems.size) {
for (second in first + 1 until movableItems.size) {
itemPairs.add(listOf(movableItems[first], movableItems[second]))
}
}
// upward
var hasMovedUpTwo = false
for (i in 0 until itemPairs.size) {
hasMovedUpTwo = enqueueOneMoveFor(state, 1, toCheck, alreadyChecked, itemPairs[i][0], itemPairs[i][1])
|| hasMovedUpTwo
}
if (!hasMovedUpTwo) {
// Optimization: Don't try to move up one item if it's possible to move up two
for (i in 0 until movableItems.size) {
enqueueOneMoveFor(state, 1, toCheck, alreadyChecked, movableItems[i])
}
}
//downward
var hasMovedDown = false
for (i in 0 until movableItems.size) {
hasMovedDown = enqueueOneMoveFor(state, -1, toCheck, alreadyChecked, movableItems[i])
|| hasMovedDown//move down
}
if (!hasMovedDown) {
// Optimization: Don't try to move down two items if it's possible to move down one
for (i in 0 until itemPairs.size) {
enqueueOneMoveFor(state,-1, toCheck, alreadyChecked, itemPairs[i][0], itemPairs[i][1]) //move down
}
}
}
private fun run(initialState: State): Int {
val toCheck = mutableListOf(initialState)
var iterations = 0
while (toCheck.size > 0) {
iterations++
val nextState = toCheck.removeAt(0)
alreadyChecked.add(nextState.getEquivalentState())
when {
nextState.isWin() -> {
println("Done after $iterations iterations")
return nextState.steps
}
nextState.isLose(nextState.items) -> {
// Should never happen with a working implementation
println("Lose state found: $nextState")
}
else -> enqueueAllPossibleMovesFor(nextState, toCheck, alreadyChecked)
}
}
// Should never happen with a working implementation
println("Ran out of things to check after $iterations iterations")
return -1
}
// Example for part 1:
// With no optimizations: 390682 iterations
// Skip already checked states (very naive approach): 1298 iterations
// Don't move to empty floors: 1209 iterations
// Only make valid moves + implementation bug fixes: 773 iterations
// Don't take one up if you can take two, don't take two down if you can take 1: 126 iterations
// Improved state checking - Discard all equivalent states: 43 iterations
//
// Part 1:
// Without improved state checking: 21498 iterations, 18 seconds
// With improved state checking: 2586 iterations, 1.5 seconds
fun solvePart1(): Int {
return run(initialState)
}
// Without improved state checking: 782718 iterations, 7 hours 27 minutes
// With improved state checking: 8039 iterations, 14 seconds
fun solvePart2(): Int {
val extendedList = initialState.items.toMutableList()
extendedList.addAll(listOf(1, 1, 1, 1))
val part2State = State(1, extendedList, 0)
return run(part2State)
}
}
| 0 | Kotlin | 0 | 6 | f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22 | 8,500 | aoc | MIT License |
2017/src/main/kotlin/Day06.kt | dlew | 498,498,097 | false | {"Kotlin": 331659, "TypeScript": 60083, "JavaScript": 262} | import utils.splitWhitespace
import utils.toIntList
object Day06 {
fun part1(input: String): Int {
var banks = input.splitWhitespace().toIntList()
val seen = mutableSetOf<List<Int>>()
var steps = 0
while (!seen.contains(banks)) {
seen.add(banks)
val indexToRedistribute = maxBankIndex(banks)
banks = redistribute(banks, indexToRedistribute)
steps++
}
return steps
}
fun part2(input: String): Int {
var banks = input.splitWhitespace().toIntList()
val seen = mutableMapOf<List<Int>, Int>()
var cycle = 0
while (!seen.containsKey(banks)) {
seen[banks] = cycle
val indexToRedistribute = maxBankIndex(banks)
banks = redistribute(banks, indexToRedistribute)
cycle++
}
return cycle - seen[banks]!!
}
private fun maxBankIndex(banks: List<Int>): Int {
var max = -1
var maxIndex = -1
for (index in 0 until banks.size) {
val bank = banks[index]
if (bank > max) {
max = bank
maxIndex = index
}
}
return maxIndex
}
private fun redistribute(banks: List<Int>, index: Int): List<Int> {
val newBanks = banks.toMutableList()
val value = newBanks[index]
newBanks[index] = 0
for (offset in 1..value) {
newBanks[(index + offset) % banks.size]++
}
return newBanks
}
} | 0 | Kotlin | 0 | 0 | 6972f6e3addae03ec1090b64fa1dcecac3bc275c | 1,353 | advent-of-code | MIT License |
src/main/kotlin/day20/Day20.kt | daniilsjb | 572,664,294 | false | {"Kotlin": 69004} | package day20
import java.io.File
fun main() {
val data = parse("src/main/kotlin/day20/Day20.txt")
val answer1 = part1(data)
val answer2 = part2(data)
println("🎄 Day 20 🎄")
println()
println("[Part 1]")
println("Answer: $answer1")
println()
println("[Part 2]")
println("Answer: $answer2")
}
@Suppress("SameParameterValue")
private fun parse(path: String): List<Int> =
File(path).readLines().map(String::toInt)
private fun solve(data: List<Int>, times: Int = 1, key: Long = 1L): Long {
val numbers = data.map { it * key }
val mixed = (0..data.lastIndex).toMutableList()
repeat(times) {
for ((i, number) in numbers.withIndex()) {
val oldMixedIndex = mixed.indexOf(i)
mixed.removeAt(oldMixedIndex)
val newMixedIndex = (oldMixedIndex + number).mod(mixed.size)
mixed.add(newMixedIndex, i)
}
}
val zeroIndex = mixed.indexOf(data.indexOf(0))
return listOf(1000, 2000, 3000).sumOf { offset ->
numbers[mixed[(zeroIndex + offset) % mixed.size]]
}
}
private fun part1(data: List<Int>): Long =
solve(data)
private fun part2(data: List<Int>): Long =
solve(data, times = 10, key = 811589153L)
| 0 | Kotlin | 0 | 0 | 6f0d373bdbbcf6536608464a17a34363ea343036 | 1,251 | advent-of-code-2022 | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/GroupThePeople.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
/**
* 1282. Group the People Given the Group Size They Belong To
* @see <a href="https://leetcode.com/problems/group-the-people-given-the-group-size-they-belong-to">Source</a>
*/
fun interface GroupThePeople {
operator fun invoke(groupSizes: IntArray): List<List<Int>>
}
class GroupThePeopleGreedy : GroupThePeople {
override fun invoke(groupSizes: IntArray): List<List<Int>> {
val ans: MutableList<List<Int>> = ArrayList()
// A map from group size to the list of indices that are there in the group.
val szToGroup: MutableMap<Int, MutableList<Int>> = HashMap()
for (i in groupSizes.indices) {
if (!szToGroup.containsKey(groupSizes[i])) {
szToGroup[groupSizes[i]] = ArrayList()
}
val group = szToGroup[groupSizes[i]]
group?.add(i)
// When the list size equals the group size, empty it and store it in the answer.
if (group?.size == groupSizes[i]) {
ans.add(group)
szToGroup.remove(groupSizes[i])
}
}
return ans
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,756 | kotlab | Apache License 2.0 |
advent_of_code/2018/solutions/day_6_b.kt | migafgarcia | 63,630,233 | false | {"C++": 121354, "Kotlin": 38202, "C": 34840, "Java": 23043, "C#": 10596, "Python": 8343} | import java.io.File
import java.lang.Math.abs
fun main(args: Array<String>) {
val ids = generateSequence(1) { it + 1 }
val points = ids.zip(File(args[0]).readLines().map { line ->
val s = line.split(",").map { it.trim() }
Pair(s[0].toInt(), s[1].toInt())
}.asSequence()).toMap()
val xMax = points.values.maxBy { it.first }!!.first
val yMax = points.values.maxBy { it.second }!!.second
var region = 0
(0..xMax).forEach { x ->
(0..yMax)
.forEach { y ->
val sum = points.map { entry ->
manhattanDistance(Pair(x, y), entry.value)
}.sumBy { it }
if(sum < 10000)
region++
}
}
println(region)
}
fun manhattanDistance(p1: Pair<Int, Int>, p2: Pair<Int, Int>): Int = abs(p1.first - p2.first) + abs(p1.second - p2.second)
| 0 | C++ | 3 | 9 | 82f5e482c0c3c03fd39e46aa70cab79391ed2dc5 | 921 | programming-challenges | MIT License |
bot/src/main/java/pl/elpassion/elabyrinth/bot/Board.kt | elpassion | 57,039,976 | false | null | package pl.elpassion.elabyrinth.bot
import pl.elpassion.elabyrinth.core.Cell
import pl.elpassion.elabyrinth.core.Direction
import java.util.*
class Board {
val map: Set<Field>
val start: Field
val finish: Field
val visited: MutableSet<Field>
constructor(map: List<List<Cell>>) {
this.map = map.withIndex().map { row -> val y = row.index; row.value.withIndex().filter { it.value != Cell.WALL }.map { Field(it.index, y) } }.flatten().toSet()
this.start = map.withIndex().map { row -> val y = row.index; row.value.withIndex().filter { it.value == Cell.START }.map { Field(it.index, y) } }.flatten().first()
this.finish = map.withIndex().map { row -> val y = row.index; row.value.withIndex().filter { it.value == Cell.END }.map { Field(it.index, y) } }.flatten().first()
this.visited = mutableSetOf(start)
}
fun solve(): List<Direction> {
return solve(Stack<Field>().apply { push(start) })
}
private fun solve(stack: Stack<Field>): List<Direction> {
if (stack.peek() == finish) {
return stack.toDirectionList()
} else {
val next = anyUnvisitedNeighbour(stack.peek())
if (next != null) {
visited.add(next)
return solve(stack.apply { push(next) })
} else {
return solve(stack.apply { pop() })
}
}
}
private fun anyUnvisitedNeighbour(field: Field): Field? {
val neighbours = field.neighbours()
return map.filter { neighbours.contains(it) && !visited.contains(it) }.firstOrNull()
}
}
fun Stack<Field>.toDirectionList(): List<Direction> {
val list = toList()
val moves = list.dropLast(1).zip(list.drop(1))
return moves.map { toDirection(it.first, it.second) }
}
fun toDirection(first: Field, second: Field) =
if (first.x == second.x) {
if (first.y < second.y) {
Direction.DOWN
} else {
Direction.UP
}
} else {
if (first.x < second.x) {
Direction.RIGHT
} else {
Direction.LEFT
}
}
| 0 | Kotlin | 0 | 0 | 72800b31ec78c22766ec9ce81e5c70c405d22708 | 2,188 | el-abyrinth-android | MIT License |
src/day08/Day08.kt | ritesh-singh | 572,210,598 | false | {"Kotlin": 99540} | package day08
import readInput
fun main() {
fun List<String>.initMatrix(matrix: Array<IntArray>) {
val rowSize = size
val colSize = this[0].length
for (row in 0 until rowSize) {
for (col in 0 until colSize) {
matrix[row][col] = this[row][col].digitToInt()
}
}
}
fun part1(input: List<String>): Int {
val rowSize = input.size
val colSize = input[0].length
val matrix = Array(rowSize) { IntArray(colSize) }
input.initMatrix(matrix)
val visibleATreeAroundTheEdges = (rowSize * 2) + ((colSize - 2) * 2)
var internalVisibleTree = 0
for (row in 1 until rowSize - 1) {
for (col in 1 until colSize - 1) {
val currentValue = matrix[row][col]
// check left
var leftPass = true
for (left in 0 until col) {
if (matrix[row][left] >= currentValue) {
leftPass = false
break
}
}
if (leftPass) {
++internalVisibleTree
continue
}
// check right
var rightPass = true
for (right in col + 1 until colSize) {
if (matrix[row][right] >= currentValue) {
rightPass = false
break
}
}
if (rightPass) {
++internalVisibleTree
continue
}
// check top
var topPass = true
for (top in 0 until row) {
if (matrix[top][col] >= currentValue) {
topPass = false
break
}
}
if (topPass) {
++internalVisibleTree
continue
}
// check bottom
var bottomPass = true
for (bottom in row + 1 until rowSize) {
if (matrix[bottom][col] >= currentValue) {
bottomPass = false
break
}
}
if (bottomPass) {
++internalVisibleTree
}
}
}
return visibleATreeAroundTheEdges + internalVisibleTree
}
fun part2(input: List<String>): Int {
val rowSize = input.size
val colSize = input[0].length
val matrix = Array(rowSize) { IntArray(colSize) }
input.initMatrix(matrix)
var answer = Int.MIN_VALUE
for (row in 1 until rowSize - 1) {
for (col in 1 until colSize - 1) {
val currentHeight = matrix[row][col]
var leftScore = 0
for (left in col - 1 downTo 0) {
if (matrix[row][left] <= currentHeight) ++leftScore
if (matrix[row][left] >= currentHeight) break
}
var rightScore = 0
for (right in col + 1 until colSize) {
if (matrix[row][right] <= currentHeight) ++rightScore
if (matrix[row][right] >= currentHeight) break
}
var topScore = 0
for (top in row - 1 downTo 0) {
if (matrix[top][col] <= currentHeight) ++topScore
if (matrix[top][col] >= currentHeight) break
}
var bottomScore = 0
for (bottom in row + 1 until rowSize) {
if (matrix[bottom][col] <= currentHeight) ++bottomScore
if (matrix[bottom][col] >= currentHeight) break
}
val totalScore = leftScore * rightScore * topScore * bottomScore
if (totalScore > answer) answer = totalScore
}
}
return answer
}
val input = readInput("/day08/Day08")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 17fd65a8fac7fa0c6f4718d218a91a7b7d535eab | 4,184 | aoc-2022-kotlin | Apache License 2.0 |
2022/src/main/kotlin/day2_imp.kt | madisp | 434,510,913 | false | {"Kotlin": 388138} | import utils.Parser
import utils.Solution
import utils.badInput
import utils.cut
import utils.mapItems
fun main() {
Day2Imp.run()
}
object Day2Imp : Solution<List<Pair<Play, Char>>>() {
override val name = "day2"
override val parser = Parser.lines.mapItems { line -> line.cut(" ", { l -> Play.fromL(l[0]) }) { it[0] } }
override fun part1(input: List<Pair<Play, Char>>): Int {
var score = 0
input.forEach { (play, char) ->
val other = Play.fromR(char)
score += (play to other).score
}
return score
}
override fun part2(input: List<Pair<Play, Char>>): Int {
var score = 0
input.forEach { (play, char) ->
val other = when (char) {
'X' -> play.winsOver // lose
'Y' -> play // draw
'Z' -> play.losesTo // win
else -> badInput()
}
score += (play to other).score
}
return score
}
}
| 0 | Kotlin | 0 | 1 | 3f106415eeded3abd0fb60bed64fb77b4ab87d76 | 892 | aoc_kotlin | MIT License |
src/main/kotlin/g0701_0800/s0720_longest_word_in_dictionary/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g0701_0800.s0720_longest_word_in_dictionary
// #Medium #Array #String #Hash_Table #Sorting #Trie
// #2023_02_27_Time_209_ms_(100.00%)_Space_37_MB_(83.33%)
@Suppress("NAME_SHADOWING")
class Solution {
private val root = Node()
private var longestWord: String? = ""
private class Node {
var children: Array<Node?> = arrayOfNulls(26)
var str: String? = null
fun insert(curr: Node?, word: String) {
var curr = curr
for (element in word) {
if (curr!!.children[element.code - 'a'.code] == null) {
curr.children[element.code - 'a'.code] = Node()
}
curr = curr.children[element.code - 'a'.code]
}
curr!!.str = word
}
}
fun longestWord(words: Array<String>): String? {
for (word in words) {
root.insert(root, word)
}
dfs(root)
return longestWord
}
private fun dfs(curr: Node?) {
for (i in 0..25) {
if (curr!!.children[i] != null && curr.children[i]!!.str != null) {
if (curr.children[i]!!.str!!.length > longestWord!!.length) {
longestWord = curr.children[i]!!.str
}
dfs(curr.children[i])
}
}
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,334 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/aoc/Day2.kt | dtsaryov | 573,392,550 | false | {"Kotlin": 28947} | package aoc
/**
* [AoC 2022: Day 2](https://adventofcode.com/2022/day/2)
*/
fun calcRockPaperScissorsScore(): Int {
val input = readInput("day2.txt") ?: return -1
var score = 0
processRounds(input) { (playerShape, opponentShape) ->
score += getPlayerRoundScore(playerShape, opponentShape)
score += getShapeScore(playerShape)
}
return score
}
fun calcRockPaperScissorsScoreByChoosing(): Int {
val input = readInput("day2.txt") ?: return -1
var score = 0
processRounds(input) { (roundResult, opponentShape) ->
val playerShape = chooseShape(opponentShape, roundResult)
score += getPlayerRoundScore(playerShape, opponentShape)
score += getShapeScore(playerShape)
}
return score
}
private fun chooseShape(opponentShape: Char, roundResult: Char): Char {
return when (roundResult) {
'X' -> {
when (opponentShape) {
'A' -> 'Z'
'B' -> 'X'
'C' -> 'Y'
else -> ' '
}
}
'Y' -> {
when (opponentShape) {
'A' -> 'X'
'B' -> 'Y'
'C' -> 'Z'
else -> ' '
}
}
'Z' -> {
when (opponentShape) {
'A' -> 'Y'
'B' -> 'Z'
'C' -> 'X'
else -> ' '
}
}
else -> ' '
}
}
private fun getPlayerRoundScore(playerShape: Char, opponentShape: Char): Int {
return when (playerShape) {
'X' -> {
when (opponentShape) {
'A' -> 3
'B' -> 0
'C' -> 6
else -> Int.MIN_VALUE
}
}
'Y' -> {
when (opponentShape) {
'A' -> 6
'B' -> 3
'C' -> 0
else -> Int.MIN_VALUE
}
}
'Z' -> {
when (opponentShape) {
'A' -> 0
'B' -> 6
'C' -> 3
else -> Int.MIN_VALUE
}
}
else -> Int.MIN_VALUE
}
}
private fun getShapeScore(shape: Char): Int {
return when (shape) {
'X' -> 1
'Y' -> 2
'Z' -> 3
else -> Int.MIN_VALUE
}
}
private fun processRounds(input: List<String>, processor: (Pair<Char, Char>) -> Unit) {
for (line in input) {
processor(line[2] to line[0])
}
} | 0 | Kotlin | 0 | 0 | 549f255f18b35e5f52ebcd030476993e31185ad3 | 2,497 | aoc-2022 | Apache License 2.0 |
src/Day19.kt | PascalHonegger | 573,052,507 | false | {"Kotlin": 66208} | import kotlin.math.max
import kotlin.system.measureTimeMillis
fun main() {
val inputPattern =
"Blueprint (.+): Each ore robot costs (.+) ore. Each clay robot costs (.+) ore. Each obsidian robot costs (.+) ore and (.+) clay. Each geode robot costs (.+) ore and (.+) obsidian.".toRegex()
data class Blueprint(
val id: Int,
val oreRobotOreCost: Int,
val clayRobotOreCost: Int,
val obsidianRobotOreCost: Int,
val obsidianRobotClayCost: Int,
val geodeRobotOreCost: Int,
val geodeRobotObsidianCost: Int
) {
override fun toString() = "Blueprint $id"
}
data class RoboterState(
val oreRobots: Int = 0,
val clayRobots: Int = 0,
val obsidianRobots: Int = 0,
val geodeRobots: Int = 0,
val ore: Int = 0,
val clay: Int = 0,
val obsidian: Int = 0,
val geode: Int = 0,
)
fun RoboterState.tick() = copy(
ore = ore + oreRobots,
clay = clay + clayRobots,
obsidian = obsidian + obsidianRobots,
geode = geode + geodeRobots,
)
fun String.toBlueprint(): Blueprint {
val match = inputPattern.matchEntire(this)!!.groupValues.drop(1).map { it.toInt() }
return Blueprint(
id = match[0],
oreRobotOreCost = match[1],
clayRobotOreCost = match[2],
obsidianRobotOreCost = match[3],
obsidianRobotClayCost = match[4],
geodeRobotOreCost = match[5],
geodeRobotObsidianCost = match[6],
)
}
fun Blueprint.runSimulation(minutes: Int): Int {
val cache = HashMap<Pair<RoboterState, Int>, Int>()
fun simulateMinute(
state: RoboterState,
remainingMinutes: Int
): Int {
val cacheKey = state to remainingMinutes
cache[cacheKey]?.let { return it }
if (remainingMinutes == 0) {
return state.geode
}
val newState = state.tick()
// If we can buy Geode robot, always do it
if (geodeRobotOreCost <= state.ore && geodeRobotObsidianCost <= state.obsidian) {
val boughtGeodeRobot = newState.copy(
ore = newState.ore - geodeRobotOreCost,
obsidian = newState.obsidian - geodeRobotObsidianCost,
geodeRobots = newState.geodeRobots + 1,
)
return simulateMinute(boughtGeodeRobot, remainingMinutes - 1)
}
var maxGeodes = simulateMinute(newState, remainingMinutes - 1)
val maxOreCost = maxOf(oreRobotOreCost, clayRobotOreCost, obsidianRobotOreCost, geodeRobotOreCost)
if (remainingMinutes > oreRobotOreCost &&
state.oreRobots < maxOreCost &&
oreRobotOreCost <= state.ore) {
val boughtOreRobot = newState.copy(
ore = newState.ore - oreRobotOreCost,
oreRobots = newState.oreRobots + 1,
)
maxGeodes = max(maxGeodes, simulateMinute(boughtOreRobot, remainingMinutes - 1))
}
val maxClayCost = maxOf(clayRobotOreCost, obsidianRobotClayCost)
if (state.clayRobots < maxClayCost && clayRobotOreCost <= state.ore) {
val boughtClayRobot = newState.copy(
ore = newState.ore - clayRobotOreCost,
clayRobots = newState.clayRobots + 1,
)
maxGeodes = max(maxGeodes, simulateMinute(boughtClayRobot, remainingMinutes - 1))
}
val maxObsidianCost = geodeRobotObsidianCost
if (state.obsidianRobots < maxObsidianCost && obsidianRobotOreCost <= state.ore && obsidianRobotClayCost <= state.clay) {
val boughtObsidianRobot = newState.copy(
ore = newState.ore - obsidianRobotOreCost,
clay = newState.clay - obsidianRobotClayCost,
obsidianRobots = newState.obsidianRobots + 1,
)
maxGeodes = max(maxGeodes, simulateMinute(boughtObsidianRobot, remainingMinutes - 1))
}
cache[cacheKey] = maxGeodes
return maxGeodes
}
val initialState = RoboterState(oreRobots = 1)
return simulateMinute(initialState, minutes).also { println("Took ${cache.size} simulations") } // 4048776 -> 4048189 -> 2045829
}
fun part1(input: List<String>): Int {
return input
.map { it.toBlueprint() }
.sumOf { blueprint ->
val maxGeodes: Int
val duration = measureTimeMillis {
maxGeodes = blueprint.runSimulation(minutes = 24)
}
println("$blueprint: $maxGeodes in ${duration}ms")
blueprint.id * maxGeodes
}
}
fun part2(input: List<String>): Int {
return input
.take(3)
.map { it.toBlueprint() }
.map { blueprint ->
val maxGeodes: Int
val duration = measureTimeMillis {
maxGeodes = blueprint.runSimulation(minutes = 32)
}
println("$blueprint: $maxGeodes in ${duration}ms")
maxGeodes
}.product()
}
val testInput = readInput("Day19_test")
check(part1(testInput) == 33)
check(part2(testInput) == 56 * 62)
val input = readInput("Day19")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 2215ea22a87912012cf2b3e2da600a65b2ad55fc | 5,591 | advent-of-code-2022 | Apache License 2.0 |
2021/kotlin/src/main/kotlin/nl/sanderp/aoc/aoc2021/day20/Day20.kt | sanderploegsma | 224,286,922 | false | {"C#": 233770, "Kotlin": 126791, "F#": 110333, "Go": 70654, "Python": 64250, "Scala": 11381, "Swift": 5153, "Elixir": 2770, "Jinja": 1263, "Ruby": 1171} | package nl.sanderp.aoc.aoc2021.day20
import nl.sanderp.aoc.common.Point2D
import nl.sanderp.aoc.common.readResource
import nl.sanderp.aoc.common.x
import nl.sanderp.aoc.common.y
fun main() {
val input = readResource("Day20.txt").replace('.', '0').replace('#', '1').lines()
val algorithm = input.first()
val image = parseImage(input.drop(2))
val enhanced1 = image.enhance(algorithm, 2)
println("Part one: ${enhanced1.pixels.count { it.value == '1' }}")
val enhanced2 = image.enhance(algorithm, 50)
println("Part two: ${enhanced2.pixels.count { it.value == '1' }}")
}
private data class Image(val pixels: Map<Point2D, Char>, val default: Char) {
val minX = pixels.minOf { it.key.x }
val minY = pixels.minOf { it.key.y }
val maxX = pixels.maxOf { it.key.x }
val maxY = pixels.maxOf { it.key.y }
}
private fun parseImage(image: List<String>): Image {
val pixels = buildMap {
for ((y, row) in image.withIndex()) {
for ((x, c) in row.withIndex()) {
put(x to y, c)
}
}
}
return Image(pixels, '0')
}
private fun Image.enhance(algorithm: String, times: Int) =
generateSequence(this) { it.enhance(algorithm) }.drop(times).first()
private fun Image.enhance(algorithm: String): Image {
val nextPixels = mutableMapOf<Point2D, Char>()
for (nextY in minY - 1..maxY + 1) {
for (nextX in minX - 1..maxX + 1) {
var bits = ""
for (y in nextY - 1..nextY + 1) {
for (x in nextX - 1..nextX + 1) {
bits += pixels[Point2D(x, y)] ?: default
}
}
nextPixels[nextX to nextY] = algorithm[bits.toInt(2)]
}
}
return Image(nextPixels, default = algorithm[default.toString().repeat(9).toInt(2)])
} | 0 | C# | 0 | 6 | 8e96dff21c23f08dcf665c68e9f3e60db821c1e5 | 1,824 | advent-of-code | MIT License |
advent-of-code-2022/src/main/kotlin/year_2022/Day19.kt | rudii1410 | 575,662,325 | false | {"Kotlin": 37749} | package year_2022
import util.Runner
fun main() {
val size = 100
/* Part 1 */
/**
* ore = 0, clay = 1, obsidian = 2, geode = 3
*/
fun parseRecipe(s: String): List<Int> {
fun List<String>.parse(idx: Int, stone: String): Int {
return this.getOrNull(idx)?.trim()?.split(" ")?.let { s ->
s[0].takeIf { s[1] == stone } ?: "0"
}?.toInt() ?: 0
}
return s.substringAfter("costs").split("and").let { r ->
listOf(r.parse(0, "ore"), r.parse(1, "clay"), r.parse(2, "obsidian"), r.parse(3, "geode"))
}
}
fun part1(input: List<String>): Int {
val config = List(size) { List(size) { List(size) { MutableList(size) { 0 } } } }
input.map { row ->
val d = row.split(": ", ".")
println(parseRecipe(d[1]))
println(parseRecipe(d[2]))
println(parseRecipe(d[3]))
println(parseRecipe(d[4]))
println()
}
return input.size
}
Runner.run(::part1, 33)
/* Part 2 */
fun part2(input: List<String>): Int {
return input.size
}
Runner.run(::part2, 0)
}
| 1 | Kotlin | 0 | 0 | ab63e6cd53746e68713ddfffd65dd25408d5d488 | 1,178 | advent-of-code | Apache License 2.0 |
src/main/kotlin/stacktic/Interpreter.kt | nschulzke | 519,260,020 | false | {"Kotlin": 24938} | package stacktic
import java.lang.Double.parseDouble
import java.lang.Integer.parseInt
class Interpreter(
val printLine: (String) -> Unit = ::println,
) {
private val vocabulary: Vocabulary = Vocabulary()
private val stackStack = Stack<Stack<Value>>(listOf(Stack()))
private val stack get() = stackStack.peek()
fun parse(tokens: Iterator<Token>): ParseTree {
val words = mutableListOf<ParseTree>()
while (tokens.hasNext()) {
val token = tokens.next()
when {
token is IntegerToken -> {
words.add(ParseTree.of(Value.Integer(parseInt(token.lexeme))))
stack.push(Type.Integer)
}
token is DoubleToken -> {
words.add(ParseTree.of(Value.Double(parseDouble(token.lexeme))))
stack.push(Type.Double)
}
token.lexeme in vocabulary -> {
val definition = vocabulary.definition(token.lexeme, stack)
?: throw RuntimeException("Error, undefined function: ${token.lexeme}")
if (definition.immediate) {
definition.parseTree.execute(stack, tokens)
} else {
words.add(definition.parseTree)
stack.take(definition.effect.input.size)
stack.addAll(definition.effect.output)
}
}
token == Dot -> {
words.add(prettyPrint)
stack.pop()
}
token == Semicolon -> {
return ParseTree.of(words)
}
else -> {
throw Error("Unknown word: ${token.lexeme}")
}
}
}
return ParseTree.of(words)
}
fun interpret(tokens: Iterator<Token>) {
stackStack.push(Stack())
val tree = parse(tokens)
stackStack.pop()
tree.execute(stack, tokens)
}
companion object {
val Dot = SymbolToken(".")
val Semicolon = SymbolToken(";")
val LParen = SymbolToken("(")
val RParen = SymbolToken(")")
val LongDash = SymbolToken("--")
}
private val prettyPrint: ParseTree = ParseTree.of {
printLine(this.pop().toString())
}
data class Effect(val input: List<Value>, val output: List<Value>) {
fun appliesTo(stack: Stack<Value>): Boolean =
stack.peek(input.size) == input
}
data class Definition(
val name: String,
val effect: Effect,
val immediate: Boolean = false,
val parseTree: ParseTree,
) {
constructor(name: String, input: List<Value>, output: List<Value>, parseTree: ParseTree) :
this(name, Effect(input, output), false, parseTree)
constructor(name: String, effect: Effect, immediate: Boolean = false, implementation: Stack<Value>.(tokens: Iterator<Token>) -> Unit) : this(
name = name,
effect = effect,
immediate = immediate,
parseTree = ParseTree.Leaf(implementation)
)
}
inner class Vocabulary {
private val definitions: MutableMap<String, MutableList<Definition>> = mutableMapOf(
"+" to mutableListOf(
Definition("+", Effect(listOf(Type.Integer, Type.Integer), listOf(Type.Integer))) {
val second = pop() as Value.Integer
val first = pop() as Value.Integer
push(first + second)
},
Definition("+", Effect(listOf(Type.Double, Type.Double), listOf(Type.Double))) {
val second = pop() as Value.Double
val first = pop() as Value.Double
push(first + second)
},
),
"-" to mutableListOf(
Definition("-", Effect(listOf(Type.Integer, Type.Integer), listOf(Type.Integer))) {
val second = pop() as Value.Integer
val first = pop() as Value.Integer
push(first - second)
},
Definition("-", Effect(listOf(Type.Double, Type.Double), listOf(Type.Double))) {
val second = pop() as Value.Double
val first = pop() as Value.Double
push(first - second)
},
),
"*" to mutableListOf(
Definition("*", Effect(listOf(Type.Integer, Type.Integer), listOf(Type.Integer))) {
val second = pop() as Value.Integer
val first = pop() as Value.Integer
push(first * second)
},
Definition("*", Effect(listOf(Type.Double, Type.Double), listOf(Type.Double))) {
val second = pop() as Value.Double
val first = pop() as Value.Double
push(first * second)
},
),
"/" to mutableListOf(
Definition("/", Effect(listOf(Type.Integer, Type.Integer), listOf(Type.Integer))) {
val second = pop() as Value.Integer
val first = pop() as Value.Integer
push(first / second)
},
Definition("/", Effect(listOf(Type.Double, Type.Double), listOf(Type.Double))) {
val second = pop() as Value.Double
val first = pop() as Value.Double
push(first / second)
},
),
":" to mutableListOf(
Definition(":", Effect(emptyList(), emptyList()), immediate = true) { tokens ->
val nameToken = tokens.next()
if (nameToken !is SymbolToken) {
throw Error("Expected symbol, got: ${nameToken.lexeme}")
}
stack.push(Value.String(nameToken.lexeme))
val lParen = tokens.next()
if (lParen != LParen) {
throw Error("Expected (, got: ${lParen.lexeme}")
}
stackStack.push(Stack())
while (true) {
val token = tokens.next()
if (token == LongDash) break
stack.push(Type.of(token) ?: throw Error("Unknown type: $token"))
}
stackStack.push(Stack())
while (true) {
val token = tokens.next()
if (token == RParen) break
stack.push(Type.of(token) ?: throw Error("Unknown type: $token"))
}
stackStack.swap()
stackStack.dup()
val parseTree = parse(tokens)
val actualOutput = stackStack.pop().takeAll()
val declaredInput = stackStack.pop().takeAll()
val declaredOutput = stackStack.pop().takeAll()
val name = stack.pop() as Value.String
if (actualOutput != declaredOutput) {
throw Error("ERROR Invalid stack effect: Expected to end with `${declaredOutput.joinToString(" ")}`; was `${actualOutput.joinToString(" ")}`")
}
define(Definition(name.value, declaredInput, declaredOutput, parseTree))
}
)
)
fun define(definition: Definition): Boolean =
definitions.getOrPut(definition.name) { mutableListOf() }.add(definition)
operator fun contains(name: String): Boolean =
name in definitions
fun definition(name: String, stack: Stack<Value>): Definition? =
definitions[name]?.firstOrNull { it.effect.appliesTo(stack) }
}
} | 0 | Kotlin | 0 | 1 | d41601100ef2756b97004b8424312f8853b62f33 | 8,022 | stacktic | MIT License |
src/main/kotlin/com/exsilicium/scripture/shared/extensions/LocationExtensions.kt | Ex-Silicium | 103,700,839 | false | null | package com.exsilicium.scripture.shared.extensions
import com.exsilicium.scripture.shared.model.ChapterRanges
import com.exsilicium.scripture.shared.model.VerseRanges
internal fun ChapterRanges.compareChapterRanges(other: ChapterRanges): Int {
val startingChapterComparison = chapterRanges.first().start.compareTo(other.chapterRanges.first().start)
return when (startingChapterComparison) {
0 -> compareAllChapterRanges(other)
else -> startingChapterComparison
}
}
private fun ChapterRanges.compareAllChapterRanges(other: ChapterRanges)
= chapterRanges.sumBy { it.endInclusive - it.start + 1 }
.compareTo(other.chapterRanges.sumBy { it.endInclusive - it.start + 1 })
internal fun VerseRanges.compareVerseRanges(other: VerseRanges): Int {
val startingVerseComparison = verseRanges.first().start.compareTo(other.verseRanges.first().start)
return when (startingVerseComparison) {
0 -> compareAllVerseRanges(other)
else -> startingVerseComparison
}
}
private fun VerseRanges.compareAllVerseRanges(other: VerseRanges)
= verseRanges.sumBy { it.endInclusive - it.start + 1 }
.compareTo(other.verseRanges.sumBy { it.endInclusive - it.start + 1 })
| 14 | Kotlin | 1 | 1 | 4815f70f5736080d7533e0d1316f0aa2c31aa85a | 1,232 | scripture-core | Apache License 2.0 |
src/main/kotlin/com/dvdmunckhof/aoc/event2022/Day12.kt | dvdmunckhof | 318,829,531 | false | {"Kotlin": 195848, "PowerShell": 1266} | package com.dvdmunckhof.aoc.event2022
import com.dvdmunckhof.aoc.common.Grid
import com.dvdmunckhof.aoc.common.Point
import com.dvdmunckhof.aoc.toGrid
import java.util.ArrayDeque
class Day12(input: List<String>) {
private val heightGrid = input.map { row -> row.map { c ->
when (c) {
'S' -> -1
'E' -> 25
else -> c - 'a'
}
}}.toGrid()
fun solvePart1(): Int {
val startIndex = heightGrid.indexOfFirst { it == -1 }
val startPoint = heightGrid.indexToPoint(startIndex)
return solve(startPoint)
}
fun solvePart2(): Int {
return heightGrid.points()
.filter { p -> heightGrid[p] <= 0 }
.minOf { solve(it) }
}
private fun solve(startPoint: Point): Int {
val stepGrid = Grid<Int?>(heightGrid.width, heightGrid.height, null)
stepGrid[startPoint] = 0
heightGrid[startPoint] = 0
val queue = ArrayDeque<Point>()
queue += startPoint
while (queue.isNotEmpty()) {
val point = queue.removeFirst()
val step = stepGrid[point]!!
val height = heightGrid[point]
val neighbors = heightGrid.adjacent(point, false)
for (neighbor in neighbors) {
if (stepGrid[neighbor] != null) {
continue
}
val neighborValue = heightGrid[neighbor]
if (neighborValue - 1 <= height) {
if (height == 25) {
return step + 1
}
stepGrid[neighbor] = step + 1
queue += neighbor
}
}
}
return Int.MAX_VALUE
}
}
| 0 | Kotlin | 0 | 0 | 025090211886c8520faa44b33460015b96578159 | 1,747 | advent-of-code | Apache License 2.0 |
src/main/kotlin/ru/spbstu/generator/TunnelGenerator.kt | belyaev-mikhail | 192,383,116 | false | null | package ru.spbstu.generator
import ru.spbstu.map.*
import ru.spbstu.player.aStarSearch
class TunnelGenerator(private val parameters: Parameters) {
enum class Cell { WALL, PATH }
private val matrix = HashMap<Point, Cell>()
private fun isWall(point: Point) = matrix[point] == Cell.WALL
private fun isPath(point: Point) = matrix[point] == Cell.PATH
private fun falseWall(point: Point) =
(isWall(point.up().left()) && !isWall(point.up()) && !isWall(point.left())) ||
(isWall(point.up().right()) && !isWall(point.up()) && !isWall(point.right())) ||
(isWall(point.down().left()) && !isWall(point.down()) && !isWall(point.left())) ||
(isWall(point.down().right()) && !isWall(point.down()) && !isWall(point.right()))
private fun generateWalls(point: Point) {
val walls = matrix.asSequence()
.filter { it.value == Cell.WALL }
.filter { it.key != point }
.map { it.key }
.toSet()
val points = aStarSearch(
from = point,
heur = { walls.map { wall -> wall.euclidDistance(it) }.min()!! },
goal = { it in walls },
neighbours = {
it.neighbours().asSequence().filterNot { isPath(it) || falseWall(it) }
})!!
points.forEach { matrix[it] = Cell.WALL }
}
private fun addWallIfCan(point: Point): Boolean {
if (point.v0 < 0 || point.v1 < 0) return false
if (point.v0 >= parameters.mapSize) return false
if (point.v1 >= parameters.mapSize) return false
if (isWall(point)) return false
if (isPath(point)) return false
if (falseWall(point)) return false
matrix[point] = Cell.WALL
return true
}
data class Pattern(val walls: Set<Point>, val paths: Set<Point>) {
companion object {
// "000 000 0x1"
fun parse(initial: Point, pattern: String): Pattern {
val lines = pattern.split(" ")
val length = lines.map { it.length }.max()!!
if (length != lines.map { it.length }.min()) throw Exception(pattern)
val walls = HashSet<Point>()
val paths = HashSet<Point>()
var relativeInitial: Point? = null
for (v0 in lines.indices) {
for (v1 in 0 until length) {
val ch = lines[v0][v1]
val point = Point(v0, v1)
when (ch) {
'0' -> paths.add(point)
'1' -> walls.add(point)
'o' -> paths.add(point)
'x' -> walls.add(point)
'-' -> { //Skip
}
else -> throw Exception(pattern)
}
if (ch == 'o' || ch == 'x') {
relativeInitial = point
}
}
}
if (relativeInitial == null) throw Exception(pattern)
return Pattern(
walls = walls.map { it - relativeInitial + initial }.toSet(),
paths = paths.map { it - relativeInitial + initial }.toSet()
)
}
}
}
private fun availablePoint(point: Point): Boolean {
if (point.v0 < -1 || point.v1 < -1) return false
if (point.v0 > parameters.mapSize) return false
if (point.v1 > parameters.mapSize) return false
return true
}
private fun match(point: Point, rawPattern: String): Boolean {
val pattern = Pattern.parse(point, rawPattern)
if (pattern.paths.any { !availablePoint(it) }) return false
if (pattern.walls.any { !availablePoint(it) }) return false
if (pattern.paths.any { isWall(it) }) return false
if (pattern.walls.any { !isWall(it) }) return false
return true
}
private fun match(point: Point, vararg rawPattern: String): Int {
return rawPattern.count { match(point, it) }
}
private fun appendCorners() {
var availableCorners = parameters.verticesMin - countCorners()
var pointsIt = emptyList<Point>().iterator()
var previousAvailableCorners = availableCorners + 1
while (availableCorners > 0) {
if (!pointsIt.hasNext()) {
if (previousAvailableCorners == availableCorners) {
println("Has not any possibilities to append, $availableCorners")
return
}
previousAvailableCorners = availableCorners
pointsIt = matrix.filter { it.value == Cell.WALL }.map { it.key }.iterator()
}
val point = pointsIt.next()
if (match(point, "000 000 1x1") && addWallIfCan(point.down())) {
availableCorners -= 4
} else if (match(point, "1x1 000 000") && addWallIfCan(point.up())) {
availableCorners -= 4
} else if (match(point, "100 x00 100") && addWallIfCan(point.right())) {
availableCorners -= 4
} else if (match(point, "001 00x 001") && addWallIfCan(point.left())) {
availableCorners -= 4
} else if (match(point, "000 000 0x1") && addWallIfCan(point.down())) {
availableCorners -= 2
} else if (match(point, "000 000 1x0") && addWallIfCan(point.down())) {
availableCorners -= 2
} else if (match(point, "1x0 000 000") && addWallIfCan(point.up())) {
availableCorners -= 2
} else if (match(point, "0x1 000 000") && addWallIfCan(point.up())) {
availableCorners -= 2
} else if (match(point, "001 00x 000") && addWallIfCan(point.left())) {
availableCorners -= 2
} else if (match(point, "000 00x 001") && addWallIfCan(point.left())) {
availableCorners -= 2
} else if (match(point, "100 x00 000") && addWallIfCan(point.right())) {
availableCorners -= 2
} else if (match(point, "000 x00 100") && addWallIfCan(point.right())) {
availableCorners -= 2
}
// if (availableCorners + countCorners() != parameters.verticesMin) {
// println("AAAAAAAA")
// println(point)
// println("$availableCorners + ${countCorners()} != ${parameters.verticesMin}")
// throw Exception()
// }
}
}
private fun removeCorners() {
}
fun generate(): Set<Point> {
parameters.pathsPoints.forEach { matrix[it] = Cell.PATH }
for (i in -1..parameters.mapSize) {
matrix[Point(i, -1)] = Cell.WALL
matrix[Point(-1, i)] = Cell.WALL
matrix[Point(i, parameters.mapSize)] = Cell.WALL
matrix[Point(parameters.mapSize, i)] = Cell.WALL
}
parameters.wallsPoints.forEach {
generateWalls(it)
}
appendCorners()
removeCorners()
println("${countCorners()} in ${parameters.verticesMin to parameters.verticesMax}")
return matrix.filter { it.value == Cell.WALL }.keys
}
private fun countCorners() = matrix.asSequence()
.filter { it.value == Cell.WALL }
.map { it.key }
.map { match(it, "00 0x", "00 x0", "x0 00", "0x 00", "01 1x", "10 x1", "x1 10", "1x 01") }
.sum()
} | 1 | Kotlin | 0 | 0 | cd5c7d668bf6615fd7e639ddfce0c135c138de42 | 7,674 | icfpc-2019 | MIT License |
src/main/kotlin/de/consuli/aoc/year2023/days/Day01.kt | ulischulte | 572,773,554 | false | {"Kotlin": 40404} | package de.consuli.aoc.year2023.days
import de.consuli.aoc.common.Day
class Day01 : Day(1, 2023) {
private val digitStrings = mapOf(
"one" to "1",
"two" to "2",
"three" to "3",
"four" to "4",
"five" to "5",
"six" to "6",
"seven" to "7",
"eight" to "8",
"nine" to "9"
)
private val digits = (1..9).map(Int::toString) + digitStrings.keys
override fun partOne(testInput: Boolean): Int = calculateCalibrationValue(testInput)
override fun partTwo(testInput: Boolean): Int =
getInput(testInput).sumOf { getCalibrationValueWithDigitStrings(it) }
private fun String.parseDigit(): String = digitStrings[this] ?: this
private fun getCalibrationValueWithDigitStrings(input: String): Int {
val first = input.findAnyOf(digits)?.second?.parseDigit()
val second = input.findLastAnyOf(digits)?.second?.parseDigit()
return "$first$second".toInt()
}
private fun calculateCalibrationValue(testInput: Boolean): Int = getInput(testInput)
.map(::removeNonDigitChars)
.map(::getFirstAndLastChar)
.sumOf(String::toInt)
private fun removeNonDigitChars(input: String) = input.replace("\\D".toRegex(), "")
private fun getFirstAndLastChar(input: String) = "${input.first()}${input.last()}"
}
| 0 | Kotlin | 0 | 2 | 21e92b96b7912ad35ecb2a5f2890582674a0dd6a | 1,347 | advent-of-code | Apache License 2.0 |
src/Day12.kt | michaelYuenAE | 573,094,416 | false | {"Kotlin": 74685} | //class Day12 {
//
// fun partOne(): Int = createField()
// .let { (field, start, end) ->
// findShortestPath(mutableListOf(field[start]!!), field, end)
// }
//
// fun partTwo(): Int = createField()
// .let { (field, _, end) ->
// field.values
// .filter { it.height == 'a' }
// .map { findShortestPath(mutableListOf(it), createField().first, end) }
// .minOf { it }
// }
//
// private fun createField(): Triple<MutableMap<Pair<Int, Int>, Point2>, Pair<Int, Int>, Pair<Int, Int>> {
// val field = mutableMapOf<Pair<Int, Int>, Point2>()
//
// var start: Pair<Int, Int> = Pair(-1, -1)
// var end: Pair<Int, Int> = Pair(-1, -1)
//
// readInput("day12_input").forEachIndexed { y, line ->
// line.toCharArray().forEachIndexed { x, char ->
// when (char) {
// 'S' -> {
// start = Pair(x, y)
// field[start] = Point2(coordinates = start, height = 'a')
// }
//
// 'E' -> {
// end = Pair(x, y)
// field[end] = Point2(coordinates = end, height = 'z')
// }
//
// else -> {
// field[Pair(x, y)] = Point2(coordinates = Pair(x, y), height = char)
// }
// }
// }
// }
// return Triple(field, start, end)
// }
//
// private fun findShortestPath(
// toVisit: MutableList<Point2>,
// allPoints: MutableMap<Pair<Int, Int>, Point2>,
// end: Pair<Int, Int>
// ): Int {
// var moves = 0
// while (toVisit.isNotEmpty()) {
// moves++
//
// val nextToVisit = mutableSetOf<Point2>()
// for (point in toVisit) {
// val left = allPoints.getOrElse(Pair(point.coordinates.first - 1, point.coordinates.second)) { null }
// if ((left?.height ?: Char.MAX_VALUE).code <= point.height.code + 1 && left?.visited == false) {
// nextToVisit.add(left)
// }
//
// val right = allPoints.getOrElse(Pair(point.coordinates.first + 1, point.coordinates.second)) { null }
// if ((right?.height ?: Char.MAX_VALUE).code <= point.height.code + 1 && right?.visited == false) {
// nextToVisit.add(right)
// }
//
// val up = allPoints.getOrElse(Pair(point.coordinates.first, point.coordinates.second - 1)) { null }
// if ((up?.height ?: Char.MAX_VALUE).code <= point.height.code + 1 && up?.visited == false) {
// nextToVisit.add(up)
// }
//
// val down = allPoints.getOrElse(Pair(point.coordinates.first, point.coordinates.second + 1)) { null }
// if ((down?.height ?: Char.MAX_VALUE).code <= point.height.code + 1 && down?.visited == false) {
// nextToVisit.add(down)
// }
//
// point.visited = true
// }
//
// if (nextToVisit.any { it.coordinates == end }) {
// return moves
// } else {
// toVisit.clear()
// toVisit.addAll(nextToVisit)
// }
// }
//
// return Int.MAX_VALUE
// }
//}
//
//data class Point(
// val coordinates: Pair<Int, Int>,
// val height: Char,
// var visited: Boolean = false
//)
//fun main() {
//
// println(Day12().partTwo())
//}
| 0 | Kotlin | 0 | 0 | ee521263dee60dd3462bea9302476c456bfebdf8 | 3,594 | advent22 | Apache License 2.0 |
src/main/kotlin/com/github/michaelbull/advent2021/day12/CaveMap.kt | michaelbull | 433,565,311 | false | {"Kotlin": 162839} | package com.github.michaelbull.advent2021.day12
fun Sequence<CaveConnection>.toCaveMap(): CaveMap {
val connections = mutableMapOf<Cave, Set<Cave>>()
for ((start, end) in this@toCaveMap) {
connections[start] = connections.getOrDefault(start, emptySet()) + end
connections[end] = connections.getOrDefault(end, emptySet()) + start
}
return CaveMap(connections)
}
data class CaveMap(
val connections: Map<Cave, Set<Cave>>
) {
fun countPaths(rule: PathRule): Int {
return countPaths(Cave.START, emptyList(), rule)
}
private fun countPaths(cave: Cave, visited: List<Cave>, rule: PathRule): Int {
return connections.getValue(cave).sumOf {
if (it == Cave.END) {
1
} else if (it == Cave.START || !rule(it, visited)) {
0
} else {
countPaths(it, visited + it, rule)
}
}
}
}
| 0 | Kotlin | 0 | 4 | 7cec2ac03705da007f227306ceb0e87f302e2e54 | 942 | advent-2021 | ISC License |
index-lib/src/main/kotlin/cz/vutbr/fit/knot/enticing/index/collection/manager/postprocess/OverlapFiltering.kt | d-kozak | 180,137,313 | false | {"Kotlin": 1104829, "TypeScript": 477922, "Python": 23617, "Shell": 19609, "HTML": 8510, "ANTLR": 2005, "CSS": 1432} | package cz.vutbr.fit.knot.enticing.index.collection.manager.postprocess
import cz.vutbr.fit.knot.enticing.eql.compiler.matching.DocumentMatch
import cz.vutbr.fit.knot.enticing.index.boundary.IndexedDocument
import cz.vutbr.fit.knot.enticing.index.boundary.MatchInfo
import cz.vutbr.fit.knot.enticing.index.collection.manager.postprocess.util.SegmentTree
import cz.vutbr.fit.knot.enticing.index.collection.manager.postprocess.util.isFree
import cz.vutbr.fit.knot.enticing.index.collection.manager.postprocess.util.take
/**
* The goal of this postprocessing is filtering out all overlapping intervals.
*
* The input is a list of intervals.
*
* The output is a filtered version of the input such that no intervals are overlapping and the shorter intervals are preferred over longer ones.
*
* Steps:
* 1) sort the intervals based on their length, shortest first
* * intervals with same length are sorted based on their starting position
* 2) traverse the sorted list and for each interval:
* 2a) check if it is not overlapping with anything already taken
* * if not, take it and mark appropriate part of the document as taken
*
* Now the question is how to store and query the information about which intervals of the document are already taken?
*
* Approach one - segment tree, which stores for each index whether it is used or not.
* The problem is that we need both interval query and interval update, therefore we would need a segment tree with lazy propagation.
* But since all we need is a binary information and we will only change it once, we could just keep it in the middle nodes, no need to actually propagate anything down or up :)
*/
/**
* First by size, then by starting position
*/
private val matchComparator = compareBy<DocumentMatch> { it.interval.size }
.thenBy { it.interval.from }
fun filterOverlappingIntervals(document: IndexedDocument, matchInfo: MatchInfo): MatchInfo {
val matchList = matchInfo.intervals.sortedWith(matchComparator)
val root = SegmentTree(0, document.size - 1)
val res = mutableListOf<DocumentMatch>()
for (match in matchList) {
if (root.isFree(match.interval)) {
root.take(match.interval)
res.add(match)
}
}
return MatchInfo(res)
}
| 0 | Kotlin | 0 | 0 | 1ea9f874c6d2e4ea158e20bbf672fc45bcb4a561 | 2,290 | enticing | MIT License |
src/main/kotlin/org/mechdancer/algebra/function/vector/Distance.kt | MechDancer | 128,765,281 | false | null | package org.mechdancer.algebra.function.vector
import org.mechdancer.algebra.core.Vector
import org.mechdancer.algebra.function.vector.DistanceType.*
import kotlin.math.acos
/** 计算两个向量之间的某种距离 */
enum class DistanceType(val between: (Vector, Vector) -> Double) {
/** 用弧度表示的夹角 */
IncludedAngle({ one, other -> acos((one dot other) / one.length / other.length) }),
/** 欧式距离 */
Euclid({ one, other -> (one - other).length }),
/** 曼哈顿距离 */
Manhattan({ one, other -> (one - other).norm(+1) }),
/** 切比雪夫距离 */
Chebyshev({ one, other -> (one - other).norm(-1) });
infix fun between(pair: Pair<Vector, Vector>) = between(pair.first, pair.second)
}
/** @return 与[other]间用弧度表示的夹角 */
infix fun Vector.includedAngle(other: Vector) = IncludedAngle.between(this, other)
/** @return 与[other]间的欧式距离 */
infix fun Vector.euclid(other: Vector) = Euclid.between(this, other)
/** @return 与[other]间的曼哈顿距离 */
infix fun Vector.manhattan(other: Vector) = Manhattan.between(this, other)
/** @return 与[other]间的切比雪夫距离 */
infix fun Vector.chebyshev(other: Vector) = Chebyshev.between(this, other)
fun distance(one: Vector, other: Vector, type: DistanceType) = type.between(one, other)
| 1 | Kotlin | 1 | 6 | 2cbc7e60b3cd32f46a599878387857f738abda46 | 1,314 | linearalgebra | Do What The F*ck You Want To Public License |
src/Day04.kt | mattfrsn | 573,195,420 | false | {"Kotlin": 5703} | import java.io.File
fun main() {
fun part1(input: List<String>): Int {
val ranges = input.map { elfAssignments ->
elfAssignments.asRanges()
}
return ranges.count { it.first.fullyOverlaps(it.second) || it.second.fullyOverlaps(it.first) }
}
fun part2(input: List<String>): Int {
val ranges = input.map { elfAssignments ->
elfAssignments.asRanges()
}
return ranges.count { it.first.overlaps(it.second) || it.second.overlaps(it.first) }
}
val input = File("src/input.txt").readLines()
println(part1(input))
println(part2(input))
}
private infix fun IntRange.fullyOverlaps(otherRange: IntRange): Boolean =
first <= otherRange.first && last >= otherRange.last
private infix fun IntRange.overlaps(otherRange: IntRange): Boolean =
first <= otherRange.last && otherRange.first <= last
private fun String.asIntRange(): IntRange =
substringBefore("-").toInt()..substringAfter("-").toInt()
private fun String.asRanges(): Pair<IntRange, IntRange> =
substringBefore(",").asIntRange() to substringAfter(",").asIntRange() | 0 | Kotlin | 0 | 0 | f17941024c1a2bac1cea88c3d9f6b7ecb9fd67e4 | 1,129 | kotlinAdvent2022 | Apache License 2.0 |
src/main/kotlin/io/rbrincke/dice/core/Solver.kt | rbrincke | 167,712,634 | false | {"Kotlin": 13146} | package io.rbrincke.dice.core
/**
* Sets up a solver that is able to find allocations of [labels] that lead to non-transitive
* elements. The number of resulting elements equals the size of [labelGroupSizes], and each
* element will contain precisely the number specified in [labelGroupSizes].
*
* @param labels labels that are to be allocated to elements
* @param labelGroupSizes the group sizes in which labels should be allocated (sum of all elements must equal the size of [labels])
* @param elementCreator function that describes how to to create an element from a list of [labels]
*/
class Solver<S, T : Element<T>>(
private val labels: List<S>,
private val labelGroupSizes: List<Int>,
private val elementCreator: (List<S>) -> T
) {
init {
check(labelGroupSizes.isNotEmpty())
check(labelGroupSizes.all { it > 0 }) {
"Input set sizes must all be strictly positive."
}
check(labelGroupSizes.sum() == labels.size) {
"Input set element count does not equal the total of combination sizes."
}
}
private fun permutationToElementSet(permutation: List<Int>): Combination<T> {
val target = labelGroupSizes.mapIndexed { index, i ->
index to ArrayList<S>(i)
}.toMap()
permutation.mapIndexed { index, i ->
target.getValue(i).add(labels[index])
}
val elements = target.values.map { elementCreator.invoke(it) }
return Combination(elements)
}
/**
* Find any non-transitive [Combination]s.
*/
fun solve(): List<Combination<T>> {
// Perform permutation on a mask to avoid duplicate groupings due
// to group-internal ordering differences.
val mask = mutableListOf<Int>()
labelGroupSizes.forEachIndexed { idx, count ->
repeat(count) { mask.add(idx) }
}
check(mask.size == labels.size)
// Fix the first item to slot 0 to avoid identical solutions
// with rotated positions.
return MultisetPermutationIterator(mask.drop(1))
.asSequence()
.map { listOf(0) + it }
.map(::permutationToElementSet)
.filter { it.isNonTransitive() }
.toList()
}
}
| 0 | Kotlin | 0 | 0 | fc5aa0365d91ce360bf6e9c7589e3f5fc6bc8a82 | 2,273 | nontransitive-dice | MIT License |
src/main/kotlin/advent/Advent6.kt | v3rm0n | 225,866,365 | false | null | package advent
class Advent6 : Advent {
private fun orbits(input: List<String>) = input.map { it.split(')').let { (a, b) -> b to a } }.toMap()
override fun firstTask(input: List<String>) = orbits(input).let { orbits ->
orbits.values.map { planets(orbits, it).count() + 1 }.sum()
}
override fun secondTask(input: List<String>) =
orbits(input).let { orbits ->
(planets(orbits, "YOU") to planets(orbits, "SAN"))
.let { (you, san) ->
you.count() + san.count() - 2 * you.intersect(san).count()
}
}
private tailrec fun planets(
orbits: Map<String, String>,
planet: String,
acc: List<String> = emptyList()
): List<String> {
if (planet == "COM") return acc
val orbitsPlanet = orbits[planet] ?: error("No planet")
return planets(orbits, orbitsPlanet, listOf(orbitsPlanet) + acc)
}
}
| 0 | Kotlin | 0 | 1 | 5c36cb254100f80a6e9c16adff5e7aadc8c9e98f | 943 | aoc2019 | MIT License |
src/main/kotlin/com/hj/leetcode/kotlin/problem17/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem17
/**
* LeetCode page: [17. Letter Combinations of a Phone Number](https://leetcode.com/problems/letter-combinations-of-a-phone-number/);
*/
class Solution {
private val digitChars = mapOf(
'2' to "abc",
'3' to "def",
'4' to "ghi",
'5' to "jkl",
'6' to "mno",
'7' to "pqrs",
'8' to "tuv",
'9' to "wxyz"
)
/* Complexity:
* Time O(N * 4^N) and Space O(N * 4^N) where N is the length of digits;
*/
fun letterCombinations(digits: String): List<String> {
if (digits.isEmpty()) {
return emptyList()
}
val result = mutableListOf<String>()
makeCombination(digits) { combination ->
result.add(combination)
}
return result
}
private fun makeCombination(
digits: String,
currentLetters: StringBuilder = StringBuilder(),
onEachCombination: (combination: String) -> Unit
) {
if (currentLetters.length == digits.length) {
onEachCombination(currentLetters.toString())
return
}
val nextDigit = digits[currentLetters.length]
for (char in checkNotNull(digitChars[nextDigit])) {
currentLetters.append(char)
makeCombination(digits, currentLetters, onEachCombination)
currentLetters.apply { deleteCharAt(lastIndex) }
}
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 1,450 | hj-leetcode-kotlin | Apache License 2.0 |
Retos/Reto #7 - EL SOMBRERO SELECCIONADOR [Media]/kotlin/malopezrom.kts | mouredev | 581,049,695 | false | {"Python": 3866914, "JavaScript": 1514237, "Java": 1272062, "C#": 770734, "Kotlin": 533094, "TypeScript": 457043, "Rust": 356917, "PHP": 281430, "Go": 243918, "Jupyter Notebook": 221090, "Swift": 216751, "C": 210761, "C++": 164758, "Dart": 159755, "Ruby": 70259, "Perl": 52923, "VBScript": 49663, "HTML": 45912, "Raku": 44139, "Scala": 30892, "Shell": 27625, "R": 19771, "Lua": 16625, "COBOL": 15467, "PowerShell": 14611, "Common Lisp": 12715, "F#": 12710, "Pascal": 12673, "Haskell": 11051, "Assembly": 10368, "Elixir": 9033, "Visual Basic .NET": 7350, "Groovy": 7331, "PLpgSQL": 6742, "Clojure": 6227, "TSQL": 5744, "Zig": 5594, "Objective-C": 5413, "Apex": 4662, "ActionScript": 3778, "Batchfile": 3608, "OCaml": 3407, "Ada": 3349, "ABAP": 2631, "Erlang": 2460, "BASIC": 2340, "D": 2243, "Awk": 2203, "CoffeeScript": 2199, "Vim Script": 2158, "Brainfuck": 1550, "Prolog": 1342, "Crystal": 783, "Fortran": 778, "Solidity": 560, "Standard ML": 525, "Scheme": 457, "Vala": 454, "Limbo": 356, "xBase": 346, "Jasmin": 285, "Eiffel": 256, "GDScript": 252, "Witcher Script": 228, "Julia": 224, "MATLAB": 193, "Forth": 177, "Mercury": 175, "Befunge": 173, "Ballerina": 160, "Smalltalk": 130, "Modula-2": 129, "Rebol": 127, "NewLisp": 124, "Haxe": 112, "HolyC": 110, "GLSL": 106, "CWeb": 105, "AL": 102, "Fantom": 97, "Alloy": 93, "Cool": 93, "AppleScript": 85, "Ceylon": 81, "Idris": 80, "Dylan": 70, "Agda": 69, "Pony": 69, "Pawn": 65, "Elm": 61, "Red": 61, "Grace": 59, "Mathematica": 58, "Lasso": 57, "Genie": 42, "LOLCODE": 40, "Nim": 38, "V": 38, "Chapel": 34, "Ioke": 32, "Racket": 28, "LiveScript": 25, "Self": 24, "Hy": 22, "Arc": 21, "Nit": 21, "Boo": 19, "Tcl": 17, "Turing": 17} | package com.malopezrom.reto7
/*
* Crea un programa que simule el comportamiento del sombrero selccionador del
* universo mágico de <NAME>.
* - De ser posible realizará 5 preguntas (como mínimo) a través de la terminal.
* - Cada pregunta tendrá 4 respuestas posibles (también a selecciona una a través de terminal).
* - En función de las respuestas a las 5 preguntas deberás diseñar un algoritmo que
* coloque al alumno en una de las 4 casas de Hogwarts (Gryffindor, Slytherin , Hufflepuff y Ravenclaw)
* - Ten en cuenta los rasgos de cada casa para hacer las preguntas y crear el algoritmo seleccionador.
* Por ejemplo, en Slytherin se premia la ambición y la astucia.
*/
/**
* Interface que representa una respuesta y sus puntos
*/
data class Question(private val question: String, private val answers: List<Answer>) {
fun ask(): Answer {
println(question)
println("")
answers.forEachIndexed { index, answer -> println("${index + 1}. ${answer.answer}") }
var answer: Int
do {
print("\nElige una opción: ")
answer = readLine()?.toIntOrNull() ?: 0
} while (answer !in 1..4)
return answers[answer - 1]
}
}
/**
* Interface que representa una respuesta y sus puntos
*/
data class Answer(val answer: String, val points: List<Point>) {
fun getPoints(team: Team): Int {
return points.firstOrNull { it.name == team }?.points ?: 0
}
}
/**
* Interface que representa los puntos de cada equipo
*/
data class Point(val name: Team, val points: Int)
/**
* Enumerado que representa los equipos
*/
enum class Team(val team: String){
Celtic("Celtic de Pulianas"),
Farsa("Farsa el equipo de los culerdos"),
GranadaCF("Vamos mi grana"),
RMadrid("Central Lechera")
}
/**
* Array de preguntas y respuestas y sus puntos correspondientes a cada equipo
*/
val quizz = listOf(
Question(
"Se acerca la fecha del próximo partido de tu equipo, ¿cómo te sientes?",
listOf(
Answer("Nervioso/a, todos los partidos de mi equipo los siento con pasión.", listOf(Point(Team.Celtic, 10), Point(Team.Farsa, 0), Point(Team.GranadaCF, 9), Point(Team.RMadrid, 2))),
Answer("No es relevante, cuando llegue la hora ya me sentaré a verlo tranquilamente.",listOf(Point(Team.Celtic, 0), Point(Team.Farsa, 7), Point(Team.GranadaCF,2), Point(Team.RMadrid, 7))),
Answer("Los vecinos hablan sobre el partido los días previos, se nota el ambiente en la calle.",listOf(Point(Team.Celtic, 4), Point(Team.Farsa, 10), Point(Team.GranadaCF,1), Point(Team.RMadrid, 9))),
Answer("No como ni duermo los días previos de los nervios. Da igual que sean dieciseisavos de Copa o la última jornada de Liga, lo vivo.",listOf(Point(Team.Celtic, 8), Point(Team.Farsa, 1), Point(Team.GranadaCF,10), Point(Team.RMadrid, 0)))
)),
Question(
"Estás en un bar y te das cuenta de que nadie es del mismo equipo que tú, ¿qué piensas?",
listOf(
Answer("Joder, mira que es raro.", listOf(Point(Team.Celtic, 10), Point(Team.Farsa, 0), Point(Team.GranadaCF, 3), Point(Team.RMadrid, 2))),
Answer("Ya está esto lleno de borregos, míralos, todos viendo el Chirincirco.",listOf(Point(Team.Celtic, 1), Point(Team.Farsa, 7), Point(Team.GranadaCF,4), Point(Team.RMadrid, 9))),
Answer("Normal, si somos 4 gatos. Eh, pero con orgullo, coño.",listOf(Point(Team.Celtic, 2), Point(Team.Farsa, 10), Point(Team.GranadaCF,1), Point(Team.RMadrid, 2))),
Answer("Ups, igual tenía que haber ido al de dos calles más abajo...",listOf(Point(Team.Celtic, 10), Point(Team.Farsa, 1), Point(Team.GranadaCF,4), Point(Team.RMadrid, 1)))
)),
Question(
"Penalti a favor del Madrid/Barcelona. En la repetición se ve que no era. ¿Cómo reaccionas?",
listOf(
Answer("Ya están robando estos perros.", listOf(Point(Team.Celtic, 10), Point(Team.Farsa, 0), Point(Team.GranadaCF, 9), Point(Team.RMadrid, 2))),
Answer("Esto es una puta vergüenza! Soy el entrenador y los saco del campo, que se rían de su madre.",listOf(Point(Team.Celtic, 3), Point(Team.Farsa, 10), Point(Team.GranadaCF,3), Point(Team.RMadrid, 9))),
Answer("Ya la tenemos liada, ahora a aguantar a la prensa toda la semana...",listOf(Point(Team.Celtic, 4), Point(Team.Farsa, 0), Point(Team.GranadaCF,9), Point(Team.RMadrid, 2))),
Answer("Ya estamos con la prensa mamadora del movimiento",listOf(Point(Team.Celtic, 10), Point(Team.Farsa, 0), Point(Team.GranadaCF,9), Point(Team.RMadrid, 2)))
)),
Question(
"Caso contrario: última jornada de liga y una victoria de tu equipo hace que supere el objetivo marcado al principio del año.",
listOf(
Answer("Coño, coño, coño, coño, coño, coño. Como les dé por ganar me desnudo en la fuente del pueblo.", listOf(Point(Team.Celtic, 10), Point(Team.Farsa, 0), Point(Team.GranadaCF, 9), Point(Team.RMadrid, 2))),
Answer("Yaya, enséñame unos rezos de esos, que es para una cosa del finde.",listOf(Point(Team.Celtic, 1), Point(Team.Farsa, 9), Point(Team.GranadaCF,2), Point(Team.RMadrid, 6))),
Answer("Pase lo que pase ha sido un temporadón, ¡qué orgullo de equipo!",listOf(Point(Team.Celtic, 6), Point(Team.Farsa, 5), Point(Team.GranadaCF,4), Point(Team.RMadrid, 4))),
Answer("Con lo bien que vivía yo cuando éramos mediocres, qué ganas de matarnos con los nervios.",listOf(Point(Team.Celtic, 10), Point(Team.Farsa, 1), Point(Team.GranadaCF,9), Point(Team.RMadrid, 4)))
)),
Question(
"Final de la temporada, tu equipo desciende a Segunda División. Vaya veranito te vas a pegar...",
listOf(
Answer("JAJAJAJAJAJAJAJAJA EN SEGUNDA DICE, ¡QUE SOY DEL MADRID/BARÇA, TOLAI!", listOf(Point(Team.Celtic, 0), Point(Team.Farsa, 10), Point(Team.GranadaCF, 0), Point(Team.RMadrid, 10))),
Answer("Lloro, me enfado, durante las primeras semanas va a ser una auténtica pesadilla. No puede pasarnos a nosotros...",listOf(Point(Team.Celtic, 5), Point(Team.Farsa, 7), Point(Team.GranadaCF,3), Point(Team.RMadrid, 4))),
Answer("No pudo ser, nos vino grande la categoría. Volveremos con más fuerza, ¡seguro!",listOf(Point(Team.Celtic, 7), Point(Team.Farsa, 2), Point(Team.GranadaCF,9), Point(Team.RMadrid, 2))),
Answer("Otra vez al hoyo. El año que viene mi abono se lo pueden meter por el...",listOf(Point(Team.Celtic, 4), Point(Team.Farsa, 0), Point(Team.GranadaCF,9), Point(Team.RMadrid, 0)))
)),
)
/**
* Función que calcula el equipo al que perteneces
*/
fun yourTeamsIs(points:MutableMap<Team,Int>){
val teamWithMaxPoints = points.maxBy { it.value }.key
println("Tu equipo es: ${teamWithMaxPoints.team}")
}
/**
* Función principal que llama a la función que muestra las preguntas
*/
fun quizGame(){
val points = mutableMapOf<Team, Int>()
points[Team.Celtic] = 0
points[Team.Farsa] = 0
points[Team.GranadaCF] = 0
points[Team.RMadrid] = 0
println("Bienvenido al test de fútbol. Responde a las siguientes preguntas y averigua qué equipo eres:\n")
quizz.forEach { question ->
val answer = question.ask()
answer.points.forEach { point ->
//points[point.name] = (points[point.name] ?: 0) + point.points
points[point.name] = (answer.getPoints(point.name) + (points[point.name] ?: 0))
}
}
yourTeamsIs(points)
}
/**
* Llamada a la función principal
*/
quizGame()
| 4 | Python | 2,929 | 4,661 | adcec568ef7944fae3dcbb40c79dbfb8ef1f633c | 7,756 | retos-programacion-2023 | Apache License 2.0 |
src/day03/Day03.kt | ritesh-singh | 572,210,598 | false | {"Kotlin": 99540} | package day03
import readInput
fun main() {
fun Char.priority() = if (isUpperCase()) this - 'A' + 27 else this - 'a' + 1
fun part1(input: List<String>): Int {
return input.sumOf { item ->
item.chunked(item.length / 2)
.map { it.toSet() }
.reduce { first, second -> first.intersect(second) }
.first().priority()
}
}
fun part2(input: List<String>): Int {
return input.map { it.toSet() }
.chunked(3)
.map { it.reduce { first, second -> first.intersect(second) } }
.sumOf { it.first().priority() }
}
val input = readInput("/day03/Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 17fd65a8fac7fa0c6f4718d218a91a7b7d535eab | 738 | aoc-2022-kotlin | Apache License 2.0 |
src/main/kotlin/com/sk/set0/91. Decode Ways.kt | sandeep549 | 262,513,267 | false | {"Kotlin": 530613} | package com.sk.set0
class Solution91 {
fun numDecodings(s: String): Int {
fun isValid(i: Int) = s[i] != '0'
fun isValid(i: Int, j: Int) = (s[i] != '0' && s.substring(i, j + 1).toInt() <= 26)
val dp = IntArray(s.length + 1) { -1 }
dp[0] = if (s[0] == '0') 0 else 1
fun ways(n: Int): Int { //ways to decode til index n
if (n < 0) return 1 // valid decoding when right part is valid and nothing left on left side
if (dp[n] == -1) {
var a = 0
if (isValid(n)) a += ways(n - 1)
if (isValid(n - 1, n)) a += ways(n - 2)
dp[n] = a
}
return dp[n]
}
ways(s.lastIndex)
return if (dp[s.lastIndex] == -1) 0 else dp[s.lastIndex]
}
fun numDecodings2(s: String): Int {
val n = s.length
val dp = IntArray(n + 1)
dp[0] = 1
dp[1] = if (s[0] != '0') 1 else 0
for (i in 2..n) { // dp[k], ways to decode string of size k, i.e. upto length k-1
val lastOne = Integer.valueOf(s.substring(i - 1, i))
val lastTwo = Integer.valueOf(s.substring(i - 2, i))
if (lastOne in 1..9) {
dp[i] += dp[i - 1]
}
if (lastTwo in 10..26) {
dp[i] += dp[i - 2]
}
}
return dp[n]
}
fun numDecodings3(s: String): Int {
val n = s.length
val dp = IntArray(n + 1)
var b = 1
var a = if (s[0] != '0') 1 else 0
for (i in 2..n) { // dp[k], ways to decode string of size k, i.e. upto length k-1
val lastOne = Integer.valueOf(s.substring(i - 1, i))
val lastTwo = Integer.valueOf(s.substring(i - 2, i))
var t = 0
if (lastOne in 1..9) {
t += a
}
if (lastTwo in 10..26) {
t += b
}
b = a
a = t
}
return a
}
} | 1 | Kotlin | 0 | 0 | cf357cdaaab2609de64a0e8ee9d9b5168c69ac12 | 2,010 | leetcode-kotlin | Apache License 2.0 |
src/main/kotlin/tr/emreone/adventofcode/days/Day04.kt | EmRe-One | 433,772,813 | false | {"Kotlin": 118159} | package tr.emreone.adventofcode.days
import tr.emreone.kotlin_utils.automation.Day
class Day04 : Day(4, 2021, "Giant Squid") {
class Field(var value: Int) {
var isMarked = false
}
class Board(lines: List<String>) {
val fields = Array(5) {
Array(5) {
Field(0)
}
}
var finished = false
init {
check(lines.size == 6) { "Invalid input. Lines have one empty line and 5 lines for the 5x5 matrix" }
val regex = """^(\d+) (\d+) (\d+) (\d+) (\d+)$""".toRegex()
for (i in 1..5) {
val preparedLine = lines[i].trim().replace("""(\s+)""".toRegex(), " ")
val (a, b, c, d, e) = regex.find(preparedLine)!!.destructured
fields[i - 1][0].value = a.toInt()
fields[i - 1][1].value = b.toInt()
fields[i - 1][2].value = c.toInt()
fields[i - 1][3].value = d.toInt()
fields[i - 1][4].value = e.toInt()
}
}
fun checkWin(): Boolean {
for (row in fields) {
if (row.all { it.isMarked }) {
this.finished = true
return true
}
}
for (col in 0..4) {
val tempCol = arrayOf(fields[0][col], fields[1][col], fields[2][col], fields[3][col], fields[4][col])
if (tempCol.all { it.isMarked }) {
this.finished = true
return true
}
}
return false
}
fun mark(d: Int) {
outer@ for (row in 0..4) {
inner@ for (f in 0..4) {
if (fields[row][f].value == d) {
fields[row][f].isMarked = true
break@outer
}
}
}
}
fun sumOfUnmarked(): Int {
return fields.sumOf { row ->
row.sumOf { field ->
if (field.isMarked)
0
else
field.value
}
}
}
}
override fun part1(): Int {
val drawingNumbers = inputAsList[0].split(",").map { it.toInt() }
val boards = inputAsList.subList(1, inputAsList.size).windowed(6, 6) {
Board(it)
}
var winningPair: Pair<Int, Board>? = null
outer@ for (d in drawingNumbers) {
inner@ for (b in boards) {
b.mark(d)
if (b.checkWin()) {
winningPair = Pair(d, b)
break@outer
}
}
}
if (winningPair != null) {
return winningPair.first * winningPair.second.sumOfUnmarked()
}
return 0
}
override fun part2(): Int {
val drawingNumbers = inputAsList[0].split(",").map { it.toInt() }
val boards = inputAsList.subList(1, inputAsList.size).windowed(6, 6) {
Board(it)
}
var numberOfFinishedBoards = 0
var lastWinningPair: Pair<Int, Board>? = null
outer@ for (d in drawingNumbers) {
inner@ for (b in boards) {
if (b.finished) {
continue@inner
}
b.mark(d)
if (b.checkWin()) {
numberOfFinishedBoards++
}
if (numberOfFinishedBoards == boards.size) {
lastWinningPair = Pair(d, b)
break@outer
}
}
}
if (lastWinningPair != null) {
return lastWinningPair.first * lastWinningPair.second.sumOfUnmarked()
}
return 0
}
}
| 0 | Kotlin | 0 | 0 | 516718bd31fbf00693752c1eabdfcf3fe2ce903c | 3,846 | advent-of-code-2021 | Apache License 2.0 |
src/day01/Day01.kt | cmargonis | 573,161,233 | false | {"Kotlin": 15730} | package day01
import readInput
private const val DIRECTORY = "./day01"
fun main() {
fun getElves(input: List<String>): List<Elf> {
var calories = 0
val elves = mutableListOf<Elf>()
input.forEach {
if (it.isNotBlank()) {
calories += it.toInt()
} else {
elves.add(Elf(calories))
calories = 0
}
}
return elves
}
fun part1(input: List<String>): Int {
val elves = getElves(input)
return elves.maxBy { it.totalCalories }.totalCalories
}
fun part2(input: List<String>): Int = getElves(input)
.asSequence()
.sortedByDescending { it.totalCalories }
.take(3)
.sumOf { it.totalCalories }
val input = readInput("${DIRECTORY}/Day01")
println(part1(input))
println(part2(input))
}
data class Elf(val totalCalories: Int)
| 0 | Kotlin | 0 | 0 | bd243c61bf8aae81daf9e50b2117450c4f39e18c | 917 | kotlin-advent-2022 | Apache License 2.0 |
src/main/kotlin/solutions/day23/Day23.kt | Dr-Horv | 112,381,975 | false | null | package solutions.day23
import solutions.Solver
import utils.*
class Day23 : Solver {
override fun solve(input: List<String>, partTwo: Boolean): String {
if (partTwo) {
return doPartTwo()
}
val registers = mutableMapOf<String, Long>().withDefault { 0 }
val instructions = input
var index = 0L
var iteration = 0
var mulUsed = 0
loop@ while (index < instructions.size) {
iteration++
val instruction = instructions[index.toInt()].splitAtWhitespace()
when (instruction[0]) {
"set" -> set(registers, instruction[1], instruction[2])
"sub" -> sub(registers, instruction[1], instruction[2])
"mul" -> {
mul(registers, instruction[1], instruction[2])
mulUsed++
}
"jnz" -> {
if (getValue(registers, instruction[1]) != 0L) {
index += getValue(registers, instruction[2])
continue@loop
}
}
}
index++
}
return mulUsed.toString()
}
private fun doPartTwo(): String {
var a = 1
var b = 0
var c = 0
var d = 0
var e = 0
var f = 0
var g = 0
var h = 0
b = 65 // set b 65
c = b // set c b
if(a != 0) {
b = b * 100 // mul b 100
b = b + 100_000 // sub b -100_000
c = b // set c b
c = c + 17_000 // sub c -17_000
}
loop3@ while (true) {
f = 1 // set f 1
d = 2 // set d 2
loop2@ while (true) {
loop1@ while (true) {
if(b % d == 0) {
f = 0
}
e = b
g = e - b // sub g b
if (g == 0) { // jnz g -8
break@loop1
}
}
d++ // sub d -1
g = d - b // sub g b
if (g == 0) { // jnz g -13
break@loop2
}
}
if (f == 0) { // jnz f 2
h++ // sub h -1
}
g = b - c // sub g c
if (g == 0) { // jnz g 2, jnz 1 3
break@loop3
}
b = b + 17 // sub - 17
// jnz 1 -23
}
return h.toString()
}
}
| 0 | Kotlin | 0 | 2 | 975695cc49f19a42c0407f41355abbfe0cb3cc59 | 2,558 | Advent-of-Code-2017 | MIT License |
src/day04/Day04.kt | commanderpepper | 574,647,779 | false | {"Kotlin": 44999} | package day04
import readInput
fun main (){
val dayFourInput = readInput("day04")
val ranges: List<Pair<IntRange,IntRange>> = dayFourInput.map { it.asRanges() }
println(ranges.count { it.first fullyOverlaps it.second || it.second fullyOverlaps it.first })
println(ranges.count { it.first overlaps it.second })
}
private fun String.asIntRange(): IntRange =
substringBefore("-").toInt() .. substringAfter("-").toInt()
private fun String.asRanges(): Pair<IntRange,IntRange> =
substringBefore(",").asIntRange() to substringAfter(",").asIntRange()
private infix fun IntRange.fullyOverlaps(other: IntRange): Boolean =
first <= other.first && last >= other.last
private infix fun IntRange.overlaps(other: IntRange): Boolean =
first <= other.last && other.first <= last
data class Section(val start: Int, val end: Int){
fun contains(otherSection: Section): Boolean {
return this.start <= otherSection.start && this.end >= otherSection.end
}
} | 0 | Kotlin | 0 | 0 | fef291c511408c1a6f34a24ed7070ceabc0894a1 | 987 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/WordBreak2.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import kotlin.math.max
/**
* 140. Word Break II
* @see <a href="https://leetcode.com/problems/word-break-ii/">Source</a>
*/
fun interface WordBreak2 {
operator fun invoke(s: String, wordDict: List<String>): List<String>
}
class WordBreak2DPDFS : WordBreak2 {
override operator fun invoke(s: String, wordDict: List<String>): List<String> {
val starts: Array<MutableList<Int>?> = arrayOfNulls(s.length + 1)
starts[0] = ArrayList()
val maxLen = getMaxLen(wordDict)
for (i in 1..s.length) {
var j = i - 1
while (j >= i - maxLen && j >= 0) {
if (starts[j] == null) {
j--
continue
}
val word = s.substring(j, i)
if (wordDict.contains(word)) {
if (starts[i] == null) {
starts[i] = ArrayList()
}
starts[i]?.add(j)
}
j--
}
}
val rst: MutableList<String> = ArrayList()
if (starts[s.length] == null) {
return rst
}
dfs(rst, "", s, starts, s.length)
return rst
}
private fun dfs(rst: MutableList<String>, path: String, s: String, starts: Array<MutableList<Int>?>, end: Int) {
if (end == 0) {
rst.add(path.substring(1))
return
}
for (start in starts[end] ?: emptyList()) {
val word = s.substring(start, end)
dfs(rst, " $word$path", s, starts, start)
}
}
private fun getMaxLen(wordDict: List<String>): Int {
var max = 0
for (s in wordDict) {
max = max(max, s.length)
}
return max
}
}
/**
* Method 3: DP Prunning + Backtracking
*/
class WordBreak2Backtracking : WordBreak2 {
override operator fun invoke(s: String, wordDict: List<String>): List<String> {
val rst: MutableList<String> = ArrayList()
val canBreak = BooleanArray(s.length) { true }
val sb = StringBuilder()
dfs(rst, sb, s, wordDict, canBreak, 0)
return rst
}
private fun dfs(
rst: MutableList<String>,
sb: StringBuilder,
s: String,
dict: List<String>,
canBreak: BooleanArray,
start: Int,
) {
if (start == s.length) {
rst.add(sb.substring(1))
return
}
if (!canBreak[start]) {
return
}
for (i in start + 1..s.length) {
val word = s.substring(start, i)
if (!dict.contains(word)) {
continue
}
val sbBeforeAdd = sb.length
sb.append(" $word")
val rstBeforeDFS = rst.size
dfs(rst, sb, s, dict, canBreak, i)
if (rst.size == rstBeforeDFS) {
canBreak[i] = false
}
sb.delete(sbBeforeAdd, sb.length)
}
}
}
class WordBreak2DFS : WordBreak2 {
override operator fun invoke(s: String, wordDict: List<String>): List<String> {
return backtrack(s, wordDict, HashMap())
}
// backtrack returns an array including all substrings derived from s.
private fun backtrack(s: String, wordDict: List<String>, mem: MutableMap<String, List<String>>): List<String> {
if (mem.containsKey(s)) return mem[s] ?: emptyList()
val result: MutableList<String> = ArrayList()
for (word in wordDict) if (s.startsWith(word)) {
val next = s.substring(word.length)
if (next.isEmpty()) {
result.add(word)
} else {
for (sub in backtrack(next, wordDict, mem)) {
result.add(
"$word $sub",
)
}
}
}
mem[s] = result
return result
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 4,568 | kotlab | Apache License 2.0 |
src/search/ExponentialSearch.kt | daolq3012 | 143,137,563 | false | null | package search
import sort.HeapSort
import java.io.IOException
import java.util.*
class ExponentialSearch : SearchAlgorithms<Int> {
override fun findIndexOf(arr: ArrayList<Int>, value: Int): Int {
val size = arr.size
// If x is present at first location itself
if (arr[0] == value) {
return 0
}
// Find range for binary search by repeated doubling
var bound = 1
while (bound < size && arr[bound] <= value) {
bound *= 2
}
return binarySearch(arr, value, bound / 2, Math.min(bound + 1, size - 1))
}
/**
* This method implements the Generic Binary Search
*
* @param array The array to make the binary search
* @param key The number you are looking for
* @param left The lower bound
* @param right The upper bound
* @return the location of the key
*/
private fun <T : Comparable<T>> binarySearch(array: ArrayList<T>, key: T, left: Int, right: Int): Int {
// this means that the key not found
if (right < left) {
return -1
}
// find median
val median = (left + right).ushr(1) // (It mean: >>> 1 or left + right /2)
val comp = key.compareTo(array[median])
if (comp < 0) {
return binarySearch(array, key, left, median - 1)
}
return if (comp > 0) {
binarySearch(array, key, median + 1, right)
} else {
median
}
}
object Run {
@Throws(IOException::class)
@JvmStatic
fun main(args: Array<String>) {
val dataInputs = arrayListOf(6, 5, 3, 1, 8, 7, 2, 4)
// sort data inputs
HeapSort().sort(dataInputs)
System.out.print("---------Input---------\n$dataInputs\n")
val searchAlgorithms: SearchAlgorithms<Int> = ExponentialSearch()
val randomInput = Random().nextInt(10)
val result = searchAlgorithms.findIndexOf(dataInputs, randomInput)
System.out.print("---------Result---------\n")
if (result != -1) {
System.out.print("Found $randomInput at index $result")
} else {
System.out.print("$randomInput not found in dataInputs!")
}
}
}
}
| 1 | Kotlin | 11 | 74 | 40e00d0d3f1c7cbb93ad28f4197e7ffa5ea36ef9 | 2,329 | Kotlin-Algorithms | Apache License 2.0 |
app/src/main/java/com/developersbreach/hangman/utils/GameDifficultyFilterUitls.kt | RajashekarRaju | 478,249,469 | false | {"Kotlin": 122892} | package com.developersbreach.hangman.utils
import com.developersbreach.hangman.repository.companyData
import com.developersbreach.hangman.repository.countryData
import com.developersbreach.hangman.repository.languageData
/**
* [EASY] -> Filters words of length 4 & 5.
* [MEDIUM] -> Filters words of length 6 & 7
* [HARD] -> Filters words of length 8 to 10
*/
enum class GameDifficulty {
EASY, MEDIUM, HARD
}
/**
* [COUNTRIES]
* [LANGUAGES]
* [COMPANIES]
*/
enum class GameCategory {
COUNTRIES, LANGUAGES, COMPANIES
}
// For adding list of 5 words to guessing list.
data class Words(
val wordName: String
)
/**
* @param gameDifficulty filter between three different guessing words lists based on [GameDifficulty].
* @param gameCategory filter game category added to [GameCategory].
*
* Return only 5 words from the whole list of guessing words.
* Since we will be having 5 levels per each game, one word per level.
*/
fun getFilteredWordsByGameDifficulty(
gameDifficulty: GameDifficulty,
gameCategory: GameCategory
): List<Words> {
val wordsList = ArrayList<Words>()
// First get the result list by filtering category.
with(
when (gameCategory) {
GameCategory.COUNTRIES -> countryData()
GameCategory.LANGUAGES -> languageData()
GameCategory.COMPANIES -> companyData()
}
) {
// From the selected category filter the result list to difficulty.
when (gameDifficulty) {
GameDifficulty.EASY -> this.filterWordsByLength(4..5)
GameDifficulty.MEDIUM -> this.filterWordsByLength(6..7)
GameDifficulty.HARD -> this.filterWordsByLength(8..10)
}.map { word ->
wordsList.add(
Words(wordName = word)
)
}
}
return wordsList
}
/**
* Return only 5 words from the whole list of guessing words.
* Since we will be having 5 levels per each game, one word per level.
*/
private fun List<String>.filterWordsByLength(
range: IntRange,
numberOfWords: Int = 5
): List<String> {
return this.filter { it.length in range }.shuffled().take(numberOfWords)
} | 2 | Kotlin | 5 | 17 | d5181339eec841407bade176e7293fc65a4a3867 | 2,165 | hangman-compose | Apache License 2.0 |
src/day20/Day20.kt | ayukatawago | 572,742,437 | false | {"Kotlin": 58880} | package day20
import readInput
fun main() {
val input = readInput("day20/test")
println(part1(input))
println(part2(input))
}
private fun part1(input: List<String>): Long {
return solve(input)
}
private fun part2(input: List<String>): Long {
return solve(input, 811589153, 10)
}
private fun solve(input: List<String>, decryptionKey: Int = 1, round: Int = 1): Long {
val numbers = input.mapIndexed { index, s -> Number(index, s.toLong() * decryptionKey) }
val size = numbers.size
val mutableList = numbers.toMutableList()
repeat(round) {
mutableList.indices.forEach { originalIndex ->
val index = mutableList.indexOfFirst { originalIndex == it.originalIndex }
val number = mutableList.removeAt(index)
val nextIndex = (index + number.value).mod(size - 1)
mutableList.add(nextIndex, number)
}
}
println(mutableList)
val zeroIndex = mutableList.indexOfFirst { it.value == 0L }
return listOf(1000, 2000, 3000).sumOf {
println(mutableList[(zeroIndex + it).mod(size)])
mutableList[(zeroIndex + it).mod(size)].value
}
}
private data class Number(val originalIndex: Int, val value: Long) | 0 | Kotlin | 0 | 0 | 923f08f3de3cdd7baae3cb19b5e9cf3e46745b51 | 1,220 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/io/github/hc1839/crul/chemistry/species/Aggregate.kt | hc1839 | 724,383,874 | false | {"Kotlin": 541316} | /*
* Copyright <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 io.github.hc1839.crul.chemistry.species
import org.apache.commons.math3.geometry.euclidean.threed.Vector3D
import io.github.hc1839.crul.apache.math.vector.*
import io.github.hc1839.crul.distinct.Referential
/**
* Interface of a species aggregate, which is a species that is composed of
* one or more referentially distinct subspecies.
*
* @param S
* Type of subspecies.
*/
interface Aggregate<S : Species> : Species {
override val atoms: List<Atom>
get() = subspecies
.flatMap { it.atoms }
.distinctBy { Referential(it) }
/**
* List of subspecies in the aggregate.
*
* Subspecies are referentially distinct. Order of the subspecies is
* maintained between evaluations but is implementation-specific.
*/
val subspecies: List<S>
/**
* Whether `species` is a subspecies in the aggregate.
*/
fun contains(species: S): Boolean =
subspecies.any { it === species }
/**
* Whether all species in `speciesCollection` are subspecies in the
* aggregate.
*/
fun containsAll(speciesCollection: Collection<S>): Boolean =
speciesCollection.all { contains(it) }
/**
* Whether an atom exists in the aggregate.
*/
fun containsAtom(atom: Atom): Boolean =
atoms.any { it === atom }
companion object {
/**
* Constructs an [Aggregate].
*
* @param subspecies
* Subspecies in the aggregate.
*
* @return
* New instance of [Aggregate].
*/
@JvmStatic
fun <S : Species> newInstance(subspecies: List<S>) : Aggregate<S> =
AggregateImpl(subspecies)
}
}
/**
* Constructs a new instance of [Aggregate].
*
* See [Aggregate.newInstance].
*/
fun <S : Species> Aggregate(subspecies: List<S>) : Aggregate<S> =
Aggregate.newInstance(subspecies)
| 0 | Kotlin | 0 | 0 | 736b3c8377ca2f2f4a4e86fde6312e50b7ea2505 | 2,532 | crul | Apache License 2.0 |
Array/huangxinyu/kotlin/src/Solution.kt | JessonYue | 268,215,243 | false | null | import com.ryujin.algorithm.ListNode
class Solution {
/**
* 删除倒数第n个节点
*/
fun removeNthFromEnd(listNode: ListNode?, n: Int): ListNode? {
val preHead = ListNode(-1, listNode)
var p1 = listNode
var i = 0
while (i < n) {
assert(p1 != null)
p1 = p1!!.next
i++
}
var p2: ListNode? = preHead
while (p1 != null) {
p1 = p1.next
p2 = p2!!.next
}
p2!!.next = p2.next!!.next
return preHead.next
}
/**
* 合并两个有序链表
*/
fun mergeTwoLists(l1: ListNode?, l2: ListNode?): ListNode? {
var l11 = l1;
var l22 = l2;
val preHead = ListNode(-1, l1)
var pre = preHead
while (l1 != null && l2 != null) {
if (l11!!.value <= l22!!.value) {
pre.next = l11
l22 = l2.next
} else {
pre.next = l22
l11 = l11.next
}
pre = pre.next!!
}
pre.next = l11 ?: l22;
return preHead.next
}
fun oddEvenList(head: ListNode?): ListNode? {
if (head == null) {
return null
}
var l1 = head
var l2 = head.next
val l2Head = l2 //用于之后接到奇数链表末尾
while (l2?.next != null) {
l1?.next = l2.next
l1 = l1?.next
l2.next = l1?.next
l2 = l2.next
}
l2?.next = l2Head;
return head;
}
/**
*判断单链表是否是回文链表
* 使用快慢指针,快指针一次走两步,慢指针走一步,当快指针走到最后时,慢指针
* 就走到中间位置(注意奇偶数),然后将慢指针作为链表头结点进行反转,再和原始链表
* 从头结点开始比较,比较完后全部相同就是回文。时间复杂度是n+0.5n
*/
fun isPalindrome(head: ListNode?): Boolean {
var fast = head
var slow = head
while (fast?.next != null) {
fast = fast.next!!.next
slow = slow!!.next
}
if (fast != null) {
//奇数个
slow = slow!!.next
}
slow = reverse(slow)
fast = head
while (slow != null) {
if (slow.value != fast!!.value) {
return false
}
slow = slow.next
fast = fast.next
}
return true
}
/**
* 反转链表
*/
private fun reverse(head: ListNode?): ListNode? {
var head = head
var pre: ListNode? = null
while (head != null) {
val next = head.next
head.next = pre
pre = head
head = next
}
return pre
}
fun arrayNesting(nums: IntArray): Int {
var ret = 0
for (i in nums.indices) {
var count = 0
var next = i
while (nums[next] != -1) {
val temp = next
next = nums[next]
nums[temp] = -1
count++
}
ret = ret.coerceAtLeast(count)
}
return ret
}
fun numOfSubarrays(arr: IntArray, k: Int, threshold: Int): Int {
var ret = 0
if (arr.size < k) {
return ret
}
var i = 0
val sumThreshld = k * threshold;
var sum = 0
while (i < k) {
sum += arr[i]
++i
}
var delta = sum - sumThreshld
while (i < arr.size) {
delta += (arr[i] - arr[i - k])
if (delta > 0) {
ret++
}
i++
}
return ret
}
} | 0 | C | 19 | 39 | 3c22a4fcdfe8b47f9f64b939c8b27742c4e30b79 | 3,805 | LeetCodeLearning | MIT License |
kotlin/src/com/s13g/aoc/aoc2019/Day16.kt | shaeberling | 50,704,971 | false | {"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245} | package com.s13g.aoc.aoc2019
import com.s13g.aoc.Result
import com.s13g.aoc.Solver
import kotlin.math.abs
/**
* --- Day 16: Flawed Frequency Transmission ---
* https://adventofcode.com/2019/day/16
*/
class Day16 : Solver {
override fun solve(lines: List<String>): Result {
val input = lines[0].map { "$it".toInt() }
val patterns = genPatterns(listOf(0, 1, 0, -1), input.size)
println("Patterns generated")
var state = input
for (n in 1..100) {
state = phaseStep(state, patterns)
}
val resultA = state.subList(0, 8).map { "$it" }.reduce { acc, i -> acc + i }
// Repeat input 10.000 times for PartB
// val inputB = mutableListOf<Int>()
// for (n in 1..10000) {
// inputB.addAll(input)
// }
// var stateB = inputB.toList()
// for (n in 1..100) {
// stateB = phaseStep(stateB, patterns)
// }
return Result(resultA, "n/a")
}
private fun phaseStep(input: List<Int>, patterns: List<List<Int>>): List<Int> {
val output = mutableListOf<Int>()
for (i in input.indices) {
output.add(calcItem(input, patterns[i]))
}
return output
}
private fun calcItem(input: List<Int>, pattern: List<Int>): Int {
var result = 0
for ((i, v) in input.withIndex()) {
result += (v * pattern[(i + 1) % pattern.size])
}
return abs(result % 10)
}
private fun genPatterns(base: List<Int>, num: Int): List<List<Int>> {
val result = mutableListOf<List<Int>>()
for (n in 0..num) {
val pattern = mutableListOf<Int>()
for (x in base) {
for (i in 0..n) {
pattern.add(x)
}
}
result.add(pattern)
}
return result
}
} | 0 | Kotlin | 1 | 2 | 7e5806f288e87d26cd22eca44e5c695faf62a0d7 | 1,679 | euler | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.