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/g1701_1800/s1707_maximum_xor_with_an_element_from_array/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1701_1800.s1707_maximum_xor_with_an_element_from_array
// #Hard #Array #Bit_Manipulation #Trie #2023_06_15_Time_1295_ms_(100.00%)_Space_130.3_MB_(100.00%)
@Suppress("NAME_SHADOWING")
class Solution {
internal class QueryComparator : Comparator<IntArray> {
override fun compare(a: IntArray, b: IntArray): Int {
return a[1].compareTo(b[1])
}
}
internal class Node {
var zero: Node? = null
var one: Node? = null
}
fun maximizeXor(nums: IntArray, queries: Array<IntArray>): IntArray {
nums.sort()
val len = queries.size
val queryWithIndex = Array(len) { IntArray(3) }
for (i in 0 until len) {
queryWithIndex[i][0] = queries[i][0]
queryWithIndex[i][1] = queries[i][1]
queryWithIndex[i][2] = i
}
queryWithIndex.sortWith(QueryComparator())
var numId = 0
val ans = IntArray(len)
val root = Node()
for (i in 0 until len) {
while (numId < nums.size && nums[numId] <= queryWithIndex[i][1]) {
addNumToTree(nums[numId], root)
numId++
}
ans[queryWithIndex[i][2]] = maxXOR(queryWithIndex[i][0], root)
}
return ans
}
private fun addNumToTree(num: Int, node: Node) {
var node: Node? = node
for (i in 31 downTo 0) {
val digit = num shr i and 1
if (digit == 1) {
if (node!!.one == null) {
node.one = Node()
}
node = node.one
} else {
if (node!!.zero == null) {
node.zero = Node()
}
node = node.zero
}
}
}
private fun maxXOR(num: Int, node: Node): Int {
var node: Node? = node
if (node!!.one == null && node.zero == null) {
return -1
}
var ans = 0
var i = 31
while (i >= 0 && node != null) {
val digit = num shr i and 1
if (digit == 1) {
if (node.zero != null) {
ans += 1 shl i
node = node.zero
} else {
node = node.one
}
} else {
if (node.one != null) {
ans += 1 shl i
node = node.one
} else {
node = node.zero
}
}
i--
}
return ans
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 2,576 | LeetCode-in-Kotlin | MIT License |
src/Day06.kt | iProdigy | 572,297,795 | false | {"Kotlin": 33616} | fun main() {
fun solve(input: String, n: Int) = input
.windowedSequence(n) { it.toHashSet() }
.indexOfFirst { it.size >= n } + n
fun part1(input: String) = solve(input, 4)
fun part2(input: String) = solve(input, 14)
// test if implementation meets criteria from the description, like:
check(part1("bvwbjplbgvbhsrlpgdmjqwftvncz") == 5)
check(part1("nppdvjthqldpwncqszvftbrmjlhg") == 6)
check(part1("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg") == 10)
check(part1("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw") == 11)
check(part2("mjqjpqmgbljsphdztnvjfqwrcgsmlb") == 19)
check(part2("bvwbjplbgvbhsrlpgdmjqwftvncz") == 23)
check(part2("nppdvjthqldpwncqszvftbrmjlhg") == 23)
check(part2("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg") == 29)
check(part2("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw") == 26)
val input = readFullInput("Day06")
println(part1(input)) // 1093
println(part2(input)) // 3534
}
| 0 | Kotlin | 0 | 1 | 784fc926735fc01f4cf18d2ec105956c50a0d663 | 942 | advent-of-code-2022 | Apache License 2.0 |
src/day07/Day07.kt | ritesh-singh | 572,210,598 | false | {"Kotlin": 99540} | package day07
import readInput
import java.util.*
enum class NodeType {
DIR, FILE
}
data class MyNode(
val name: String,
val type: NodeType,
val parent: MyNode? = null,
val child: Stack<MyNode> = Stack<MyNode>(),
var size: Long = 0L
) {
override fun toString(): String {
return "$name - $type - $size"
}
}
// Command related
fun String.isCommand() = this == "$"
fun String.isCd() = this == "cd"
fun String.isLs() = this == "ls"
fun String.isDir() = this == "dir"
fun String.navigateToRoot() = this == "/"
fun String.navigateToParent() = this == ".."
fun main() {
val tree = LinkedList<MyNode>()
var rootNode: MyNode? = null
var currentDir: MyNode? = null
fun addFileInCurrentDirectory(fileSize: String, fileName: String) {
if (currentDir == null) return
currentDir!!.child.push(
MyNode(
name = "$fileSize-$fileName",
parent = currentDir,
type = NodeType.FILE,
size = fileSize.toLong()
)
)
currentDir!!.size = currentDir!!.size + fileSize.toLong()
// add the file size to parent dirs
var tempDir:MyNode? = currentDir?.parent
while (tempDir != null && tempDir.type == NodeType.DIR){
tempDir.size = tempDir.size + fileSize.toLong()
tempDir = tempDir.parent
}
}
fun addDirectoryInCurrentNode(dirName: String) {
if (currentDir == null) return
currentDir!!.child.push(
MyNode(
name = dirName,
type = NodeType.DIR,
parent = currentDir
)
)
}
// This is for cd -> / or .. or dir name
fun navigateToInTree(to: String) {
when {
to.navigateToRoot() -> {
if (tree.isEmpty()) {
val node = MyNode(name = to, type = NodeType.DIR, parent = null)
tree.add(node)
rootNode = node
currentDir = node
} else {
currentDir = rootNode
}
}
to.navigateToParent() -> currentDir = currentDir?.parent
else -> {
// navigate to given directory, like a,e,d
val tempDir = currentDir
// dfs
val stack = Stack<MyNode>()
stack.push(tempDir)
while (stack.isNotEmpty()) {
val current = stack.pop() ?: return
for (node in current.child) {
if (node.type == NodeType.DIR && node.name == to) {
currentDir = node
return
}
if (node.type == NodeType.DIR){
stack.push(node)
}
}
}
}
}
}
fun initTree(input: List<String>) {
tree.clear()
rootNode = null
currentDir = null
input.forEach {
val lineInput = it.split(" ").map { it.trim() }
if (lineInput[0].isCommand()) {
when {
lineInput[1].isCd() -> {
val navigateTo = lineInput[2]
navigateToInTree(navigateTo)
}
lineInput[1].isLs() -> {
// do nothing as of now
}
}
} else if (lineInput[0].isDir()) {
// add directory in current node
addDirectoryInCurrentNode(lineInput[1])
} else {
// it's a file
val fileSize = lineInput[0]
val fileName = lineInput[1]
addFileInCurrentDirectory(
fileSize = fileSize,
fileName = fileName
)
}
}
}
fun part1(input: List<String>): Long {
initTree(input)
val list = mutableListOf<Long>()
val tempRootNode = rootNode
// dfs
val stack = Stack<MyNode>()
stack.push(tempRootNode)
while (stack.isNotEmpty()) {
val current = stack.pop() ?: break
if (current.type == NodeType.DIR && current.size <= 100000) {
list.add(current.size)
}
for (node in current.child) {
if (node.type == NodeType.DIR){
stack.push(node)
}
}
}
return list.sum()
}
fun part2(input: List<String>): Long {
initTree(input)
val list = mutableListOf<Long>()
val tempRootNode = rootNode
// dfs
val stack = Stack<MyNode>()
stack.push(tempRootNode)
while (stack.isNotEmpty()) {
val current = stack.pop() ?: break
if (current.type == NodeType.DIR) {
list.add(current.size)
}
for (node in current.child) {
if (node.type == NodeType.DIR){
stack.push(node)
}
}
}
val unusedSpace:Long = 70000000 - rootNode!!.size
val needed = 30000000 - unusedSpace
return list.sorted().find { it >= needed }!!
}
val input = readInput("/day07/Day07")
check(part1(input) == 1350966L)
check(part2(input) == 6296435L)
}
| 0 | Kotlin | 0 | 0 | 17fd65a8fac7fa0c6f4718d218a91a7b7d535eab | 5,528 | aoc-2022-kotlin | Apache License 2.0 |
src/main/aoc2015/Day5.kt | nibarius | 154,152,607 | false | {"Kotlin": 963896} | package aoc2015
class Day5(val input: List<String>) {
private fun String.isNice(): Boolean {
var numVowels = 0
var twiceInARow = false
val blacklist = setOf("ab", "cd", "pq", "xy")
val vowels = setOf('a', 'e', 'i', 'o', 'u')
for (i in indices) {
if (i > 0) {
if (blacklist.contains(substring(i - 1, i + 1))) {
return false
}
if (!twiceInARow && this[i - 1] == this[i]) {
twiceInARow = true
}
}
if (vowels.contains(this[i])) {
numVowels++
}
}
return twiceInARow && numVowels >= 3
}
private fun String.isReallyNice(): Boolean {
var repeatWithSpace = false
// pair to list of indices where they show up
val pairs = mutableMapOf<String, MutableList<Int>>()
for (i in indices) {
if (i > 0) {
val pair = substring(i - 1, i + 1)
if (!pairs.containsKey(pair)) {
pairs[pair] = mutableListOf()
}
pairs[pair]!!.add(i - 1)
}
if (i > 1) {
if (!repeatWithSpace && this[i - 2] == this[i]) {
repeatWithSpace = true
}
}
}
return repeatWithSpace && pairs.values.any {
// three or more pairs means that at least two of them are without overlap
// with two paris there might be an overlap, check that distance is at least 2
it.size >= 3 || (it.size == 2 && it[1] - it[0] >= 2)
}
}
fun solvePart1(): Int {
return input.count { it.isNice() }
}
fun solvePart2(): Int {
return input.count { it.isReallyNice() }
}
} | 0 | Kotlin | 0 | 6 | f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22 | 1,843 | aoc | MIT License |
src/test/kotlin/chapter4/solutions/ex7/listing.kt | DavidGomesh | 680,857,367 | false | {"Kotlin": 204685} | package chapter4.solutions.ex7
import chapter3.Cons
import chapter3.List
import chapter3.Nil
import chapter4.Either
import chapter4.Left
import chapter4.Right
import chapter4.map2
import io.kotest.matchers.shouldBe
import io.kotest.core.spec.style.WordSpec
class Solution7 : WordSpec({
//tag::init[]
fun <E, A, B> traverse(
xs: List<A>,
f: (A) -> Either<E, B>
): Either<E, List<B>> =
when (xs) {
is Nil -> Right(Nil)
is Cons ->
map2(f(xs.head), traverse(xs.tail, f)) { b, xb ->
Cons(b, xb)
}
}
fun <E, A> sequence(es: List<Either<E, A>>): Either<E, List<A>> =
traverse(es) { it }
//end::init[]
fun <A> catches(a: () -> A): Either<String, A> =
try {
Right(a())
} catch (e: Throwable) {
Left(e.message!!)
}
"traverse" should {
"""return a right either of a transformed list if all
transformations succeed""" {
val xa =
List.of("1", "2", "3", "4", "5")
traverse(xa) { a ->
catches { Integer.parseInt(a) }
} shouldBe Right(
List.of(1, 2, 3, 4, 5)
)
}
"return a left either if any transformations fail" {
val xa =
List.of("1", "2", "x", "4", "5")
traverse(xa) { a ->
catches { Integer.parseInt(a) }
} shouldBe Left(
"""For input string: "x""""
)
}
}
"sequence" should {
"turn a list of right eithers into a right either of list" {
val xe: List<Either<String, Int>> =
List.of(Right(1), Right(2), Right(3))
sequence(xe) shouldBe Right(List.of(1, 2, 3))
}
"""convert a list containing any left eithers into a
left either""" {
val xe: List<Either<String, Int>> =
List.of(Right(1), Left("boom"), Right(3))
sequence(xe) shouldBe Left("boom")
}
}
})
| 0 | Kotlin | 0 | 0 | 41fd131cd5049cbafce8efff044bc00d8acddebd | 2,162 | fp-kotlin | MIT License |
kotlin/combinatorics/Partitions.kt | polydisc | 281,633,906 | true | {"Java": 540473, "Kotlin": 515759, "C++": 265630, "CMake": 571} | package combinatorics
import numeric.FFT
import optimization.Simplex
// https://en.wikipedia.org/wiki/Partition_(number_theory)
object Partitions {
fun nextPartition(p: List<Integer>): Boolean {
val n: Int = p.size()
if (n <= 1) return false
var s: Int = p.remove(n - 1) - 1
var i = n - 2
while (i > 0 && p[i].equals(p[i - 1])) {
s += p.remove(i)
--i
}
p.set(i, p[i] + 1)
while (s-- > 0) {
p.add(1)
}
return true
}
fun partitionByNumber(n: Int, number: Long): List<Integer> {
var number = number
val p: List<Integer> = ArrayList()
var x = n
while (x > 0) {
var j = 1
while (true) {
val cnt = partitionFunction(x)[x][j]
if (number < cnt) break
number -= cnt
++j
}
p.add(j)
x -= j
}
return p
}
fun numberByPartition(p: List<Integer>): Long {
var res: Long = 0
var sum = 0
for (x in p) {
sum += x
}
for (cur in p) {
for (j in 0 until cur) {
res += partitionFunction(sum)[sum][j]
}
sum -= cur
}
return res
}
fun generateIncreasingPartitions(p: IntArray, left: Int, last: Int, pos: Int) {
if (left == 0) {
for (i in 0 until pos) System.out.print(p[i].toString() + " ")
System.out.println()
return
}
p[pos] = last + 1
while (p[pos] <= left) {
generateIncreasingPartitions(p, left - p[pos], p[pos], pos + 1)
p[pos]++
}
}
fun countPartitions(n: Int): Long {
val p = LongArray(n + 1)
p[0] = 1
for (i in 1..n) {
for (j in i..n) {
p[j] += p[j - i]
}
}
return p[n]
}
fun partitionFunction(n: Int): Array<LongArray> {
val p = Array(n + 1) { LongArray(n + 1) }
p[0][0] = 1
for (i in 1..n) {
for (j in 1..i) {
p[i][j] = p[i - 1][j - 1] + p[i - j][j]
}
}
return p
}
fun partitionFunction2(n: Int): Array<LongArray> {
val p = Array(n + 1) { LongArray(n + 1) }
p[0][0] = 1
for (i in 1..n) {
for (j in 1..i) {
for (k in 0..j) {
p[i][j] += p[i - j][k]
}
}
}
return p
}
// Usage example
fun main(args: Array<String?>?) {
System.out.println(7L == countPartitions(5))
System.out.println(627L == countPartitions(20))
System.out.println(5604L == countPartitions(30))
System.out.println(204226L == countPartitions(50))
System.out.println(190569292L == countPartitions(100))
val p: List<Integer> = ArrayList()
Collections.addAll(p, 1, 1, 1, 1, 1)
do {
System.out.println(p)
} while (nextPartition(p))
val p1 = IntArray(8)
generateIncreasingPartitions(p1, p1.size, 0, 0)
val list: List<Integer> = partitionByNumber(5, 6)
System.out.println(list)
System.out.println(numberByPartition(list))
}
}
| 1 | Java | 0 | 0 | 4566f3145be72827d72cb93abca8bfd93f1c58df | 3,351 | codelibrary | The Unlicense |
src/nativeMain/kotlin/com.qiaoyuang.algorithm/round1/Questions26.kt | qiaoyuang | 100,944,213 | false | {"Kotlin": 338134} | package com.qiaoyuang.algorithm.round1
import com.qiaoyuang.algorithm.round0.BinaryTreeNode
fun test26() {
val (head0, head1) = testCase1()
printlnResult(head0, head1)
val (head2, head3) = testCase2()
printlnResult(head2, head3)
val (head4, head5) = testCase3()
printlnResult(head4, head5)
val (head6, head7) = testCase4()
printlnResult(head6, head7)
val (head8, head9) = testCase5()
printlnResult(head8, head9)
printlnResult(head0, head0)
}
/**
* Questions26: Judged a binary tree whether is other binary tree's subtree
*/
private infix fun <T> BinaryTreeNode<T>.judgeSubtree(root: BinaryTreeNode<T>): Boolean =
judge(root, root)
private fun <T> BinaryTreeNode<T>.judge(subRoot: BinaryTreeNode<T>, currentSubNode: BinaryTreeNode<T>): Boolean =
(value == currentSubNode.value && currentSubNode.left?.let { left?.judge(subRoot, it) == true } != false && currentSubNode.right?.let { right?.judge(subRoot, it) == true } != false)
|| left?.judge(subRoot, subRoot) == true
|| right?.judge(subRoot, subRoot) == true
private fun <T> printlnResult(head: BinaryTreeNode<T>, subHead: BinaryTreeNode<T>) =
println("Whether the tree: ${subHead.preOrderList()}(pre-order) is subtree of the tree: ${head.preOrderList()}(pre-order): ${head judgeSubtree subHead}")
private fun testCase1(): Pair<BinaryTreeNode<Int>, BinaryTreeNode<Int>> {
val node0 = BinaryTreeNode(8, right = BinaryTreeNode(7))
val node1 = BinaryTreeNode(8, BinaryTreeNode(9))
val node4 = BinaryTreeNode(2, BinaryTreeNode(4), BinaryTreeNode(7))
node0.left = node1
node1.right = node4
val node7 = BinaryTreeNode(8, BinaryTreeNode(9), BinaryTreeNode(2))
return node0 to node7
}
private fun testCase2(): Pair<BinaryTreeNode<Int>, BinaryTreeNode<Int>> {
val node0 = BinaryTreeNode(8, right = BinaryTreeNode(7))
val node1 = BinaryTreeNode(8, BinaryTreeNode(9, BinaryTreeNode(3), BinaryTreeNode(7)))
val node4 = BinaryTreeNode(2, BinaryTreeNode(4), BinaryTreeNode(7))
node0.left = node1
node1.right = node4
val node7 = BinaryTreeNode(8, BinaryTreeNode(9), BinaryTreeNode(2))
return node0 to node7
}
private fun testCase3(): Pair<BinaryTreeNode<Int>, BinaryTreeNode<Int>> {
val node0 = BinaryTreeNode(8, right = BinaryTreeNode(7))
val node1 = BinaryTreeNode(8, BinaryTreeNode(9, BinaryTreeNode(3), BinaryTreeNode(7)))
val node4 = BinaryTreeNode(2, BinaryTreeNode(4), BinaryTreeNode(7))
node0.left = node1
node1.right = node4
val node7 = BinaryTreeNode(8, BinaryTreeNode(9), BinaryTreeNode(2, BinaryTreeNode(5)))
return node0 to node7
}
private fun testCase4(): Pair<BinaryTreeNode<Int>, BinaryTreeNode<Int>> =
BinaryTreeNode(9) to BinaryTreeNode(9)
private fun testCase5(): Pair<BinaryTreeNode<Int>, BinaryTreeNode<Int>> {
val node0 = BinaryTreeNode(8, right = BinaryTreeNode(7))
val node1 = BinaryTreeNode(8, BinaryTreeNode(9))
val node4 = BinaryTreeNode(2, BinaryTreeNode(4), BinaryTreeNode(7))
node0.left = node1
node1.right = node4
val node7 = BinaryTreeNode(2)
return node0 to node7
} | 0 | Kotlin | 3 | 6 | 66d94b4a8fa307020d515d4d5d54a77c0bab6c4f | 3,145 | Algorithm | Apache License 2.0 |
src/day10/Day10.kt | ZsemberiDaniel | 159,921,870 | false | null | package day10
import RunnablePuzzleSolver
import java.lang.Math.abs
import java.lang.StringBuilder
import java.util.regex.Pattern
class Day10 : RunnablePuzzleSolver {
lateinit var movingLights: Array<MovingLight>
var part2Solution: Int = -1
override fun readInput1(lines: Array<String>) {
val regex = Pattern.compile("""position=<\s*(.*),\s*(.*)> velocity=<\s*(.*),\s*(.*)>""")
movingLights = lines.map {
val matcher = regex.matcher(it).apply { matches() }
MovingLight(matcher.group(1).toInt(), matcher.group(2).toInt(),
matcher.group(3).toInt(), matcher.group(4).toInt())
}.toTypedArray()
}
override fun readInput2(lines: Array<String>) { }
override fun solvePart1(): String {
var tickCount = 0
var yDifference = Int.MAX_VALUE
// we go until they assemble in the y dimension
while (yDifference > 9) {
// for each light we add the distance to the closest light
var highestY = movingLights[0].position.y
var lowestY = movingLights[0].position.y
// updating each light
for (movingLight in movingLights) {
movingLight.update()
if (movingLight.position.y > highestY)
highestY = movingLight.position.y
if (movingLight.position.y < lowestY)
lowestY = movingLight.position.y
}
yDifference = highestY - lowestY
tickCount++
}
part2Solution = tickCount
// we determine the top left and the bottom right positions (bounding rectangle)
val topLeft = Vector(Int.MAX_VALUE, Int.MAX_VALUE)
val botRight = Vector(Int.MIN_VALUE, Int.MIN_VALUE)
for (movingLight in movingLights) {
if (movingLight.position.x < topLeft.x)
topLeft.x = movingLight.position.x
if (movingLight.position.y < topLeft.y)
topLeft.y = movingLight.position.y
if (movingLight.position.x > botRight.x)
botRight.x = movingLight.position.x
if (movingLight.position.y > botRight.y)
botRight.y = movingLight.position.y
}
// we make the letters on a boolean 'board' (matrix)
val letterArray =
Array(botRight.x - topLeft.x + 1) { Array(botRight.y - topLeft.y + 1) { false } }
for (movingLight in movingLights) {
letterArray[movingLight.position.x - topLeft.x][movingLight.position.y - topLeft.y] = true
}
// we convert the board to a string
val out = StringBuilder()
for (i in 0 until letterArray[0].size) {
for (k in 0 until letterArray.size) {
out.append(if (letterArray[k][i]) { "*" } else { " " })
}
out.append("\n")
}
return out.toString()
}
override fun solvePart2(): String {
return part2Solution.toString()
}
data class MovingLight(var position: Vector, var velocity: Vector) {
constructor(x: Int, y: Int, xVel: Int, yVel: Int) : this(Vector(x, y), Vector(xVel, yVel))
fun update(secondCount: Int = 1) {
this.position += this.velocity * secondCount
}
}
data class Vector(var x: Int, var y: Int) {
operator fun plus(vect: Vector) = Vector(this.x + vect.x, this.y + vect.y)
operator fun minus(vect: Vector) = Vector(this.x - vect.x, this.y - vect.y)
operator fun times(scalar: Int) = Vector(scalar * this.x, scalar * this.y)
}
}
| 0 | Kotlin | 0 | 0 | bf34b93aff7f2561f25fa6bd60b7c2c2356b16ed | 3,626 | adventOfCode2018 | MIT License |
mps-analyser/src/main/kotlin/nl/dslconsultancy/mps/analyser/projectOnDisk.kt | dslmeinte | 131,405,227 | false | null | package nl.dslconsultancy.mps.analyser
import nl.dslconsultancy.mps.analyser.util.asList
import nl.dslconsultancy.mps.analyser.util.csvRowOf
import nl.dslconsultancy.mps.analyser.xml.languageMetaDataXmlFromDisk
import java.nio.file.Files
import java.nio.file.Path
data class MpsProjectOnDisk(val mpsFiles: List<Path>, val languages: List<Language>)
fun mpsProjectFromDisk(mpsProject: Path): MpsProjectOnDisk {
val mpsFiles = Files.walk(mpsProject)
.asList()
.filter { mpsFileType(it) != MpsFileType.None }
.sorted()
return MpsProjectOnDisk(
mpsFiles,
mpsFiles.filter { mpsFileType(it) == MpsFileType.Language }.map { languageMetaDataXmlFromDisk(it) }
)
}
enum class MpsFileType {
None,
Language,
Solution, // can also be a devkit or ?
Model
}
fun mpsFileType(path: Path): MpsFileType {
val fileName = path.last().toString()
return when {
fileName.endsWith(".mpl") -> MpsFileType.Language
fileName.endsWith(".msd") -> MpsFileType.Solution
fileName.endsWith(".mps") && !isNotAModelFile(path) -> MpsFileType.Model
else -> MpsFileType.None
}
}
private fun isNotAModelFile(path: Path) =
path.last().toString() == ".mps" || path.any { listOf("classes_gen", "source_gen", "source_gen.caches").contains(it.toString()) }
fun isStructureModel(path: Path) =
mpsFileType(path) == MpsFileType.Model && path.toList().takeLast(2) == listOf("models", "structure")
fun MpsProjectOnDisk.languageReportAsCsvLines() =
listOf(csvRowOf("\"language name\"", "version", "uuid")) + languages.sortedBy { it.name }.map { csvRowOf(it.name, it.languageVersion, it.uuid) }
| 2 | JetBrains MPS | 2 | 10 | 17b3014ebb78cb299844d8b8c284557f30ee211b | 1,686 | mps-open-source | MIT License |
src/nativeMain/kotlin/com.qiaoyuang.algorithm/special/Questions44.kt | qiaoyuang | 100,944,213 | false | {"Kotlin": 338134} | package com.qiaoyuang.algorithm.special
import com.qiaoyuang.algorithm.round0.BinaryTreeNode
import com.qiaoyuang.algorithm.round0.Queue
fun test44() {
printlnResult(binaryTreeTestCase1())
printlnResult(binaryTreeTestCase2())
}
/**
* Questions 44: Find the biggest values every line in a binary tree
*/
private fun <T : Comparable<T>> BinaryTreeNode<T>.maxValues(): List<T> {
var queue1 = Queue<BinaryTreeNode<T>>()
var queue2 = Queue<BinaryTreeNode<T>>()
val result = ArrayList<T>()
queue1.enqueue(this)
var currentLineMaxValue = value
while (queue1.isNotEmpty) {
val node = queue1.dequeue()
node.left?.let { queue2.enqueue(it) }
node.right?.let { queue2.enqueue(it) }
if (node.value > currentLineMaxValue)
currentLineMaxValue = node.value
if (queue1.isEmpty) {
result.add(currentLineMaxValue)
if (queue2.isNotEmpty) {
queue1 = queue2.also { queue2 = queue1 }
currentLineMaxValue = queue1.last.value
}
}
}
return result
}
private fun printlnResult(root: BinaryTreeNode<Int>) =
println("The maximum values line by line in binary tree: ${root.postOrderList()}(post order) is ${root.maxValues()}")
fun binaryTreeTestCase1() = BinaryTreeNode(
value = 3,
left = BinaryTreeNode(
value = 4,
left = BinaryTreeNode(value = 5),
right = BinaryTreeNode(value = 1),
),
right = BinaryTreeNode(
value = 2,
right = BinaryTreeNode(value = 9))
) | 0 | Kotlin | 3 | 6 | 66d94b4a8fa307020d515d4d5d54a77c0bab6c4f | 1,563 | Algorithm | Apache License 2.0 |
src/main/kotlin/dayFolders/day5/letterCombinationsOfPhone.kt | lilimapradhan9 | 255,344,059 | false | null | package dayFolders.day5
val digitToLetterMap = mapOf(
2 to listOf('a', 'b', 'c'),
3 to listOf('d', 'e', 'f'),
4 to listOf('g', 'h', 'i'),
5 to listOf('j', 'k', 'l'),
6 to listOf('m', 'n', 'o'),
7 to listOf('p', 'q', 'r', 's'),
8 to listOf('t', 'u', 'v'),
9 to listOf('w', 'x', 'y', 'z')
)
fun letterCombinations(digits: String): List<String> {
val result = mutableListOf<String>()
if (digits.isEmpty()) return result
addAllPermutations(digits, "", 0, result)
return result
}
fun addAllPermutations(digits: String, permutation: String, k: Int, result: MutableList<String>) {
if (k == digits.length) {
result.add(permutation)
return
}
val characters = digitToLetterMap.getValue(digits[k].toString().toInt())
for (element in characters) {
addAllPermutations(digits, permutation + element, k + 1, result)
}
}
| 0 | Kotlin | 0 | 0 | 356cef0db9f0ba1106c308d33c13358077aa0674 | 906 | kotlin-problems | MIT License |
src/Day10.kt | Akhunzaada | 573,119,655 | false | {"Kotlin": 23755} | class CPU {
private var register = 1
private var cycles = 0
fun exec(program: List<String>, op: (register: Int, cycles: Int) -> Unit) {
program.forEach {
op(register, ++cycles)
if (it.startsWith("addx")) {
op(register, ++cycles)
register += it.substringAfter(" ").toInt()
}
}
}
}
fun main() {
fun part1(input: List<String>): Int {
var signalStrength = 0
CPU().exec(input) { register, cycles ->
if (cycles % 40 == 20)
signalStrength += cycles * register
}
return signalStrength
}
fun part2(input: List<String>) = buildString(6 * 40) {
CPU().exec(input) { register, cycles ->
val sprite = register-1..register+1
if ((cycles-1) % 40 in sprite) append('#') else append('.')
if ((cycles) % 40 == 0) appendLine()
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day10_test")
check(part1(testInput) == 13140)
val input = readInput("Day10")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | b2754454080989d9579ab39782fd1d18552394f0 | 1,187 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/be/inniger/euler/problems01to10/Problem04.kt | bram-inniger | 135,620,989 | false | {"Kotlin": 20003} | package be.inniger.euler.problems01to10
import be.inniger.euler.util.isPalindrome
private const val BIGGEST_N_DIGIT_NUMBER = 999
private const val SMALLEST_N_DIGIT_NUMBER = 100
/**
* Largest palindrome product
*
* A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
* Find the largest palindrome made from the product of two 3-digit numbers.
*/
fun solve04() = (SMALLEST_N_DIGIT_NUMBER..BIGGEST_N_DIGIT_NUMBER)
.flatMap { i ->
(SMALLEST_N_DIGIT_NUMBER..i).map { j -> i to j }
}
.map { it.first * it.second }
.filter { isPalindrome(it.toString().toList()) }
.max()!!
| 0 | Kotlin | 0 | 0 | 8fea594f1b5081a824d829d795ae53ef5531088c | 685 | euler-kotlin | MIT License |
src/Day17.kt | Aldas25 | 572,846,570 | false | {"Kotlin": 106964} | import kotlin.math.max
fun main() {
val rocks: List<Array<Array<Boolean>>> = listOf(
// rock 1
arrayOf(arrayOf(true, true, true, true)),
// rock 2
arrayOf(
arrayOf(false, true, false),
arrayOf(true, true, true),
arrayOf(false, true, false)
),
// rock 3
arrayOf(
arrayOf(true, true, true),
arrayOf(false, false, true),
arrayOf(false, false, true)
),
// rock 4
arrayOf(
arrayOf(true),
arrayOf(true),
arrayOf(true),
arrayOf(true)
),
// rock 5
arrayOf(
arrayOf(true, true),
arrayOf(true, true)
)
)
fun part1(input: String): Int {
val maxRocks = 2022
var h = 0
val grid = Array(100000) { Array(7) { false } }
for (c in grid[0].indices)
grid[0][c] = true
var jet = 0
fun canPlaceRock(rock: Array<Array<Boolean>>, pos: Pair<Int, Int>): Boolean {
for (i in rock.indices)
for (j in rock[0].indices) {
if (pos.first + i < 0 || pos.second + j < 0)
return false
if (pos.first + i >= grid.size || pos.second + j >= grid[0].size)
return false
if (rock[i][j] && grid[pos.first + i][pos.second + j])
return false
}
return true
}
fun dropRock(rock: Array<Array<Boolean>>) {
var pos = Pair(h + 3 + 1, 2)
fun jetPush() {
var r = pos.first
var c = pos.second
if (input[jet] == '<') c--
else c++
jet = (jet + 1) % input.length
if (canPlaceRock(rock, Pair(r, c)))
pos = Pair(r, c)
}
while (true) {
jetPush()
val r = pos.first - 1
val c = pos.second
if (!canPlaceRock(rock, Pair(r, c)))
break
pos = Pair(r, c)
}
for (i in rock.indices)
for (j in rock[0].indices) {
if (rock[i][j]) {
grid[pos.first + i][pos.second + j] = true
h = maxOf(h, pos.first + i)
}
}
}
var rock = 0
repeat(maxRocks) {
dropRock(rocks[rock])
rock = (rock + 1) % rocks.size
}
return h
}
fun part2(input: String): Long {
val maxRocks = 1000000
val answerRocks = 1000000000000L
var h = 0
val grid = Array(maxRocks * 5) { Array(7) { false } }
for (c in grid[0].indices)
grid[0][c] = true
var jet = 0
fun canPlaceRock(rock: Array<Array<Boolean>>, pos: Pair<Int, Int>): Boolean {
for (i in rock.indices)
for (j in rock[0].indices) {
if (pos.first + i < 0 || pos.second + j < 0)
return false
if (pos.first + i >= grid.size || pos.second + j >= grid[0].size)
return false
if (rock[i][j] && grid[pos.first + i][pos.second + j])
return false
}
return true
}
fun dropRock(rock: Array<Array<Boolean>>) {
var pos = Pair(h + 3 + 1, 2)
fun jetPush() {
var r = pos.first
var c = pos.second
if (input[jet] == '<') c--
else c++
jet = (jet + 1) % input.length
if (canPlaceRock(rock, Pair(r, c)))
pos = Pair(r, c)
}
while (true) {
jetPush()
val r = pos.first - 1
val c = pos.second
if (!canPlaceRock(rock, Pair(r, c)))
break
pos = Pair(r, c)
}
for (i in rock.indices)
for (j in rock[0].indices) {
if (rock[i][j]) {
grid[pos.first + i][pos.second + j] = true
h = maxOf(h, pos.first + i)
}
}
}
var rock = 0
val changes: MutableList<Long> = mutableListOf()
repeat(maxRocks) {
val lastH = h
dropRock(rocks[rock])
changes.add((h - lastH).toLong())
rock = (rock + 1) % rocks.size
}
fun checkPattern(len: Int): Boolean {
fun subEquals(fr1: Int, to1: Int, fr2: Int, to2: Int): Boolean {
var i = 0
while (fr1 + i <= to1) {
if (changes[fr1+i] != changes[fr2+i])
return false
i++
}
return true
}
val sz = changes.size
// [sz-len; sz) should be similar to
// [sz-2*len; sz-len)
// [sz-i*len; sz-(i-1)*len)
var i = 2
while (true) {
if (sz - (i+5)*len < 0) return true
if(!subEquals(sz - i*len, sz - (i-1)*len - 1, sz - len, sz-1))
return false
i++
}
return true
}
fun calcPattern(): Int {
var i = 5
while (!checkPattern(i)) {
i++
}
return i
}
fun calcValueChanges(fr: Int, to: Int): Long {
var res = 0L
for (i in fr..to)
res += changes[i]
return res
}
val pattern = calcPattern().toLong()
var ans = h.toLong()
var movesLeft: Long = answerRocks - maxRocks
ans += (movesLeft / pattern) * calcValueChanges(
changes.size - pattern.toInt(),
changes.size-1
)
movesLeft %= pattern.toInt()
if (movesLeft > 0)
ans += calcValueChanges(
changes.size - pattern.toInt(),
changes.size - pattern.toInt()+movesLeft.toInt()-1
)
return ans
}
val filename =
// "inputs/day17_sample"
"inputs/day17"
val input = readInput(filename)
println("Part 1: ${part1(input[0])}")
println("Part 2: ${part2(input[0])}")
} | 0 | Kotlin | 0 | 0 | 80785e323369b204c1057f49f5162b8017adb55a | 6,586 | Advent-of-Code-2022 | Apache License 2.0 |
src/main/kotlin/dataModel/v3/AccumulatedTaxBracketV2.kt | daniel-rusu | 669,564,782 | false | {"Kotlin": 70755} | package dataModel.v3
import dataModel.v3.AccumulatedTaxBracketV2.Companion.toAccumulatedBracketsV2
import dataModel.base.Money
import dataModel.base.Money.Companion.dollars
import dataModel.base.Percent
import dataModel.base.TaxBracket
import solutions.linear.computeBracketTax
/**
* Similar to [TaxBracket] except that it also stores the accumulated tax up to the start of this bracket.
*
* Private constructor so that the only way to create accumulated brackets is from a list of regular brackets via the
* [toAccumulatedBracketsV2] function so that the [next] references are set correctly.
*/
class AccumulatedTaxBracketV2 private constructor(
val from: Money,
val taxRate: Percent,
val accumulatedTax: Money,
) {
var next: AccumulatedTaxBracketV2? = null // null when this is the last bracket
private set
val to: Money?
get() = next?.from
override fun toString(): String {
return "AccumulatedTaxBracket[from = $from, to = $to, taxRate = $taxRate]"
}
fun computeTotalTax(income: Money): Money {
require(income >= from) { "$income is below the lower bound of $from" }
to?.let { require(income < it) }
return accumulatedTax + taxRate * (income - from)
}
companion object {
fun List<TaxBracket>.toAccumulatedBracketsV2(): List<AccumulatedTaxBracketV2> {
val accumulatedBrackets = ArrayList<AccumulatedTaxBracketV2>(this.size)
var nextAccumulatedTax = 0.dollars
this.mapTo(accumulatedBrackets) { bracket ->
val accumulatedTax = nextAccumulatedTax
if (bracket.to != null) {
nextAccumulatedTax += bracket.computeBracketTax(bracket.to)
}
AccumulatedTaxBracketV2(bracket.from, bracket.taxRate, accumulatedTax)
}
// Link each bracket to the next one
accumulatedBrackets.forEachIndexed { index, bracket ->
bracket.next = accumulatedBrackets.getOrNull(index + 1)
}
return accumulatedBrackets
}
}
}
| 0 | Kotlin | 0 | 1 | 166d8bc05c355929ffc5b216755702a77bb05c54 | 2,107 | tax-calculator | MIT License |
hand-ins/app/src/main/java/com/example/handins/hand_in_1.kt | Josef-TL | 751,238,665 | false | {"Kotlin": 11689} | package com.example.handins
import java.util.Scanner
fun main(){
checkAge()
val max : Int = getMax(1,18,8);
val min : Int = getMin(1,18,-8);
println(max); //18
println(min); //-8
val numList: List<Int> = listOf(0,-12,4,6,123)
println("Average of the list ${numList} is: " + calculateAverage(numList))
val cpr: String = "3203139999"
println("Is $cpr a valid CPR Number?")
println(isCprValid(cpr))
fizzBuzz()
abbrevName("<NAME>")
val testStringList: List<String> = listOf("Hello", "banana", "elephant", "pizza", "computer", "mountain", "butterfly", "galaxy", "happiness", "freedom")
filterWordsByLength(testStringList,3)
}
/*********************
* Opgave 1
* A person is elligible to vote if his/her age is greater than or equal to 18.
* Define a method to find out if he/she is elligible to vote
*********************/
fun checkAge(){
val reader = Scanner(System.`in`)
println("Please enter age: ")
val userAge: Int = reader.nextInt()
if(userAge < 18) println("You cannot vote") else println("Vote NOW!")
}
/*********************
* Opgave 2
* Define two functions to print the maximum and the minimum number respectively
* among three numbers
*********************/
fun getMax(a:Int,b:Int,c:Int):Int{
return maxOf(a,b,c)
}
fun getMin(a:Int,b:Int,c:Int):Int{
return minOf(a,b,c)
}
/*********************
* Opgave 3
* Write a Kotlin function named calculateAverage
* that takes in a list of numbers and returns their average.
*********************/
fun calculateAverage(l:List<Int>):Double{
val listLeng: Double = l.size.toDouble()
val listSum: Double = l.sumOf { it.toDouble() }
return listSum/listLeng
}
/*
Opgave 4
Write a method that returns if a user has input a valid CPR number.
A valid CPR number has:
* 10 Digits.
* The first 2 digits are not above 31.
* The middle 2 digits are not above 12.
* The method returns true if the CPR number is valid, false if it is not.
Bruger RegEx. Bruger ChatGPT til at finde en Expression
*/
fun isCprValid(cprString: String):Boolean{
val validationExpression = "^(0[1-9]|[12][0-9]|3[01])(0[1-9]|1[0-2])(\\d{2})\\d{4}\$".toRegex()
return validationExpression.matches(cprString)
}
/*
Opgave 5
Write a program that prints the numbers from 1 to 100.
But for multiples of three print “Fizz” instead of the number
and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.
*/
fun fizzBuzz(){
for (l in 1..100){
if(l%3 == 0 && l%5 != 0){
println("Fizz")
} else if(l%3!=0 && l%5 == 0){
println("Buzz")
} else if(l%3==0 && l%5==0){
println("FizzBuzz")
}
else{ println(l) }
}
}
/*
Opgave 6
Write a program that takes your full name as input and displays
the abbreviations of the first and middle names except the last name which is displayed as it is.
For example, if your name is <NAME>, then the output should be <NAME>.
Or <NAME> will be <NAME>
*/
fun abbrevName(name:String){
val nameArr = name.split(" ")
val returnArr = nameArr.mapIndexed { index, s ->
if(index == nameArr.lastIndex) s else s[0]
}
println(returnArr.joinToString(separator = ". "))
}
/*
Opgave 7
Write a program that takes a numerical grade (0-100) as input
and prints out the corresponding american letter grade.
Implement a function calculateGrade that takes an integer parameter representing the grade
and returns a string representing the letter grade according to the following scale:
90-100: "A"
80-89: "B"
70-79: "C"
60-69: "D"
Below 60: "F"
*/
fun calculateGrade(grade:Int):String{
return when{
grade > 100 -> "Enter valid number"
grade < 0 -> "Enter valid number"
grade in 90..100 -> "A"
grade in 80..89 -> "B"
grade in 70..79 -> "C"
grade in 60..69 -> "D"
else -> "F"
}
}
/*
Opgave 8
Write a Kotlin function named filterWordsByLength that takes in a list of strings and a minimum length,
and returns a list containing only the words that have a length greater than or equal to
the specified minimum length.
Use filter function and lambda expressions
*/
fun filterWordsByLength(l:List<String>,minLen:Int):List<String>{
return l.filter { str -> str.length >= minLen }
} | 0 | Kotlin | 0 | 0 | f613326087e43ea6553a03ac30becf0d23f99478 | 4,454 | app-dev | MIT License |
src/Day10.kt | li-xin-yi | 573,617,763 | false | {"Kotlin": 23422} | fun main() {
fun solvePart1(input: List<String>): Int {
var res = 0
var time = 0
var value = 1
var i = 0
for (line in input) {
val inst = line.split(" ")
val newTime = time + inst.size
if (newTime >= 20 + i * 40) {
res += value * (20 + i * 40)
i += 1
}
if (i > 5) break
if (inst.size == 2)
value += inst[1].toInt()
time = newTime
}
return res
}
fun solvePart2(input: List<String>) {
var time = 0
var value = 1
var res = ""
for (line in input) {
val inst = line.split(" ")
for (t in time until time + inst.size) {
if (Math.abs(value - t % 40) <= 1) {
res += '#'
} else {
res += "."
}
}
if (inst.size == 2)
value += inst[1].toInt()
time += inst.size
if (time > 241)
break
}
for (i in 0..200 step 40) {
println(res.substring(i, i + 40))
}
}
val testInput = readInput("input/Day10_test")
check(solvePart1(testInput) == 13140)
solvePart2(testInput)
val input = readInput("input/Day10_input")
println(solvePart1(input))
// Too hard to see the letters, my poor eyes
solvePart2(input)
} | 0 | Kotlin | 0 | 1 | fb18bb7e462b8b415875a82c5c69962d254c8255 | 1,476 | AoC-2022-kotlin | Apache License 2.0 |
kotlin/src/katas/kotlin/eightQueen/EightQueen21.kt | dkandalov | 2,517,870 | false | {"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221} | package katas.kotlin.eightQueen
import datsok.shouldEqual
import org.junit.Test
class EightQueen21 {
@Test fun `find positions of queens so that they don't attack each other`() {
Board(size = 0).findPositions().toList() shouldEqual listOf(Board(size = 0))
Board(size = 1).findPositions().toList() shouldEqual listOf(Board(size = 1, queens = listOf(Queen(0, 0))))
Board(size = 2).findPositions().toList() shouldEqual emptyList()
Board(size = 3).findPositions().toList() shouldEqual emptyList()
Board(size = 4).findPositions().toList() shouldEqual listOf(
Board(size = 4, queens = listOf(Queen(0, 2), Queen(1, 0), Queen(2, 3), Queen(3, 1))),
Board(size = 4, queens = listOf(Queen(0, 1), Queen(1, 3), Queen(2, 0), Queen(3, 2)))
)
Board(size = 8).findPositions().toList().size shouldEqual 92
}
@Test fun `generate all possible queen positions`() {
Board(size = 1).allPossiblePositions().toList() shouldEqual listOf(Queen(0, 0))
Board(size = 2).allPossiblePositions().toList() shouldEqual listOf(Queen(0, 0), Queen(0, 1), Queen(1, 0), Queen(1, 1))
}
@Test fun `determine valid queen positions`() {
Board(size = 4, queens = listOf(Queen(0, 0))).apply {
add(Queen(0, 0)) shouldEqual null
add(Queen(0, 2)) shouldEqual null
add(Queen(2, 0)) shouldEqual null
add(Queen(2, 2)) shouldEqual null
add(Queen(1, 2)) shouldEqual Board(size = 4, queens = listOf(Queen(0, 0), Queen(1, 2)))
}
}
private data class Board(val size: Int, val queens: List<Queen> = emptyList()) {
fun findPositions(): Sequence<Board> = sequence {
var boards = listOf(Board(size))
allPossiblePositions().forEach { queen ->
boards += boards.mapNotNull { it.add(queen) }.toList()
}
boards.filter { it.size == it.queens.size }.forEach { yield(it) }
}
fun allPossiblePositions(): Sequence<Queen> = sequence {
0.until(size).forEach { x ->
0.until(size).forEach { y ->
yield(Queen(x, y))
}
}
}
fun add(queen: Queen): Board? = if (isValidMove(queen)) copy(queens = queens + queen) else null
private fun isValidMove(queen: Queen) =
queens.size < size &&
queens.none { it.x == queen.x || it.y == queen.y } &&
queens.none { Math.abs(it.x - queen.x) == Math.abs(it.y - queen.y) }
}
private data class Queen(val x: Int, val y: Int) {
override fun toString() = "$x,$y"
}
} | 7 | Roff | 3 | 5 | 0f169804fae2984b1a78fc25da2d7157a8c7a7be | 2,670 | katas | The Unlicense |
src/main/kotlin/dev/shtanko/algorithms/leetcode/SlidingWindowMax.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import java.util.Deque
import java.util.LinkedList
/**
* 239. Sliding Window Maximum
* @see <a href="https://leetcode.com/problems/sliding-window-maximum/">Source</a>
*/
fun interface SlidingWindowMax {
operator fun invoke(nums: IntArray, k: Int): IntArray
}
class MonotonicDeque : SlidingWindowMax {
override operator fun invoke(nums: IntArray, k: Int): IntArray {
val dq: Deque<Int> = LinkedList()
val res: MutableList<Int> = ArrayList()
for (i in 0 until k) {
while (dq.isNotEmpty() && nums[i] >= nums[dq.peekLast()]) {
dq.pollLast()
}
dq.offerLast(i)
}
res.add(nums[dq.peekFirst()])
for (i in k until nums.size) {
if (dq.peekFirst() == i - k) {
dq.pollFirst()
}
while (dq.isNotEmpty() && nums[i] >= nums[dq.peekLast()]) {
dq.pollLast()
}
dq.offerLast(i)
res.add(nums[dq.peekFirst()])
}
// Return the result as an array.
return res.stream().mapToInt { i: Int? -> i!! }.toArray()
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,775 | kotlab | Apache License 2.0 |
src/main/kotlin/com/mhv2109/difflib/SequenceMatcher.kt | mhv2109 | 155,640,302 | false | null | package com.mhv2109.difflib
private data class QueueElem(
val alo: Int,
val ahi: Int,
val blo: Int,
val bhi: Int
)
/**
* Kotlin implementation of Python difflib.SequenceMatcher.
*
* From difflib docs:
*
* The basic algorithm predates, and is a little fancier than, an algorithm published in the late 1980's by Ratcliff and
* Obershelp under the hyperbolic name "gestalt pattern matching". The basic idea is to find the longest contiguous
* matching subsequence that contains no "junk" elements (R-O doesn't address junk). The same idea is then applied
* recursively to the pieces of the sequences to the left and to the right of the matching subsequence. This does not
* yield minimal edit sequences, but does tend to yield matches that "look right" to people.
*
* Reference implementation here: https://github.com/python/cpython/blob/3.7/Lib/difflib.py
*
* @param a the first of two sequences to be compared, by default, an empty List
* @param b the second of two sequences to be compared, by default, an empty List
* @param isJunk a one-argument function that takes a sequence element and returns true iff the element is junk
* @param autoJunk should be set to False to disable the "automatic junk heuristic" that treats popular elements as junk
*/
class SequenceMatcher<T>(
private var a: List<T> = emptyList(),
private var b: List<T> = emptyList(),
private val isJunk: (T) -> Boolean = { false },
private val autoJunk: Boolean = true
) {
private val opcodes = mutableListOf<Opcode>()
private var matchingBlocks = mutableListOf<Match>()
private val b2j = mutableMapOf<T, MutableList<Int>>()
private val bjunk = mutableSetOf<T>()
private val bpopular = mutableSetOf<T>()
init {
setSeqs(a, b)
}
fun setSeqs(a: List<T>, b: List<T>) {
setSeq1(a)
setSeq2(b)
}
fun setSeq1(a: List<T>) {
this.a = a
opcodes.clear()
matchingBlocks.clear()
}
fun setSeq2(b: List<T>) {
this.b = b
opcodes.clear()
matchingBlocks.clear()
chainB()
}
private fun chainB() {
b2j.clear()
b.forEachIndexed { index, c ->
if(b2j.containsKey(c))
b2j[c]!!.add(index)
else
b2j[c] = mutableListOf(index)
}
// purge junk elements
bjunk.clear()
b2j.keys.forEach {
if(isJunk(it))
bjunk.add(it)
}
bjunk.forEach {
b2j.remove(it)
}
// purge popular elements that are not junk
bpopular.clear()
val n = b.size
if(autoJunk && n >= 200) {
val ntest = n / 100 + 1
b2j.forEach { t, u ->
if(u.size > ntest)
bpopular.add(t)
}
bpopular.forEach {
b2j.remove(it)
}
}
}
fun findLongestMatch(alo: Int, ahi: Int, blo: Int, bhi: Int): Match {
var besti = alo
var bestj = ahi
var bestSize = 0
// find longest junk-free match
var j2len = mutableMapOf<Int, Int>()
for(i in alo until ahi) {
// look at all instances of a[i] in b. Note that because b2j has no junk keys, the loop is skipped if
// a[i] is junk
val newj2len = mutableMapOf<Int, Int>()
for(j in b2j[a[i]] ?: emptyList<Int>()) {
if(j < blo)
continue
if(j >= bhi)
break
val k = (j2len[j-1] ?: 0) + 1
newj2len[j] = k
if(k > bestSize) {
besti = i - k + 1
bestj = j - k + 1
bestSize = k
}
}
j2len = newj2len
}
// Extend the best by non-junk elements on each end
while(besti > alo &&
bestj > blo &&
!bjunk.contains(b[bestj - 1]) &&
(a[besti - 1] == b[bestj - 1])) {
besti -= 1
bestj -= 1
bestSize += 1
}
while((besti + bestSize < ahi) &&
(bestj + bestSize < bhi) &&
!bjunk.contains(b[bestj + bestSize]) &&
(a[besti + bestSize] == b[bestj + bestSize])) {
bestSize += 1
}
// add all matching junk on each side of Match
while((besti > alo) &&
(bestj > blo) &&
bjunk.contains(b[bestj - 1]) &&
(a[besti - 1] == b[bestj - 1])) {
besti -= 1
bestj -= 1
bestSize += 1
}
while((besti + bestSize < ahi) &&
(bestj + bestSize < bhi) &&
bjunk.contains(b[bestj + bestSize]) &&
(a[besti + bestSize] == b[bestj + bestSize])) {
bestSize += 1
}
return Match(besti, bestj, bestSize)
}
fun getMatchingBlocks(): List<Match> {
if(matchingBlocks.isNotEmpty())
return matchingBlocks.toList()
val la = a.size
val lb = b.size
val queue = mutableListOf(QueueElem(0, la, 0, lb))
matchingBlocks.clear()
while(!queue.isEmpty()) {
val elem = queue.removeAt(queue.size - 1)
val match = findLongestMatch(elem.alo, elem.ahi, elem.blo, elem.bhi)
if(match.size > 0) { // if size == 0, there was no matching block.
matchingBlocks.add(match)
if(elem.alo < match.a && elem.blo < match.b)
queue.add(QueueElem(elem.alo, match.a, elem.blo, match.b))
if(match.a + match.size < elem.ahi && match.b + match.size < elem.bhi)
queue.add(QueueElem(match.a + match.size, elem.ahi, match.b + match.size, elem.bhi))
}
}
matchingBlocks = matchingBlocks.sortedWith(compareBy(Match::a, Match::b, Match::size)).toMutableList()
// collapse adjacent equal blocks
var i1 = 0
var j1 = 0
var k1 = 0
val nonAdjacent = mutableListOf<Match>()
matchingBlocks.forEach {
if(i1 + k1 == it.a && j1 + k1 == it.b)
k1 += it.size
else {
if (k1 > 0)
nonAdjacent.add(Match(i1, j1, k1))
i1 = it.a
j1 = it.b
k1 = it.size
}
}
if(k1 > 0)
nonAdjacent.add(Match(i1, j1, k1))
nonAdjacent.add(Match(la, lb, 0))
matchingBlocks = nonAdjacent
return matchingBlocks.toList()
}
fun ratio(): Double {
val matches = getMatchingBlocks().map { it.size }.toIntArray().sum()
return calculateRatio(matches, a.size + b.size)
}
fun getOpcodes(): List<Opcode> {
if(opcodes.isNotEmpty())
return opcodes
var i = 0
var j = 0
getMatchingBlocks().forEach {
val tag: Tag? = when {
i < it.a && j < it.b -> Tag.REPLACE
i < it.a -> Tag.DELETE
j < it.b -> Tag.INSERT
else -> null
}
if(tag != null)
opcodes.add(Opcode(tag, i, it.a, j, it.b))
i = it.a + it.size
j = it.b + it.size
if(it.size > 0)
opcodes.add(Opcode(Tag.EQUAL, it.a, i, it.b, j))
}
return opcodes.toList()
}
fun getGroupedOpcodes(n: Int = 3): List<List<Opcode>> {
var codes = getOpcodes().toMutableList()
if(codes.isEmpty())
codes = mutableListOf(Opcode(Tag.EQUAL, 0,1,0,1))
// Fixup leading and trailing groups if they show no changes
if(codes.first().tag == Tag.EQUAL) {
val code = codes.first()
codes[0] = code.copy(alo = Math.max(code.alo, code.ahi-n), blo = Math.max(code.blo, code.bhi-n))
}
if(codes.last().tag == Tag.EQUAL) {
val code = codes.last()
codes[codes.size-1] = code.copy(ahi = Math.min(code.ahi, code.alo+n), bhi = Math.min(code.bhi, code.blo+n))
}
val nn = n + n
val group = mutableListOf<Opcode>()
val result = mutableListOf<List<Opcode>>()
codes.forEach {
if(it.tag == Tag.EQUAL && it.ahi-it.alo > nn) {
group.add(it.copy(ahi = Math.min(it.ahi, it.alo+n), bhi = Math.min(it.bhi, it.blo+n)))
result.add(group.toList())
group.clear()
group.add(it.copy(alo = Math.max(it.alo, it.ahi-n), blo = Math.max(it.blo, it.bhi-n)))
} else {
group.add(it.copy())
}
}
if(group.isNotEmpty() && !(group.size == 1 && group.first().tag == Tag.EQUAL))
result.add(group.toList())
return result.toList()
}
}
/**
* Use SequenceMatcher to return list of the best "good enough" matches.
*
* @param sequence sequence for which close matches are desired (typically a string cast to a List<Char>)
* @param possibilities possibilities is a list of sequences against which to match
* @param n the maximum number of close matches to return
* @param cutoff (default 0.6) is a Double in 0 <= cutoff <= 1
*/
fun <T> getCloseMatches(sequence: List<T>, possibilities: Collection<List<T>>,
n: Int = 3, cutoff: Double = 0.6): List<List<T>> {
if(n <= 0)
throw IllegalArgumentException("Expected: n > 0. Actual: n = $n")
if(cutoff > 1.0 || cutoff < 0.0)
throw IllegalArgumentException("Expected: 0.0 < cutoff < 1.0. Actual: cutoff = $cutoff")
var allResults = mutableListOf<Pair<Double, List<T>>>()
val s = SequenceMatcher<T>()
s.setSeq2(sequence)
possibilities.forEach {
s.setSeq1(it)
val ratio = s.ratio()
if(ratio >= cutoff)
allResults.add(Pair(ratio, it))
}
allResults = allResults.sortedWith(compareBy { it.first } ).toMutableList()
val result = mutableListOf<List<T>>()
for(i in 0 until n) {
if(i < allResults.size)
result.add(allResults[i].second)
else
break
}
return result.toList()
} | 2 | Kotlin | 0 | 1 | 73b83a5eb87440a53171aedcff634e9d542710cb | 8,482 | difflib | MIT License |
CombinacionesPalabras/src/main/java/Main.kt | ariannysOronoz | 603,181,296 | false | null | package com.includehelp.basic
import java.util.*
/* fun main(args: Array<String>) {
val num = 10
var i = 1
var factorial: Long = 1
while (i <= num) {
factorial *= i.toLong()
i++
}
println(" El Factorial de $num = $factorial")
}*/
// Kotlin program for
// Print all permutations of a string
class Permutation
{
// Swapping two string elements by index
fun swap(
info: String,
size: Int,
a: Int,
b: Int
): String
{
var text = info;
// Check valid location of swap element
if ((a >= 0 && a < size) && (b >= 0 && b < size))
{
// Get first character
val first: Char = text.get(a);
// Get second character
val second: Char = text.get(b);
// Put character
text = text.substring(0, b) + first.toString() +
text.substring(b + 1);
text = text.substring(0, a) + second.toString() +
text.substring(a + 1);
}
return text;
}
// Method which is print all permutations of given string
fun findPermutation(info: String, n: Int, size: Int): Unit
{
if (n > size)
{
return;
}
if (n == size)
{
println(info);
return;
}
var text = info;
var i: Int = n;
while (i < size)
{
// Swap the element
text = this.swap(text, size, i, n);
this.findPermutation(text, n + 1, size);
// Swap the element
text = this.swap(text, size, i, n);
i += 1;
}
}
}
fun main(args: Array < String > ): Unit
{
val task: Permutation = Permutation();
var text: String = "CARACOL";
var size: Int = text.length;
task.findPermutation(text, 0, size);
println("");
text = "caracol";
size = text.length;
task.findPermutation(text, 0, size);
}
| 0 | Kotlin | 0 | 0 | a779f54a7ca7db9e377e2b911a101daaababf84c | 2,034 | tutorialKotlin | MIT License |
src/day06/Day06.kt | schrami8 | 572,631,109 | false | {"Kotlin": 18696} | package day06
import readInput
fun String.isUniqueCharacters() = toSet().size == length
// better to use https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/windowed.html
fun getStartOfMessageMarker(line: String, differentChars: Int): Int {
var i = 0
while (i + differentChars <= line.length) {
if (line.substring(i, i + differentChars).isUniqueCharacters())
return i + differentChars
++i
}
return -1
}
const val MARKER_4 = 4
const val MARKER_14 = 14
fun main() {
fun part1(input: List<String>): Int {
for (line in input) {
val marker = getStartOfMessageMarker(line, MARKER_4)
if (marker != -1)
return marker
}
return -1
}
fun part2(input: List<String>): Int {
for (line in input) {
val marker = getStartOfMessageMarker(line, MARKER_14)
if (marker != -1)
return marker
}
return -1 }
// test if implementation meets criteria from the description, like:
var testInput = readInput("day06/Day06_test")
check(part1(testInput) == 5)
check(part2(testInput) == 23)
testInput = readInput("day06/Day06_test2")
check(part1(testInput) == 11)
check(part2(testInput) == 26)
val input = readInput("day06/Day06")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 215f89d7cd894ce58244f27e8f756af28420fc94 | 1,384 | advent-of-code-kotlin | Apache License 2.0 |
src/advent/of/code/EightPuzzle.kt | 1nco | 725,911,911 | false | {"Kotlin": 112713, "Shell": 103} | package advent.of.code
import java.util.*
class EightPuzzle {
companion object {
private val day = "8";
private var input: MutableList<String> = arrayListOf();
private var result = 0L;
private var resultSecond = 0L;
private var instructions: String = "";
private var map = hashMapOf<String, Node>();
private var needToFind = "ZZZ"
private var startingNodes = arrayListOf<Path>();
fun solve() {
val startingTime = Date();
input.addAll(Reader.readInput(day));
var lineNum = 0;
input.forEach { line ->
if (lineNum == 0) {
instructions = line;
} else if (line.isNotBlank()) {
val node = Node(line.split("=")[0].trim(), line.split("=")[1].trim().split(", ")[0].replace("(", "").trim(), line.split("=")[1].trim().split(", ")[1].replace(")", "").trim())
// map.add(node);
map[line.split("=")[0].trim()] = node;
}
lineNum++;
}
// FIRST
// var found = false;
// var currentNodeValue = "AAA";
// var i = 0;
// while (!found) {
// if (currentNodeValue == needToFind) {
// found = true;
// } else {
// if (instructions[i].toString() == "L") {
// currentNodeValue = map.get(currentNodeValue)!!.left;
// }
//
// if (instructions[i].toString() == "R") {
// currentNodeValue = map.get(currentNodeValue)!!.right;
// }
// result++;
// }
//
// i++;
// if (i == instructions.length) {
// i = 0;
// }
// }
println(result)
// SECOND
startingNodes.addAll(map.filter { node -> node.value.value[2].toString() == "A" }.map { node -> Path(node.value.value, node.value.value) });
var i = 0;
while (!allFound()) {
startingNodes.forEach{ node ->
move(instructions[i].toString(), node);
}
resultSecond++;
i++;
if (i == instructions.length) {
i = 0;
}
}
// var isLcm = false;
// var lcmValue = startingNodes.map { n -> n.firstZOccurence }.sorted().get(startingNodes.size - 1)
// while (!isLcm) {
// isLcm = startingNodes.map { n -> n.firstZOccurence }.all { v -> lcmValue % v == 0L };
// lcmValue++;
// }
var lcmValue = findLCMOfListOfNumbers(startingNodes.map { n -> n.firstZOccurence })
println(lcmValue);
println(startingTime);
println(Date());
}
private fun allFound(): Boolean {
return startingNodes.size == startingNodes.filter { node -> node.firstZOccurence != 0L }.size;
}
private fun move(instruction: String, path: Path) {
if (path.firstZOccurence == 0L && path.currentNode[2].toString() == "Z") {
path.firstZOccurence = resultSecond;
}
if (instruction == "L" && path.firstZOccurence == 0L) {
path.currentNode = map.get(path.currentNode)!!.left;
}
if (instruction == "R" && path.firstZOccurence == 0L) {
path.currentNode = map.get(path.currentNode)!!.right;
}
}
fun findLCMOfListOfNumbers(numbers: List<Long>): Long {
var result = numbers[0]
for (i in 1 until numbers.size) {
result = findLCM(result, numbers[i])
}
return result
}
private fun findLCM(a: Long, b: Long): Long {
val larger = if (a > b) a else b
val maxLcm = a * b
var lcm = larger
while (lcm <= maxLcm) {
if (lcm % a == 0L && lcm % b == 0L) {
return lcm
}
lcm += larger
}
return maxLcm
}
}
}
class Path(startingNode: String, currentNode: String) {
var startingNode: String;
var currentNode: String;
var firstZOccurence: Long;
init {
this.startingNode = startingNode;
this.currentNode = currentNode;
this.firstZOccurence = 0L
}
}
class Node(value: String, left: String, right: String) {
var value: String;
var left: String;
var right: String;
init {
this.value = value;
this.left = left;
this.right = right;
}
} | 0 | Kotlin | 0 | 0 | 0dffdeba1ebe0b44d24f94895f16f0f21ac8b7a3 | 4,837 | advent-of-code | Apache License 2.0 |
kotlin/structures/PersistentTree.kt | polydisc | 281,633,906 | true | {"Java": 540473, "Kotlin": 515759, "C++": 265630, "CMake": 571} | package structures
import numeric.FFT
import optimization.Simplex
// https://en.wikipedia.org/wiki/Persistent_data_structure
object PersistentTree {
fun build(left: Int, right: Int): Node {
if (left == right) return Node(0)
val mid = left + right shr 1
return Node(build(left, mid), build(mid + 1, right))
}
fun sum(from: Int, to: Int, root: Node?, left: Int, right: Int): Int {
if (from > right || left > to) return 0
if (from <= left && right <= to) return root!!.sum
val mid = left + right shr 1
return sum(from, to, root!!.left, left, mid) + sum(from, to, root.right, mid + 1, right)
}
operator fun set(pos: Int, value: Int, root: Node?, left: Int, right: Int): Node {
if (left == right) return Node(value)
val mid = left + right shr 1
return if (pos <= mid) Node(set(pos, value, root!!.left, left, mid), root.right) else Node(
root!!.left, set(pos, value, root.right, mid + 1, right)
)
}
// Usage example
fun main(args: Array<String?>?) {
val n = 10
val t1 = build(0, n - 1)
val t2 = set(0, 1, t1, 0, n - 1)
System.out.println(0 == sum(0, 9, t1, 0, n - 1))
System.out.println(1 == sum(0, 9, t2, 0, n - 1))
}
class Node {
var left: Node? = null
var right: Node? = null
var sum = 0
internal constructor(value: Int) {
sum = value
}
internal constructor(left: Node?, right: Node?) {
this.left = left
this.right = right
if (left != null) sum += left.sum
if (right != null) sum += right.sum
}
}
}
| 1 | Java | 0 | 0 | 4566f3145be72827d72cb93abca8bfd93f1c58df | 1,704 | codelibrary | The Unlicense |
src/main/kotlin/com/ab/advent/day04/Models.kt | battagliandrea | 574,137,910 | false | {"Kotlin": 27923} | package com.ab.advent.day04
data class Assignment(val start: Int, val end: Int){
private val range = start..end
fun containsAll(other: Assignment) = range.intersect(other.range).size == other.range.count()
fun containsAny(other: Assignment) = range.intersect(other.range).isNotEmpty()
companion object {
fun parse(input: String) =
input.split("-").map { uniqueId -> uniqueId.toInt() }
.let { (start, end) -> Assignment(start, end) }
}
}
data class AssignmentSheet(val left: Assignment, val right: Assignment){
fun hasOverlap() = left.containsAll(right) || right.containsAll(left)
fun anyOverlap() = left.containsAny(right) || right.containsAny(left)
companion object {
fun parse(input: String) =
input.split(",").map(Assignment::parse)
.let { (left, right) -> AssignmentSheet(left, right) }
}
}
| 0 | Kotlin | 0 | 0 | cb66735eea19a5f37dcd4a31ae64f5b450975005 | 911 | Advent-of-Kotlin | Apache License 2.0 |
src/chapter1/section4/ex8.kt | w1374720640 | 265,536,015 | false | {"Kotlin": 1373556} | package chapter1.section4
/**
* 编写一个程序,计算输入文件中相等的整数对的数量。
* 如果你的第一个程序是平方级别的,请继续思考并用Array.sort()给出一个线性对数级别的答案。
*/
fun ex8a(array: IntArray): Long {
var count = 0L
for (i in array.indices) {
for (j in i + 1 until array.size) {
if (array[i] == array[j]) {
count++
}
}
}
return count
}
/**
* 优化后的方法
* 先排序,再统计每个数字的重复次数,再用组合公式计算组合数
* array.sort()排序算法复杂度为NlgN,遍历所有元素复杂度为N,用组合公式计算组合数复杂度为常数,所以总复杂度为NlgN
*/
fun ex8b(array: IntArray): Long {
array.sort()
var count = 0L
var index = 0
while (index < array.size) {
val value = array[index]
var equalNum = 1
while (index + equalNum < array.size && array[index + equalNum] == value) {
equalNum++
}
if (equalNum > 1) {
count += combination(equalNum, 2)
}
index += equalNum
}
return count
}
fun main() {
println("fast method:")
timeRatio(path = "./data/largeT.txt") { ex8b(it) }
println("slow method:")
timeRatio(path = "./data/largeT.txt") { ex8a(it) }
}
| 0 | Kotlin | 1 | 6 | 879885b82ef51d58efe578c9391f04bc54c2531d | 1,368 | Algorithms-4th-Edition-in-Kotlin | MIT License |
app/src/main/kotlin/kotlinadventofcode/2023/2023-23.kt | pragmaticpandy | 356,481,847 | false | {"Kotlin": 1003522, "Shell": 219} | // Originally generated by the template in CodeDAO
package kotlinadventofcode.`2023`
import com.github.h0tk3y.betterParse.combinators.*
import com.github.h0tk3y.betterParse.grammar.*
import com.github.h0tk3y.betterParse.lexer.*
import kotlinadventofcode.Day
import kotlinadventofcode.UI.UI
class `2023-23` : Day {
override val year: Int = 2023
override val day: Int = 23
context(UI)
override fun runPartOne(input: String): String {
return input.toGrid().getLongestPathToFinish().toString()
}
context(UI)
override fun runPartTwo(input: String): String {
return input.toGrid().getLongestPathWithReducedGraph().toString()
}
companion object {
data class Grid(val grid: List<List<Tile>>) {
val height = grid.size
val width = grid[0].size
data class Coord(val x: Int, val y: Int)
val Coord.tile get() = grid[y][x]
context(UI)
fun getLongestPathToFinish(): Int {
val start = Coord(1, 0)
val end = Coord(width - 2, height - 1)
val paths: MutableList<List<Coord>> = mutableListOf(listOf(start))
var longestLengthToEnd = -1
val numNonForest = grid.flatten().count { it != Tile.FOREST }
show("grid size", "$width by $height")
show("num non-forest", numNonForest)
while (paths.isNotEmpty()) {
show("paths in queue", paths.size)
val path = paths.removeLast()
show("current path length", path.size)
if (path.last() == end) {
longestLengthToEnd = maxOf(longestLengthToEnd, path.size - 1)
show("longest length to end", "$longestLengthToEnd")
} else {
paths.addAll(path.getNextPaths())
}
}
return longestLengthToEnd
}
fun List<Coord>.getNextPaths(): List<List<Coord>> {
if (last().tile == Tile.UP_SLOPE) return listOf(this + Coord(last().x, last().y - 1))
if (last().tile == Tile.DOWN_SLOPE) return listOf(this + Coord(last().x, last().y + 1))
if (last().tile == Tile.LEFT_SLOPE) return listOf(this + Coord(last().x - 1, last().y))
if (last().tile == Tile.RIGHT_SLOPE) return listOf(this + Coord(last().x + 1, last().y))
val seen = this.toSet()
return this.last().adjacent()
.filter { it !in seen }
.filter {
when(it.tile) {
Tile.UP_SLOPE -> Coord(it.x, it.y - 1) !in seen
Tile.DOWN_SLOPE -> Coord(it.x, it.y + 1) !in seen
Tile.LEFT_SLOPE -> Coord(it.x - 1, it.y) !in seen
Tile.RIGHT_SLOPE -> Coord(it.x + 1, it.y) !in seen
Tile.FOREST -> false
Tile.PATH -> true
}
}
.map { this + it }
}
fun Coord.adjacent(): List<Coord> {
val result = listOf(
Coord(x - 1, y),
Coord(x + 1, y),
Coord(x, y - 1),
Coord(x, y + 1)
)
.filter { it.x in 0 until width && it.y in 0 until height }
.filter { it.tile != Tile.FOREST }
return result
}
context(UI)
fun getLongestPathWithReducedGraph() : Int {
data class Node(val location: Coord)
val start = Coord(1, 0)
val startNode = Node(start)
val end = Coord(width - 2, height - 1)
val endNode = Node(end)
val nodes = mutableListOf(startNode, endNode)
for (x in 0 until width) {
for (y in 0 until height) {
val coord = Coord(x, y)
if (coord.tile == Tile.FOREST) continue
if (coord.adjacent().size < 3) continue
nodes.add(Node(coord))
}
}
val nodesByLocation = nodes.associateBy { it.location }
val edges: MutableMap<Node, MutableMap<Node, Int>> = mutableMapOf()
for (node in nodes) {
node.location.adjacent().forEach { coordAdjacentToNode ->
var length = 1
var previous = node.location
var current = coordAdjacentToNode
while (current !in nodesByLocation) {
val next = current.adjacent().filter { it != previous }[0]
previous = current
current = next
length++
}
val adjacentNode = nodesByLocation[current]!!
edges.getOrPut(node) { mutableMapOf() }[adjacentNode] = length
}
}
show("num nodes", nodes.size)
show("num edges", edges.values.sumOf { it.size } / 2)
fun List<Node>.getNextPaths(): List<List<Node>> {
return edges[this.last()]!!
.filter { (node, _) -> node !in this }
.map { (node, _) -> this + node }
}
fun List<Node>.pathLength(): Int {
return windowed(2).sumOf { (from, to) -> edges[from]!![to]!! }
}
val paths: MutableList<List<Node>> = mutableListOf(listOf(startNode))
var longestLengthToEnd = -1
while (paths.isNotEmpty()) {
show("paths in queue", paths.size)
val path = paths.removeLast()
show("current path length", path.size)
if (path.last() == endNode) {
longestLengthToEnd = maxOf(longestLengthToEnd, path.pathLength())
show("longest length to end", "$longestLengthToEnd")
} else {
paths.addAll(path.getNextPaths())
}
}
return longestLengthToEnd
}
}
enum class Tile {
PATH, FOREST, UP_SLOPE, DOWN_SLOPE, RIGHT_SLOPE, LEFT_SLOPE
}
fun String.toGrid() : Grid {
val grammar = object : Grammar<Grid>() {
// tokens
val newlineLit by literalToken("\n")
val pathLit by literalToken(".")
val forestLit by literalToken("#")
val upSlopeLit by literalToken("^")
val downSlopeLit by literalToken("v")
val rightSlopeLit by literalToken(">")
val leftSlopeLit by literalToken("<")
// parsers
val path by pathLit use { Tile.PATH }
val forest by forestLit use { Tile.FOREST }
val upSlope by upSlopeLit use { Tile.UP_SLOPE }
val downSlope by downSlopeLit use { Tile.DOWN_SLOPE }
val rightSlope by rightSlopeLit use { Tile.RIGHT_SLOPE }
val leftSlope by leftSlopeLit use { Tile.LEFT_SLOPE }
val tile by path or forest or upSlope or downSlope or rightSlope or leftSlope
val row by oneOrMore(tile)
override val rootParser by separatedTerms(row, newlineLit) map { Grid(it) }
}
return grammar.parseToEnd(this)
}
}
override val defaultInput = """#.###########################################################################################################################################
#.........#...###.....#...#...###...#...#.....#.....#...#...###.......#...#...#...###.......###...#...#...#...#.....#####...........#...#...#
#########.#.#.###.###.#.#.#.#.###.#.#.#.#.###.#.###.#.#.#.#.###.#####.#.#.#.#.#.#.###.#####.###.#.#.#.#.#.#.#.#.###.#####.#########.#.#.#.#.#
#.........#.#.....#...#.#.#.#...#.#.#.#.#...#.#.#...#.#.#.#...#.....#.#.#.#.#...#...#.....#.....#.#.#.#.#.#.#.#.#...#.....#.........#.#.#.#.#
#.#########.#######.###.#.#.###.#.#.#.#.###.#.#.#.###.#.#.###.#####.#.#.#.#.#######.#####.#######.#.#.#.#.#.#.#.#.###.#####.#########.#.#.#.#
#.....#...#...#...#.###.#.#.#...#.#...#.....#.#.#...#.#.#.#...#.....#.#.#.#.....#...#...#...#.....#.#.#.#.#.#.#.#...#.....#...........#...#.#
#####.#.#.###.#.#.#.###.#.#.#.###.###########.#.###.#.#.#.#.###.#####.#.#.#####.#.###.#.###.#.#####.#.#.#.#.#.#.###.#####.#################.#
###...#.#...#...#.#.#...#...#...#.........#...#.#...#.#.#.#.###.....#.#.#...#...#...#.#.###.#...#...#.#.#...#...#...#...#.#.................#
###.###.###.#####.#.#.#########.#########.#.###.#.###.#.#.#.#######.#.#.###.#.#####.#.#.###.###.#.###.#.#########.###.#.#.#.#################
#...#...###...#...#...#.........#.......#.#...#.#...#.#.#.#.#...###.#...#...#.....#...#.>.>.#...#.#...#.#.........###.#...#...###...#.......#
#.###.#######.#.#######.#########.#####.#.###.#.###.#.#.#.#.#.#.###.#####.#######.#######v###.###.#.###.#.###########.#######.###.#.#.#####.#
#.....#...#...#.#.......#...#.....#.....#...#.#.#...#.#.#.#...#.#...#...#.#...###.......#...#...#.#.#...#...........#.......#...#.#.#.#.....#
#######.#.#.###.#.#######.#.#.#####.#######.#.#.#.###.#.#.#####.#.###.#.#.#.#.#########.###.###.#.#.#.#############.#######.###.#.#.#.#.#####
#.....#.#.#.....#.......#.#.#.....#.#...###.#...#...#.#.#.#...#.#.#...#.#.#.#...#.......#...###.#.#.#.#.............#...###...#...#...#.....#
#.###.#.#.#############.#.#.#####.#.#.#.###.#######.#.#.#.#.#.#.#.#.###.#.#.###.#.#######.#####.#.#.#.#.#############.#.#####.#############.#
#...#...#...#...#.....#.#.#.#.....#.#.#...#.....#...#.#.#.#.#...#...#...#.#.###.#.###...#.....#.#.#.#.#...#.>.>.###...#.#.....#.......#.....#
###.#######.#.#.#.###.#.#.#.#.#####.#.###.#####.#.###.#.#.#.#########.###.#.###.#.###.#.#####.#.#.#.#.###.#.#v#.###.###.#.#####.#####.#.#####
###.....#...#.#.#...#...#.#.#.....#.#.#...###...#.#...#.#.#...#.>.>...#...#...#.#.#...#.......#.#.#.#...#...#.#...#...#.#.....#.#...#...#...#
#######.#.###.#.###v#####.#.#####.#.#.#.#####.###.#.###.#.###.#.#v#####.#####.#.#.#.###########.#.#.###.#####.###.###.#.#####.#.#.#.#####.#.#
#.......#...#.#.###.>...#.#...#...#...#.>.>.#.#...#.#...#...#...#...###.....#.#...#...........#.#.#.....###...###...#.#...#...#...#.#.....#.#
#.#########.#.#.###v###.#.###.#.#########v#.#.#.###.#.#####.#######.#######.#.###############.#.#.#########.#######.#.###.#.#######.#.#####.#
#.........#...#...#...#.#.#...#.#.....#...#.#.#.#...#...#...###...#.......#...###.......#.....#.#.#.........#...###.#.#...#...#...#...#.....#
#########.#######.###.#.#.#.###.#.###.#.###.#.#.#.#####.#.#####.#.#######.#######.#####.#.#####.#.#.#########.#.###.#.#.#####.#.#.#####.#####
#.........#.....#.....#...#...#.#...#.#...#...#.#.....#.#.#.....#.#...#...###...#.....#.#...###...#...........#...#...#.......#.#.......#...#
#.#########.###.#############.#.###.#.###.#####.#####.#.#.#.#####.#.#.#.#####.#.#####.#.###.#####################.#############.#########.#.#
#.....#.....#...#.......#...#.#.#...#.....#.....#.....#.#.#.#...#...#...#.....#.###...#...#.....#.................#...#...#...#.........#.#.#
#####.#.#####.###.#####.#.#.#.#.#.#########.#####.#####.#.#.#.#.#########.#####.###.#####.#####.#.#################.#.#.#.#.#.#########.#.#.#
#.....#.#.....###...#...#.#.#.#.#.........#.....#...###...#...#.........#.....#.....#...#.......#...............###.#.#.#.#.#.#...#.....#.#.#
#.#####.#v#########.#.###.#.#.#.#########.#####.###.###################.#####.#######.#.#######################.###.#.#.#.#.#.#.#.#v#####.#.#
#.......#.>.#.....#.#...#.#.#...#...#...#.#.....#...#...#...#...........#.....#.....#.#.....#...................#...#...#.#.#.#.#.>.#.....#.#
#########v#.#.###.#.###.#.#.#####.#.#.#.#.#.#####.###.#.#.#.#.###########.#####.###.#.#####.#.###################.#######.#.#.#.###v#.#####.#
#.........#...#...#.#...#.#.###...#.#.#...#.......###.#...#.#.......#...#.....#.###...#...#.#...........#.......#.......#...#...###...#.....#
#.#############.###.#.###.#.###.###.#.###############.#####.#######.#.#.#####.#.#######.#.#.###########.#.#####.#######.###############.#####
#...........#...#...#...#.#.....###...#...###.......#.#...#.........#.#.#...#...###.....#...#...#.....#...#.....#.......#...............#...#
###########.#.###.#####.#.#############.#.###.#####.#.#.#.###########.#.#.#.#######.#########.#.#.###.#####.#####.#######.###############.#.#
#...#####...#.....###...#...#...#.....#.#...#.....#.#...#...#.........#.#.#.........###...###.#.#.#...#...#.....#.....###.......#.........#.#
#.#.#####.###########.#####.#.#.#.###.#.###.#####.#.#######.#.#########.#.#############.#.###.#.#.#.###.#.#####.#####.#########.#.#########.#
#.#.......#...###...#...###...#.#.#...#...#.#...#.#...#...#...#.........#.............#.#...#.#...#.#...#...#...#...#.....###...#.#.........#
#.#########.#.###.#.###.#######v#.#.#####.#.#.#.#.###.#.#.#####.#####################.#.###.#.#####.#.#####.#.###.#.#####.###.###.#.#########
#.#.......#.#.....#...#.#...#.>.>.#.#...#.#.#.#.#...#.#.#.#...#.#.......#...#...#.....#...#.#...#...#.#.....#...#.#...#...#...#...#...#.....#
#.#.#####.#.#########.#.#.#.#.#v###.#.#.#.#.#.#.###.#.#.#.#.#.#v#.#####.#.#.#.#.#.#######.#.###.#.###.#.#######v#.###.#.###.###.#####.#.###.#
#.#.###...#.#.........#...#...#...#.#.#.#.#...#.#...#.#.#.#.#.>.>.#.....#.#.#.#.#...#...#.#.....#.#...#...#...>.>.###...###...#.#.....#.#...#
#.#.###.###.#.###################.#.#.#.#.#####.#.###.#.#.#.###v###.#####.#.#.#.###v#.#.#.#######.#.#####.#.###v#############.#.#.#####.#.###
#.#...#...#.#.#...........#.......#.#.#.#.....#.#...#.#.#...###.###.....#.#...#.#.>.>.#.#...#.....#.....#.#.###.............#...#.#...#.#.###
#.###.###.#.#.#.#########.#.#######.#.#.#####.#.###.#.#.#######.#######.#.#####.#.#v###.###.#.#########.#.#.###############.#####.#.#.#.#.###
#.....###...#...#.........#.#...###.#.#.#...#.#.#...#...###.....#.....#.#...###...#...#.#...#.....#...#.#...#.....#...#...#.....#...#...#...#
#################.#########.#.#.###.#.#.#.#.#.#.#.#########.#####.###.#.###.#########.#.#.#######.#.#.#.#####.###.#.#.#.#.#####.###########.#
###...#.........#.......###...#...#...#.#.#...#...#####...#.....#.#...#...#...#.......#...###.....#.#.#.###...###.#.#.#.#.#...#.#...........#
###.#.#.#######.#######.#########.#####.#.#############.#.#####.#.#.#####.###.#.#############.#####.#.#.###.#####.#.#.#.#.#.#.#.#.###########
###.#.#.......#...#...#.#.........#...#...###...#...#...#.#.....#.#.#...#.....#.#.......#...#...#...#...#...#.....#.#.#.#...#...#.........###
###.#.#######.###.#.#.#.#.#########.#.#######.#.#.#.#.###.#.#####.#.#.#.#######.#.#####.#.#.###.#.#######.###.#####.#.#.#################.###
#...#...#...#...#...#...#...#.......#.###...#.#.#.#.#...#.#.......#.#.#.###...#...#.....#.#.#...#...###...###.......#...###...#...#.....#...#
#.#####.#.#.###.###########.#.#######.###.#.#.#.#.#.###.#.#########v#.#.###.#.#####.#####.#.#.#####.###.###################.#.#.#.#.###.###.#
#.#...#...#.....#...#...###...#.......#...#.#.#.#.#...#.#.......#.>.>.#...#.#.#...#.#...#.#.#.......#...###...#...#...#.....#.#.#.#.#...#...#
#.#.#.###########.#.#.#.#######.#######.###.#.#.#.###.#.#######.#.#v#####.#.#.#.#.#.#.#.#.#.#########.#####.#.#.#.#.#.#.#####.#.#.#.#.###.###
#.#.#.#...#.....#.#...#.....#...#.....#...#.#.#.#...#.#.#.......#.#.#.....#.#.#.#.#.#.#.#.#.#...#...#.......#.#.#...#.#.....#...#.#.#.#...###
#.#.#.#.#.#.###.#.#########.#.###.###.###.#.#.#.###.#.#.#.#######.#.#.#####.#.#.#.#v#.#.#.#.#.#.#.#.#########.#.#####.#####.#####.#.#.#.#####
#...#...#...###.#.#.........#...#...#...#.#...#.#...#.#.#.......#.#.#...#...#.#.#.>.>.#...#.#.#.#.#.#.........#...#...#...#.#.....#.#.#...###
###############.#.#v###########.###.###.#.#####.#.###.#.#######.#.#.###.#.###.#.###v#######.#.#.#.#.#v###########.#.###.#.#.#.#####.#.###.###
###...#...#...#...#.>...#.....#...#...#.#...#...#...#.#.#.....#...#...#.#.###.#.###...#.....#.#.#.#.>.>.#.....#...#.#...#.#.#.#.....#...#...#
###.#.#.#.#.#.#####v###.#.###.###.###.#.###.#.#####.#.#.#.###.#######.#.#.###.#.#####.#.#####.#.#.###v#.#.###.#.###.#.###.#.#.#.#######.###.#
#...#...#...#...###.#...#.#...#...#...#...#.#...#...#.#.#...#.#...#...#.#.#...#.#...#.#.....#.#...#...#...#...#.#...#.#...#.#.#.....#...#...#
#.#############.###.#.###.#.###v###.#####.#.###.#.###.#.###.#.#.#.#.###.#.#.###.#.#.#.#####.#.#####.#######.###.#.###.#.###.#.#####.#.###v###
#...#.........#...#.#.....#...>.>.#.....#.#.#...#.#...#.#...#.#.#.#...#...#.....#.#...#...#...#...#.......#.#...#...#.#.#...#...#...#...>.###
###.#.#######.###.#.###########v#.#####.#.#.#.###.#.###.#.###.#.#.###.###########.#####.#.#####.#.#######.#.#.#####.#.#.#.#####.#.#######v###
###...#.......#...#...#.........#.......#...#.#...#...#.#...#...#.#...###.....###.......#.....#.#.........#.#...#...#.#.#.....#.#.#.......###
#######.#######.#####.#.#####################.#.#####.#.###.#####.#.#####.###.###############.#.###########.###.#.###.#.#####.#.#.#.#########
#.....#.......#...#...#...#.........#.......#...#...#...###.....#.#.....#...#.................#.....#.....#.#...#...#.#.#.....#.#.#.........#
#.###.#######.###.#.#####.#.#######.#.#####.#####.#.###########.#.#####.###.#######################.#.###.#.#.#####.#.#.#.#####.#.#########.#
#...#.#...#...#...#.....#...#.......#.#.....#...#.#.#...#.......#.......###.................#...###.#.#...#...#...#...#.#.....#...###.......#
###.#.#.#.#.###.#######.#####.#######.#.#####.#.#.#.#.#.#.#################################.#.#.###.#.#.#######.#.#####.#####.#######.#######
#...#...#...###.........#...#.........#.#...#.#...#.#.#.#...............###...#.............#.#.###...#.........#.....#.#...#.....#...#.....#
#.#######################.#.###########.#.#.#.#####.#.#.###############.###.#.#.#############.#.#####################.#.#.#.#####.#.###.###.#
#.#...#.......#.......###.#.............#.#...#.....#.#.........#.....#.#...#.#.#...........#.#.....#...#.......#.....#.#.#.......#.....#...#
#.#.#.#.#####.#.#####.###.###############.#####.#####.#########.#.###.#.#.###.#.#.#########.#.#####.#.#.#.#####.#.#####.#.###############.###
#...#...###...#.....#...#.#...#.........#.#...#.....#.........#...###...#...#.#...#.........#.#.....#.#.#...###...#...#...###.....#...#...###
###########v#######.###.#.#.#.#.#######.#.#.#.#####.#########.#############.#.#####.#########.#.#####.#.###v#######.#.#######.###.#.#.#.#####
#.......###.>...###...#.#...#...#...###...#.#.......#.........#...#...#...#.#.#...#...###...#.#.#...#.#.#.>.>.#...#.#.###...#.#...#.#.#.....#
#.#####.###v###.#####.#.#########.#.#######v#########.#########.#.#.#.#.#.#.#.#.#.###v###.#.#.#.#.#.#.#.#.#v#.#.#.#.#.###.#.#.#.###.#.#####.#
#.....#.....###.#...#.#...#.....#.#.#.....>.>.#...###...........#.#.#...#.#.#...#...>.>...#.#.#.#.#.#.#.#.#.#...#.#.#...#.#.#.#...#.#.#.....#
#####.#########.#.#.#.###.#.###.#.#.#.#####v#.#.#.###############.#.#####.#.#########v#####.#.#.#.#.#.#.#.#.#####.#.###.#.#.#.###.#.#.#.#####
#.....#...#...#...#.#...#...###.#.#.#.###...#...#...#...#.......#.#.....#...#...#...#.#.....#.#...#...#.#.#...###...#...#.#.#.#...#.#.#...###
#.#####.#.#.#.#####.###.#######.#.#.#.###.#########.#.#.#.#####.#.#####.#####.#.#.#.#.#.#####.#########.#.###.#######.###.#.#.#.###.#.###v###
#.......#...#.....#...#.......#...#...#...#.........#.#.#.#...#...#...#...#...#.#.#.#.#.....#.........#...###...#.....#...#.#.#...#.#...>.###
#################.###.#######.#########.###.#########.#.#.#.#.#####.#.###.#.###.#.#.#.#####.#########.#########.#.#####.###.#.###.#.#####v###
#.................###...#...#.#...#.....###.....###...#.#.#.#...###.#.#...#...#...#.#...#...#...#.....#.........#.#...#.###.#...#...#.....###
#.#####################.#.#.#.#.#.#.###########.###.###.#.#.###.###.#.#.#####.#####.###.#.###.#.#.#####.#########.#.#.#.###.###.#####.#######
#...#.................#...#...#.#...#.......###...#...#.#...#...#...#.#.#.....#...#.....#...#.#.#.#...#.........#.#.#.#.###.....#...#.......#
###.#.###############.#########.#####.#####.#####.###.#.#####v###.###.#.#.#####.#.#########.#.#.#.#.#.#########.#.#.#.#.#########.#.#######.#
#...#.#...............###...#...#...#.#.....#...#.#...#...#.>.>...###.#.#.......#.......#...#.#...#.#...........#.#.#.#.#.........#.......#.#
#.###.#.#################.#.#.###.#.#.#.#####.#.#.#.#####.#.#v#######.#.###############.#.###.#####.#############.#.#.#.#.###############.#.#
#.#...#.................#.#.#.....#...#.......#.#.#.###...#.#...#...#...#...#...#.....#.#...#.#.....#.....#...###...#.#.#...............#...#
#.#.###################.#.#.###################.#.#.###.###.###.#.#.#####.#.#.#.#.###.#.###.#.#.#####.###.#.#.#######.#.###############.#####
#.#.#...........#.......#.#...#...#.............#.#.#...#...###...#.....#.#...#...###.#...#...#...#...###...#.......#...#...#...###...#.....#
#.#.#.#########.#.#######.###.#.#.#.#############.#.#.###.#############.#.###########.###.#######.#.###############.#####.#.#.#.###.#.#####.#
#...#.....#...#...#.....#.#...#.#.#.....#...#####...#.#...#...#.........#.#.....#...#.....#.....#.#.#...#...........###...#...#.....#.......#
#########.#.#.#####.###.#.#.###.#.#####.#.#.#########.#.###.#.#.#########.#.###.#.#.#######.###.#.#.#.#.#.#############.#####################
###...###...#...###...#...#...#.#.......#.#.........#...#...#...#...#...#...#...#.#...#...#.#...#...#.#...#.......#...#...#...#...#.........#
###.#.#########.#####.#######.#.#########.#########.#####.#######.#.#.#.#####v###.###.#.#.#.#.#######.#####.#####.#.#.###.#.#.#.#.#.#######.#
#...#...........#.....#.......#...........#.........#...#.......#.#...#.#...>.>...#...#.#.#.#.###...#.#.....#.....#.#...#...#.#.#.#.#.....#.#
#.###############.#####.###################.#########.#.#######.#.#####.#.###v#####.###.#.#.#.###.#.#.#.#####.#####.###.#####.#.#.#.#.###.#.#
#...............#.....#.#...#...#...###.....#...#.....#.......#...#.....#...#.#.....###.#.#.#.###.#.#.#.#...#.......#...#...#...#...#...#...#
###############.#####.#.#.#.#.#.#.#.###v#####.#.#.###########.#####.#######.#.#.#######.#.#.#.###.#.#.#.#.#.#########.###.#.###########.#####
###...#.........#.....#.#.#.#.#.#.#...>.>...#.#.#.........#...#.....#...#...#.#.......#.#...#.....#.#...#.#.......#...#...#.#.....#...#.....#
###.#.#.#########.#####.#.#.#.#.#.#####v###.#.#.#########.#.###.#####.#.#.###.#######.#.###########.#####.#######.#.###.###.#.###.#.#.#####.#
#...#.#.......###.....#.#.#...#...###...#...#.#...#...#...#...#.....#.#.#.#...#.......#.......#.....#...#.....###...#...#...#...#...#.....#.#
#.###.#######v#######.#.#.###########.###.###.###.#.#.#.#####.#####.#.#.#.#.###.#############.#.#####.#.#####v#######.###.#####.#########.#.#
#...#.#...###.>.......#.#.#.........#...#...#...#.#.#.#.#.....#...#.#.#...#...#.#...#...#...#.#.#...#.#...#.>.>.#...#...#.#...#.........#...#
###.#.#.#.###v#########.#.#.#######.###.###.###.#.#.#.#.#.#####.#.#v#.#######.#.#.#.#.#.#.#.#.#.#.#.#.###.#.#v#.#.#.###.#.#.#.#########v#####
#...#...#...#.........#...#...#...#.#...###...#.#.#.#.#.#.#...#.#.>.>.#.......#.#.#...#.#.#...#.#.#.#.#...#.#.#...#...#.#.#.#.#.....#.>.#...#
#.#########.#########.#######.#.#.#.#.#######.#.#.#.#.#.#.#.#.#.###v###.#######.#.#####.#.#####.#.#.#.#.###.#.#######.#.#.#.#.#.###.#.#v#.#.#
#.........#...#.......###.....#.#.#...###...#...#.#.#...#.#.#.#.###...#.......#.#.....#.#.....#.#.#...#.....#...#...#...#.#.#.#...#...#...#.#
#########.###.#.#########.#####.#.#######.#.#####.#.#####.#.#.#.#####.#######.#.#####.#.#####.#.#.#############.#.#.#####.#.#.###.#########.#
#.........#...#.........#.......#...#...#.#.......#.#.....#.#.#.#.....###.....#...#...#.....#.#.#.#...........#...#...#...#.#.#...#.........#
#.#########.###########.###########.#.#.#.#########.#.#####.#.#.#.#######.#######.#.#######.#.#.#.#.#########.#######.#.###.#.#.###.#########
#.........#.....#.......#...........#.#.#.......#...#.#...#.#...#.......#...###...#.......#.#.#...#.....#...#.....#...#.....#.#.###.....#...#
#########.#####.#.#######.###########.#.#######.#.###.#.#.#.###########.###.###.#########.#.#.#########.#.#.#####.#.#########.#.#######.#.#.#
###...###.....#...#...###.............#...#.....#...#.#.#.#.#.........#.###...#.#.........#...#.....###...#.....#.#.#.......#.#.#.......#.#.#
###.#.#######.#####.#.###################.#.#######.#.#.#.#.#.#######.#.#####.#.#.#############.###.###########.#.#.#.#####.#.#.#.#######.#.#
#...#.........###...#...#.......#...#.....#.........#...#...#.......#...#.....#...#...#...#...#.#...#...........#.#...#.....#.#.#.#.......#.#
#.###############.#####.#.#####.#.#.#.#############################.#####.#########.#.#.#.#.#.#.#.###.###########.#####.#####.#.#.#.#######.#
#.#...#...###...#.#.....#.#...#...#...#####.........###...#...#.....#...#...###...#.#.#.#.#.#.#.#...#...........#.......#####...#...#.......#
#.#.#.#.#.###.#.#.#.#####.#.#.#############.#######.###.#.#.#.#.#####.#.###.###.#.#.#.#.#.#.#.#.###.###########.#####################.#######
#...#...#.....#...#.....#...#.............#.......#...#.#.#.#.#.......#...#...#.#.#.#.#.#.#.#.#.#...#...#...###.###...#...#...#.....#.......#
#######################.#################.#######.###.#.#.#.#.###########.###.#.#.#.#.#.#.#.#.#.#.###.#.#.#.###v###.#.#.#.#.#.#.###.#######.#
#.............#...#.....###...............#...#...#...#.#...#.....#.....#.#...#.#.#.#.#.#.#.#.#.#...#.#.#.#.#.>.>.#.#.#.#.#.#.#...#.#...#...#
#.###########.#.#.#.#######.###############.#.#.###.###.#########.#.###.#.#.###.#.#.#.#.#.#.#.#.###.#.#.#.#.#.###.#.#.#.#.#.#.###.#.#.#.#v###
#...........#...#...#.....#...............#.#.#...#...#.........#.#...#...#.#...#.#.#.#.#.#.#.#.#...#.#...#.#.#...#.#.#.#.#.#...#.#...#.>.###
###########.#########.###.###############.#.#.###.###.#########.#.###.#####v#.###.#.#.#.#.#.#.#.#.###.#####.#.#.###.#.#.#.#.###.#.#######v###
#...........#...#...#.#...#...###.........#.#...#...#.#.....#...#.#...#...>.>.#...#.#.#.#.#.#...#...#...#...#.#.....#...#.#...#.#.#.......###
#.###########.#.#.#.#.#.###.#.###.#########.###.###.#.#.###.#.###.#.###.#######.###.#.#.#.#.#######.###.#.###.###########.###.#.#.#.#########
#...#.....#...#...#.#.#...#.#.#...#...#...#...#.###.#.#...#.#...#.#.###.......#...#.#...#.#.#.....#.#...#...#.....#####...#...#.#.#.........#
###.#.###.#.#######.#.###.#.#.#.###.#.#.#.###.#.###.#.###.#.###.#.#v#########.###.#.#####.#.#.###.#.#.#####.#####.#####.###.###.#.#########.#
#...#.#...#.#.......#.#...#.#.#...#.#.#.#.#...#...#.#...#.#.#...#.>.>.#.....#...#.#.#...#...#...#...#.###...#.....#.....#...###.#.#.....###.#
#.###.#.###.#.#######.#.###.#.###v#.#.#.#.#.#####.#.###.#.#.#.#######.#.###.###.#.#.#.#.#######.#####.###.###.#####.#####.#####.#.#.###.###.#
#...#.#...#.#.......#.#.#...#.#.>.>.#.#.#.#...#...#...#.#.#.#.......#.#...#...#.#.#...#.......#.#...#...#...#...#...#...#.#...#...#...#.....#
###.#.###.#.#######.#.#.#.###.#.#####.#.#.###.#.#####.#.#.#.#######.#.###.###.#.#.###########.#.#.#.###.###.###.#.###.#.#.#.#.#######.#######
###.#.#...#.#.......#.#.#.###.#.....#.#.#.#...#...#...#.#.#.#...#...#...#...#.#.#.#...#...#...#.#.#.#...#...#...#...#.#.#...#.#.......#.....#
###.#.#.###.#.#######.#.#.###.#####.#.#.#.#.#####.#.###.#.#.#.#.#.#####.###.#.#.#.#.#.#.#.#.###.#.#.#.###.###.#####.#.#.#####.#.#######.###.#
###...#.....#.........#...###.......#...#...#####...###...#...#...#####.....#...#...#...#...###...#...###.....#####...#.......#.........###.#
###########################################################################################################################################.#"""
} | 0 | Kotlin | 0 | 3 | 26ef6b194f3e22783cbbaf1489fc125d9aff9566 | 27,937 | kotlinadventofcode | MIT License |
src/main/kotlin/net/mguenther/adventofcode/day12/Graph.kt | mguenther | 115,937,032 | false | null | package net.mguenther.adventofcode.day12
import java.util.Optional
import java.util.Queue
import java.util.concurrent.LinkedBlockingQueue
/**
* @author <NAME> (<EMAIL>)
*/
class UndirectedGraph(val resourceFile: String) {
private val adjacencyList: Map<Int, List<Int>> = load()
fun sizeOfConnectedComponentFor(root: Int): Int {
val Q: Queue<Int> = LinkedBlockingQueue()
val visited: MutableSet<Int> = mutableSetOf()
Q.add(root)
while (Q.isNotEmpty()) {
val node = Q.poll()
visited.add(node)
adjacencyList.getOrDefault(node, emptyList())
.filterNot { visited.contains(it) }
.forEach { Q.offer(it) }
}
return visited.size
}
fun numberOfConnectedComponents(): Int {
val Q: Queue<Int> = LinkedBlockingQueue()
val visited: MutableSet<Int> = mutableSetOf()
var scc = 0
firstUnvisited(visited).ifPresent { Q.add(it); visited.add(it); scc++ }
while (Q.isNotEmpty()) {
val node = Q.poll()
adjacencyList.getOrDefault(node, emptyList())
.filterNot { visited.contains(it) }
.forEach { Q.offer(it); visited.add(it) }
if (Q.isEmpty()) firstUnvisited(visited).ifPresent { Q.add(it); visited.add(it); scc++ }
}
return scc
}
private fun firstUnvisited(visited: Set<Int>): Optional<Int> {
return adjacencyList.keys.stream().filter { n -> !visited.contains(n) }.findFirst()
}
private fun load(): Map<Int, List<Int>> {
val adjacencyList: MutableMap<Int, List<Int>> = mutableMapOf()
val lines = UndirectedGraph::class.java
.getResource(resourceFile)
.readText()
.split("\n")
for (line in lines) {
val tokens = line.split("<->")
val from = tokens[0].trim().toInt()
val neighbours = tokens[1].trim().split(",").map { i -> i.trim().toInt() }
for (neighbour in neighbours) {
adjacencyList.put(from, adjacencyList.getOrDefault(from, emptyList()) + neighbour)
adjacencyList.put(neighbour, adjacencyList.getOrDefault(neighbour, emptyList()) + from)
}
}
return adjacencyList
}
}
| 0 | Kotlin | 0 | 0 | c2f80c7edc81a4927b0537ca6b6a156cabb905ba | 2,378 | advent-of-code-2017 | MIT License |
common/iteration/src/main/kotlin/com/curtislb/adventofcode/common/iteration/Permutations.kt | curtislb | 226,797,689 | false | {"Kotlin": 2146738} | package com.curtislb.adventofcode.common.iteration
/**
* Returns a [Sequence] of all ordered permutations of the elements in this list.
*/
fun <T> List<T>.permutations(): Sequence<List<T>> =
if (isEmpty()) {
emptySequence()
} else {
permutationsRecursive(prefix = mutableListOf(), usedIndices = mutableSetOf())
}
/**
* Returns a [Sequence] of ordered permutations of this list that begin with the given [prefix] and
* contain all other elements whose indices are not in [usedIndices].
*/
private fun <T> List<T>.permutationsRecursive(
prefix: MutableList<T>,
usedIndices: MutableSet<Int>
): Sequence<List<T>> {
return sequence {
if (prefix.size == size) {
yield(prefix.toList())
} else {
forEachIndexed { index, item ->
if (index !in usedIndices) {
prefix.add(item)
usedIndices.add(index)
yieldAll(permutationsRecursive(prefix, usedIndices))
prefix.removeLast()
usedIndices.remove(index)
}
}
}
}
}
| 0 | Kotlin | 1 | 1 | 6b64c9eb181fab97bc518ac78e14cd586d64499e | 1,141 | AdventOfCode | MIT License |
src/main/kotlin/g1401_1500/s1482_minimum_number_of_days_to_make_m_bouquets/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1401_1500.s1482_minimum_number_of_days_to_make_m_bouquets
// #Medium #Array #Binary_Search #Binary_Search_II_Day_7
// #2023_06_13_Time_538_ms_(50.00%)_Space_53_MB_(83.33%)
class Solution {
fun minDays(bloomDay: IntArray, m: Int, k: Int): Int {
if (bloomDay.size < m.toLong() * k) return -1
var minDay = Int.MAX_VALUE
var maxDay = 0
for (day in bloomDay) {
if (day > maxDay) {
maxDay = day
}
if (day < minDay) {
minDay = day
}
}
var left = minDay
var right = maxDay
while (left < right) {
val mid = left + (right - left) / 2
if (canMake(bloomDay, m, k, mid)) {
// search in the left
right = mid
} else {
left = mid + 1
}
}
return right
}
private fun canMake(bloomDay: IntArray, m: Int, k: Int, day: Int): Boolean {
var count = 0
var bouquets = 0
for (i in bloomDay.indices) {
if (bloomDay[i] > day) {
count = 0
} else {
count++
if (count == k) {
bouquets++
count = 0
}
}
}
return bouquets >= m
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,361 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/d13/D13.kt | MTender | 734,007,442 | false | {"Kotlin": 108628} | package d13
fun parseInput(lines: List<String>): List<List<String>> {
return lines.split { it.isEmpty() }
}
fun equalRows(pattern: List<String>, i1: Int, i2: Int): Boolean {
return pattern[i1] == pattern[i2]
}
fun equalCols(pattern: List<String>, i1: Int, i2: Int): Boolean {
return pattern.all { it[i1] == it[i2] }
}
fun getCol(pattern: List<String>, i: Int): String {
return pattern.map { it[i] }.joinToString("")
}
fun <T> List<T>.split(predicate: (T) -> Boolean): List<List<T>> {
val idx = this.indexOfFirst(predicate)
return if (idx == -1) {
listOf(this)
} else {
return listOf(this.take(idx)) + this.drop(idx + 1).split(predicate)
}
}
fun findDoubleRows(pattern: List<String>): List<Int> {
val doubleRows = mutableListOf<Int>()
for (i in 1..<pattern.size) {
if (pattern[i] != pattern[i - 1]) continue
doubleRows.add(i)
}
return doubleRows
}
fun findDoubleCols(pattern: List<String>): List<Int> {
val doubleCols = mutableListOf<Int>()
for (i in 1..<pattern[0].length) {
if (getCol(pattern, i) != getCol(pattern, i - 1)) continue
doubleCols.add(i)
}
return doubleCols
} | 0 | Kotlin | 0 | 0 | a6eec4168b4a98b73d4496c9d610854a0165dbeb | 1,194 | aoc2023-kotlin | MIT License |
src/day3/result.kt | davidcurrie | 437,645,413 | false | {"Kotlin": 37294} | package day3
import java.io.File
import kotlin.reflect.KFunction1
fun main() {
val lines = File("src/day3/input.txt")
.readLines()
.map { line -> line.toList().map { char -> Character.getNumericValue(char) } }
val columns = lines.transpose()
println(columns.map { it.gamma() }.toDecimal() * columns.map { it.epsilon() }.toDecimal())
println(filter(lines, List<Int>::gamma).toDecimal() * filter(lines, List<Int>::epsilon).toDecimal())
}
fun List<Int>.gamma() = if (sum() >= size / 2.0) 1 else 0
fun List<Int>.epsilon() = 1 - gamma()
fun List<Int>.toDecimal() = reduce { a, b -> a * 2 + b }
fun <T> List<List<T>>.transpose(): List<List<T>> = (first().indices).map { column(it) }
fun <T> List<List<T>>.column(index: Int): List<T> = fold(listOf()) { acc, row -> acc + row[index] }
fun filter(lines: List<List<Int>>, fn: KFunction1<List<Int>, Int>): List<Int> =
lines.indices.fold(lines) { candidates, index ->
if (candidates.size == 1) candidates
else candidates.filter { line -> line[index] == fn(candidates.column(index)) } }.single() | 0 | Kotlin | 0 | 0 | dd37372420dc4b80066efd7250dd3711bc677f4c | 1,089 | advent-of-code-2021 | MIT License |
src/main/kotlin/g0801_0900/s0865_smallest_subtree_with_all_the_deepest_nodes/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g0801_0900.s0865_smallest_subtree_with_all_the_deepest_nodes
// #Medium #Hash_Table #Depth_First_Search #Breadth_First_Search #Tree #Binary_Tree
// #2023_04_04_Time_147_ms_(100.00%)_Space_35.1_MB_(55.56%)
import com_github_leetcode.TreeNode
/*
* Example:
* var ti = TreeNode(5)
* var v = ti.`val`
* Definition for a binary tree node.
* class TreeNode(var `val`: Int) {
* var left: TreeNode? = null
* var right: TreeNode? = null
* }
*/
class Solution {
private var deepLevel = 0
private var left: TreeNode? = null
private var right: TreeNode? = null
fun subtreeWithAllDeepest(root: TreeNode?): TreeNode? {
if (root == null || root.left == null && root.right == null) {
return root
}
deep(root, 0)
return if (right == null) {
left
} else {
lca(root, left!!.`val`, right!!.`val`)
}
}
private fun lca(root: TreeNode?, left: Int, right: Int): TreeNode? {
if (root == null) {
return null
}
if (root.`val` == left || root.`val` == right) {
return root
}
val leftLca: TreeNode? = lca(root.left, left, right)
val rightLca: TreeNode? = lca(root.right, left, right)
return if (leftLca != null && rightLca != null) {
root
} else leftLca ?: rightLca
}
private fun deep(root: TreeNode?, level: Int) {
if (root == null) {
return
}
if (deepLevel < level) {
deepLevel = level
left = root
right = null
} else if (deepLevel == level) {
right = root
}
deep(root.left, level + 1)
deep(root.right, level + 1)
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,758 | LeetCode-in-Kotlin | MIT License |
src/day8/day8.kt | Eynnzerr | 576,874,345 | false | {"Kotlin": 23356} | package day8
import java.io.File
import kotlin.math.max
fun main() {
var count = 0
var maxScore = 0
val matrix = File("src/day8/input.txt")
.readLines() // List<String>
.map { s ->
s.toCharArray().map { c ->
c.digitToInt()
}
} // List<List<Int>>
val totalWidth = matrix[0].size
val totalHeight = matrix.size
matrix.forEachIndexed { row, list ->
list.forEachIndexed { col, height ->
// A tree is visible only if it satisfies at least one of four conditions:
// taller than matrix[row][0:col-1] or matrix[row][col+1:] or matrix[0:row-1][col] or matrix[row+1:][col]
var (left, right, top, down) = listOf(true, true, true, true,)
var (leftScore, rightScore, topScore, downScore) = listOf(0, 0, 0, 0)
for (pos in col - 1 downTo 0) {
if (matrix[row][pos] >= height) {
left = false
leftScore ++
break
}
else leftScore ++
}
for (pos in col + 1 until totalWidth) {
if (matrix[row][pos] >= height) {
right = false
rightScore ++
break
}
else rightScore ++
}
for (pos in row - 1 downTo 0) {
if (matrix[pos][col] >= height) {
top = false
topScore ++
break
}
else topScore ++
}
for (pos in row + 1 until totalHeight) {
if (matrix[pos][col] >= height) {
down = false
downScore ++
break
}
else downScore ++
}
if (left || right || top || down) count ++
if (row != 0 && row != totalHeight - 1 && col != 0 && col != totalWidth - 1)
maxScore = max(maxScore, leftScore * rightScore * topScore * downScore)
}
}
// TODO BF algorithm. Need to be improved.
println("Part1: visible count: $count")
println("Part2: max visible score: $maxScore")
} | 0 | Kotlin | 0 | 0 | 92e85d65f62900d98284cbc9f6f9a3010efb21b7 | 2,269 | advent-of-code-2022 | Apache License 2.0 |
src/Day15.kt | frozbiz | 573,457,870 | false | {"Kotlin": 124645} | import java.lang.Math.min
import kotlin.math.absoluteValue
class MultiRange {
val rangeList = mutableListOf<IntRange>()
operator fun plusAssign(range: IntRange) {
add(range)
}
operator fun plus(range: IntRange): MultiRange {
val ret = MultiRange()
ret.rangeList.addAll(rangeList)
ret.add(range)
return ret
}
fun add(multiRange: MultiRange) {
for (range in multiRange.rangeList) {
add(range)
}
}
fun add(range: IntRange) {
if (range.count() <= 0) return
var ix = 0
var firstOverlapIx: Int? = null
while ((ix < rangeList.size) && (rangeList[ix].first - 1 <= range.last)) {
// if they overlap
if ((range.first - 1 <= rangeList[ix].last) && (firstOverlapIx == null)) {
firstOverlapIx = ix
}
++ix
}
if (firstOverlapIx == null) {
rangeList.add(ix, range)
} else {
val lastOverlap = ix - 1
val newRange = minOf(range.first, rangeList[firstOverlapIx].first)..maxOf(range.last, rangeList[lastOverlap].last)
rangeList[firstOverlapIx] = newRange
if (firstOverlapIx < lastOverlap) {
rangeList.subList(firstOverlapIx+1, ix).clear()
}
}
}
fun IntRange.count(): Int {
return maxOf(last - first + 1, 0)
}
operator fun minusAssign(points: Collection<Int>) {
for (point in points) {
subtract(point)
}
}
operator fun minusAssign(point: Int) {
subtract(point)
}
fun subtract(point: Int) {
val ix = rangeList.indexOfFirst { point in it }
if (ix >= 0) {
val range = rangeList[ix]
if (range.count() == 1) {
rangeList.removeAt(ix)
} else if (range.first == point) {
rangeList[ix] = (point + 1)..range.last
} else if (range.last == point) {
rangeList[ix] = range.first..(point - 1)
} else {
rangeList[ix] = range.first..(point - 1)
rangeList.add(ix+1, (point + 1)..range.last)
}
}
}
fun clear() {
rangeList.clear()
}
operator fun contains(v: Int): Boolean {
return rangeList.any { v in it }
}
fun count(): Int {
return rangeList.map { it.count() }.sum()
}
fun trimToRange(range: IntRange) {
rangeList.removeIf { it.last < range.first || range.last < it.first }
if (rangeList.isEmpty()) return
val first = rangeList.first()
val last = rangeList.last()
if (first.first < range.first) {
rangeList[0] = range.first .. first.last
}
if (last.last > range.last) {
rangeList[rangeList.size - 1] = last.first .. range.last
}
}
override fun toString(): String {
return rangeList.toString()
}
override fun hashCode(): Int {
return rangeList.hashCode()
}
override fun equals(other: Any?): Boolean {
if (other !is MultiRange) return false
return super.equals(other) || other.rangeList == rangeList
}
}
fun main() {
infix fun Pair<Point, Point>.intersectRow(row:Int): IntRange {
val distance = first.manhattanDistanceTo(second)
val width = distance - (first.y - row).absoluteValue
return (first.x-width)..(first.x+width)
}
fun part1(input: List<String>, intercept: Int): Int {
val rowPoints = MultiRange()
val rowBeacons = mutableSetOf<Int>()
val regex = "Sensor at x=(-?\\d+), y=(-?\\d+): closest beacon is at x=(-?\\d+), y=(-?\\d+)".toRegex()
for (line in input) {
val match = regex.find(line)
val (sx, sy, bx, by) = match?.groupValues?.drop(1)?.map { it.toInt() } ?: throw IllegalArgumentException("fdvbfdfhfytdty")
val s = Point(sx, sy)
val b = Point(bx, by)
val pair = Pair(s, b)
rowPoints += pair intersectRow intercept
if (by == intercept) {
rowBeacons += bx
}
}
rowPoints -= rowBeacons
return rowPoints.count()
}
fun part2(input: List<String>, minPoint: Point, maxPoint: Point): Point {
val regex = "Sensor at x=(-?\\d+), y=(-?\\d+): closest beacon is at x=(-?\\d+), y=(-?\\d+)".toRegex()
val pointList = mutableListOf<Pair<Point, Point>>()
for (line in input) {
val match = regex.find(line)
val (sx, sy, bx, by) = match?.groupValues?.drop(1)?.map { it.toInt() } ?: throw IllegalArgumentException("fdvbfdfhfytdty")
val s = Point(sx, sy)
val b = Point(bx, by)
val pair = Pair(s, b)
pointList.add(pair)
}
val rowPoints = MultiRange()
for (row in minPoint.y .. maxPoint.y) {
for (pair in pointList) {
rowPoints += pair intersectRow row
}
rowPoints.trimToRange(minPoint.x .. maxPoint.x)
if (rowPoints.rangeList.size > 1) {
val x = rowPoints.rangeList.first().last + 1
return Point(x,row)
}
rowPoints.clear()
}
return Point(-1,-1)
}
// test if implementation meets criteria from the description, like:
val testInput = listOf(
"Sensor at x=2, y=18: closest beacon is at x=-2, y=15\n",
"Sensor at x=9, y=16: closest beacon is at x=10, y=16\n",
"Sensor at x=13, y=2: closest beacon is at x=15, y=3\n",
"Sensor at x=12, y=14: closest beacon is at x=10, y=16\n",
"Sensor at x=10, y=20: closest beacon is at x=10, y=16\n",
"Sensor at x=14, y=17: closest beacon is at x=10, y=16\n",
"Sensor at x=8, y=7: closest beacon is at x=2, y=10\n",
"Sensor at x=2, y=0: closest beacon is at x=2, y=10\n",
"Sensor at x=0, y=11: closest beacon is at x=2, y=10\n",
"Sensor at x=20, y=14: closest beacon is at x=25, y=17\n",
"Sensor at x=17, y=20: closest beacon is at x=21, y=22\n",
"Sensor at x=16, y=7: closest beacon is at x=15, y=3\n",
"Sensor at x=14, y=3: closest beacon is at x=15, y=3\n",
"Sensor at x=20, y=1: closest beacon is at x=15, y=3\n",
)
check(part1(testInput, 10) == 26)
var pt2 = part2(testInput, Point(0,0), Point(20,20))
println(pt2)
println(pt2.x * 4000000 + pt2.y)
val input = readInput("day15")
println(part1(input, 2000000))
pt2 = part2(input, Point(0,0), Point(4000000,4000000))
println(pt2)
println(pt2.x * 4000000L + pt2.y)
// println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 4feef3fa7cd5f3cea1957bed1d1ab5d1eb2bc388 | 6,756 | 2022-aoc-kotlin | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/ProductExceptSelf.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
/**
* 238. Product of Array Except Self
* @see <a href="https://leetcode.com/problems/product-of-array-except-self">Source</a>
*/
fun interface ProductExceptSelf {
operator fun invoke(nums: IntArray): IntArray
}
class ProductExceptSelfArr : ProductExceptSelf {
override operator fun invoke(nums: IntArray): IntArray {
val n = nums.size
val output = IntArray(n)
for (i in 0 until n) {
var product = 1
for (j in 0 until n) {
if (i == j) continue
product *= nums[j]
}
output[i] = product
}
return output
}
}
class ProductExceptSelfDp : ProductExceptSelf {
override operator fun invoke(nums: IntArray): IntArray {
val n = nums.size
val ans = IntArray(n)
val leftProduct = IntArray(n)
val rightProduct = IntArray(n)
leftProduct[0] = 1
for (i in 1 until n) {
leftProduct[i] = leftProduct[i - 1] * nums[i - 1]
}
rightProduct[n - 1] = 1
for (i in n - 2 downTo 0) {
rightProduct[i] = rightProduct[i + 1] * nums[i + 1]
}
for (i in 0 until n) {
ans[i] = leftProduct[i] * rightProduct[i]
}
return ans
}
}
class ProductExceptSelfDpOpt : ProductExceptSelf {
override operator fun invoke(nums: IntArray): IntArray {
val n = nums.size
val output = IntArray(n)
output[0] = 1
for (i in 1 until n) {
output[i] = output[i - 1] * nums[i - 1]
}
var right = 1
for (i in n - 1 downTo 0) {
output[i] *= right
right *= nums[i]
}
return output
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,374 | kotlab | Apache License 2.0 |
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2015/2015-05.kt | ferinagy | 432,170,488 | false | {"Kotlin": 787586} | package com.github.ferinagy.adventOfCode.aoc2015
import com.github.ferinagy.adventOfCode.println
import com.github.ferinagy.adventOfCode.readInputLines
fun main() {
val input = readInputLines(2015, "05-input")
val test1 = readInputLines(2015, "05-test1")
val test2 = readInputLines(2015, "05-test2")
println("Part1:")
part1(test1).println()
part1(input).println()
println()
println("Part2:")
part2(test2).println()
part2(input).println()
}
private fun part1(input: List<String>): Int {
return input.count { isNice1(it) }
}
private fun part2(input: List<String>): Int {
return input.count { isNice2(it) }
}
private fun isNice1(input: String): Boolean {
if (input.count { it in "aeiou" } < 3) return false
if (setOf("ab", "cd", "pq", "xy").any { it in input }) return false
if (input.windowed(2).all { it[0] != it[1] }) return false
return true
}
private fun isNice2(input: String): Boolean {
if (input.windowed(3).all { it[0] != it[2] }) return false
val windowed = input.windowed(2)
for (i in 0 .. windowed.lastIndex - 2) {
for (j in i + 2 .. windowed.lastIndex) {
if (windowed[i] == windowed[j]) return true
}
}
return false
}
| 0 | Kotlin | 0 | 1 | f4890c25841c78784b308db0c814d88cf2de384b | 1,253 | advent-of-code | MIT License |
src/main/kotlin/se/saidaspen/aoc/aoc2016/Day22.kt | saidaspen | 354,930,478 | false | {"Kotlin": 301372, "CSS": 530} | package se.saidaspen.aoc.aoc2016
import se.saidaspen.aoc.util.*
import kotlin.math.abs
fun main() = Day22.run()
object Day22 : Day(2016, 22) {
override fun part1(): Any {
val disk = mutableMapOf<P<Int, Int>, P<Int, Int>>()
input.lines().drop(2).map {
val (x, y, _, used, avail) = ints(it)
disk[P(x, y)] = P(used, avail)
}
var viablePairs = 0
val keys = disk.keys.toList()
for (i in keys.indices) {
val a = disk[keys[i]]!!
for (k in keys.indices) {
if (i == k) continue
val b = disk[keys[k]]!!
if (a.first <= b.second && a.first > 0)
viablePairs += 1
}
}
return viablePairs
}
override fun part2(): Any {
val disk = mutableMapOf<P<Int, Int>, P<Int, Int>>()
input.lines().drop(2).map {
val (x, y, _, used, avail) = ints(it)
disk[P(x, y)] = P(used, avail)
}
val xMax = disk.keys.maxBy { it.x }.x
val wall = disk.entries.filter { it.value.first > 250 }.minBy { it.key.x }
val emptyNode = disk.entries.first { it.value.first == 0 }
var result = abs(emptyNode.key.x - wall.key.x) + 1 // Empty around wall X.
result += emptyNode.key.y // Empty to top
result += (xMax - wall.key.x) // Empty over next to goal
result += (5 * xMax.dec()) + 1 // Goal back to start
return result
}
}
| 0 | Kotlin | 0 | 1 | be120257fbce5eda9b51d3d7b63b121824c6e877 | 1,496 | adventofkotlin | MIT License |
kotlin/2021/qualification-round/cheating-detection/src/main/kotlin/ConsideringIfCheatingSolution.kts | ShreckYe | 345,946,821 | false | null | import kotlin.math.exp
import kotlin.math.ln
fun main() {
val t = readLine()!!.toInt()
val p = readLine()!!.toInt()
repeat(t, ::testCase)
}
fun testCase(ti: Int) {
val results = List(100) {
readLine()!!.map { it - '0' }
}
// simple estimation by averaging
val ss = results.map {
val estimatedP = it.average()
val ifCheatingEstimatedP = ((estimatedP - 0.5) * 2).coerceAtLeast(0.0)
inverseSigmoid(estimatedP).coerceIn(-3.0, 3.0) to
inverseSigmoid(ifCheatingEstimatedP).coerceIn(-3.0, 3.0)
}
//println(ss.withIndex().toList().joinToString("\n"))
val qs = (0 until 10000).map { j ->
inverseSigmoid(results.asSequence().map { it[j] }.average()).coerceIn(-3.0, 3.0)
}
// logarithms of player probabilities
val lnIfCheatingPDivPs = (ss zip results).asSequence().map { (s, rs) ->
(rs.asSequence() zip qs.asSequence()).map { (r, q) ->
val pCorrect = sigmoid(s.first - q)
val ifCheatingPCorrect = 0.5 + 0.5 * sigmoid(s.second - q)
val (p, ifCheatingP) = when (r) {
1 -> pCorrect to ifCheatingPCorrect
0 -> 1 - pCorrect to 1 - ifCheatingPCorrect
else -> throw IllegalArgumentException(r.toString())
}
ln(ifCheatingP / p)
}.sum()
}
//println(lnIfCheatingPDivPs.withIndex().toList().joinToString("\n"))
val y = lnIfCheatingPDivPs.withIndex().maxByOrNull { it.value }!!.index
println("Case #${ti + 1}: ${y + 1}")
}
fun sigmoid(x: Double) =
1 / (1 + exp(-x))
fun inverseSigmoid(y: Double) =
ln(y / (1 - y))
fun Double.squared() =
this * this | 0 | Kotlin | 1 | 1 | 743540a46ec157a6f2ddb4de806a69e5126f10ad | 1,696 | google-code-jam | MIT License |
src/main/kotlin/adventofcode/y2021/Day04.kt | Tasaio | 433,879,637 | false | {"Kotlin": 117806} | import adventofcode.parseNumbersToSingleInt
import java.lang.RuntimeException
fun main() {
val day = Day04()
println(day.part1())
day.reset()
println(day.part2())
}
class Day04 : Y2021Day(4) {
private val input = fetchInput()
private val numbers = input[0].split(",").map { it.parseNumbersToSingleInt() }
private val boards = input.subList(1, input.size).chunked(6).map { Board(it.filter { it.isNotBlank() }) }
private class Board(input: List<String>) {
private val rows: List<List<Int>>
private val marks = Array(5) { Array(5) { false} }
init {
rows = input.map { it.trim().split(Regex("[ ]+")).map { it.parseNumbersToSingleInt() } }
}
fun call(num: Int) {
for (x in 0..4) {
for (y in 0..4) {
if (rows[x][y] == num) {
marks[x][y] = true
}
}
}
}
fun bingo(): Boolean {
upper@for (x in 0..4) {
for (y in 0..4) {
if (!marks[x][y]) {
continue@upper
}
}
return true
}
upper@for (x in 0..4) {
for (y in 0..4) {
if (!marks[y][x]) {
continue@upper
}
}
return true
}
return false
}
fun reset() {
for (x in 0..4) {
for (y in 0..4) {
marks[x][y] = false
}
}
}
fun score(winningNo: Int): Int {
var sum = 0
for (x in 0..4) {
for (y in 0..4) {
if (!marks[x][y]) {
sum += rows[x][y]
}
}
}
return sum * winningNo
}
}
override fun reset() {
boards.forEach { it.reset() }
}
override fun part1(): Number? {
numbers.forEach { num ->
boards.forEach { board ->
board.call(num)
if (board.bingo()) {
return board.score(num)
}
}
}
throw RuntimeException("Failed")
}
override fun part2(): Number? {
val skip = HashSet<Int>()
numbers.forEach { num ->
boards.indices.forEach { boardNo ->
if (!skip.contains(boardNo)) {
boards[boardNo].call(num)
if (boards[boardNo].bingo()) {
if (skip.size < boards.size - 1) {
skip.add(boardNo)
} else {
return boards[boardNo].score(num)
}
}
}
}
}
throw RuntimeException("Failed")
}
}
| 0 | Kotlin | 0 | 0 | cc72684e862a782fad78b8ef0d1929b21300ced8 | 2,997 | adventofcode2021 | The Unlicense |
2023/src/main/kotlin/de/skyrising/aoc2023/day11/solution.kt | skyrising | 317,830,992 | false | {"Kotlin": 411565} | package de.skyrising.aoc2023.day11
import de.skyrising.aoc.*
val test = TestInput("""
...#......
.......#..
#.........
..........
......#...
.#........
.........#
..........
.......#..
#...#.....
""")
fun sumDistances(grid: CharGrid, scale: Int): Long {
val countRow = IntArray(grid.height)
val countCol = IntArray(grid.width)
val galaxies = grid.where { it == '#' }
for (g in galaxies) {
countRow[g.y]++
countCol[g.x]++
}
var sum = 0L
for (i in galaxies.indices) {
val a = galaxies[i]
for (j in i + 1..galaxies.lastIndex) {
val b = galaxies[j]
for (x in a.x minUntilMax b.x) sum += if (countRow[x] == 0) scale else 1
for (y in a.y minUntilMax b.y) sum += if (countRow[y] == 0) scale else 1
}
}
"".trim(Char::isWhitespace)
return sum
}
@PuzzleName("Cosmic Expansion")
fun PuzzleInput.part1() = sumDistances(charGrid, 1)
fun PuzzleInput.part2() = sumDistances(charGrid, 1000000)
| 0 | Kotlin | 0 | 0 | 19599c1204f6994226d31bce27d8f01440322f39 | 1,038 | aoc | MIT License |
src/Day08.kt | zfz7 | 573,100,794 | false | {"Kotlin": 53499} | fun main() {
println(day8A(readFile("Day08")))
println(day8B(readFile("Day08")))
}
fun visibleNorth(forest: List<List<Int>>, i: Int, j: Int): Boolean {
val height = forest[i][j]
var iPos = i -1
while(iPos >= 0){
if(forest[iPos][j] >= height)
return false
iPos--;
}
return true
}
fun visibleSouth(forest: List<List<Int>>, i: Int, j: Int): Boolean {
val height = forest[i][j]
var iPos = i +1
while(iPos <= forest[j].size -1){
if(forest[iPos][j] >= height)
return false
iPos++;
}
return true
}
fun visibleEast(forest: List<List<Int>>, i: Int, j: Int): Boolean {
val height = forest[i][j]
var jPos = j-1
while(jPos >= 0){
if(forest[i][jPos] >= height)
return false
jPos--;
}
return true
}
fun visibleWest(forest: List<List<Int>>, i: Int, j: Int): Boolean {
val height = forest[i][j]
var jPos = j +1
while(jPos <= forest[j].size -1){
if(forest[i][jPos] >= height)
return false
jPos++;
}
return true
}
fun day8A(input: String): Int {
val forest: List<List<Int>> = input.trim().split("\n").map { line -> line.map { it.toString().toInt() } }
var count = 0
for (i in 1 until forest.size -1 ) {
for (j in 1 until forest[i].size -1) {
if(visibleNorth(forest,i,j)
||visibleSouth(forest,i,j)
||visibleEast(forest,i,j)
||visibleWest(forest,i,j)
){
count++
}
}
}
return count + forest.size + forest.size + forest[0].size +forest[0].size -4
}
//--
fun scoreNorth(forest: List<List<Int>>, i: Int, j: Int): Int {
val height = forest[i][j]
var iPos = i -1
var score = 1
while(iPos > 0){
if(forest[iPos][j] >= height)
return score
score ++
iPos--
}
return score
}
fun scoreSouth(forest: List<List<Int>>, i: Int, j: Int): Int {
val height = forest[i][j]
var iPos = i+1
var score = 1
while(iPos < forest[j].size -1){
if(forest[iPos][j] >= height)
return score
iPos++;
score++
}
return score
}
fun scoreEast(forest: List<List<Int>>, i: Int, j: Int): Int {
val height = forest[i][j]
var jPos = j-1
var score = 1
while(jPos > 0){
if(forest[i][jPos] >= height)
return score
jPos--
score++
}
return score
}
fun scoreWest(forest: List<List<Int>>, i: Int, j: Int): Int {
val height = forest[i][j]
var jPos = j +1
var score = 1
while(jPos < forest[j].size -1){
if(forest[i][jPos] >= height)
return score
jPos++
score++
}
return score
}
fun day8B(input: String): Int {
val forest: List<List<Int>> = input.trim().split("\n").map { line -> line.map { it.toString().toInt() } }
var max = 0
for (i in 1 until forest.size -1 ) {
for (j in 1 until forest[i].size -1) {
if(max< scoreNorth(forest,i,j) * scoreSouth(forest,i,j) *scoreEast(forest,i,j) *scoreWest(forest,i,j)){
max = scoreNorth(forest,i,j) * scoreSouth(forest,i,j) *scoreEast(forest,i,j) *scoreWest(forest,i,j)
println("max: $max - $i,$j")
}
}
}
return max
} | 0 | Kotlin | 0 | 0 | c50a12b52127eba3f5706de775a350b1568127ae | 3,355 | AdventOfCode22 | Apache License 2.0 |
2015/15/kotlin/b.kt | shrivatsas | 583,681,989 | false | {"Kotlin": 17998, "Python": 9402, "Racket": 4669, "Clojure": 2953} | import java.io.File
import kotlin.math.max
data class Ingredient(val name: String, val capacity: Int, val durability: Int, val flavor: Int, val texture: Int, val calories: Int)
fun main() {
val lines: List<String> = File("../15.input").useLines { it.toList() }
// Sugar: capacity 3, durability 0, flavor 0, texture -3, calories 2
val regex = Regex("""(\w+): capacity (-?\d+), durability (-?\d+), flavor (-?\d+), texture (-?\d+), calories (-?\d+)""")
val ingredients = lines.map { line ->
val (name, capacity, durability, flavor, texture, calories) = regex.matchEntire(line)!!.destructured
Ingredient(name, capacity.toInt(), durability.toInt(), flavor.toInt(), texture.toInt(), calories.toInt())
}
var max_score = 0
for (i in 0..100) {
for (j in 0..100 - i) {
for (k in 0..100 - i - j) {
val l = 100 - i - j - k
val capacity = i * ingredients[0].capacity + j * ingredients[1].capacity + k * ingredients[2].capacity + l * ingredients[3].capacity
val durability = i * ingredients[0].durability + j * ingredients[1].durability + k * ingredients[2].durability + l * ingredients[3].durability
val flavor = i * ingredients[0].flavor + j * ingredients[1].flavor + k * ingredients[2].flavor + l * ingredients[3].flavor
val texture = i * ingredients[0].texture + j * ingredients[1].texture + k * ingredients[2].texture + l * ingredients[3].texture
val calories = i * ingredients[0].calories + j * ingredients[1].calories + k * ingredients[2].calories + l * ingredients[3].calories
if (capacity > 0 && durability > 0 && flavor > 0 && texture > 0 && calories == 500) {
max_score = max(max_score, capacity * durability * flavor * texture)
}
}
}
}
println(max_score)
} | 0 | Kotlin | 0 | 1 | 529a72ff55f1d90af97f8e83b6c93a05afccb44c | 1,779 | AoC | MIT License |
src/AOC2022/Day11/Day11.kt | kfbower | 573,519,224 | false | {"Kotlin": 44562} | package AOC2022.Day11
import AOC2022.readInput
fun main(){
fun part1(input: List<String>): Long {
val cycles: Int = 20
val worryDivisor: Long = 3L
val monkeyInfoList = parseMonkeys(input)
var currentWorry: Long = 0L
var newWorry: Long = 0L
var nextMonkeysWorry: Long = 0L
var r = 0
while (r < cycles) {
monkeyInfoList.forEachIndexed { _, monkeyInfo ->
val max = monkeyInfo.holdingItems.size
var j = 0
if (monkeyInfo.holdingItems != emptyList<String>()) {
while (j < max) {
monkeyInfo.monkeyInspection += 1
currentWorry = monkeyInfo.holdingItems[0]
if (monkeyInfo.operation.second == "old") {
when (monkeyInfo.operation.first) {
"+" -> {
newWorry = currentWorry + currentWorry
}
"*" -> {
newWorry = currentWorry * currentWorry
}
}
} else {
when (monkeyInfo.operation.first) {
"+" -> {
newWorry = currentWorry + monkeyInfo.operation.second.toLong()
}
"*" -> {
newWorry = currentWorry * monkeyInfo.operation.second.toLong()
}
}
}
nextMonkeysWorry = newWorry / worryDivisor
monkeyInfo.holdingItems.remove(monkeyInfo.holdingItems[0])
if ((nextMonkeysWorry % monkeyInfo.test) == 0L) {
val destination = monkeyInfoList.find { it.monkeyNumber == monkeyInfo.trueMonkey }
destination?.holdingItems?.add(nextMonkeysWorry)
} else {
val destination = monkeyInfoList.find { it.monkeyNumber == monkeyInfo.falseMonkey }
destination?.holdingItems?.add(nextMonkeysWorry)
}
j++
}
}
}
r++
}
val businessList = mutableListOf<Long>()
monkeyInfoList.forEachIndexed { _, monkeyInfo ->
businessList.add(monkeyInfo.monkeyInspection)
}
businessList.sortDescending()
println(businessList)
return businessList[0] * businessList[1]
}
fun part2(input: List<String>): Long {
val cycles: Int = 10000
val worryDivisor: Long = 3L
val monkeyInfoList = parseMonkeys(input)
var currentWorry: Long = 0L
var newWorry: Long = 0L
var nextMonkeysWorry: Long = 0L
var r = 0
while (r < cycles) {
monkeyInfoList.forEachIndexed { _, monkeyInfo ->
val max = monkeyInfo.holdingItems.size
var j = 0
if (monkeyInfo.holdingItems != emptyList<String>()) {
while (j < max) {
monkeyInfo.monkeyInspection += 1
currentWorry = monkeyInfo.holdingItems[0]
if (monkeyInfo.operation.second == "old") {
when (monkeyInfo.operation.first) {
"+" -> {
newWorry = currentWorry + currentWorry
}
"*" -> {
newWorry = currentWorry * currentWorry
}
}
} else {
when (monkeyInfo.operation.first) {
"+" -> {
newWorry = currentWorry + monkeyInfo.operation.second.toLong()
}
"*" -> {
newWorry = currentWorry * monkeyInfo.operation.second.toLong()
}
}
}
nextMonkeysWorry = newWorry
monkeyInfo.holdingItems.remove(monkeyInfo.holdingItems[0])
if ((nextMonkeysWorry % monkeyInfo.test) == 0L) {
val destination = monkeyInfoList.find { it.monkeyNumber == monkeyInfo.trueMonkey }
destination?.holdingItems?.add(nextMonkeysWorry)
} else {
val destination = monkeyInfoList.find { it.monkeyNumber == monkeyInfo.falseMonkey }
destination?.holdingItems?.add(nextMonkeysWorry)
}
j++
}
}
}
r++
}
val businessList = mutableListOf<Long>()
monkeyInfoList.forEachIndexed { _, monkeyInfo ->
businessList.add(monkeyInfo.monkeyInspection)
}
businessList.sortDescending()
println(businessList)
return businessList[0] * businessList[1]
}
val input = readInput("Day11_test")
println(part1(input))
println(part2(input))
}
data class MonkeyInfo(
var monkeyNumber: Int = 0,
var holdingItems: MutableList<Long> = mutableListOf(),
var operation: Pair<String,String> = Pair("",""),
var test: Long =0L,
var trueMonkey: Int = 0,
var falseMonkey: Int = 0,
var monkeyInspection: Long = 0L)
fun parseMonkeys(input: List<String>): MutableList<MonkeyInfo> {
val monkeyInfoList: MutableList<MonkeyInfo> = mutableListOf()
var j=0
while (j<input.size){
//Get the monkey number
val currentMonkey: MonkeyInfo = MonkeyInfo()
val newMonk = input[j].replace("Monkey ","")
val monkNum = newMonk.replace(":","")
currentMonkey.monkeyNumber += monkNum.toInt()
//Get the monkey items
val items = input[j+1].replace(" Starting items: ","")
val itemsList = items.split(", ")
itemsList.forEachIndexed { _, s ->
currentMonkey.holdingItems.plusAssign(s.toLong())
}
//Get the worry assignment
val cleanOperation = input[j+2].replace(" Operation: new = old ", "")
val splitOps = cleanOperation.split(" ")
val op = splitOps[0]
val opNum = splitOps[1]
currentMonkey.operation = Pair(first = op,second=opNum)
//Get the test
val testText = input[j+3].replace(" Test: divisible by ","")
currentMonkey.test = testText.toLong()
//Get the true
val trueText = input[j+4].replace(" If true: throw to monkey ","")
currentMonkey.trueMonkey = trueText.toInt()
//Get the false
val falseText = input[j+5].replace(" If false: throw to monkey ","")
currentMonkey.falseMonkey = falseText.toInt()
monkeyInfoList.add(currentMonkey)
j+=7
}
return monkeyInfoList
} | 0 | Kotlin | 0 | 0 | 48a7c563ebee77e44685569d356a05e8695ae36c | 7,381 | advent-of-code-2022 | Apache License 2.0 |
Code/LetterCombinationsPhoneNumber.kt | Guaidaodl | 26,102,098 | false | {"Java": 20880, "Kotlin": 6663, "C++": 4106, "Python": 1216} | class Solution {
private val letterMap: Map<Int, CharArray> = mapOf(
Pair(2, charArrayOf('a', 'b', 'c')),
Pair(3, charArrayOf('d', 'e', 'f')),
Pair(4, charArrayOf('g', 'h', 'i')),
Pair(5, charArrayOf('j', 'k', 'l')),
Pair(6, charArrayOf('m', 'n', 'o')),
Pair(7, charArrayOf('p', 'q', 'r', 's')),
Pair(8, charArrayOf('t', 'u', 'v')),
Pair(9, charArrayOf('w', 'x', 'y', 'z'))
)
fun letterCombinations(digits: String): List<String> {
val charArrays = digits.filter { it in '2' .. '9' }
.map { letterMap[it - '0']!! }
val r = merge(charArrays)
return r.map { String(it.toCharArray()) }
}
private fun merge(charArrays: List<CharArray>): List<List<Char>> {
if (charArrays.isEmpty()) {
return ArrayList()
}
val initial: List<List<Char>> = ArrayList()
return charArrays.fold(initial) { acc, chars ->
if (acc.isEmpty()) {
chars.map { listOf(it) }
} else {
acc.flatMap { list -> chars.map { list.plus(it) } }
}
}
}
} | 0 | Java | 0 | 0 | a5e9c36d34e603906c06df642231bfdeb0887088 | 1,205 | leetcode | Apache License 2.0 |
src/pl/shockah/aoc/y2015/Day9.kt | Shockah | 159,919,224 | false | null | package pl.shockah.aoc.y2015
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.DynamicTest
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.TestFactory
import pl.shockah.aoc.AdventTask
import pl.shockah.aoc.UnorderedPair
import pl.shockah.aoc.expects
import pl.shockah.aoc.parse3
import java.util.regex.Pattern
class Day9: AdventTask<Map<UnorderedPair<String>, Int>, Int, Int>(2015, 9) {
private val inputPattern: Pattern = Pattern.compile("(.*) to (.*) = (\\d+)")
override fun parseInput(rawInput: String): Map<UnorderedPair<String>, Int> {
return rawInput.lines().map {
val (from, to, distance) = inputPattern.parse3<String, String, Int>(it)
return@map UnorderedPair(from, to) to distance
}.toMap()
}
private fun getDistance(distances: Map<UnorderedPair<String>, Int>, path: List<String>): Int {
var distance = 0
for (i in 1 until path.size) {
distance += distances[UnorderedPair(path[i - 1], path[i])]!!
}
return distance
}
override fun part1(input: Map<UnorderedPair<String>, Int>): Int {
val locations = input.keys.map { it.first }.toSet() + input.keys.map { it.second }.toSet()
fun findShortestPath(distances: Map<UnorderedPair<String>, Int>, path: List<String>, available: Set<String>): List<String> {
if (available.isEmpty())
return path
return available.map { findShortestPath(distances, path + it, available - it) }.minByOrNull { getDistance(distances, it) }!!
}
return getDistance(input, findShortestPath(input, listOf(), locations))
}
override fun part2(input: Map<UnorderedPair<String>, Int>): Int {
val locations = input.keys.map { it.first }.toSet() + input.keys.map { it.second }.toSet()
fun findLongestPath(distances: Map<UnorderedPair<String>, Int>, path: List<String>, available: Set<String>): List<String> {
if (available.isEmpty())
return path
return available.map { findLongestPath(distances, path + it, available - it) }.maxByOrNull { getDistance(distances, it) }!!
}
return getDistance(input, findLongestPath(input, listOf(), locations))
}
class Tests {
private val task = Day9()
private val rawInput = """
London to Dublin = 464
London to Belfast = 518
Dublin to Belfast = 141
""".trimIndent()
@TestFactory
fun parseInput(): Collection<DynamicTest> = createTestCases(
"London to Dublin = 464" expects (UnorderedPair("London", "Dublin") to 464),
"London to Belfast = 518" expects (UnorderedPair("London", "Belfast") to 518),
"Dublin to Belfast = 141" expects (UnorderedPair("Dublin", "Belfast") to 141)
) { rawInput, expected -> Assertions.assertEquals(mapOf(expected), task.parseInput(rawInput)) }
@Test
fun part1() {
val input = task.parseInput(rawInput)
Assertions.assertEquals(605, task.part1(input))
}
@Test
fun part2() {
val input = task.parseInput(rawInput)
Assertions.assertEquals(982, task.part2(input))
}
}
} | 0 | Kotlin | 0 | 0 | 9abb1e3db1cad329cfe1e3d6deae2d6b7456c785 | 2,912 | Advent-of-Code | Apache License 2.0 |
tree/src/main/kotlin/com/seanshubin/code/structure/tree/Tree.kt | SeanShubin | 678,139,745 | false | {"Kotlin": 105240, "CSS": 4128, "Shell": 1423, "HTML": 842} | package com.seanshubin.code.structure.tree
sealed interface Tree<KeyType, ValueType> {
fun setValue(path: List<KeyType>, value: ValueType): Tree<KeyType, ValueType>
fun getValue(path: List<KeyType>): ValueType?
fun toLines(
keyOrder: Comparator<KeyType>,
keyToString: (KeyType) -> String,
valueToString: (ValueType) -> String
): List<String>
fun pathValues(path: List<KeyType>): List<Pair<List<KeyType>, ValueType>>
data class Branch<KeyType, ValueType>(val parts: Map<KeyType, Tree<KeyType, ValueType>>) :
Tree<KeyType, ValueType> {
override fun setValue(path: List<KeyType>, value: ValueType): Tree<KeyType, ValueType> {
if (path.isEmpty()) return Leaf(value)
val key = path[0]
val remainingPath = path.drop(1)
val innerValue = when (val existingInnerValue = parts[key]) {
is Branch -> existingInnerValue
else -> empty()
}
val newInnerValue = innerValue.setValue(remainingPath, value)
val newValue = Branch(parts + (key to newInnerValue))
return newValue
}
override fun getValue(path: List<KeyType>): ValueType? {
if (path.isEmpty()) return null
val key = path[0]
val remainingPath = path.drop(1)
val innerValue = when (val existingInnerValue = parts[key]) {
is Branch -> existingInnerValue
is Leaf -> return existingInnerValue.value
null -> return null
}
val finalValue = innerValue.getValue(remainingPath)
return finalValue
}
override fun toLines(
keyOrder: Comparator<KeyType>,
keyToString: (KeyType) -> String,
valueToString: (ValueType) -> String
): List<String> {
val keys = parts.keys.toList().sortedWith(keyOrder)
val lines = keys.flatMap { key ->
val value = parts.getValue(key)
val thisLine = keyToString(key)
val subLines = value.toLines(keyOrder, keyToString, valueToString).map { " $it" }
listOf(thisLine) + subLines
}
return lines
}
override fun pathValues(path: List<KeyType>): List<Pair<List<KeyType>, ValueType>> {
return parts.flatMap { (key, value) ->
val newPath = path + key
value.pathValues(newPath)
}
}
}
data class Leaf<KeyType, ValueType>(val value: ValueType) : Tree<KeyType, ValueType> {
override fun setValue(path: List<KeyType>, value: ValueType): Tree<KeyType, ValueType> {
return empty<KeyType, ValueType>().setValue(path, value)
}
override fun getValue(path: List<KeyType>): ValueType? {
return if (path.isEmpty()) this.value
else null
}
override fun toLines(
keyOrder: Comparator<KeyType>,
keyToString: (KeyType) -> String,
valueToString: (ValueType) -> String
): List<String> = listOf(valueToString(value))
override fun pathValues(path: List<KeyType>): List<Pair<List<KeyType>, ValueType>> {
return listOf(path to value)
}
}
companion object {
fun <KeyType, ValueType> empty(): Branch<KeyType, ValueType> = Branch(emptyMap())
}
}
| 0 | Kotlin | 0 | 0 | f83b9e3927d41f290baa25e3ffaeaa0ab53aab47 | 3,447 | code-structure-2 | The Unlicense |
src/Day04.kt | nGoldi | 573,158,084 | false | {"Kotlin": 6839} | fun main() {
fun part1(pairs: List<String>): Int =
pairs.map { pair -> pair.split(",", "-").map { it.toInt() } }.count { (first, second, third, fourth) ->
first >= third && second <= fourth || first <= third && second >= fourth
}
fun part2(pairs: List<String>): Int =
pairs.map { pair -> pair.split(",", "-").map { it.toInt() } }.count { (first, second, third, fourth) ->
first <= fourth && second >= third
}
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | bc587f433aa38c4d745c09d82b7d231462f777c8 | 569 | advent-of-code | Apache License 2.0 |
src/aoc2022/day10/AoC10.kt | Saxintosh | 576,065,000 | false | {"Kotlin": 30013} | package aoc2022.day10
import readLines
sealed class Instruction {
companion object {
fun from(line: String): Instruction {
val s = line.split(" ")
return when (s[0]) {
"noop" -> Noop
"addx" -> AddX(s[1].toInt())
else -> throw Exception("Unexpected")
}
}
}
}
object Noop : Instruction()
class AddX(val n: Int) : Instruction()
class Cpu(private val prg: List<String>, val peekBlock: Cpu.() -> Unit) {
var x = 1
var cycle = 0
// Current instruction register
private var cir: Instruction = Noop
// Program Counter
private var pc = 0
private fun doCycle() {
cycle++
peekBlock(this)
when (val thisCir = cir) {
Noop -> cir = Instruction.from(prg[pc++])
is AddX -> x += thisCir.n.also { cir = Noop }
}
}
fun run() {
while (pc < prg.size)
doCycle()
}
}
class Crt {
private val pixels = Array(6) { CharArray(40) { ' ' } }
private fun toRowCol(cycle: Int): Pair<Int, Int> {
val pos = (cycle - 1) % 240
val row = pos / 40
val col = pos % 40
return row to col
}
fun printScreen() {
pixels.forEach {
println(String(it))
}
println()
}
fun draw(cycle: Int, x: Int) {
val xx = x % 40
val xr = xx - 1..xx + 1
val (row, col) = toRowCol(cycle)
if (col in xr)
pixels[row][col] = '#'
else
pixels[row][col] = '.'
}
}
fun main() {
fun part1(lines: List<String>): Int {
var signalStrength = 0
Cpu(lines) {
if (cycle % 40 == 20)
signalStrength += cycle * x
}.run()
return signalStrength
}
fun part2(lines: List<String>): Int {
val crt = Crt()
Cpu(lines) {
crt.draw(cycle, x)
}.run()
crt.printScreen()
return 1
}
readLines(13140, 1, ::part1, ::part2)
} | 0 | Kotlin | 0 | 0 | 877d58367018372502f03dcc97a26a6f831fc8d8 | 1,679 | aoc2022 | Apache License 2.0 |
src/Day02.kt | hadiamin | 572,509,248 | false | null | fun main() {
fun part1(input: List<String>): Int {
var totalScore = 0
for (item in input) {
when (item) {
"A Y" -> totalScore += (2 + 6)
"B Z" -> totalScore += (3 + 6)
"C X" -> totalScore += (1 + 6)
"A Z" -> totalScore += (3 + 0)
"B X" -> totalScore += (1 + 0)
"C Y" -> totalScore += (2 + 0)
"A X" -> totalScore += (1 + 3)
"B Y" -> totalScore += (2 + 3)
"C Z" -> totalScore += (3 + 3)
}
}
return totalScore
}
fun part2(input: List<String>): Int {
var totalScore = 0
for (item in input) {
when (item) {
"A X" -> totalScore += 3
"B X" -> totalScore += 1
"C X" -> totalScore += 2
"A Y" -> totalScore += 4
"B Y" -> totalScore += 5
"C Y" -> totalScore += 6
"A Z" -> totalScore += 8
"B Z" -> totalScore += 9
"C Z" -> totalScore += 7
}
}
return totalScore
}
val input = readInput("Day02")
println(part2(input))
} | 0 | Kotlin | 0 | 0 | e63aea2a55b629b9ac3202cdab2a59b334fb7041 | 1,233 | advent-of-code-2022-kotlin | Apache License 2.0 |
archive/2022/Day22.kt | mathijs81 | 572,837,783 | false | {"Kotlin": 167658, "Python": 725, "Shell": 57} | private const val EXPECTED_1 = 6032
private const val EXPECTED_2 = 5031
/**
* Very hard problem. I ended up hardcoding the cube face linking edges. Didn't have time anymore
* to clean up.
*/
private class Day22(isTest: Boolean) : Solver(isTest) {
val map = readAsString().split("\n\n")[0].split("\n").let {
val maxWidth = it.maxOf { it.length }
it.map { it.padEnd(maxWidth, ' ') }
}
val Y = map.size
val X = map[0].length
val instructions = readAsString().split("\n\n")[1].let {
it.splitInts() zip it.split("\\d+".toRegex()).drop(1)
}
val dirs = listOf(1 to 0, 0 to 1, -1 to 0, 0 to -1)
fun part1(): Any {
var pos = Triple(map[0].indexOf('.'), 0, 0)
fun Triple<Int, Int, Int>.nextStep() = copy(first = (first + dirs[third].first).mod(X), (second + dirs[third].second).mod(Y))
fun Triple<Int, Int, Int>.next(): Triple<Int, Int, Int> {
check(map[second][first] != ' ')
var next = nextStep()
while (map[next.second][next.first] == ' ') next = next.nextStep()
return next
}
for (inst in instructions) {
for (i in 0 until inst.first) {
var newpos = pos.next()
if (map[newpos.second][newpos.first] == '#') {
break
}
pos = newpos
}
when (inst.second) {
"L" -> pos = pos.copy(third = (pos.third - 1).mod(dirs.size))
"R" -> pos = pos.copy(third = (pos.third + 1).mod(dirs.size))
else -> {}
}
}
return (pos.second + 1) * 1000 + (pos.first + 1) * 4 + pos.third
}
fun part2(): Any {
val cubesize = if (isTest) 4 else 50
var pos = Triple(map[0].indexOf('.'), 0, 0)
var connections =
if (isTest) {
mapOf(
Triple(2, 1, 0) to Triple(3, 2, 3),
Triple(2, 2, 1) to Triple(0, 1, 1),
Triple(0, 1, 3) to Triple(2, 0, 2),
Triple(1, 1, 3) to Triple(2, 0, 2),
)
} else {
mapOf(
Triple(1, 0, 3) to Triple(0, 3, 2),
Triple(1, 0, 2) to Triple(0, 2, 2),
Triple(0, 3, 1) to Triple(2, 0, 3),
Triple(2, 0, 1) to Triple(1, 1, 0),
Triple(1, 2, 0) to Triple(2, 0, 0),
Triple(1, 2, 1) to Triple(0, 3, 0),
Triple(0, 2, 3) to Triple(1, 1, 2),
)
}
connections = connections + connections.map { it.value to it.key }.toMap()
fun Triple<Int, Int, Int>.rotate() = Triple(cubesize - second - 1, first, (third + 1).mod(4))
fun connectedSide(lastPos: Triple<Int, Int, Int>): Triple<Int, Int, Int> {
val cube = Triple(lastPos.first / cubesize, lastPos.second / cubesize, lastPos.third)
val newcube = connections[cube] ?: error("$cube $lastPos")
var nextFirst = (lastPos.first + dirs[lastPos.third].first).mod(cubesize)
var nextSecond = (lastPos.second + dirs[lastPos.third].second).mod(cubesize)
var newpos = Triple(nextFirst, nextSecond, lastPos.third)
while (newpos.third != (newcube.third + 2).mod(4)) {
newpos = newpos.rotate()
}
return Triple(newpos.first + cubesize * newcube.first, newpos.second + cubesize * newcube.second, (newcube.third + 2).mod(4))
}
fun Triple<Int, Int, Int>.nextStep(): Triple<Int, Int, Int> {
val nextFirst = first + dirs[third].first
val nextSecond = second + dirs[third].second
if (nextFirst !in 0 until X || nextSecond !in 0 until Y || map[nextSecond][nextFirst] == ' ') {
return connectedSide(this)
} else {
return copy(nextFirst, nextSecond)
}
}
fun Triple<Int, Int, Int>.next(): Triple<Int, Int, Int> {
check(map[second][first] != ' ')
var next = nextStep()
while (map[next.second][next.first] == ' ') {
next = next.nextStep()
}
return next
}
for (inst in instructions) {
for (i in 0 until inst.first) {
var newpos = pos.next()
if (map[newpos.second][newpos.first] == '#') {
break
}
pos = newpos
}
when (inst.second) {
"L" -> pos = pos.copy(third = (pos.third - 1).mod(dirs.size))
"R" -> pos = pos.copy(third = (pos.third + 1).mod(dirs.size))
else -> {}
}
}
return (pos.second + 1) * 1000 + (pos.first + 1) * 4 + pos.third
}
}
fun main() {
val testInstance = Day22(true)
val instance = Day22(false)
testInstance.part1().let { check(it == EXPECTED_1) { "part1: $it != $EXPECTED_1" } }
println("part1 ANSWER: ${instance.part1()}")
testInstance.part2().let {
check(it == EXPECTED_2) { "part2: $it != $EXPECTED_2" }
println("part2 ANSWER: ${instance.part2()}")
}
}
| 0 | Kotlin | 0 | 2 | 92f2e803b83c3d9303d853b6c68291ac1568a2ba | 5,377 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/at/mpichler/aoc/solutions/year2022/Day24.kt | mpichler94 | 656,873,940 | false | {"Kotlin": 196457} | package at.mpichler.aoc.solutions.year2022
import at.mpichler.aoc.lib.*
open class Part24A : PartSolution() {
private var width = 0
var height = 0
var start = 0
var goal = 0
private lateinit var blizzards: List<Blizzard>
private lateinit var blizzardIterator: BlizzardIterator
private lateinit var blizzardCache: MutableMap<Int, Set<Vector2i>>
override fun parseInput(text: String) {
val lines = text.trimEnd().split("\n")
width = lines.first().length - 2
height = lines.size - 2
start = findDoor(lines.first())
goal = findDoor(lines.last())
val blizzards = mutableListOf<Blizzard>()
for (y in 1..<lines.size - 1) {
for ((x, c) in lines[y].withIndex()) {
when (c) {
'^' -> blizzards.add(Blizzard(Vector2i(0, -1), Vector2i(x - 1, y - 1)))
'v' -> blizzards.add(Blizzard(Vector2i(0, 1), Vector2i(x - 1, y - 1)))
'<' -> blizzards.add(Blizzard(Vector2i(-1, 0), Vector2i(x - 1, y - 1)))
'>' -> blizzards.add(Blizzard(Vector2i(1, 0), Vector2i(x - 1, y - 1)))
}
}
}
this.blizzards = blizzards
}
private fun findDoor(line: String): Int {
for ((i, c) in line.withIndex()) {
if (c == '.') {
return i - 1
}
}
error("No door in line")
}
override fun config() {
blizzardIterator = BlizzardIterator(blizzards, width, height)
blizzardCache = mutableMapOf()
}
@Suppress("kotlin:S6611") // value is always present in map
private fun blizzards(time: Int): Set<Vector2i> {
if (time in blizzardCache) {
return blizzardCache[time]!!
}
blizzardCache[time] = blizzardIterator.next()
return blizzardCache[time]!!
}
fun nextEdges(state: State, traversal: Traversal<State>): Sequence<Pair<State, Int>> {
return sequence {
val nextTime = state.time + 1
val blizzardLocations = blizzards(nextTime)
for ((nextX, nextY) in state.pos.neighbors(moves(zeroMove = true))) {
val nextPos = Vector2i(nextX, nextY)
if (nextX in 0..<width && nextY in 0..<height && nextPos !in blizzardLocations) {
yield(Pair(State(nextPos, nextTime), 1))
}
if (nextX == start && nextY == -1) {
yield(Pair(State(nextPos, nextTime), 1))
}
if (nextX == goal && nextY == height) {
yield(Pair(State(nextPos, nextTime), 1))
}
}
}
}
fun getHeuristic(end: Vector2i): (node: State) -> Int {
return { current -> (current.pos - end).norm(Order.L1) }
}
override fun compute(): Int {
val traversal = AStar(this::nextEdges, getHeuristic(Vector2i(goal, height)))
traversal.startFrom(State(Vector2i(start, -1), 0))
for (state in traversal) {
if (state.y == height && state.x == goal) {
return traversal.depth
}
}
error("No path found")
}
override fun getExampleInput(): String? {
return """
#.######
#>>.<^<#
#.<..<<#
#>v.><>#
#<^v^^>#
######.#
""".trimIndent()
}
override fun getExampleAnswer(): Int {
return 18
}
data class Blizzard(val dir: Vector2i, val pos: Vector2i)
class BlizzardIterator(private val blizzards: List<Blizzard>, private val width: Int, private val height: Int) :
Iterator<Set<Vector2i>> {
val it = generator().iterator()
override fun hasNext(): Boolean {
return true
}
private fun generator(): Sequence<Set<Vector2i>> {
return sequence {
var count = 1
while (true) {
val blizzardLocations = mutableSetOf<Vector2i>()
for (blizzard in blizzards) {
val (dir, pos) = blizzard
val p = pos + dir * count
val x = p.x.mod(width)
val y = p.y.mod(height)
blizzardLocations.add(Vector2i(x, y))
}
count += 1
yield(blizzardLocations)
}
}
}
override fun next(): Set<Vector2i> {
return it.next()
}
}
data class State(val pos: Vector2i, val time: Int) {
val x get() = pos.x
val y get() = pos.y
}
}
class Part24B : Part24A() {
override fun compute(): Int {
val paths = listOf(
Pair(Vector2i(start, -1), Vector2i(goal, height)),
Pair(Vector2i(goal, height), Vector2i(start, -1)),
Pair(Vector2i(start, -1), Vector2i(goal, height))
)
var totalTime = 0
for ((start, end) in paths) {
val traversal = AStar(this::nextEdges, getHeuristic(end))
traversal.startFrom(State(start, totalTime))
for (state in traversal) {
if (state.pos == end) {
totalTime += traversal.depth
break
}
}
}
return totalTime
}
override fun getExampleAnswer(): Int {
return 54
}
}
fun main() {
Day(2022, 24, Part24A(), Part24B())
} | 0 | Kotlin | 0 | 0 | 69a0748ed640cf80301d8d93f25fb23cc367819c | 5,562 | advent-of-code-kotlin | MIT License |
src/main/kotlin/utils/Utils.kt | embuc | 735,933,359 | false | {"Kotlin": 110920, "Java": 60263} | package se.embuc.utils
import java.math.BigInteger
import kotlin.math.abs
import kotlin.math.sqrt
// this one is neat and simple but not fast for many numbers to check
fun isPalindrome(n: Int): Boolean {
return n.toString() == n.toString().reversed()
}
fun isPalindrome(n: String): Boolean {
return n == n.reversed()
}
fun isDecimalPalindrome(number: Int): Boolean {
var reversed = 0
var temp = number
while (temp > 0) {
reversed = reversed * 10 + temp % 10
temp /= 10
}
return number == reversed
}
fun isBinaryPalindrome(number: Int): Boolean {
var reversed = 0
var temp = number
while (temp > 0) {
reversed = (reversed shl 1) or (temp and 1)
temp = temp ushr 1
}
return number == reversed
}
fun gcd(a: Int, b: Int): Int {
return if (b == 0) a else gcd(b, a % b)
}
fun gcd(a: Long, b: Long): Long {
if (b == 0L) return a
return gcd(b, a % b)
}
fun lcm(a: Long, b: Long): Long {
return a / gcd(a, b) * b
}
fun lcm(a: Int, b: Int): Int {
return if (a == 0 || b == 0) 0 else abs(a * b) / gcd(a, b)
}
fun findLCD(denominators: List<Int>): Int {
return denominators.fold(1) { lcm, denominator ->
lcm(lcm, denominator)
}
}
fun isDivisibleByAll(n: Long, d: Long): Boolean {
for (i in 1..d) {
if (n % i != 0L) {
return false
}
}
return true
}
fun getTriangleNumber(n: Long): Long = n * (n + 1) / 2
fun getTriangleNumber(n: Int): Int = n * (n + 1) / 2
fun getTriangleNumbersUpTo(n: Int): BooleanArray {
val triangleNumbers = BooleanArray(n) { false }
for (i in 1..sqrt(n.toDouble()).toInt()) {
val triangleNumber = getTriangleNumber(i.toLong()).toInt()
triangleNumbers[triangleNumber] = true
}
return triangleNumbers
}
fun getSquareNumber(n: Long): Long = n * n
fun getSquareNumber(n: Int): Int = n * n
fun getPentagonalNumber(n: Long): Long = n * (3 * n - 1) / 2
fun getPentagonalNumber(n: Int): Int = n * (3 * n - 1) / 2
fun getHexagonalNumber(n: Long): Long = n * (2 * n - 1)
fun getHexagonalNumber(n: Int): Int = n * (2 * n - 1)
fun getHeptagonalNumber(n: Long): Long = n * (5 * n - 3) / 2
fun getHeptagonalNumber(n: Int): Int = n * (5 * n - 3) / 2
fun getOctagonalNumber(n: Long): Long = n * (3 * n - 2)
fun getOctagonalNumber(n: Int): Int = n * (3 * n - 2)
/* not efficient for large n but nice for debug and printing */
fun getDivisors(n: Long): List<Long> {
val divisors = mutableListOf<Long>()
for (i in 1..n) {
if (n % i == 0L) {
divisors.add(i)
}
}
return divisors
}
// Int version, be cautious with large n
fun getDivisors(n: Int): Set<Int> {
val divisors = mutableSetOf<Int>()
for (i in 1..n) {
if (n % i == 0) {
divisors.add(i)
}
}
return divisors
}
/**
* Instead of iterating all the way up to n, you only need to go up to the square root of n. Every divisor found below
* the square root has a corresponding divisor above the square root. For example, if n is divisible by i, then it's
* also divisible by n / i. This reduces the time complexity significantly.
*/
fun getDivisorsCount(n: Long): Int {
var count = 0
var i = 1L
while (i * i <= n) {
if (n % i == 0L) {
count += 1
if (i != n / i) count += 1 // Count the divisor pair only if they are different
}
i++
}
return count
}
/* Similar to above */
fun getDivisorsSum(n: Long): Long {
var count = 0L
var i = 1L
while (i * i <= n) {
if (n % i == 0L) {
count += i
if (i != n / i && i != 1L) {//skip n itself too
count += n / i
} // Count the divisor pair only if they are different
}
i++
}
return count
}
fun getDivisorsSum(n: Int): Int {
var count = 0
var i = 1
while (i * i <= n) {
if (n % i == 0) {
count += i
if (i != n / i && i != 1) {//skip n itself too
count += n / i
} // Count the divisor pair only if they are different
}
i++
}
return count
}
fun factorialBig(n: Int): BigInteger {
return if (n == 0) BigInteger.ONE else BigInteger.valueOf(n.toLong()) * factorialBig(n - 1)
}
fun factorial(n: Int): Int = if (n <= 1) 1 else n * factorial(n - 1)
fun factorial(n: Long): Long = if (n <= 1) 1 else n * factorial(n - 1)
// This method is used to find the number of permutations of a string. It will find ALL permutations, this is quite slow
// for instance for a string of length 10(Task 24). Better to use specialized method bellow, that one is O(n)
fun String.permutations(): List<String> {
if (this.length == 1) return listOf(this)
val perms = mutableListOf<String>()
val toInsert = this[0]
val subPerms = this.substring(1).permutations()
for (perm in subPerms) {
for (i in 0..perm.length) {
val newPerm = perm.substring(0, i) + toInsert + perm.substring(i)
perms.add(newPerm)
}
}
return perms
}
// this one is fast, O(n)
fun computeNthPermutation(numbers: MutableList<Char>, n: Int): String {
var index = n - 1 // Adjusting index to be zero-based
var result = ""
while (numbers.isNotEmpty()) {
val factorial = factorial(numbers.size - 1)
if (index >= factorial * numbers.size) {
// If the index is out of the valid range
return "Invalid permutation index"
}
val listIndex = index / factorial
result += numbers[listIndex]
index %= factorial
numbers.removeAt(listIndex)
}
return result
}
fun isPermutation(i: Int, j: Int): Boolean {
var i = i
var j = j
val digitsI = IntArray(10)
val digitsJ = IntArray(10)
while (i > 0) {
digitsI[i % 10]++
i /= 10
}
while (j > 0) {
digitsJ[j % 10]++
j /= 10
}
for (k in 0..9) {
if (digitsI[k] != digitsJ[k]) return false
}
return true
}
fun isPermutation(i: Long, j: Long): Boolean {
var i = i
var j = j
val digitsI = LongArray(getLongMagnitude(i).second.toInt())
val digitsJ = LongArray(getLongMagnitude(j).second.toInt())
while (i > 0) {
digitsI[(i % 10).toInt()]++
i /= 10
}
while (j > 0) {
digitsJ[(j % 10).toInt()]++
j /= 10
}
for (k in 0..9) {
if (digitsI[k] != digitsJ[k]) return false
}
return true
}
fun isPanDigit(arr: IntArray): Boolean {
var map = 0 // (binary 0000000000) no digits encountered yet
for (number in arr) {
var num = number
while (num > 0) {
val bit = 1 shl (num % 10) // shift left in java: <<
if (map and bit != 0) return false // bit already set in map, not pandigital
map = map or bit
num /= 10
}
}
val width = arr.sumOf { getIntMagnitude(it).second }
when (width) {
1 -> return map == 2 //1digits binary 10, representing digit 1 once for length of 1
2 -> return map == 6 //2digits binary 110, representing digits 1 to 2 once for length of 2
3 -> return map == 14
4 -> return map == 30
5 -> return map == 62
6 -> return map == 126
7 -> return map == 254
8 -> return map == 510
9 -> return map == 1022
}
return (map == 1022 //9digits binary 1111111110, representing digits 1 to 9 once for length of 9
|| map == 510 //8digits
|| map == 254 //7digits
|| map == 126 //6digits
|| map == 62 //5digits
|| map == 30 //4digits
|| map == 14 //3digits
|| map == 6 //2digits
|| map == 2); //1digits
}
fun getIntMagnitude(i: Int): Pair<Int, Int> {
var n = i
var log = 1
var exp = 1
// Loop (Determining the Magnitude): The while loop increases exp by multiplying it by 10 each time
// until 10*exp is >= than n. Simultaneously, log is incremented to track the number of digits in n.
// For example, if n is 1234, after this loop, exp will be 1000 and log will be 4.
while (10 * exp <= n) {
exp *= 10
++log
}
return Pair(exp, log)
}
fun getLongMagnitude(i: Long): Pair<Long, Long> {
var n = i
var log = 1L
var exp = 1L
// Loop (Determining the Magnitude): The while loop increases exp by multiplying it by 10 each time
// until 10*exp is >= than n. Simultaneously, log is incremented to track the number of digits in n.
// For example, if n is 1234, after this loop, exp will be 1000 and log will be 4.
while (10 * exp <= n) {
exp *= 10
++log
}
return Pair(exp, log)
}
fun getPentagonalNumbers(n: Int): Pair<IntArray, BooleanArray> {
var arrDict = BooleanArray(n * 3 * n / 2) { false }
var arr = IntArray(n)
for (i in 1..n) {
val pentagonalNumber = i * (3 * i - 1) / 2
arrDict[pentagonalNumber] = true
arr[i - 1] = pentagonalNumber
}
return Pair(arr, arrDict)
}
fun getHexagonalNumbers(n: Int): Pair<IntArray, BooleanArray> {
var arrDict = BooleanArray(n * 2 * n) { false }
var arr = IntArray(n)
for (i in 1..n) {
val hexagonalNumber = i * (2 * i - 1)
arrDict[hexagonalNumber] = true
arr[i - 1] = hexagonalNumber
}
return Pair(arr, arrDict)
}
fun solveQuadratic(a: Double, b: Double, c: Double): Pair<Double?, Double?> {
if (a == 0.0) {
// Not a quadratic equation
return null to null
}
val discriminant = b * b - 4 * a * c
return if (discriminant > 0) {
// Two real and distinct roots
Pair((-b + sqrt(discriminant)) / (2 * a), (-b - sqrt(discriminant)) / (2 * a))
} else if (discriminant == 0.0) {
// One real root (roots are equal)
Pair(-b / (2 * a), -b / (2 * a))
} else {
// Roots are complex and different
null to null
}
}
fun findPositiveIntegerRoot(a: Double, b: Double, c: Double): Double? {
if (a == 0.0) {
// Not a quadratic equation
return null
}
val discriminant = b * b - 4 * a * c
if (discriminant < 0) {
// No real roots
return null
}
val sqrtDiscriminant = sqrt(discriminant)
val root1 = (-b + sqrtDiscriminant) / (2 * a)
val root2 = (-b - sqrtDiscriminant) / (2 * a)
// Check for positive integer roots
if (root1 > 0 && root1 % 1 == 0.0) {
// Root1 is a positive integer
return root1
}
if (root2 > 0 && root2 % 1 == 0.0) {
// Root2 is a positive integer
return root2
}
return null
}
inline fun Long.digitsCount(): IntArray {
var map = IntArray(10) // (0, 1, 2 ....) no digits encountered yet
val digits = this.digits();
for (number in digits) {
map[number]++
}
return map
}
inline fun Long.digits(): IntArray {
val digits = mutableListOf<Int>()
var number = this
while (number > 0L) {
digits.add((number % 10L).toInt())
number /= 10L
}
return digits.toIntArray()
}
inline fun BigInteger.digits(): IntArray {
val digits = mutableListOf<Int>()
var number = this
while (number > BigInteger.ZERO) {
digits.add((number % BigInteger.TEN).toInt())
number /= BigInteger.TEN
}
return digits.toIntArray()
}
inline fun Int.pow(exponent: Int): Int {
require(exponent >= 0) { "Exponent must be non-negative" }
var result = 1
var base = this
for (i in 1..exponent) {
result *= base
}
return result
}
// 37,18 -> 3718 etc.
fun concatenate(first: Int, second: Int): Int {
var second = second
var power = 1
while (power <= second) {
power *= 10
}
return first * power + second
}
fun concatenate(first: Long, second: Long): Long {
var second = second
var power = 1
while (power <= second) {
power *= 10
}
return first * power + second
}
data class Fraction(var numerator: BigInteger, var denominator: BigInteger)
fun solvePell(n: Int): Fraction? {
val initialRoot = sqrt(n.toDouble()).toInt()
var y = initialRoot
var z = 1
var r = initialRoot * 2
var fraction1 = Fraction(BigInteger.ONE, BigInteger.ZERO)
var fraction2 = Fraction(BigInteger.ZERO, BigInteger.ONE)
var resultFraction = Fraction(BigInteger.ZERO, BigInteger.ZERO)
while (true) {
y = r * z - y
z = (n - y * y) / z
r = (initialRoot + y) / z
nextNum(fraction1, r)
nextNum(fraction2, r)
var invFraction = Fraction(fraction1.denominator, fraction2.denominator)
nextNum(invFraction, initialRoot)
resultFraction.numerator = invFraction.denominator
resultFraction.denominator = fraction2.denominator
if (resultFraction.numerator * resultFraction.numerator -
n.toBigInteger() * resultFraction.denominator * resultFraction.denominator == BigInteger.ONE) {
return Fraction(resultFraction.numerator, resultFraction.denominator)
}
}
return null
}
private fun nextNum(f: Fraction, term: Int) {
var temp = f.numerator
f.numerator = f.denominator
f.denominator = f.denominator * BigInteger.valueOf(term.toLong()) + temp
} | 0 | Kotlin | 0 | 1 | 79c87068303f862037d27c1b33ea037ab43e500c | 11,955 | projecteuler | MIT License |
src/main/kotlin/com/jacobhyphenated/day22/Day22.kt | jacobhyphenated | 572,119,677 | false | {"Kotlin": 157591} | package com.jacobhyphenated.day22
import com.jacobhyphenated.Day
import java.io.File
class Day22: Day<List<Instruction>> {
override fun getInput(): List<Instruction> {
return parseInstructions(
this.javaClass.classLoader.getResource("day22/input.txt")!!.readText()
)
}
override fun part1(input: List<Instruction>): Number {
val deck = List(10007) { it.toLong() }
val shuffled = executeInstructions(input, deck)
return shuffled.indexOf(2019)
}
override fun part2(input: List<Instruction>): Number {
// TODO: verified we can reverse the value from the previous part
// now we need to find a way to repeat the operation k times
val reversed = input.reversed()
var i = 2020L
var lastDiff = 0L
repeat(10) {
i = reversed.fold(i){ index, instruction ->
instruction.reverseFromIndex(index, 119315717514047L)
}.also {newIndex ->
val diff = if(newIndex < i) { newIndex + 119315717514047L - i } else { newIndex - i}
println("run $it - $newIndex - $i = $diff} (${diff - lastDiff})")
lastDiff = diff
}
}
return input.reversed().fold(7171L){ index, instruction ->
instruction.reverseFromIndex(index, 10007)
}
}
fun executeInstructions(instructions: List<Instruction>, deck: List<Long>): List<Long> {
return instructions.fold(deck) { d, instruction ->
instruction.execute(d)
}
}
fun parseInstructions(input: String): List<Instruction> {
return input.lines().map {
val n = it.split(" ").last()
if (it.contains("stack")) {
NewStack
} else if (it.contains("increment")) {
Increment(n.toInt())
} else if (it.contains("cut")) {
Cut(n.toInt())
} else {
throw UnsupportedOperationException("Invalid instruction $it")
}
}
}
}
sealed interface Instruction {
fun execute(deck: List<Long>): List<Long>
fun reverseFromIndex(i: Long, size: Long): Long
}
object NewStack : Instruction {
override fun execute(deck: List<Long>): List<Long> {
return deck.reversed()
}
override fun reverseFromIndex(i: Long, size: Long): Long {
return size - 1 - i
}
}
class Increment(val n: Int): Instruction {
override fun execute(deck: List<Long>): List<Long> {
val newDeck: MutableList<Long?> = MutableList(deck.size) { null }
var index = 0
for (card in deck) {
newDeck[index] = card
index = (index + n) % deck.size
}
return newDeck.mapNotNull { it }
}
override fun reverseFromIndex(i: Long, size: Long): Long {
// going forward:
// index * n % size = final
var modInverse = i
while (modInverse % n != 0L) {
modInverse += size
}
return modInverse / n
}
}
class Cut(val n: Int): Instruction {
override fun execute(deck: List<Long>): List<Long> {
val (front, back) = if (n >= 0) {
Pair(deck.subList(0,n), deck.subList(n, deck.size))
} else {
Pair(deck.subList(0, deck.size + n), deck.subList(deck.size + n, deck.size))
}
return back.toMutableList().apply {
addAll(front)
}
}
override fun reverseFromIndex(i: Long, size: Long): Long {
// Note: as of kotlin 1.5, mod() is different from % and has the behavior of floorMod()
// The % operator functions as .rem()
// -9 % 10 == -9
// -9.mod(10) == 1
return (i + n).mod(size)
}
} | 0 | Kotlin | 0 | 0 | 1a0b9cb6e9a11750c5b3b5a9e6b3d63649bf78e4 | 3,763 | advent2019 | The Unlicense |
src/main/kotlin/day13/solution.kt | bukajsytlos | 433,979,778 | false | {"Kotlin": 63913} | package day13
import java.io.File
fun main() {
var points: Set<Point> = emptySet()
var foldCommands: List<FoldCommand> = emptyList()
File("src/main/kotlin/day13/input.txt").useLines { linesSequence ->
val linesIterator = linesSequence.iterator()
points = linesIterator.asSequence().takeWhile { s -> s.isNotBlank() }.map {
Point(
it.substringBefore(",").toInt(),
it.substringAfter(",").toInt()
)
}.toSet()
foldCommands = linesIterator.asSequence().map {
FoldCommand(
it.substringBefore('=').last(),
it.substringAfter('=').toInt()
)
}.toList()
}
println(fold(points, foldCommands[0]).count())
val codePoints = foldCommands.fold(points) { acc, foldCommand -> fold(acc, foldCommand) }
codePoints.display()
}
fun fold(points: Set<Point>, foldCommand: FoldCommand): Set<Point> = points.map { point ->
if (foldCommand.axis == 'x' && point.x > foldCommand.position) {
Point(2 * foldCommand.position - point.x, point.y)
} else if (foldCommand.axis == 'y' && point.y > foldCommand.position) {
Point(point.x, 2 * foldCommand.position - point.y)
} else {
point
}
}.toSet()
fun Set<Point>.display() {
(0..this.maxOf { it.y }).forEach { y ->
(0..this.maxOf { it.x }).forEach { x ->
print(if (Point(x, y) in this) "\u2588" else "\u2591")
}
println()
}
}
data class Point(val x: Int, val y: Int)
data class FoldCommand(val axis: Char, val position: Int) | 0 | Kotlin | 0 | 0 | f47d092399c3e395381406b7a0048c0795d332b9 | 1,607 | aoc-2021 | MIT License |
math/NumberTheoreticTransform.kt | wangchaohui | 737,511,233 | false | {"Kotlin": 36737} | @JvmInline
value class ModInt private constructor(val value: Int) {
operator fun plus(other: ModInt) = plus(other.value)
operator fun plus(other: Int) = from(value + other)
operator fun minus(other: ModInt) = minus(other.value)
operator fun minus(other: Int) = from(value - other)
operator fun times(other: ModInt) = times(other.value)
operator fun times(other: Int) = from(value.toLong() * other)
fun pow(exponent: Int): ModInt {
var ans = One
var a = this
var b = exponent
while (b > 0) {
if (b % 2 == 1) ans *= a
a *= a
b /= 2
}
return ans
}
fun inv(): ModInt = pow(MOD - 2)
companion object {
fun from(value: Int) = ModInt(value.mod())
fun from(value: Long) = ModInt(value.mod())
fun Int.mod() = mod(MOD)
fun Long.mod() = mod(MOD)
val Zero = from(0)
val One = from(1)
const val MOD = 998244353 // prime, 7 * 17 * 2^23 + 1
}
}
class NumberTheoreticTransform {
private val rev = IntArray(N).apply {
for (i in 1..<N) {
this[i] = this[i / 2] / 2
if (i and 1 == 1) {
this[i] += N / 2
}
}
}
fun ntt(p: Array<ModInt>, inverse: Boolean = false) {
prepare(p)
var subProblemSize = 2
while (subProblemSize <= N) {
val gn = G.pow((ModInt.MOD - 1) / subProblemSize)
for (subProblemStart in 0..<N step subProblemSize) {
var g = ModInt.One
for (j in subProblemStart..<subProblemStart + subProblemSize / 2) {
val u = p[j]
val t = g * p[j + subProblemSize / 2]
p[j] = u + t
p[j + subProblemSize / 2] = u - t
g *= gn
}
}
subProblemSize *= 2
}
if (inverse) {
p.reverse(1, N)
for (j in 0..<N) p[j] *= InvN
}
}
private fun prepare(x: Array<ModInt>) {
for (i in 1..<N) {
if (i < rev[i]) x[i] = x[rev[i]].also { x[rev[i]] = x[i] }
}
}
companion object {
const val LOG_N = 20
const val N = 1 shl LOG_N
private val InvN = ModInt.from(N).inv()
private val G = ModInt.from(3)
}
}
| 0 | Kotlin | 0 | 0 | 241841f86fdefa9624e2fcae2af014899a959cbe | 2,378 | kotlin-lib | Apache License 2.0 |
src/y2016/Day13.kt | gaetjen | 572,857,330 | false | {"Kotlin": 325874, "Mermaid": 571} | package y2016
import util.Pos
import util.neighborsManhattan
import util.printMatrix
object Day13 {
fun isWall(favorite: Int, x: Int, y: Int): Boolean {
val n = x * x + 3 * x + 2 * x * y + y + y * y + favorite
val binary = n.toString(2)
return binary.count { it == '1' } % 2 == 1
}
fun part1(favorite: Int, target: Pos): Int {
val start: Pos = 1 to 1
var steps = 0
val explored = mutableSetOf(start)
var current = setOf(start)
while (target !in current) {
current = current
.flatMap { it.neighborsManhattan() }
.filter { it.first >= 0 && it.second >= 0 }
.filter { !isWall(favorite, it.first, it.second) }
.filter { it !in explored }
.toSet()
explored.addAll(current)
steps++
}
return steps
}
fun part2(favorite: Int): Int {
val start: Pos = 1 to 1
var steps = 0
val explored = mutableSetOf(start)
var current = setOf(start)
while (steps < 50) {
current = current
.flatMap { it.neighborsManhattan() }
.filter { it.first >= 0 && it.second >= 0 }
.filter { !isWall(favorite, it.first, it.second) }
.filter { it !in explored }
.toSet()
explored.addAll(current)
steps++
}
return explored.size
}
}
fun main() {
val testFavorite = 10
val testTargetPos = 7 to 4
println("------Tests------")
println(Day13.part1(testFavorite, testTargetPos))
println("------Real------")
val favorite = 1350
val targetPos = 31 to 39
println(Day13.part1(favorite, targetPos))
println(Day13.part2(favorite))
val officePlan = List(50) { y ->
List(50) { x->
Day13.isWall(favorite, x, y)
}
}
printMatrix(officePlan) {
if (it) "██" else " "
}
} | 0 | Kotlin | 0 | 0 | d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a | 2,004 | advent-of-code | Apache License 2.0 |
Problems/Algorithms/1905. Count Sub Islands/CountSubIslands.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 countSubIslands(grid1: Array<IntArray>, grid2: Array<IntArray>): Int {
val n = grid1.size
val m = grid1[0].size
val visited = Array(n) { BooleanArray(m) { false } }
val neighbors = arrayOf(intArrayOf(0, 1), intArrayOf(0, -1), intArrayOf(1, 0), intArrayOf(-1, 0))
var ans = 0
for (i in 0..n-1) {
for (j in 0..m-1) {
if (!visited[i][j] && grid1[i][j] == 1 && grid2[i][j] == 1) {
var flag = true
val queue = ArrayDeque<IntArray>()
queue.add(intArrayOf(i, j))
while (!queue.isEmpty()) {
for (k in 0..queue.size-1) {
val curr = queue.removeLast()
val row = curr[0]
val col = curr[1]
visited[row][col] = true
for (neighbor in neighbors) {
val r = row + neighbor[0]
val c = col + neighbor[1]
if (r < 0 || r >= grid1.size || c < 0 || c >= grid1[0].size || grid2[r][c] == 0 || visited[r][c]) continue
visited[r][c] = true
if (grid1[r][c] == 0) flag = false
queue.add(intArrayOf(r, c))
}
}
}
if (flag) ans++
}
}
}
return ans
}
}
| 0 | Kotlin | 0 | 1 | 5e919965b43917eeee15e4bff12a0b6bea4fd0e7 | 1,748 | leet-code | MIT License |
src/main/kotlin/de/consuli/aoc/year2022/days/Day04.kt | ulischulte | 572,773,554 | false | {"Kotlin": 40404} | package de.consuli.aoc.year2022.days
import de.consuli.aoc.common.Day
class Day04 : Day(4, 2022) {
override fun partOne(testInput: Boolean): Any {
return getInput(testInput).count { sectionAssignment ->
val sections = getSections(sectionAssignment)
sections.first.first in sections.second && sections.first.last in sections.second
|| sections.second.first in sections.first && sections.second.last in sections.first
}
}
override fun partTwo(testInput: Boolean): Any {
return getInput(testInput).count { sectionAssignment ->
val sections = getSections(sectionAssignment)
sections.first.first in sections.second || sections.first.last in sections.second
|| sections.second.first in sections.first || sections.second.last in sections.first
}
}
private fun getSections(sectionAssignment: String): Pair<IntRange, IntRange> {
val sectionAssignmentPairs = sectionAssignment.split(",")
val (startSection1, endSection1) = sectionAssignmentPairs[0].split("-").map { it.toInt() }
val (startSection2, endSection2) = sectionAssignmentPairs[1].split("-").map { it.toInt() }
return Pair(startSection1..endSection1, startSection2..endSection2)
}
}
| 0 | Kotlin | 0 | 2 | 21e92b96b7912ad35ecb2a5f2890582674a0dd6a | 1,312 | advent-of-code | Apache License 2.0 |
src/Day10.kt | maximilianproell | 574,109,359 | false | {"Kotlin": 17586} | fun main() {
fun part1(input: List<String>): Int {
var cycles = 0
var currentX = 1
var totalSignalStrength = 0
input.forEach { line ->
val instruction = if (line.contains("noop")) {
Instruction.Noop
} else {
// must be addx instruction
val x = line
.substringAfter("addx ")
.toInt()
Instruction.AddX(x)
}
cycles++
fun checkCycle() {
when (cycles) {
20, 60, 100, 140, 180, 220 -> {
totalSignalStrength += cycles * currentX
}
}
}
checkCycle()
if (instruction is Instruction.AddX) {
cycles++
checkCycle() // check DURING the cycle
currentX += instruction.x
}
}
return totalSignalStrength
}
fun part2(input: List<String>): String {
// 40 x 6 "pixels", i.e. "#", otherwise "."
// the x value controls the position of the sprite
val charList = buildList {
var cycles = 0
var currentX = 1 // here, the current x is the middle position of the sprite "###"
input.forEach { line ->
val instruction = if (line.contains("noop")) {
Instruction.Noop
} else {
// must be addx instruction
val x = line
.substringAfter("addx ")
.toInt()
Instruction.AddX(x)
}
cycles++
fun movePixelAndCheckForDrawing() {
val spriteRange = currentX - 1..currentX + 1
// debug code
/*val debugSpritePosition = List(40) { index -> if (index in spriteRange) "#" else "." }
.joinToString(separator = "")
println(debugSpritePosition)
println("crt draws at position ${(cycles - 1) % 40}")*/
if ((cycles - 1) % 40 in spriteRange) {
add('#')
} else add('.')
}
movePixelAndCheckForDrawing()
if (instruction is Instruction.AddX) {
cycles++
movePixelAndCheckForDrawing()
currentX += instruction.x
}
}
}
val result = charList.chunked(40).joinToString(separator = "") { crtRow ->
String(crtRow.toCharArray()) + "\n"
}
return result
}
val input = readInput("Day10")
println(part1(input))
println(part2(input))
}
private sealed interface Instruction {
data class AddX(
val x: Int
) : Instruction
object Noop : Instruction
}
| 0 | Kotlin | 0 | 0 | 371cbfc18808b494ed41152256d667c54601d94d | 2,975 | kotlin-advent-of-code-2022 | Apache License 2.0 |
kotlin/src/com/daily/algothrim/leetcode/medium/Permute.kt | idisfkj | 291,855,545 | false | null | package com.daily.algothrim.leetcode.medium
/**
* 46. 全排列
* 给定一个不含重复数字的数组 nums ,返回其 所有可能的全排列 。你可以 按任意顺序 返回答案。
*/
class Permute {
companion object {
@JvmStatic
fun main(args: Array<String>) {
Permute().permute(intArrayOf(1, 2, 3)).forEach {
it.forEach { item ->
print(item)
}
println()
}
Permute().permute(intArrayOf(0, 1)).forEach {
it.forEach { item ->
print(item)
}
println()
}
Permute().permute(intArrayOf(1)).forEach {
it.forEach { item ->
print(item)
}
println()
}
}
}
// nums = [1,2,3]
// [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
fun permute(nums: IntArray): List<List<Int>> {
val result = arrayListOf<List<Int>>()
backtracking(nums, 0, arrayListOf(), result)
return result
}
private fun backtracking(nums: IntArray, currentIndex: Int, subResult: ArrayList<Int>, resultList: ArrayList<List<Int>>) {
if (subResult.size == nums.size) {
resultList.add(ArrayList(subResult))
return
}
subResult.add(nums[currentIndex])
backtracking(nums, currentIndex + 1, subResult, resultList)
subResult.removeAt(subResult.size - 1)
var right = currentIndex + 1
while (right < nums.size) {
val temp = nums[right]
nums[right] = nums[currentIndex]
nums[currentIndex] = temp
subResult.add(nums[currentIndex])
backtracking(nums, currentIndex + 1, subResult, resultList)
subResult.removeAt(subResult.size - 1)
val tempReversal = nums[right]
nums[right] = nums[currentIndex]
nums[currentIndex] = tempReversal
right++
}
}
} | 0 | Kotlin | 9 | 59 | 9de2b21d3bcd41cd03f0f7dd19136db93824a0fa | 2,071 | daily_algorithm | Apache License 2.0 |
src/leetcode/mayChallenge2020/weekfive/CourseSchedule.kt | adnaan1703 | 268,060,522 | false | null | package leetcode.mayChallenge2020.weekfive
import utils.println
import java.util.*
import kotlin.collections.ArrayList
fun main() {
var courses = arrayOf(intArrayOf(1, 0))
canFinish(2, courses).println() // ans: true
courses = arrayOf(intArrayOf(1, 0), intArrayOf(0, 1))
canFinish(2, courses).println() // ans: false
courses = arrayOf(intArrayOf(1, 0), intArrayOf(1, 2), intArrayOf(0, 1))
canFinish(3, courses).println() // ans: false
courses = arrayOf(
intArrayOf(3, 1),
intArrayOf(1, 2),
intArrayOf(1, 0)
)
canFinish(4, courses).println() // ans: true
courses = arrayOf(
intArrayOf(3, 1),
intArrayOf(1, 2),
intArrayOf(1, 0),
intArrayOf(0, 3)
)
canFinish(4, courses).println() // ans: false
courses = arrayOf(
intArrayOf(1, 0),
intArrayOf(2, 6),
intArrayOf(1, 7),
intArrayOf(5, 1),
intArrayOf(6, 4),
intArrayOf(7, 0),
intArrayOf(0, 5)
)
canFinish(8, courses).println() // ans: false
}
fun canFinish(numCourses: Int, prerequisites: Array<IntArray>): Boolean {
val graph = Array(numCourses) { ArrayList<Int>() }
val inDegrees = IntArray(numCourses)
prerequisites.forEach {
graph[it[1]].add(it[0])
inDegrees[it[0]]++
}
val q: Queue<Int> = LinkedList<Int>()
inDegrees.forEachIndexed { index, i ->
if (i == 0)
q.offer(index)
}
while (q.isNotEmpty()) {
val node = q.poll()
graph[node].forEach {
inDegrees[it]--
if (inDegrees[it] == 0)
q.offer(it)
}
}
inDegrees.forEach { if (it != 0) return false }
return true
}
// using dfs to track back edge
fun canFinish2(numCourses: Int, prerequisites: Array<IntArray>): Boolean {
val graph = Array(numCourses) { ArrayList<Int>() }
val visited = BooleanArray(numCourses) { false }
prerequisites.forEach { ints ->
graph[ints[1]].add(ints[0])
}
for (i in visited.indices) {
if (visited[i].not()) {
if (dfsNoCycle(graph, i, BooleanArray(numCourses), visited).not())
return false
}
}
return true
}
fun dfsNoCycle(graph: Array<ArrayList<Int>>, source: Int, inStack: BooleanArray, visited: BooleanArray): Boolean {
var retValue = true
if (inStack[source])
return false
visited[source] = true
inStack[source] = true
graph[source].forEach {
if (inStack[it])
return false
if (visited[it].not())
retValue = retValue && dfsNoCycle(graph, it, inStack, visited)
}
inStack[source] = false
return retValue
}
| 0 | Kotlin | 0 | 0 | e81915db469551342e78e4b3f431859157471229 | 2,842 | KotlinCodes | The Unlicense |
2023/src/main/kotlin/Day04.kt | dlew | 498,498,097 | false | {"Kotlin": 331659, "TypeScript": 60083, "JavaScript": 262} | object Day04 {
fun part1(input: String): Int {
return parseScores(input)
.sumOf { if (it == 0) 0 else 1 shl (it - 1) }
}
fun part2(input: String): Int {
val scores = parseScores(input)
val memo = IntArray(scores.size)
scores.indices.reversed().forEach {
memo[it] = 1 + memo.slice(it + 1..it + scores[it]).sum()
}
return memo.sum()
}
private fun parseScores(input: String): List<Int> {
val regex = Regex(".+: (.+) \\| (.+)")
return input.splitNewlines()
.map {
val match = regex.matchEntire(it)!!
val winningNumbers = match.groupValues[1].splitWhitespace().toIntList()
val numbersYouHave = match.groupValues[2].splitWhitespace().toIntList().toSet()
return@map winningNumbers.intersect(numbersYouHave).size
}
}
} | 0 | Kotlin | 0 | 0 | 6972f6e3addae03ec1090b64fa1dcecac3bc275c | 813 | advent-of-code | MIT License |
src/Day05.kt | ChenJiaJian96 | 576,533,624 | false | {"Kotlin": 11529} | fun main() {
fun MutableList<MutableList<Char>>.addOriginChars(originData: String) {
originData.forEachIndexed { index, c ->
if (c == '[') {
this[index / 4].add(originData[index + 1])
}
}
}
fun MutableList<MutableList<Char>>.execAction(moveActions: MoveAction, needReverse: Boolean) {
val newList = this[moveActions.startIndex].subList(0, moveActions.quantity)
if (needReverse) {
newList.reverse()
}
this[moveActions.endIndex].addAll(0, newList)
IntRange(0, moveActions.quantity - 1).reversed().forEach {
this[moveActions.startIndex].removeAt(it)
}
}
fun extracMoveActions(
input: List<String>,
moveActionStartIndex: Int
): List<MoveAction> {
val moveActions = input.subList(moveActionStartIndex, input.size).map {
it.split(" ").run {
MoveAction(
quantity = get(1).toInt(),
startIndex = get(3).toInt() - 1, // change to index
endIndex = get(5).toInt() - 1, // change to index
)
}
}
return moveActions
}
fun extractOriginalData(input: List<String>): MutableList<MutableList<Char>> {
val emptyLineIndex = input.indexOf("")
val numLineIndex = emptyLineIndex - 1
val totalSize = input[numLineIndex].length / 4 + 1
val originalData: MutableList<MutableList<Char>> = MutableList(totalSize) { mutableListOf() }
input.subList(0, numLineIndex).forEach {
originalData.addOriginChars(it)
}
return originalData
}
fun part1(input: List<String>): String {
val emptyLineIndex = input.indexOf("")
val originalData = extractOriginalData(input)
val moveActions = extracMoveActions(input, emptyLineIndex + 1)
moveActions.forEach {
originalData.execAction(it, true)
}
return originalData.map {
it.first()
}.joinToString("") { it.toString() }
}
fun part2(input: List<String>): String {
val emptyLineIndex = input.indexOf("")
val originalData = extractOriginalData(input)
val moveActions = extracMoveActions(input, emptyLineIndex + 1)
moveActions.forEach {
originalData.execAction(it, false)
}
return originalData.map {
it.first()
}.joinToString("") { it.toString() }
}
val testInput = readInput("05", true)
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("05")
part1(input).println()
part2(input).println()
}
data class MoveAction(
val quantity: Int,
val startIndex: Int, // start from 0
val endIndex: Int, // max is last_index
) | 0 | Kotlin | 0 | 0 | b1a88f437aee756548ac5ba422e2adf2a43dce9f | 2,861 | Advent-Code-2022 | Apache License 2.0 |
2021/src/test/kotlin/Day12.kt | jp7677 | 318,523,414 | false | {"Kotlin": 171284, "C++": 87930, "Rust": 59366, "C#": 1731, "Shell": 354, "CMake": 338} | import kotlin.test.Test
import kotlin.test.assertEquals
class Day12 {
data class Connection(val from: String, val to: String)
@Test
fun `run part 01`() {
val connections = getCaveConnections()
val path = mutableListOf<List<String>>()
connections.buildAllPaths("start", 1, path)
val count = path.count()
assertEquals(4720, count)
}
@Test
fun `run part 02`() {
val connections = getCaveConnections()
val paths = mutableListOf<List<String>>()
connections.buildAllPaths("start", 2, paths)
val count = paths.count()
assertEquals(147848, count)
}
private fun Set<Connection>.buildAllPaths(
element: String,
maxVisits: Int = 1,
acc: MutableList<List<String>>,
path: List<String> = listOf()
) {
if (element == "end")
acc += path
if (element == "end" || path.maxVisitsExceeded(maxVisits))
return
this
.filter { it.from == element }
.map { it.to }
.forEach { to -> this.buildAllPaths(to, maxVisits, acc, path + to) }
}
private fun List<String>.maxVisitsExceeded(maxVisits: Int) = this
.filter { it.all { c -> c.isLowerCase() } }
.groupingBy { it }.eachCount()
.let {
it.any { c -> c.value > maxVisits } || (it.count { c -> c.value == 2 } > 1)
}
private fun getCaveConnections(name: String = "day12-input.txt") = Util.getInputAsListOfString(name)
.map { it.split("-").let { s -> Connection(s.first(), s.last()) } }
.let { connections ->
connections
.map { Connection(it.to, it.from) }
.union(connections)
.filter { it.from != "end" && it.to != "start" }
.toSet()
}
}
| 0 | Kotlin | 1 | 2 | 8bc5e92ce961440e011688319e07ca9a4a86d9c9 | 1,858 | adventofcode | MIT License |
src/main/kotlin/bsu/cc/schedule/ConflictChecking.kt | JordanPaoletti | 167,065,523 | false | null | package bsu.cc.schedule
import bsu.cc.constraints.ClassConstraint
import bsu.cc.constraints.ConstraintPriority
import com.brein.time.timeintervals.collections.ListIntervalCollection
import com.brein.time.timeintervals.indexes.IntervalTree
import com.brein.time.timeintervals.indexes.IntervalTreeBuilder
import com.brein.time.timeintervals.indexes.IntervalValueComparator
import java.time.DayOfWeek
import java.util.stream.Collectors
fun buildScheduleIntervalTree(): IntervalTree {
val tree = IntervalTreeBuilder.newBuilder()
.collectIntervals { ListIntervalCollection() }
.build()
// required for overlap operations
tree.configuration.setValueComparator(IntervalValueComparator::compareInts)
// required for find operations
tree.configuration.setIntervalFilter { comp, val1, val2 ->
comp.compare(val1.getNormStart(), val2.getNormStart()) == 0 &&
comp.compare(val1.getNormEnd(), val2.getNormEnd()) == 0
}
return tree
}
@Suppress("UNCHECKED_CAST")
fun checkForOverlaps(classes: Collection<ClassSchedule>, tree: IntervalTree): Set<List<ClassSchedule>>
= (classes.map { tree.overlap(it) }.filter { it.size > 1}.toSet() as Set<List<ClassSchedule>>)
.flatMap(::findDateConflicts).toSet()
fun checkConstraints(classes: Collection<ClassSchedule>,
constraints: Collection<ClassConstraint>): Map<ClassConstraint, Set<List<ClassSchedule>>> {
val conflicts = HashMap<ClassConstraint, List<ClassSchedule>>()
constraints.filter { it.priority != ConstraintPriority.IGNORE }.forEach { constraint ->
conflicts[constraint] = classes.filter { constraint.classes.contains(it.classString) }.toList()
}
return conflicts.mapValues { considerDaysOfWeek(it.value) }
}
fun checkRooms(classes: Collection<ClassSchedule>,
constraints: Collection<ClassConstraint>): Map<String, Set<List<ClassSchedule>>>
= classes.groupBy { it.room }
.filterKeys { it.trim() != "" }
.mapValues { considerDaysOfWeek(it.value) }
.mapValues { considerIgnoreConstraints(it.value, constraints) }
.filterValues {
!it.isEmpty() }
fun checkInstructors(classes: Collection<ClassSchedule>,
constraints: Collection<ClassConstraint>): Map<Instructor, Set<List<ClassSchedule>>> {
val instructors = HashMap<Instructor, MutableList<ClassSchedule>>()
classes.forEach { c ->
c.instructors.forEach { instructor ->
val taughtClasses = instructors.getOrElse(instructor, ::ArrayList)
taughtClasses.add(c)
instructors[instructor] = taughtClasses
}
}
val generalInstructor = Instructor("STAFF", "STAFF")
return instructors.filterKeys { it != generalInstructor }
.mapValues { considerDaysOfWeek(it.value) }
.mapValues { considerIgnoreConstraints(it.value, constraints) }
.filterValues { !it.isEmpty() }
}
internal fun considerIgnoreConstraints(conflicts: Set<List<ClassSchedule>>,
constraints: Collection<ClassConstraint>): Set<List<ClassSchedule>> {
val ignore = constraints
.filter { it.priority == ConstraintPriority.IGNORE }
.map{ it.classes }
return conflicts.filter { conflict ->
!ignore.contains(conflict.map { it.classString }.toSet())
}.toSet()
}
internal fun considerDaysOfWeek(classes: List<ClassSchedule>): Set<List<ClassSchedule>> {
val dayMap = HashMap<DayOfWeek, MutableList<ClassSchedule>>()
classes.forEach { c ->
c.meetingDays.forEach { day ->
val classesOnDay = dayMap.getOrElse(day, ::ArrayList)
classesOnDay.add(c)
dayMap[day] = classesOnDay
}
}
val conflicts = HashSet<List<ClassSchedule>>()
dayMap.values.forEach { classesOnDay ->
val tree = buildScheduleIntervalTree()
tree.addAll(classesOnDay)
conflicts.addAll(checkForOverlaps(classesOnDay, tree))
}
return conflicts
}
/**
* Brute force method for determining if the classes that conflict in time also conflict in date.
* Ideally, the size of a conflict should be very small, making the brute force nature a non issue.
*/
internal fun findDateConflicts(classes: Collection<ClassSchedule>): Set<List<ClassSchedule>> {
val conflicts = HashSet<ArrayList<ClassSchedule>>()
classes.forEach { curr ->
val conflict = ArrayList<ClassSchedule>()
classes.forEach { c ->
if (curr.meetingDates.overlaps(c.meetingDates)) {
conflict.add(c)
}
}
if (conflict.size > 1) {
conflicts.add(conflict)
}
}
return conflicts
}
| 4 | Kotlin | 1 | 0 | 0b17d34f45cb162e82c76546708dca0c739880ae | 4,761 | Conflict_Checker | MIT License |
shared/src/main/kotlin/adventofcode/util/algorithm/AStarSearch.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.util.algorithm
import java.util.*
interface IState {
fun getNeighbors(): Sequence<IState>
val isGoal: Boolean
val heuristic: Int
}
fun aStar(start: IState): PathfinderState? {
val openList = PriorityQueue(compareBy<PathfinderState> { it.expectedCost + it.cost })
openList.add(PathfinderState(start, 0, start.heuristic))
val closedList = mutableSetOf(start)
var i = 0
while (openList.isNotEmpty()) {
i++
val candidate = openList.poll()
if (candidate.IState.isGoal) {
return candidate
} else {
candidate.move()
.filterNot { it.IState in closedList }
.forEach {
openList.add(it)
closedList.add(it.IState)
}
}
}
return null
}
fun aStarExhaustive(start: IState): Sequence<PathfinderState> = sequence {
val openList = PriorityQueue(compareBy<PathfinderState> { it.expectedCost + it.cost })
openList.add(PathfinderState(start, 0, start.heuristic))
val closedList = mutableSetOf(start)
var i = 0
while (openList.isNotEmpty()) {
i++
val candidate = openList.poll()
if (candidate.IState.isGoal) {
yield(candidate)
} else {
candidate.move()
.filterNot { it.IState in closedList }
.forEach {
openList.add(it)
closedList.add(it.IState)
}
}
}
}
data class PathfinderState(
val IState: IState,
val cost: Int,
val expectedCost: Int
) {
fun move(): Sequence<PathfinderState> = IState.getNeighbors()
.map {
copy(IState = it, cost = cost + 1, expectedCost = cost + 1 + it.heuristic)
}
} | 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 1,814 | advent-of-code | MIT License |
AoC2021day12-PassagePathing/src/main/kotlin/Main.kt | mcrispim | 533,770,397 | false | {"Kotlin": 29888} | import java.io.File
val ways = mutableMapOf<String, MutableList<String>>()
fun main() {
val input = File("data.txt").readLines()
for (line in input) {
val (start, end) = line.split("-")
ways.getOrPut(start) { mutableListOf() }.add(end)
ways.getOrPut(end) { mutableListOf() }.add(start)
}
val allPathways1 = searchPathways1()
println("If you can only enter a little cave once, there are ${allPathways1.size} pathways from start to end.")
val allPathways2 = searchPathways2()
println("If you can enter one little cave twice, there are ${allPathways2.size} pathways from start to end.")
}
fun searchPathways1(): MutableList<MutableList<String>> {
val validPathways = mutableListOf<MutableList<String>>()
val pathsToSearch = mutableListOf(mutableListOf("start"))
while (pathsToSearch.isNotEmpty()) {
val myPath = pathsToSearch.removeAt(0)
val myNode = myPath.last()
if (myNode == "end") {
validPathways.add(myPath)
continue
}
for (node in ways[myNode]!!) {
if (node.first().isLowerCase() && node in myPath) {
continue
}
val tempPath = myPath.toMutableList()
tempPath.add(node)
pathsToSearch.add(tempPath)
}
}
return validPathways
}
fun searchPathways2(): MutableList<MutableList<String>> {
val validPathways = mutableListOf<MutableList<String>>()
val pathsToSearch = mutableListOf<MutableList<String>>(mutableListOf("start"))
while (pathsToSearch.isNotEmpty()) {
val myPath = pathsToSearch.removeAt(0)
val myNode = myPath.last()
if (myNode == "end") {
validPathways.add(myPath)
continue
}
val lastNode = if (myNode.startsWith('_')) myNode.drop(1) else myNode
for (node in ways[lastNode]!!) {
var n = node
if (node == "start") {
continue
}
if (node.first().isLowerCase() && node in myPath) {
if ("_$node" in myPath) {
continue
} else {
n = "_$node"
}
}
val tempPath = myPath.toMutableList()
tempPath.add(n)
if (!isValidPath(tempPath)) {
continue
}
pathsToSearch.add(tempPath)
}
}
return validPathways
}
fun isValidPath(path: List<String>) = path.filter { it.startsWith('_') }.count() <= 1
| 0 | Kotlin | 0 | 0 | ac4aa71c9b5955fa4077ae40fc7e3fc3d5242523 | 2,555 | AoC2021 | MIT License |
src/advent/of/code/FourthPuzzle.kt | 1nco | 725,911,911 | false | {"Kotlin": 112713, "Shell": 103} | package advent.of.code
class FourthPuzzle {
companion object {
private val day = "4";
private var input: MutableList<String> = arrayListOf();
private var sum = 0;
private var sumSecond = 0;
fun solve() {
input.addAll(Reader.readInput(day));
input.forEach { line ->
processScratchCardFirst(line);
processScratchCardSecond(line);
}
System.out.println("firstSum: " + sum);
System.out.println("secondSum: " + sumSecond);
}
private fun processScratchCardFirst(line: String) {
var numbers = line.split(":")[1].split("|")
var winningNumbers = numbers[0].split(" ").filter { it -> !it.equals("") };
var myNumbers = numbers[1].split(" ").filter { it -> !it.equals("") };
var points = 0;
winningNumbers.forEach { winningNumber ->
myNumbers.forEach { myNumber ->
if (Integer.parseInt(winningNumber.trim()) == Integer.parseInt(myNumber.trim())) {
if (points == 0) {
points = 1;
} else {
points = points * 2
}
}
}
}
sum += points;
}
private fun getScratchCard(num: Int): String {
return input.get(num - 1);
}
private fun processScratchCardSecond(line: String) {
var cardNum = Integer.parseInt(line.split(":")[0].replace("Card ", "").trim())
var numbers = line.split(":")[1].split("|")
var winningNumbers = numbers[0].split(" ").filter { it -> !it.equals("") };
var myNumbers = numbers[1].split(" ").filter { it -> !it.equals("") };
var winnerNumberCount = 0;
winningNumbers.forEach { winningNumber ->
myNumbers.forEach { myNumber ->
if (Integer.parseInt(winningNumber.trim()) == Integer.parseInt(myNumber.trim())) {
winnerNumberCount++;
}
}
}
sumSecond++;
var listOfWinnings = arrayListOf<String>()
var i = 1;
while (i <= winnerNumberCount) {
listOfWinnings.add(getScratchCard(cardNum + i));
i++;
}
if (!listOfWinnings.isEmpty()) {
listOfWinnings.forEach { winning ->
processScratchCardSecond(winning);
}
}
}
// private fun processScratchCard(line: String): List<String> {
// var cardNum = Integer.parseInt(line.split(":")[0].replace("Card ", ""))
// var numbers = line.split(":")[1].split("|")
// var winningNumbers = numbers[0].split(" ").filter { it -> !it.equals("") };
// var myNumbers = numbers[1].split(" ").filter { it -> !it.equals("") };
//
// var winnerNumberCount = 0;
//
// winningNumbers.forEach { winningNumber ->
// myNumbers.forEach { myNumber ->
// if (Integer.parseInt(winningNumber.trim()) == Integer.parseInt(myNumber.trim())) {
// winnerNumberCount++;
// }
// }
// }
//
// var listOfWinnings = arrayListOf<String>()
//
// var i = 1;
// while (i <= winnerNumberCount) {
// listOfWinnings.add(getScratchCard(cardNum + i));
// i++;
// }
//
// sum++;
// return listOfWinnings;
// }
}
} | 0 | Kotlin | 0 | 0 | 0dffdeba1ebe0b44d24f94895f16f0f21ac8b7a3 | 3,723 | advent-of-code | Apache License 2.0 |
app/src/main/kotlin/com/github/ilikeyourhat/kudoku/solving/deduction/algorithm/HiddenValuesAlgorithm.kt | ILikeYourHat | 139,063,649 | false | {"Kotlin": 166134} | package com.github.ilikeyourhat.kudoku.solving.deduction.algorithm
import com.github.ilikeyourhat.kudoku.model.Region
import com.github.ilikeyourhat.kudoku.model.hint.SudokuHintGrid
import com.github.ilikeyourhat.kudoku.solving.deduction.combinations.CollectionCombinator
import java.util.Collections
class HiddenValuesAlgorithm(
regions: List<Region>,
possibilities: SudokuHintGrid,
private val size: Int
) : DeductionAlgorithm(regions, possibilities) {
class Factory(private val size: Int) : DeductionAlgorithm.Factory {
override fun instance(regions: List<Region>, possibilities: SudokuHintGrid): HiddenValuesAlgorithm {
return HiddenValuesAlgorithm(regions, possibilities, size)
}
}
private val combinator = CollectionCombinator(size)
override fun solve(region: Region): Boolean {
var changed = false
val allHintValues = possibilities.forRegion(region)
combinator.iterate(allHintValues) { result ->
val values = result.toSet()
val fields = countFieldsThatContainsValues(region, values)
if (fields == size) {
changed = changed or removeAllOtherValues(region, values)
}
}
return changed
}
private fun countFieldsThatContainsValues(region: Region, values: Set<Int>): Int {
var sum = 0
for (field in region) {
val hints = possibilities.forField(field)
if (!Collections.disjoint(hints, values)) {
sum++
}
}
return sum
}
private fun removeAllOtherValues(region: Region, values: Set<Int>): Boolean {
var changed = false
for (field in region) {
val hints = possibilities.forField(field).toMutableSet()
val initialSize = hints.size
if (!Collections.disjoint(hints, values)) {
hints.removeIf { !values.contains(it) }
}
if (initialSize != hints.size) {
possibilities.replace(field, hints)
changed = true
}
}
return changed
}
}
| 1 | Kotlin | 0 | 0 | b234b2de2edb753844c88ea3cd573444675fc1cf | 2,143 | Kudoku | Apache License 2.0 |
src/main/kotlin/g1001_1100/s1039_minimum_score_triangulation_of_polygon/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1001_1100.s1039_minimum_score_triangulation_of_polygon
// #Medium #Array #Dynamic_Programming #2023_05_26_Time_147_ms_(100.00%)_Space_38.9_MB_(50.00%)
class Solution {
private val dp = Array(101) { IntArray(101) }
fun minScoreTriangulation(values: IntArray): Int {
val n = values.size
for (row: IntArray? in dp) {
row!!.fill(-1)
}
return util(values, 1, n - 1)
}
private fun util(values: IntArray, i: Int, j: Int): Int {
if (i >= j) {
return 0
}
if (dp[i][j] != -1) {
return dp[i][j]
}
var ans = Int.MAX_VALUE
for (k in i until j) {
val temp = (
util(values, i, k) +
util(values, k + 1, j) +
(values[i - 1] * values[k] * values[j])
)
ans = ans.coerceAtMost(temp)
dp[i][j] = ans
}
return dp[i][j]
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 972 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/tr/emreone/adventofcode/days/Day12.kt | EmRe-One | 726,902,443 | false | {"Kotlin": 95869, "Python": 18319} | package tr.emreone.adventofcode.days
import tr.emreone.adventofcode.CacheSupport.withCaching
import tr.emreone.kotlin_utils.automation.Day
class Day12 : Day(12, 2023, "Hot Springs") {
data class State(
val charIndex: Int,
val lastGroupIndex: Int,
val lastGroupSize: Int,
val isGroupActive: Boolean
) {
fun nextState(inGroup: Boolean): State {
return copy(
charIndex = charIndex + 1,
lastGroupIndex = if (!isGroupActive && inGroup) lastGroupIndex + 1 else lastGroupIndex,
lastGroupSize = if (!isGroupActive && inGroup) 1 else if (inGroup) lastGroupSize + 1 else lastGroupSize,
isGroupActive = inGroup
)
}
}
class SpringCondition(row: String, factor: Int = 1) {
val spring: String
val groups: List<Int>
companion object {
const val UNKNOWN_STATE = '?'
const val WORKKING_STATE = '#'
const val EMPTY = '.'
}
init {
val (a, b) = row.split(" ").take(2)
val springList = mutableListOf<String>()
val groupList = mutableListOf<Int>()
if (factor > 0) {
for (i in 0 until factor) {
springList.add(a)
groupList.addAll(b.split(",").map { it.toInt() })
}
}
this.spring = springList.joinToString("?")
this.groups = groupList.toList()
}
fun possibleArrangements(): Long {
return process(
state = State(
charIndex = 0,
lastGroupIndex = -1,
lastGroupSize = 0,
isGroupActive = false
)
)
}
private fun process(state: State): Long = withCaching(state) {
if (it.lastGroupIndex >= this.groups.size) {
0L
}
else if (!it.isGroupActive && it.lastGroupSize < this.groups.getOrElse(it.lastGroupIndex, { 0 })) {
0L
}
else if (it.lastGroupSize > this.groups.getOrElse(it.lastGroupIndex, { 0 })) {
0L
}
else if (it.charIndex == this.spring.length) {
// Check for completeness
if (it.lastGroupSize == this.groups.getOrElse(it.lastGroupIndex, { 0 })
&& it.lastGroupIndex == this.groups.size - 1
) {
1L
}
else {
0L
}
}
else {
var total = 0L
when (this.spring[it.charIndex]) {
UNKNOWN_STATE -> {
// Wildcard, process both options
total += process(state = it.nextState(inGroup = false))
total += process(state = it.nextState(inGroup = true))
}
EMPTY -> {
// Finish group if possible
total += process(state = it.nextState(inGroup = false))
}
WORKKING_STATE -> {
// Increase group count
total += process(state = it.nextState(inGroup = true))
}
}
total
}
}
}
override fun part1(): Long {
return inputAsList.sumOf {
SpringCondition(it).possibleArrangements()
}
}
override fun part2(): Long {
return inputAsList.sumOf {
SpringCondition(it, 5).possibleArrangements()
}
}
}
| 0 | Kotlin | 0 | 0 | c75d17635baffea50b6401dc653cc24f5c594a2b | 3,769 | advent-of-code-2023 | Apache License 2.0 |
src/test/kotlin/be/brammeerten/y2022/Day7Test.kt | BramMeerten | 572,879,653 | false | {"Kotlin": 170522} | package be.brammeerten.y2022
import be.brammeerten.readFile
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
import kotlin.math.min
class Day7Test {
@Test
fun `part 1`() {
val root1 = readDirectory("2022/day7/exampleInput.txt")
Assertions.assertEquals(95437, root1.getLimitedSize(100000))
}
@Test
fun `part 2`() {
val root = readDirectory("2022/day7/exampleInput.txt")
val extraSpaceNeeded = 30000000 - (70000000 - root.totalSize())
Assertions.assertEquals(24933642, root.findSmallestDirectoryWithMinimumSpace(extraSpaceNeeded))
}
private fun readDirectory(file: String): Dir {
val root = Dir("/")
val regex = Regex("^(\\d+) (.+)$")
val lines = readFile(file)
var dir = root
for (line in lines.drop(1)) {
if (line.startsWith("$ cd ..")) {
dir = dir.parent!!
} else if (line.startsWith("$ cd ")) {
dir = dir.addDir(line.drop("$ cd ".length))
} else if (regex.matches(line)) {
val result = regex.find(line)
dir.addFile(result!!.groupValues[2], result.groupValues[1].toInt())
}
}
return root
}
class Dir(
val name: String, val parent: Dir? = null,
val subDirs: HashMap<String, Dir> = HashMap(),
var files: HashMap<String, Int> = HashMap()
) {
fun addDir(name: String): Dir {
val newDir = Dir(name, this)
return subDirs.putIfAbsent(name, newDir) ?: newDir
}
fun addFile(name: String, value: Int) {
files.putIfAbsent(name, value)
}
fun totalSize(): Int {
return files.values.sum() + subDirs.values.sumOf { it.totalSize() }
}
fun getLimitedSize(limit: Int): Int {
val total = totalSize()
val value = if (total < limit) total else 0
return value + subDirs.values.sumOf { it.getLimitedSize(limit) }
}
fun findSmallestDirectoryWithMinimumSpace(minSpace: Int, maxSpace: Int = Int.MAX_VALUE): Int? {
val total = totalSize()
if (total < minSpace)
return null
val smallest = min(total, maxSpace)
return min(
subDirs.values
.mapNotNull { it.findSmallestDirectoryWithMinimumSpace(minSpace, smallest) }
.minOrNull() ?: Int.MAX_VALUE,
smallest)
}
}
} | 0 | Kotlin | 0 | 0 | 1defe58b8cbaaca17e41b87979c3107c3cb76de0 | 2,547 | Advent-of-Code | MIT License |
solutions/src/SeachMatrix.kt | JustAnotherSoftwareDeveloper | 139,743,481 | false | {"Kotlin": 305071, "Java": 14982} | /**
* https://leetcode.com/problems/search-a-2d-matrix/
*/
class SeachMatrix {
fun searchMatrix(matrix: Array<IntArray>, target: Int) : Boolean {
if (matrix.isEmpty()) {
return false;
}
val rowToSearch = searchColumn(matrix,target,0,matrix.lastIndex)
return binarySearch(array = matrix[rowToSearch], target = target, low = 0, high = matrix[rowToSearch].lastIndex)
}
private fun binarySearch(array: IntArray, target: Int,low: Int,high: Int) : Boolean {
if (low > high || array.isEmpty()) {
return false
}
val mid = (high-low)/2 + low
return when {
target == array[mid] -> true
target > array[mid] -> binarySearch(array,target,mid+1,high)
else -> binarySearch(array,target,low,mid-1)
}
}
private fun searchColumn(matrix: Array<IntArray>, target: Int, low: Int, high : Int) : Int {
if (high == low) {
return high
}
val mid = (high-low)/2 + low
return when {
target >= matrix[mid][0] && target <= matrix[mid][matrix[0].lastIndex] -> {
mid
}
target > matrix[mid][matrix[0].lastIndex] -> {
searchColumn(matrix,target,mid+1,high)
}
else -> {
searchColumn(matrix,target,low,mid)
}
}
}
} | 0 | Kotlin | 0 | 0 | fa4a9089be4af420a4ad51938a276657b2e4301f | 1,410 | leetcode-solutions | MIT License |
src/main/kotlin/co/csadev/advent2022/Day24.kt | gtcompscientist | 577,439,489 | false | {"Kotlin": 252918} | /**
* Copyright (c) 2022 by <NAME>
* Advent of Code 2022, Day 24
* Problem Description: http://adventofcode.com/2021/day/24
*/
package co.csadev.advent2022
import co.csadev.adventOfCode.BaseDay
import co.csadev.adventOfCode.Resources.resourceAsList
import java.util.*
class Day24(override val input: List<String> = resourceAsList("22day24.txt")) :
BaseDay<List<String>, Int, Int> {
private val height = input.size
private val width = input.first().length
private val gridRange = (0 until height).map { y -> (0 until width).map { x -> y to x } }.flatten().toSet()
private var blizzardMaps: MutableMap<Int, MutableSet<Pair<Int, Int>>> = mutableMapOf()
private val entryX = input[0].indexOfFirst { it != '#' }
private val endX = input[height - 1].indexOfLast { it != '#' }
// Cache the maps and generate them on demand
private fun Int.map(): MutableSet<Pair<Int, Int>> {
return blizzardMaps.getOrPut(this) {
val newBlizzard = mutableSetOf<Pair<Int, Int>>()
gridRange.map { (y, x) ->
val newPoint = when (input[y][x]) {
'>' -> y to 1 + ((x - 1 + this).mod(width - 2))
'<' -> y to 1 + ((x - 1 - this).mod(width - 2))
'v' -> 1 + ((y - 1 + this).mod(height - 2)) to x
'^' -> 1 + ((y - 1 - this).mod(height - 2)) to x
else -> null
}
newPoint?.let { newBlizzard.add(it) }
}
newBlizzard
}
}
private data class Hiking(val y: Int, val x: Int, val time: Int) {
fun withNeighbors(): Sequence<Hiking> =
listOf(this, copy(y = y + 1), copy(y = y - 1), copy(x = x + 1), copy(x = x - 1)).asSequence()
}
@Suppress("LoopWithTooManyJumpStatements")
private fun findPath(startTime: Int = 0, startX: Int = entryX, startY: Int = 0, goal: Int = height - 1): Int {
val hikingQueue = LinkedList<Hiking>()
hikingQueue.add(Hiking(startY, startX, startTime))
val knownHikers = mutableSetOf<Hiking>()
var currBlizzard: MutableSet<Pair<Int, Int>>
while (hikingQueue.size > 0) {
var (y, x, time) = hikingQueue.poll()
if (y to x !in gridRange || input[y][x] == '#') continue
if (y == goal) return time
val newHiker = Hiking(y, x, time)
if (!knownHikers.add(newHiker)) continue
time += 1
currBlizzard = time.map()
newHiker.copy(time = time).withNeighbors().filter { it.y to it.x !in currBlizzard }.forEach { hikingQueue.add(it) }
}
return Int.MIN_VALUE
}
private var firstSearchTime: Int? = null
override fun solvePart1() = findPath().also { firstSearchTime = it }
override fun solvePart2() = findPath(findPath(firstSearchTime ?: findPath(), endX, height - 2, 0))
}
| 0 | Kotlin | 0 | 1 | 43cbaac4e8b0a53e8aaae0f67dfc4395080e1383 | 2,909 | advent-of-kotlin | Apache License 2.0 |
Course_Schedule_II_v1.kt | xiekch | 166,329,519 | false | {"C++": 165148, "Java": 103273, "Kotlin": 97031, "Go": 40017, "Python": 22302, "TypeScript": 17514, "Swift": 6748, "Rust": 6579, "JavaScript": 4244, "Makefile": 349} | // Given the total number of courses and a list of prerequisite pairs,
// return the ordering of courses you should take to finish all courses.
class Solution {
fun findOrder(numCourses: Int, prerequisites: Array<IntArray>): IntArray {
val res = ArrayList<Int>()
val indegree = IntArray(numCourses)
val edges = ArrayList<ArrayList<Int>>()
for (i in 1..numCourses) {
edges.add(ArrayList())
}
// println(edges.size)
for (pre in prerequisites) {
edges[pre[1]].add(pre[0])
indegree[pre[0]]++
}
var finished = false
while (!finished) {
finished = true
for (i in 0 until numCourses) {
if (indegree[i] == 0) {
res.add(i)
finished = false
for (e in edges[i]) {
indegree[e]--
}
indegree[i] = -1
break
}
}
}
return if (res.size == numCourses) res.toIntArray() else IntArray(0)
}
}
fun main(args: Array<String>) {
val solution = Solution()
val testset = arrayOf(
arrayOf(
intArrayOf(1, 0)
),
arrayOf(
intArrayOf(1, 0),
intArrayOf(2, 0),
intArrayOf(3, 1),
intArrayOf(3, 2)
),
arrayOf(
intArrayOf(1, 0),
intArrayOf(0, 1)
)
)
val nums = intArrayOf(2, 4, 2)
for (i in testset.indices) {
solution.findOrder(nums[i], testset[i]).forEach { print("%d ".format(it)) }
println()
}
} | 0 | C++ | 0 | 0 | eb5b6814e8ba0847f0b36aec9ab63bcf1bbbc134 | 1,688 | leetcode | MIT License |
src/Day14.kt | RobvanderMost-TomTom | 572,005,233 | false | {"Kotlin": 47682} | enum class Material(val char: Char) {
SAND('o'),
ROCK('#'),
AIR('.')
}
// Cave type. Index of Map is x coordinate, index in each List is y coordinate
typealias CaveMap = MutableMap<Int, MutableList<Material>>
fun main() {
fun CaveMap.print() {
println()
val maxDepth = values.maxOf { it.lastIndex }
val sorted = this.toSortedMap()
for (y in 0..maxDepth) {
sorted.values.forEach {
print((it.getOrNull(y) ?: Material.AIR).char)
}
println()
}
}
fun readCaveMap(input: List<String>): CaveMap {
val caveMap = mutableMapOf<Int, MutableList<Material>>()
fun drawRockVertical(start: Pair<Int, Int>, end: Pair<Int, Int>) {
val x = start.first
val y1 = minOf(start.second, end.second)
val y2 = maxOf(start.second, end.second)
val col = caveMap.getOrPut(x, ::mutableListOf)
if (col.lastIndex < y2) {
for (y in col.size..y2) {
col.add(Material.AIR)
}
}
for (y in y1..y2) {
col[y] = Material.ROCK
}
}
fun drawRockHorizontal(start: Pair<Int, Int>, end: Pair<Int, Int>) {
val x1 = minOf(start.first, end.first)
val x2 = maxOf(start.first, end.first)
val y = start.second
for (x in x1..x2) {
val col = caveMap.getOrPut(x, ::mutableListOf)
if (col.lastIndex < y) {
for (y in col.size..y) {
col.add(Material.AIR)
}
}
col[y] = Material.ROCK
}
}
fun drawRock(start: Pair<Int, Int>, end: Pair<Int, Int>) =
if (start.first == end.first) {
drawRockVertical(start, end)
} else if (start.second == end.second) {
drawRockHorizontal(start, end)
} else {
throw RuntimeException("Cannot draw diagonal rock!")
}
input.map { line ->
line.split(" -> ")
.map { pair ->
pair.split(",").map { it.toInt() }
}.map {
it[0] to it[1]
}
}.forEach { coords ->
coords.windowed(2, 1).forEach {
drawRock(it.first(), it.last())
}
}
return caveMap
}
fun CaveMap.dropSand(getCol: (x: Int) -> MutableList<Material>?): Boolean {
var x = 500
var y = 0
while (true) {
val col = getCol(x) ?: return false // No material here, falling into abyss
if (col[y] != Material.AIR) {
return false
}
val airBelow = col.drop(y).indexOfFirst { it != Material.AIR }
if (airBelow > 1) {
y += airBelow - 1
continue
}
val leftCol = getCol(x - 1) ?: return false // No material to the left, abyss
if (leftCol.lastIndex < y + 1) {
// No rock below on the left side, fall into abyss
return false
} else if (leftCol[y + 1] == Material.AIR) {
x--
y++
continue
}
val rightCol = getCol(x + 1) ?: return false // No material to the right, abyss
if (rightCol.lastIndex < y + 1) {
// No rock below on the right side, fall into abyss
return false
} else if (rightCol[y + 1] == Material.AIR) {
x++
y++
continue
}
// Cannot fall further
col[y] = Material.SAND
return true
}
}
fun part1(input: List<String>): Int {
val caveMap = readCaveMap(input)
caveMap.print()
var count = 0
while (caveMap.dropSand { caveMap[it] }) {
count++
}
caveMap.print()
return count
}
fun CaveMap.addFloor() {
val floorDepth = values.maxOf { it.lastIndex } + 2
values.forEach {
for (y in it.size until floorDepth) {
it.add(Material.AIR)
}
it.add(Material.ROCK)
}
}
fun CaveMap.getOrExtendFloor(index: Int) =
getOrPut(index) {
val floorDepth = values.first().lastIndex
buildList(floorDepth + 1) {
for (y in 0 until floorDepth) {
add(Material.AIR)
}
add(Material.ROCK)
}.toMutableList()
}
fun part2(input: List<String>): Int {
val caveMap = readCaveMap(input)
caveMap.addFloor()
caveMap.print()
var count = 0
while (caveMap.dropSand { caveMap.getOrExtendFloor(it) }) {
count++
}
caveMap.print()
return count
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day14_test")
check(part1(testInput) == 24)
check(part2(testInput) == 93)
val input = readInput("Day14")
check(part1(input) == 1330)
println(part2(input))
}
| 5 | Kotlin | 0 | 0 | b7143bceddae5744d24590e2fe330f4e4ba6d81c | 5,316 | advent-of-code-2022 | Apache License 2.0 |
src/Day03.kt | AlaricLightin | 572,897,551 | false | {"Kotlin": 87366} | fun main() {
fun getPriority(c: Char): Int {
return if (c in 'A'..'Z')
c - 'A' + 27
else
c - 'a' + 1
}
fun part1(inputFilename: String): Int {
var result = 0
getInputFile(inputFilename).forEachLine {
val set = mutableSetOf<Char>()
val length = it.length
val half = it.length / 2
for(i in 0 until half)
set.add(it[i])
for(i in half until length) {
if (set.contains(it[i])) {
result += getPriority(it[i])
break
}
}
}
return result
}
fun part2(inputFilename: String): Int {
var result = 0
val first = mutableSetOf<Char>()
val firstAndSecond = mutableSetOf<Char>()
readInput(inputFilename).forEachIndexed { index, s ->
when(index % 3) {
0 -> {
first.clear()
s.forEach { first.add(it) }
}
1 -> {
firstAndSecond.clear()
s
.filter { first.contains(it) }
.forEach { firstAndSecond.add(it) }
}
2 -> {
s.forEach {
if (firstAndSecond.contains(it)) {
result += getPriority(it)
return@forEachIndexed
}
}
}
}
}
return result
}
check(part1("Day03_test") == 157)
check(part2("Day03_test") == 70)
println(part1("Day03"))
println(part2("Day03"))
} | 0 | Kotlin | 0 | 0 | ee991f6932b038ce5e96739855df7807c6e06258 | 1,747 | AdventOfCode2022 | Apache License 2.0 |
src/leetcodeProblem/leetcode/editor/en/MinStack.kt | faniabdullah | 382,893,751 | false | null | //Design a stack that supports push, pop, top, and retrieving the minimum
//element in constant time.
//
// Implement the MinStack class:
//
//
// MinStack() initializes the stack object.
// void push(int val) pushes the element val onto the stack.
// void pop() removes the element on the top of the stack.
// int top() gets the top element of the stack.
// int getMin() retrieves the minimum element in the stack.
//
//
//
// Example 1:
//
//
//Input
//["MinStack","push","push","push","getMin","pop","top","getMin"]
//[[],[-2],[0],[-3],[],[],[],[]]
//
//Output
//[null,null,null,null,-3,null,0,-2]
//
//Explanation
//MinStack minStack = new MinStack();
//minStack.push(-2);
//minStack.push(0);
//minStack.push(-3);
//minStack.getMin(); // return -3
//minStack.pop();
//minStack.top(); // return 0
//minStack.getMin(); // return -2
//
//
//
// Constraints:
//
//
// -2³¹ <= val <= 2³¹ - 1
// Methods pop, top and getMin operations will always be called on non-empty
//stacks.
// At most 3 * 10⁴ calls will be made to push, pop, top, and getMin.
//
// Related Topics Stack Design 👍 6128 👎 538
package leetcodeProblem.leetcode.editor.en
import java.util.*
class MinStack {
fun solution() {
}
//below code will be used for submission to leetcode (using plugin of course)
//leetcode submit region begin(Prohibit modification and deletion)
class MinStack() {
private val stack = Stack<Int>()
private val minStack = Stack<Int>()
fun push(x: Int) {
stack.push(x)
if (minStack.empty() || x <= minStack.peek()) {
minStack.push(x)
}
}
fun pop() {
val el = stack.pop()
if (!minStack.empty() && el == minStack.peek()) {
minStack.pop()
}
}
fun top(): Int {
return stack.peek()
}
fun getMin(): Int {
return minStack.peek()
}
}
/**
* Your MinStack object will be instantiated and called as such:
* var obj = MinStack()
* obj.push(`val`)
* obj.pop()
* var param_3 = obj.top()
* var param_4 = obj.getMin()
*/
//leetcode submit region end(Prohibit modification and deletion)
}
fun main() {}
| 0 | Kotlin | 0 | 6 | ecf14fe132824e944818fda1123f1c7796c30532 | 2,300 | dsa-kotlin | MIT License |
src/main/kotlin/com/github/davio/aoc/y2022/Day7.kt | Davio | 317,510,947 | false | {"Kotlin": 405939} | package com.github.davio.aoc.y2022
import com.github.davio.aoc.general.Day
import com.github.davio.aoc.general.getInputAsSequence
import kotlin.system.measureTimeMillis
fun main() {
println(Day7.getResultPart1())
measureTimeMillis {
println(Day7.getResultPart2())
}.also { println("Took $it ms") }
}
/**
* See [Advent of Code 2022 Day 7](https://adventofcode.com/2022/day/7#part2])
*/
object Day7 : Day() {
private sealed interface TerminalOutput
private sealed interface Command : TerminalOutput
private data class ChangeDirectory(val target: String) : Command
private object ListDirectory : Command
private sealed interface DirectoryOrFileOutput : TerminalOutput {
fun getTotalSize(): Long
}
private data class Directory(
val name: String,
var parent: Directory? = null,
val subdirectories: MutableList<Directory> = mutableListOf(),
val files: MutableList<File> = mutableListOf()
) : TerminalOutput, DirectoryOrFileOutput {
override fun getTotalSize(): Long = subdirectories.sumOf { it.getTotalSize() } + files.sumOf { it.getTotalSize() }
}
private data class File(val name: String, val size: Long) : TerminalOutput, DirectoryOrFileOutput {
override fun getTotalSize() = size
}
fun getResultPart1() {
val root = Directory(name = "/")
var currentWorkingDirectory = root
getInputAsSequence().drop(1).map {
parseTerminalOutput(it)
}.forEach {
currentWorkingDirectory = processTerminalOutput(it, currentWorkingDirectory)
}
recursiveVisit(root, { dir -> dir.getTotalSize() < 100000L }, 0L, { it.getTotalSize() }) { left, right ->
left + right
}
}
fun getResultPart2() {
val root = Directory(name = "/")
var currentWorkingDirectory = root
getInputAsSequence().drop(1).map {
parseTerminalOutput(it)
}.forEach {
currentWorkingDirectory = processTerminalOutput(it, currentWorkingDirectory)
}
val totalDiskSpace = 70000000L
val freeSpaceNeeded = 30000000L
val totalSpaceUsed = root.getTotalSize()
val unusedSpace = totalDiskSpace - totalSpaceUsed
val spaceToFree = freeSpaceNeeded - unusedSpace
recursiveVisit(root, { dir -> dir.getTotalSize() >= spaceToFree }, Long.MAX_VALUE, { it.getTotalSize() }) { left, right ->
minOf(left, right)
}
}
private fun processTerminalOutput(
terminalOutput: TerminalOutput,
currentWorkingDirectory: Directory
): Directory {
when (terminalOutput) {
is ChangeDirectory -> {
return if (terminalOutput.target == "..") {
currentWorkingDirectory.parent!!
} else {
currentWorkingDirectory.subdirectories.first { subdir -> subdir.name == terminalOutput.target }
}
}
is ListDirectory -> {}
is Directory -> {
terminalOutput.parent = currentWorkingDirectory
currentWorkingDirectory.subdirectories.add(terminalOutput)
}
is File -> currentWorkingDirectory.files.add(terminalOutput)
}
return currentWorkingDirectory
}
private fun parseTerminalOutput(line: String): TerminalOutput {
if (line.startsWith("$")) {
return parseCommand(line.substringAfter("$ "))
}
return parseRegularOutput(line)
}
private fun parseCommand(commandLine: String) =
if (commandLine.startsWith("cd")) {
val parts = commandLine.split(" ")
ChangeDirectory(parts[1])
} else {
ListDirectory
}
private fun parseRegularOutput(line: String): DirectoryOrFileOutput {
return if (line.startsWith("dir")) {
Directory(line.substringAfter("dir "))
} else {
val parts = line.split(" ")
File(name = parts[1], size = parts[0].toLong())
}
}
private fun <T> recursiveVisit(
dir: Directory,
filter: (Directory) -> Boolean,
defaultValue: T,
operation: (Directory) -> T,
combinator: (T, T) -> T
): T {
var result = if (filter.invoke(dir)) operation.invoke(dir) else defaultValue
dir.subdirectories.forEach { subdir ->
result = combinator.invoke(result, recursiveVisit(subdir, filter, defaultValue, operation, combinator))
}
return result
}
}
| 1 | Kotlin | 0 | 0 | 4fafd2b0a88f2f54aa478570301ed55f9649d8f3 | 4,605 | advent-of-code | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/LongestAwesome.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
import kotlin.math.min
/**
* 1542. Find Longest Awesome Substring
* @see <a href="https://leetcode.com/problems/find-longest-awesome-substring/">Source</a>
*/
fun interface LongestAwesome {
operator fun invoke(s: String): Int
}
class LongestAwesomeImpl : LongestAwesome {
override operator fun invoke(s: String): Int {
val dp = IntArray(LIMIT) { s.length }
var res = 0
var mask = 0
dp[0] = -1
for (i in s.indices) {
val ch = s[i]
mask = mask.xor(1 shl ch - '0')
res = max(res, i - dp[mask])
for (j in 0..9) {
res = max(res, i - dp[mask xor (1 shl j)])
}
dp[mask] = min(dp[mask], i)
}
return res
}
companion object {
private const val LIMIT = 1024
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,494 | kotlab | Apache License 2.0 |
src/ca/josue/taxipark/src/TaxiParkTask.kt | josue-lubaki | 428,923,506 | false | {"Kotlin": 171443} | package ca.josue.taxipark.src
/*
* Task #1. Find all the drivers who performed no trips.
*/
fun TaxiPark.findFakeDrivers(): Set<Driver> =
this.allDrivers.subtract(this.trips.map { it.driver }.toSet())
// this.allDrivers.filter {
// it !in trips.map { trip -> trip.driver }
// }.toSet()
// this.allDrivers.filter { driver ->
// this.trips.none { trip -> trip.driver == driver }
// }.toSet()
/*
* Task #2. Find all the clients who completed at least the given number of trips.
*/
fun TaxiPark.findFaithfulPassengers(minTrips: Int): Set<Passenger> =
this.allPassengers.filter {
this.trips.count { trip -> it in trip.passengers } >= minTrips
}.toSet()
/*
* Task #3. Find all the passengers, who were taken by a given driver more than once.
*/
fun TaxiPark.findFrequentPassengers(driver: Driver): Set<Passenger> =
this.allPassengers.filter {
this.trips.count { trip ->
it in trip.passengers && trip.driver == driver
} > 1
}.toSet()
// this.allPassengers.filter {
// passager -> this.trips.filter {
// trip -> passager in trip.passengers && trip.driver == driver
// }.count() > 1
// }.toSet()
/*
* Task #4. Find the passengers who had a discount for majority of their trips.
*/
fun TaxiPark.findSmartPassengers(): Set<Passenger> =
this.allPassengers.filter {
this.trips.count { trip -> it in trip.passengers && trip.discount != null } >
this.trips.count { trip -> it in trip.passengers && trip.discount == null }
}.toSet()
/*
* Task #5. Find the most frequent trip duration among minute periods 0..9, 10..19, 20..29, and so on.
* Return any period if many are the most frequent, return `null` if there're no trips.
*/
fun TaxiPark.findTheMostFrequentTripDurationPeriod(): IntRange? {
if(this.trips.isEmpty())
return null
val maxDurationAllTrip = this.trips.maxOfOrNull { it.duration } ?: 0
val result = HashMap<Int, IntRange>()
for (i in 0..maxDurationAllTrip step 10){
// Actual Range
val range = IntRange(i, i + 9)
//count of trip by Range
val numberTripByRange = this.trips.count{ it.duration in range }
result[numberTripByRange] = range
}
return result.maxByOrNull { it.key }?.value
}
/*
* Task #6.
* Check whether 20% of the drivers contribute 80% of the income.
*/
fun TaxiPark.checkParetoPrinciple(): Boolean {
return if (this.trips.isNotEmpty())
this.trips
.map{it.driver to it.cost}
.groupBy{it.first}
.mapValues { it.value.sumOf { pair -> pair.second } }
.values
.sortedDescending()
.take((this.allDrivers.size * 0.2).toInt())
.sum() >= this.trips.map { it.cost }.sum() * 0.8
else false
}
| 0 | Kotlin | 0 | 1 | 847f7af8ba9b5712241c36ca3979e4195766b9ab | 2,848 | TaxiPark | Apache License 2.0 |
year2022/src/main/kotlin/net/olegg/aoc/year2022/day12/Day12.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2022.day12
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.utils.Directions.Companion.NEXT_4
import net.olegg.aoc.utils.Vector2D
import net.olegg.aoc.utils.fit
import net.olegg.aoc.utils.get
import net.olegg.aoc.utils.set
import net.olegg.aoc.year2022.DayOf2022
/**
* See [Year 2022, Day 12](https://adventofcode.com/2022/day/12)
*/
object Day12 : DayOf2022(12) {
override fun first(): Any? {
val map = matrix.map { it.toMutableList() }
val from = map.mapIndexedNotNull { y, row ->
row.mapIndexedNotNull { x, char ->
if (char == 'S') Vector2D(x, y) else null
}.firstOrNull()
}.first()
map[from] = 'a'
val to = map.mapIndexedNotNull { y, row ->
row.mapIndexedNotNull { x, char ->
if (char == 'E') Vector2D(x, y) else null
}.firstOrNull()
}.first()
map[to] = 'z'
val visited = mutableSetOf<Vector2D>()
val queue = ArrayDeque(listOf(from to 0))
while (queue.isNotEmpty()) {
val (curr, step) = queue.removeFirst()
if (curr == to) {
return step
}
if (curr in visited) {
continue
}
visited += curr
queue += NEXT_4.map { curr + it.step }
.filter { map.fit(it) }
.filter { it !in visited }
.filter { map[it]!! - map[curr]!! <= 1 }
.map { it to step + 1 }
}
return null
}
override fun second(): Any? {
val map = matrix.map { it.toMutableList() }
val from = map.mapIndexedNotNull { y, row ->
row.mapIndexedNotNull { x, char ->
if (char == 'S') Vector2D(x, y) else null
}.firstOrNull()
}.first()
map[from] = 'a'
val to = map.mapIndexedNotNull { y, row ->
row.mapIndexedNotNull { x, char ->
if (char == 'E') Vector2D(x, y) else null
}.firstOrNull()
}.first()
map[to] = 'z'
val visited = mutableSetOf<Vector2D>()
val queue = ArrayDeque(listOf(to to 0))
while (queue.isNotEmpty()) {
val (curr, step) = queue.removeFirst()
if (map[curr] == 'a') {
return step
}
if (curr in visited) {
continue
}
visited += curr
queue += NEXT_4.map { curr + it.step }
.filter { map.fit(it) }
.filter { it !in visited }
.filter { map[it]!! - map[curr]!! >= -1 }
.map { it to step + 1 }
}
return null
}
}
fun main() = SomeDay.mainify(Day12)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 2,422 | adventofcode | MIT License |
src/main/kotlin/com/leetcode/random_problems/easy/substract_product_and_sum/Main.kt | frikit | 254,842,734 | false | null | package com.leetcode.random_problems.easy.substract_product_and_sum
fun main() {
println("SOLUTION 1")
println("Test case 1:")
println(Solution().subtractProductAndSum(234)) // 15
println()
println("Test case 2:")
println(Solution().subtractProductAndSum(4421)) // 21
println()
println("SOLUTION 2")
println("Test case 1:")
println(Solution2().subtractProductAndSum(234)) // 15
println()
println("Test case 2:")
println(Solution2().subtractProductAndSum(4421)) // 21
println()
}
class Solution {
fun subtractProductAndSum(n: Int): Int {
val numbers = n.toString().toCharArray().map { it.toString().toInt() }
var product = 1
var sum = 0
numbers.forEach { num ->
product *= num
sum += num
}
return product - sum
}
}
class Solution2 {
fun subtractProductAndSum(n: Int): Int {
val numbers = n.toString().toCharArray().map { it.toString().toInt() }
val product = numbers.reduce { acc, i -> acc * i }
val sum = numbers.sum()
return product - sum
}
}
| 0 | Kotlin | 0 | 0 | dda68313ba468163386239ab07f4d993f80783c7 | 1,130 | leet-code-problems | Apache License 2.0 |
src/day9/Day9.kt | gautemo | 317,316,447 | false | null | package day9
import shared.getLines
fun xmasWeakness(numbers: List<Long>, preamble: Int = 25): Long{
for(i in preamble until numbers.size){
val toCheck = allPairs(numbers.take(i).takeLast(preamble))
val valid = toCheck.any { it.first + it.second == numbers[i] }
if(!valid) return numbers[i]
}
return -1
}
fun allPairs(numbers: List<Long>): List<Pair<Long, Long>>{
val pairs = mutableListOf<Pair<Long, Long>>()
for(number1 in numbers){
for(number2 in numbers){
if(number1 != number2 && !pairs.any { (it.first == number1 && it.second == number2) || (it.first == number2 && it.second == number1) }){
pairs.add(Pair(number1, number2))
}
}
}
return pairs
}
fun xmasWeaknessPart2(numbers: List<Long>, preamble: Int = 25): Long{
val weaknessNr = xmasWeakness(numbers, preamble)
for(i in numbers.indices){
for(j in i + 1 until numbers.size){
val toCheck = numbers.subList(i, j)
if(toCheck.sum() == weaknessNr){
return toCheck.min()!! + toCheck.max()!!
}else if(toCheck.sum() > weaknessNr){
break
}
}
}
return -1
}
fun main(){
val numbers = getLines("day9.txt").map { it.toLong() }
val weakness = xmasWeakness(numbers)
println(weakness)
val weakness2 = xmasWeaknessPart2(numbers)
println(weakness2)
} | 0 | Kotlin | 0 | 0 | ce25b091366574a130fa3d6abd3e538a414cdc3b | 1,436 | AdventOfCode2020 | MIT License |
src/main/kotlin/dev/austinzhu/algods/containers/util/TreePrinter.kt | AustinZhu | 287,033,539 | false | null | package dev.austinzhu.algods.containers.util
import dev.austinzhu.algods.containers.tree.AbstractBinaryTree
import dev.austinzhu.algods.containers.tree.Tree
import kotlin.math.max
interface TreePrinter<N : Tree.Node<*, *, N>> {
override fun toString(): String
fun MutableList<TreeLine>.getWidth(): Int {
val topLine = this.firstOrNull() ?: return 0
return topLine.lIndent + topLine.line.length + topLine.rIndent
}
fun MutableList<TreeLine>.halfWidths(): Pair<Int, Int> {
val topLine = this.firstOrNull() ?: return 0 to 0
val leftWidth = topLine.lIndent + (topLine.line.length) / 2
val rightWidth = topLine.rIndent + (topLine.line.length - 1) / 2
return leftWidth to rightWidth
}
fun TreeLine.halfBodyWidths(): Pair<Int, Int> {
val leftWidth = (this.line.length) / 2
val rightWidth = (this.line.length - 1) / 2
return leftWidth to rightWidth
}
fun buildRootLine(
root: String,
fst: MutableList<TreeLine>,
leftWidth: Int,
snd: MutableList<TreeLine>,
rightWidth: Int
): TreeLine {
val rootLineFst = (root.length) / 2
val rootLineSnd = (root.length - 1) / 2
val lIndent: Int
val rIndent: Int
// if the root line take more space than the merged tree lines
if (rootLineFst - leftWidth <= 0) {
lIndent = leftWidth - rootLineFst
} else {
lIndent = 0
val excessIndent = rootLineFst - leftWidth
fst.forEach { it.lIndent += excessIndent }
}
if (rootLineSnd - rightWidth <= 0) {
rIndent = rightWidth - rootLineSnd
} else {
rIndent = 0
val excessIndent = rootLineSnd - rightWidth
snd.forEach { it.rIndent += excessIndent }
}
return TreeLine(lIndent, StringBuilder(root), rIndent)
}
}
data class TreeLine(var lIndent: Int, val line: StringBuilder, var rIndent: Int) {
override fun toString(): String {
return StringBuilder().append(" ".repeat(lIndent)).append(line).append(" ".repeat(rIndent)).toString()
}
}
// Number of spaces that separates the nodes
const val SEP_LENGTH = 2
class NAryTreePrinter<N : Tree.Node<*, *, N>>(private val root: N?) : TreePrinter<N> {
private fun addRootLine(treeLines: MutableList<TreeLine>, root: String) {
val branchLine = treeLines.firstOrNull()
// modify the branch line
if (branchLine != null) {
val mid = branchLine.line.length / 2
when (branchLine.line[mid]) {
'─' -> branchLine.line[mid] = '┴'
'┬' -> branchLine.line[mid] = '┼'
else -> branchLine.line[mid] = '│'
}
}
val (leftWidth, rightWidth) = treeLines.halfWidths()
val rootLine = buildRootLine(root, treeLines, leftWidth, treeLines, rightWidth)
treeLines.add(0, rootLine)
}
private fun buildSingleBranchLine(line: TreeLine, isFirst: Boolean, isLast: Boolean): TreeLine {
val branchLine = TreeLine(0, StringBuilder(), 0)
var lIndent = line.lIndent
var rIndent = line.rIndent
val (fstHalf, sndHalf) = line.halfBodyWidths()
if (isFirst) {
lIndent += fstHalf
rIndent += sndHalf
branchLine.line.append('┌')
} else if (isLast) {
lIndent += fstHalf
rIndent += sndHalf
branchLine.line.append('┐')
} else {
branchLine.line.append("─".repeat(fstHalf)).append('┬').append("─".repeat(sndHalf))
}
return TreeLine(lIndent, branchLine.line, rIndent)
}
private fun mergeLines(fst: MutableList<TreeLine>, snd: MutableList<TreeLine>): MutableList<TreeLine> {
val result = mutableListOf<TreeLine>()
val fstWidth = fst.getWidth()
val sndWidth = snd.getWidth()
for (i in 0 until max(fst.size, snd.size)) {
val line1 = fst.getOrNull(i)
val line2 = snd.getOrNull(i)
if (line1 != null && line2 != null) {
val lineBody = StringBuilder(line1.line)
// if it is the branch line
if (i == 0) {
lineBody.append("─".repeat(line1.rIndent + SEP_LENGTH + line2.lIndent))
} else {
// add space between the lines for separation
lineBody.append(" ".repeat(line1.rIndent + SEP_LENGTH + line2.lIndent))
}
val both = TreeLine(
line1.lIndent,
lineBody.append(line2.line),
line2.rIndent
)
result.add(both)
} else if (line1 != null) {
// add indent to compensate for the separation space
result.add(TreeLine(line1.lIndent, line1.line, line1.rIndent + sndWidth + SEP_LENGTH))
} else if (line2 != null) {
result.add(TreeLine(line2.lIndent + fstWidth + SEP_LENGTH, line2.line, line2.rIndent))
}
}
return result
}
private fun mergeAll(childTreeLines: MutableList<MutableList<TreeLine>>): MutableList<TreeLine> {
if (childTreeLines.size == 0) {
return mutableListOf()
}
if (childTreeLines.size == 1) {
return childTreeLines.first()
}
val result = mutableListOf<TreeLine>()
val mid = childTreeLines.size / 2
val left = mergeAll(childTreeLines.subList(0, mid))
val right = mergeAll(childTreeLines.subList(mid, childTreeLines.size))
val treeLines = mergeLines(left, right)
result.addAll(treeLines)
return result
}
private fun printHelper(node: N?): MutableList<TreeLine> {
if (node == null) {
return mutableListOf()
}
val children = node.getChildren().filterNotNull()
val childrenLines = mutableListOf<MutableList<TreeLine>>()
for (i in children.indices) {
val childLines = printHelper(children[i])
val branchLine = buildSingleBranchLine(childLines[0], i == 0, i == children.size - 1)
childLines.add(0, branchLine)
childrenLines.add(childLines)
}
val result = mergeAll(childrenLines)
addRootLine(result, node.toString())
return result
}
override fun toString(): String {
val treeLines = printHelper(root)
val sb = StringBuilder()
treeLines.forEach {
sb.append(it).append("\n")
}
return sb.toString()
}
}
class BinaryTreePrinter<N : AbstractBinaryTree<*, *, N>.Node>(private val root: N?) : TreePrinter<N> {
private fun mergeSubTreeLine(left: MutableList<TreeLine>, right: MutableList<TreeLine>): MutableList<TreeLine> {
val result = mutableListOf<TreeLine>()
val width1 = left.getWidth()
val width2 = right.getWidth()
for (i in 0 until max(left.size, right.size)) {
val line1 = left.getOrNull(i)
val line2 = right.getOrNull(i)
if (line1 != null && line2 != null) {
val both = TreeLine(
line1.lIndent,
line1.line.append(" ".repeat(line1.rIndent + 1 + line2.lIndent)).append(line2.line),
line2.rIndent
)
result.add(both)
} else if (line1 != null) {
result.add(TreeLine(line1.lIndent, line1.line, line1.rIndent + width2 + 1))
} else if (line2 != null) {
result.add(TreeLine(line2.lIndent + width1 + 1, line2.line, line2.rIndent))
}
}
return result
}
private fun buildBranchLine(leftRootLine: TreeLine?, rightRootLine: TreeLine?): TreeLine {
if (leftRootLine == null && rightRootLine == null) {
return TreeLine(0, StringBuilder(), 0)
}
val branch = StringBuilder()
val lIndent: Int
val rIndent: Int
val rootChar: Char = if (leftRootLine != null && rightRootLine != null) {
'┴'
} else if (leftRootLine != null) {
'┘'
} else {
'└'
}
if (leftRootLine != null) {
val (fstHalfT1, sndHalfT1) = leftRootLine.halfBodyWidths()
lIndent = leftRootLine.lIndent + fstHalfT1
branch.append('┌').append("─".repeat(sndHalfT1 + leftRootLine.rIndent))
} else {
lIndent = 0
}
branch.append(rootChar)
if (rightRootLine != null) {
val (fstHalfT2, sndHalfT2) = rightRootLine.halfBodyWidths()
rIndent = rightRootLine.rIndent + sndHalfT2
branch.append("─".repeat(rightRootLine.lIndent + fstHalfT2)).append('┐')
} else {
rIndent = 0
}
return TreeLine(lIndent, branch, rIndent)
}
private fun printHelper(node: N?): MutableList<TreeLine> {
if (node == null) {
return mutableListOf()
}
val treeLines = mutableListOf<TreeLine>()
val left = printHelper(node.left)
val right = printHelper(node.right)
if (left.isEmpty() && right.isEmpty()) {
return mutableListOf(TreeLine(0, StringBuilder(node.toString()), 0))
}
val rootLine = buildRootLine(node.toString(), left, left.getWidth(), right, right.getWidth())
treeLines.add(rootLine)
val branchLine = buildBranchLine(left.firstOrNull(), right.firstOrNull())
treeLines.add(branchLine)
val subTreeLines = mergeSubTreeLine(left, right)
treeLines.addAll(subTreeLines)
return treeLines
}
override fun toString(): String {
val treeLines = printHelper(root)
val sb = StringBuilder()
treeLines.forEach {
sb.append(it).append("\n")
}
return sb.toString()
}
}
| 0 | Kotlin | 0 | 0 | e0188bad8a6519e571bdc3ee21c41764c1271f10 | 10,037 | AlgoDS | MIT License |
src/main/kotlin/com/groundsfam/advent/y2021/d02/Day02.kt | agrounds | 573,140,808 | false | {"Kotlin": 281620, "Shell": 742} | package com.groundsfam.advent.y2021.d02
import com.groundsfam.advent.DATAPATH
import com.groundsfam.advent.Direction
import com.groundsfam.advent.points.Point
import com.groundsfam.advent.asPoint
import com.groundsfam.advent.points.sum
import com.groundsfam.advent.timed
import kotlin.io.path.div
import kotlin.io.path.useLines
fun parseLine(line: String): Point = line.split(" ")
.let { (dir, amount) ->
when (dir) {
"forward" -> Direction.RIGHT
"down" -> Direction.DOWN
"up" -> Direction.UP
else -> throw RuntimeException("Illegal direction $dir")
}.asPoint() * amount.toInt()
}
fun followDirectionsWithAim(directions: List<Point>): Point {
var aim = 0
var position = Point(0, 0)
directions.forEach { (x, y) ->
if (x != 0) { // forward
position += Point(x, aim * x)
} else { // up or down
aim += y
}
}
return position
}
fun main() = timed {
val directions = (DATAPATH / "2021/day02.txt").useLines { lines ->
lines.toList().map(::parseLine)
}
directions.sum()
.also { println("Part one: ${it.x * it.y}") }
followDirectionsWithAim(directions)
.also { println("Part two: ${it.x * it.y}") }
}
| 0 | Kotlin | 0 | 1 | c20e339e887b20ae6c209ab8360f24fb8d38bd2c | 1,278 | advent-of-code | MIT License |
2020/src/year2021/day03/Day03.kt | eburke56 | 436,742,568 | false | {"Kotlin": 61133} | package year2021.day03
import util.readAllLines
fun main() {
//part1()
part2()
}
private fun part1() {
val input = readAllLines("test.txt")
val length = input[0].length
val zeroes = mutableListOf<Int>().also { list ->
for(i in 0 until length){
list.add(0)
}
}
val ones = mutableListOf<Int>().also { list ->
for(i in 0 until length){
list.add(0)
}
}
input.forEach{ line ->
line.forEachIndexed { index, digit ->
when (digit) {
'0' -> zeroes[index]++
'1' -> ones[index]++
}
}
}
var gamma = 0
var epsilon = 0
for (i in 0 until length) {
gamma = gamma shl 1
epsilon = epsilon shl 1
if (ones[i] > zeroes[i]) {
gamma = gamma or 1
} else {
epsilon = epsilon or 1
}
}
println(gamma * epsilon)
}
private fun part2() {
val func = { listInput: List<String>, block: (MutableList<MutableList<String>>, MutableList<MutableList<String>>, Int) -> MutableList<String> ->
var list = mutableListOf<String>().apply { addAll(listInput) }
var currentBit = 0
while (list.size > 1) {
val length = list[0].length
val zeroes = mutableListOf<MutableList<String>>().also {
for (i in 0 until length) {
it.add(mutableListOf())
}
}
val ones = mutableListOf<MutableList<String>>().also {
for (i in 0 until length) {
it.add(mutableListOf())
}
}
list.forEach { line ->
line.forEachIndexed { index, digit ->
when (digit) {
'0' -> zeroes[index].add(line)
'1' -> ones[index].add(line)
}
}
}
list = block(zeroes, ones, currentBit)
currentBit++
}
list.first()
}
val input = readAllLines("input.txt")
val listO2 = func(input) { zeroes, ones, i ->
if (ones[i].size >= zeroes[i].size) ones[i] else zeroes[i]
}
val valO2 = listO2.toIntBinary()
val listC02 = func(input) { zeroes, ones, i ->
if (ones[i].size < zeroes[i].size) ones[i] else zeroes[i]
}
val valC02 = listC02.toIntBinary()
println(valO2 * valC02)
}
private fun String.toIntBinary(): Int {
var value = 0
for (i in 0 until length) {
value = value shl 1
when (this[i]) {
'1' -> value = value or 1
}
}
return value
} | 0 | Kotlin | 0 | 0 | 24ae0848d3ede32c9c4d8a4bf643bf67325a718e | 2,679 | adventofcode | MIT License |
kotlin/src/main/kotlin/dev/mikeburgess/euler/problems/Problem014.kt | mddburgess | 261,028,925 | false | null | package dev.mikeburgess.euler.problems
import dev.mikeburgess.euler.sequences.CollatzLengthSequence
/**
* The following iterative sequence is defined for the set of positive integers:
*
* n -> n / 2 (n is even)
* n -> 3n + 1 (n is odd)
*
* Using the rule above and starting with 13, we generate the following sequence:
*
* 13 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1
*
* It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms.
* Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers
* finish at 1.
*
* Which starting number, under one million, produces the longest chain?
*
* NOTE: Once the chain starts the terms are allowed to go above one million.
*/
class Problem014 : Problem {
override fun solve(): Long =
CollatzLengthSequence()
.take(999_999)
.withIndex()
.maxBy { it.value }!!
.index + 1L
}
| 0 | Kotlin | 0 | 0 | 86518be1ac8bde25afcaf82ba5984b81589b7bc9 | 962 | project-euler | MIT License |
aoc2022/aoc2022-kotlin/src/main/kotlin/de/havox_design/aoc2022/day18/BoilingBoulders.kt | Gentleman1983 | 737,309,232 | false | {"Kotlin": 746488, "Java": 441473, "Scala": 33415, "Groovy": 5725, "Python": 3319} | package de.havox_design.aoc2022.day18
import de.havox_design.aoc.utils.kotlin.model.positions.Position3d
class BoilingBoulders(private var filename: String) {
private val data = readFile()
fun processPart1(): Int =
data
.sumOf { point ->
point
.neighbours()
.count { it !in data }
}
fun processPart2(): Int {
val xLimits = data.minOf { it.x } - 1..data.maxOf { it.x } + 1
val yLimits = data.minOf { it.y } - 1..data.maxOf { it.y } + 1
val zLimits = data.minOf { it.z } - 1..data.maxOf { it.z } + 1
val toVisit = mutableListOf(Position3d(xLimits.first, yLimits.first, zLimits.first))
val visited = mutableSetOf<Position3d<Int>>()
var sides = 0
while (toVisit.isNotEmpty()) {
val current = toVisit.removeFirst()
if (current !in visited) {
current.neighbours()
.filter { it.x in xLimits && it.y in yLimits && it.z in zLimits }
.forEach { next -> if (next in data) sides++ else toVisit += next }
visited += current
}
}
return sides
}
private fun readFile(): Set<Position3d<Int>> {
val fileData = getResourceAsText(filename)
return fileData
.map { row ->
row
.split(",")
.map(String::toInt)
}
.map { (x, y, z) -> Position3d(x, y, z) }
.toSet()
}
private fun getResourceAsText(path: String): List<String> =
this.javaClass.classLoader.getResourceAsStream(path)!!.bufferedReader().readLines()
}
private fun Position3d<Int>.neighbours(): List<Position3d<Int>> {
return listOf(
Position3d<Int>(x - 1, y, z),
Position3d<Int>(x + 1, y, z),
Position3d<Int>(x, y - 1, z),
Position3d<Int>(x, y + 1, z),
Position3d<Int>(x, y, z - 1),
Position3d<Int>(x, y, z + 1)
)
}
| 4 | Kotlin | 0 | 1 | 35ce3f13415f6bb515bd510a1f540ebd0c3afb04 | 2,041 | advent-of-code | Apache License 2.0 |
src/Day20.kt | fmborghino | 573,233,162 | false | {"Kotlin": 60805} | fun main() {
val _day_ = "20"
fun log(message: Any?) {
println(message)
}
data class Node(val start: Long, val value: Long)
fun parse(input: List<String>, key: Long = 1): MutableList<Node> {
return input.mapIndexed { index, s -> Node(index.toLong(), s.toLong() * key) }.toMutableList()
}
fun shuffle(ring: MutableList<Node>) {
(0L until ring.size).forEach { origPos ->
val nodeToMoveIndex = ring.indexOfFirst { it.start == origPos }
// log("$origPos -> $nodeToMoveIndex -> ${ring[nodeToMoveIndex]}")
val nodeToMove = ring.removeAt(nodeToMoveIndex)
val newPosition = (nodeToMoveIndex + nodeToMove.value).mod(ring.size)
// log("$origPos -> $nodeToMoveIndex + ${nodeToMove.value} mod(${ring.size}) = $newPosition")
ring.add(newPosition, nodeToMove)
}
}
fun result(ring: MutableList<Node>): Long {
val pos0 = ring.indexOfFirst { it.value == 0L }
return ring[(pos0 + 1000).mod(ring.size)].value +
ring[(pos0 + 2000).mod(ring.size)].value +
ring[(pos0 + 3000).mod(ring.size)].value
}
fun part1(input: List<String>): Long {
val ring: MutableList<Node> = parse(input)
// log("s -> ${ring.map { it.value }}")
shuffle(ring)
return result(ring)
}
fun part2(input: List<String>): Long {
val ring: MutableList<Node> = parse(input, key = 811589153L)
// log("s -> ${ring.map { it.value }}")
repeat(10) {
shuffle(ring)
}
return result(ring)
}
// test inputs
val testInput = readInput("Day${_day_}_test.txt")
// test part 1
val test1 = part1(testInput)
check(test1 == 3L) { "!!! test part 1 failed with: $test1" }
// game inputs
val gameInput = readInput("Day${_day_}.txt")
// game part 1
val game1 = part1(gameInput)
println("*** game part 1: $game1")
check(game1 == 5498L) { "!!! game part 1 failed with: $game1" }
// test part 2
val test2 = part2(testInput)
check(test2 == 1623178306L) { "!!! test part 2 failed with: $test2" }
// game part 2
val game2 = part2(gameInput)
println("*** game part 2: $game2")
check(game2 == 3390007892081L) { "!!! game part 2 failed with: $game2" }
} | 0 | Kotlin | 0 | 0 | 893cab0651ca0bb3bc8108ec31974654600d2bf1 | 2,347 | aoc2022 | Apache License 2.0 |
src/main/kotlin/day18/part2/Part2.kt | bagguley | 329,976,670 | false | null | package day18.part2
import day18.data
fun main() {
val result = data.map{calc(it)}.sum()
println(result)
}
fun calc(string: String): Long {
var input = string
while (input.contains("(")) {
input = parse(input)
}
input = calcAdd(input)
input = calcMultiply(input)
return input.toLong()
}
fun parse(string: String): String {
var str = string
val regX = Regex("\\((\\d+(?: [+*] \\d+)*)\\)")
val matchRes = regX.find(str)
val match = matchRes?.groupValues?.get(1) ?: return str
str = calcAdd(match)
str = calcMultiply(str)
return string.replaceFirst("($match)", str)
}
fun calcAdd(string: String): String {
val regX = Regex("(\\d+) \\+ (\\d+)")
var str = string
while(str.contains(Regex("\\+"))) {
val matchRes = regX.find(str)
val matches = matchRes?.groupValues ?: return str
val first = matches[1].toLong()
val second = matches[2].toLong()
val result = first + second
str = str.replaceFirst(matches[0], result.toString())
}
return str
}
fun calcMultiply(string: String) : String {
val regX = Regex("(\\d+) \\* (\\d+)")
var str = string
while (str.contains(Regex("\\*"))) {
val matchRes = regX.find(str)
val matches = matchRes?.groupValues ?: return str
val first = matches[1].toLong()
val second = matches[2].toLong()
val result = first * second
str = str.replaceFirst(matches[0], result.toString())
}
return str
} | 0 | Kotlin | 0 | 0 | 6afa1b890924e9459f37c604b4b67a8f2e95c6f2 | 1,538 | adventofcode2020 | MIT License |
kotlin/misc/MaximumZeroSubmatrix.kt | polydisc | 281,633,906 | true | {"Java": 540473, "Kotlin": 515759, "C++": 265630, "CMake": 571} | package misc
object MaximumZeroSubmatrix {
fun maximumZeroSubmatrix(a: Array<IntArray>): Int {
val R = a.size
val C: Int = a[0].length
var res = 0
val d = IntArray(C)
Arrays.fill(d, -1)
val d1 = IntArray(C)
val d2 = IntArray(C)
val st = IntArray(C)
for (r in 0 until R) {
for (c in 0 until C) if (a[r][c] == 1) d[c] = r
var size = 0
for (c in 0 until C) {
while (size > 0 && d[st[size - 1]] <= d[c]) --size
d1[c] = if (size == 0) -1 else st[size - 1]
st[size++] = c
}
size = 0
for (c in C - 1 downTo 0) {
while (size > 0 && d[st[size - 1]] <= d[c]) --size
d2[c] = if (size == 0) C else st[size - 1]
st[size++] = c
}
for (j in 0 until C) res = Math.max(res, (r - d[j]) * (d2[j] - d1[j] - 1))
}
return res
}
// random test
fun main(args: Array<String?>?) {
val rnd = Random(1)
for (step in 0..999) {
val R: Int = rnd.nextInt(10) + 1
val C: Int = rnd.nextInt(10) + 1
val a = Array(R) { IntArray(C) }
for (r in 0 until R) for (c in 0 until C) a[r][c] = rnd.nextInt(2)
val res1 = maximumZeroSubmatrix(a)
val res2 = slowMaximumZeroSubmatrix(a)
if (res1 != res2) throw RuntimeException("$res1 $res2")
}
}
fun slowMaximumZeroSubmatrix(a: Array<IntArray>): Int {
var res = 0
val R = a.size
val C: Int = a[0].length
for (r2 in 0 until R) for (c2 in 0 until C) for (r1 in 0..r2) m1@ for (c1 in 0..c2) {
for (r in r1..r2) for (c in c1..c2) if (a[r][c] != 0) continue@m1
res = Math.max(res, (r2 - r1 + 1) * (c2 - c1 + 1))
}
return res
}
}
| 1 | Java | 0 | 0 | 4566f3145be72827d72cb93abca8bfd93f1c58df | 1,917 | codelibrary | The Unlicense |
src/Day04.kt | arturradiuk | 571,954,377 | false | {"Kotlin": 6340} | fun main() {
fun partOne(input: List<String>): Int = input.count {
val (first, second) = it.split(",").map(String::toSet)
first.containsAll(second) || second.containsAll(first)
}
fun partTwo(input: List<String>): Int = input.count {
val (first, second) = it.split(",").map(String::toSet)
first.intersect(second).isNotEmpty()
}
val input = readInput("Day04")
println(partOne(input))
println(partTwo(input))
}
fun String.toSet(): Set<Int> = this.split("-").map(String::toInt).let { (it.first()..it.last()).toSet() }
| 0 | Kotlin | 0 | 0 | 85ef357643e5e4bd2ba0d9a09f4a2d45653a8e28 | 579 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day05.kt | devheitt | 573,207,407 | false | {"Kotlin": 11944} | fun main() {
fun part1(input: List<String>): String {
val stacks = HashMap<Int, ArrayDeque<String>>()
var linesIndex = 0
var line = input[linesIndex]
while (!line.contains("1")) {
val split = line.split("")
var lineIndex = 2
var stackIndex = 0
while (lineIndex < split.size) {
val container = split[lineIndex]
if(!container.trim().isEmpty()) {
if(stacks[stackIndex] == null) {
stacks[stackIndex] = ArrayDeque()
}
stacks[stackIndex]?.addFirst(container)
}
lineIndex += 4
stackIndex++
}
linesIndex++
line = input[linesIndex]
}
linesIndex += 2;
while (linesIndex < input.size) {
line = input[linesIndex]
val split = line.split(" ")
val count = split[1].toInt()
val from = split[3].toInt() - 1
val to = split[5].toInt() - 1
for (i in 0 until count){
stacks[from]?.removeLast()?.let { stacks[to]?.addLast(it) }
}
linesIndex++
}
var result = ""
for (cont in stacks.values) {
result += cont.last()
}
return result
}
fun part2(input: List<String>): String {
val stacks = HashMap<Int, ArrayDeque<String>>()
var linesIndex = 0
var line = input[linesIndex]
while (!line.contains("1")) {
val split = line.split("")
var lineIndex = 2
var stackIndex = 0
while (lineIndex < split.size) {
val container = split[lineIndex]
if(!container.trim().isEmpty()) {
if(stacks[stackIndex] == null) {
stacks[stackIndex] = ArrayDeque()
}
stacks[stackIndex]?.addFirst(container)
}
lineIndex += 4
stackIndex++
}
linesIndex++
line = input[linesIndex]
}
linesIndex += 2;
while (linesIndex < input.size) {
line = input[linesIndex]
val split = line.split(" ")
val count = split[1].toInt()
val from = split[3].toInt() - 1
val to = split[5].toInt() - 1
val tmpQueue = ArrayDeque<String>()
for (i in 0 until count){
stacks[from]?.removeLast()?.let { tmpQueue.addLast(it) }
}
for (container in tmpQueue.reversed()) {
stacks[to]?.addLast(container)
}
linesIndex++
}
var result = ""
for (cont in stacks.values) {
result += cont.last()
}
return result
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | a9026a0253716d36294709a547eaddffc6387261 | 3,209 | advent-of-code-2022-kotlin | Apache License 2.0 |
benchmark/src/test/kotlin/me/leon/translate/IcibaVocabulary.kt | Leon406 | 381,644,086 | false | {"Kotlin": 1392660, "JavaScript": 96128, "Java": 16541, "Batchfile": 4706, "Shell": 259, "CSS": 169} | package me.leon.translate
data class IcibaVocabulary(
val phrase: List<Phrase>?,
val derivation: List<Derivation>?,
val baesInfo: BaesInfo?,
) {
fun phraseInfo() = phrase?.joinToString(System.lineSeparator()) { it.info() }.orEmpty()
data class BaesInfo(
val word_name: String?,
val is_CRI: String?,
val exchange: Exchange?,
val symbols: List<Symbol?>?
) {
fun info(): String {
println(this)
return ("$word_name\t" + pronunciation() + "\n" + exchange?.info + "\n\n" + meanings())
}
fun pronunciation() = symbols?.get(0)?.run { "UK: /$ph_en/ US: /$ph_am/" }
fun meanings(separator: String = System.lineSeparator()) =
symbols?.get(0)?.parts?.run {
joinToString(separator) { "${it.part} ${it.means?.joinToString(";")}" }
}
data class Symbol(
val ph_en: String,
val ph_am: String,
val ph_other: String?,
val ph_en_mp3: String?,
val ph_am_mp3: String?,
val ph_tts_mp3: String?,
val ph_en_mp3_bk: String?,
val ph_am_mp3_bk: String?,
val ph_tts_mp3_bk: String?,
val parts: List<Part>?
) {
data class Part(val part: String?, val means: List<String?>?)
}
}
data class Phrase(val cizu_name: String, val jx: List<Jx>) {
data class Jx(val jx_en_mean: String, val jx_cn_mean: String, val lj: List<Lj>?) {
data class Lj(val lj_ly: String?, val lj_ls: String?)
}
fun info() = cizu_name + ": ${jx.joinToString("; ") { it.jx_cn_mean }}"
}
data class Derivation(val yuyuan_name: String?)
data class Exchange(
val word_pl: List<String>?,
val word_third: List<String>?,
val word_past: List<String>?,
val word_done: List<String>?,
val word_ing: List<String>?,
val word_adj: List<String>?
) {
val info
get() =
"pl/third/past/done/ing/adj: ${word_pl?.joinToString(",") ?: "-"} " +
"${word_third?.joinToString(",") ?: "-"} " +
"${word_past?.joinToString(",") ?: "-"} " +
"${word_done?.joinToString(",") ?: "-"} " +
"${word_ing?.joinToString(",") ?: "-"} " +
"${word_adj?.joinToString(",") ?: "-"} "
}
override fun toString(): String {
val p =
with(phraseInfo()) {
if (isNotEmpty()) {
"\n\n词组:\n\n$this"
} else {
""
}
}
val origin =
with(derivation?.get(0)?.yuyuan_name) {
if (isNullOrEmpty()) {
""
} else {
"\n\n来历:\n\n$this"
}
}
return baesInfo?.info().orEmpty() + p + origin
}
}
| 4 | Kotlin | 236 | 1,218 | dde1cc6e8e589f4a46b89e2e22918e8b789773e4 | 2,990 | ToolsFx | ISC License |
src/main/kotlin/adventofcode/year2020/Day12RainRisk.kt | pfolta | 573,956,675 | false | {"Kotlin": 199554, "Dockerfile": 227} | package adventofcode.year2020
import adventofcode.Puzzle
import adventofcode.PuzzleInput
import adventofcode.year2020.Day12RainRisk.Companion.Action.EAST
import adventofcode.year2020.Day12RainRisk.Companion.Action.FORWARD
import adventofcode.year2020.Day12RainRisk.Companion.Action.LEFT
import adventofcode.year2020.Day12RainRisk.Companion.Action.NORTH
import adventofcode.year2020.Day12RainRisk.Companion.Action.RIGHT
import adventofcode.year2020.Day12RainRisk.Companion.Action.SOUTH
import adventofcode.year2020.Day12RainRisk.Companion.Action.WEST
import kotlin.math.absoluteValue
class Day12RainRisk(customInput: PuzzleInput? = null) : Puzzle(customInput) {
private val navigationInstructions by lazy { input.lines().map(::NavigationInstruction) }
override fun partOne() = navigationInstructions
.fold(NavigationDirection.EAST to Pair(0, 0)) { (direction, position), instruction ->
when (instruction.action) {
EAST -> direction to position.copy(first = position.first + instruction.value)
WEST -> direction to position.copy(first = position.first - instruction.value)
NORTH -> direction to position.copy(second = position.second + instruction.value)
SOUTH -> direction to position.copy(second = position.second - instruction.value)
FORWARD -> when (direction) {
NavigationDirection.EAST -> direction to position.copy(first = position.first + instruction.value)
NavigationDirection.WEST -> direction to position.copy(first = position.first - instruction.value)
NavigationDirection.NORTH -> direction to position.copy(second = position.second + instruction.value)
NavigationDirection.SOUTH -> direction to position.copy(second = position.second - instruction.value)
}
RIGHT -> NavigationDirection(direction.heading + instruction.value) to position
LEFT -> NavigationDirection(direction.heading - instruction.value) to position
}
}
.second
.toList()
.sumOf { it.absoluteValue }
override fun partTwo() = navigationInstructions
.fold(Pair(Pair(10, 1), Pair(0, 0))) { acc, instruction ->
val value = instruction.value
val waypoint = acc.first
val position = acc.second
when (instruction.action) {
EAST -> acc.copy(first = waypoint.copy(first = waypoint.first + value))
WEST -> acc.copy(first = waypoint.copy(first = waypoint.first - value))
NORTH -> acc.copy(first = waypoint.copy(second = waypoint.second + value))
SOUTH -> acc.copy(first = waypoint.copy(second = waypoint.second - value))
FORWARD -> acc.copy(second = Pair(position.first + value * waypoint.first, position.second + value * waypoint.second))
RIGHT -> {
var wx = waypoint.first
var wy = waypoint.second
repeat(value / 90) { val oldwx = wx; wx = wy; wy = -oldwx }
acc.copy(first = Pair(wx, wy))
}
LEFT -> {
var wx = waypoint.first
var wy = waypoint.second
repeat(value / 90) { val oldwx = wx; wx = -wy; wy = oldwx }
acc.copy(first = Pair(wx, wy))
}
}
}
.second
.toList()
.sumOf { it.absoluteValue }
companion object {
private enum class NavigationDirection(val heading: Int) {
EAST(0),
SOUTH(90),
WEST(180),
NORTH(270);
companion object {
operator fun invoke(heading: Int) = entries.associateBy(NavigationDirection::heading)[Math.floorMod(heading, 360)]!!
}
}
private enum class Action(val action: String) {
NORTH("N"),
SOUTH("S"),
EAST("E"),
WEST("W"),
LEFT("L"),
RIGHT("R"),
FORWARD("F");
companion object {
operator fun invoke(action: String) = entries.associateBy(Action::action)[action]!!
}
}
private data class NavigationInstruction(
val action: Action,
val value: Int
) {
constructor(action: String) : this(Action(action.substring(0, 1)), action.substring(1).toInt())
}
}
}
| 0 | Kotlin | 0 | 0 | 72492c6a7d0c939b2388e13ffdcbf12b5a1cb838 | 4,558 | AdventOfCode | MIT License |
src/Day15.kt | erwinw | 572,913,172 | false | {"Kotlin": 87621} | @file:Suppress("MagicNumber")
import kotlin.math.abs
private const val DAY = "15"
private const val PART1_CHECK = 26
private const val PART2_CHECK = 56000011L
fun main() {
data class Coordinate(
val x: Int,
val y: Int,
) {
fun distance(other: Coordinate): Int =
abs(x - other.x) + abs(y - other.y)
}
data class SensorBeacon(
val sensor: Coordinate,
val beacon: Coordinate,
val distance: Int = sensor.distance(beacon),
)
val parseRegexp = Regex("Sensor at x=(-?\\d+), y=(-?\\d+): closest beacon is at x=(-?\\d+), y=(-?\\d+)")
fun parseSensorBeacons(input: List<String>): List<SensorBeacon> =
@Suppress("DestructuringDeclarationWithTooManyEntries")
input.map { line ->
val (sx, sy, bx, by) = parseRegexp.matchEntire(line)!!.groupValues.drop(1).map(String::toInt)
SensorBeacon(Coordinate(sx, sy), Coordinate(bx, by))
}
fun part1(input: List<String>, targetY: Int): Int {
val sensorBeacons = parseSensorBeacons(input)
val minX = sensorBeacons.minOf { (sensor, beacon) ->
sensor.x - sensor.distance(beacon)
} - 100
val maxX = sensorBeacons.maxOf { (sensor, beacon) ->
sensor.x + sensor.distance(beacon)
} + 100
val cannotContainCount = (minX..maxX).count { x ->
sensorBeacons.any { (sensor, beacon, seeDistance) ->
if (beacon.y == targetY && beacon.x == x) {
return@count false
}
val atDistance = sensor.distance(Coordinate(x, targetY))
val canSee = atDistance <= seeDistance
// if (canSee) {
// println("X: $x, Sensor $sensor (beacon $beacon, distance $seeDistance), $atDistance")
// }
canSee
}
}
println("CannotContainCount: $cannotContainCount")
return cannotContainCount
}
fun subtractLor(parts: List<IntRange>, operand: IntRange): List<IntRange> = buildList {
parts.forEach { part ->
when {
// no overlap
operand.last < part.first ||
operand.first > part.last -> {
add(part)
}
// complete overlap
operand.first <= part.first && operand.last >= part.last -> {
// skip
}
else -> {
// head
if (part.first < operand.first) {
add(part.first until operand.first)
}
// tail
if (part.last > operand.last) {
add(operand.last + 1..part.last)
}
}
}
}
}
fun part2(input: List<String>, maxDx: Int): Long {
val sensorBeacons = parseSensorBeacons(input)
fun getCandidate(y: Int): Int? {
// For each row we create a range of candidates, then subtract the range of each sensor for that row
var candidates = listOf(0..maxDx)
sensorBeacons.forEach { (sensor, _, distance) ->
val dx = distance - abs(sensor.y - y)
if (dx < 0) {
return@forEach
}
val sensorRange = (sensor.x - dx)..(sensor.x + dx)
candidates = subtractLor(candidates, sensorRange)
if (candidates.isEmpty()) {
return null
}
}
return candidates.firstOrNull()?.first
}
for (y in 0..maxDx) {
getCandidate(y)?.let { x ->
return x.toLong() * 4_000_000 + y
}
}
return 0
}
println("Day $DAY")
val testInput = readInput("Day${DAY}_test")
check(part1(testInput, 10).also { println("Part1 output: $it") } == PART1_CHECK)
check(part2(testInput, 20).also { println("Part2 output: $it") } == PART2_CHECK)
val input = readInput("Day$DAY")
println("Part1 final output: ${part1(input, 2_000_000)}")
println("Part2 final output: ${part2(input, 4_000_000)}")
}
| 0 | Kotlin | 0 | 0 | 57cba37265a3c63dea741c187095eff24d0b5381 | 4,261 | adventofcode2022 | Apache License 2.0 |
src/Day02.kt | Sghazzawi | 574,678,250 | false | {"Kotlin": 10945} | enum class MyMove(val value: String) {
Rock("X"),
Paper("Y"),
Scissors("Z");
companion object {
infix fun from(value: String): MyMove = MyMove.values().firstOrNull { it.value == value } ?: throw Exception()
}
}
enum class OpponentMove(val value: String) {
Rock("A"),
Paper("B"),
Scissors("C");
companion object {
infix fun from(value: String): OpponentMove =
OpponentMove.values().firstOrNull { it.value == value } ?: throw Exception()
}
}
enum class DesiredOutcome(val value: String) {
Lose("X"),
Draw("Y"),
Win("Z");
companion object {
infix fun from(value: String): DesiredOutcome =
DesiredOutcome.values().firstOrNull { it.value == value } ?: throw Exception()
}
}
fun getOpponentMove(input: String): OpponentMove {
return OpponentMove.from(input.split(" ")[0])
}
fun getMyMove(input: String): MyMove {
return MyMove.from(input.split(" ")[1])
}
fun getDesiredOutcome(input: String): DesiredOutcome {
return DesiredOutcome.from(input.split(" ")[1])
}
fun getScore(input: String): Int {
return getScore(getMyMove(input), getOpponentMove(input))
}
fun getScore(myMove: MyMove, opponentMove: OpponentMove): Int {
return getWinScore(myMove, opponentMove) + getPlayScore(myMove)
}
fun getMyMoveForDesiredOutcome(input: String): MyMove {
return getMyMoveForDesiredOutcome(getOpponentMove(input), getDesiredOutcome((input)))
}
fun getMyMoveForDesiredOutcome(opponentMove: OpponentMove, desiredOutcome: DesiredOutcome): MyMove {
return when (opponentMove) {
OpponentMove.Rock -> when (desiredOutcome) {
DesiredOutcome.Lose -> MyMove.Scissors
DesiredOutcome.Draw -> MyMove.Rock
DesiredOutcome.Win -> MyMove.Paper
}
OpponentMove.Paper -> when (desiredOutcome) {
DesiredOutcome.Lose -> MyMove.Rock
DesiredOutcome.Draw -> MyMove.Paper
DesiredOutcome.Win -> MyMove.Scissors
}
OpponentMove.Scissors -> when (desiredOutcome) {
DesiredOutcome.Lose -> MyMove.Paper
DesiredOutcome.Draw -> MyMove.Scissors
DesiredOutcome.Win -> MyMove.Rock
}
}
}
fun getPlayScore(myMove: MyMove): Int {
return when (myMove) {
MyMove.Rock -> 1
MyMove.Paper -> 2
MyMove.Scissors -> 3
}
}
fun getWinScore(myMove: MyMove, opponentMove: OpponentMove): Int {
return when (myMove) {
MyMove.Rock -> when (opponentMove) {
OpponentMove.Rock -> 3
OpponentMove.Paper -> 0
OpponentMove.Scissors -> 6
}
MyMove.Paper -> when (opponentMove) {
OpponentMove.Rock -> 6
OpponentMove.Paper -> 3
OpponentMove.Scissors -> 0
}
MyMove.Scissors -> when (opponentMove) {
OpponentMove.Rock -> 0
OpponentMove.Paper -> 6
OpponentMove.Scissors -> 3
}
}
}
fun main() {
fun part1(input: List<String>): Int {
return input.fold(0) { acc, current ->
acc + getScore(current)
}
}
fun part2(input: List<String>): Int {
return input.map {
Pair(getOpponentMove(it), getMyMoveForDesiredOutcome(it))
}.fold(0) { acc, current: Pair<OpponentMove, MyMove> ->
acc + getScore(current.second, current.first)
}
}
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | a26111fa1bcfec28cc43a2f48877455b783acc0d | 3,526 | advent-of-code-kotlin | Apache License 2.0 |
implementation/src/main/kotlin/io/github/tomplum/aoc/hash/HashAlgorithm.kt | TomPlum | 724,225,748 | false | {"Kotlin": 141244} | package io.github.tomplum.aoc.hash
import io.github.tomplum.libs.extensions.product
class HashAlgorithm(private val input: String) {
fun run(): Int = input.split(",").sumOf { step -> step.hash() }
fun calculateFocusingPower(): Int {
val boxes = mutableMapOf<Int, MutableList<Pair<String, Int>>>()
(0..255).forEach { number -> boxes[number] = mutableListOf() }
input.split(",").forEach { step ->
val (label, focalLength) = if ('-' in step) step.split("-") else step.split("=")
val box = label.hash()
val lenses = boxes[box]!!
if ('-' in step) {
val lens = lenses.find { (lensLabel) -> lensLabel == label }
if (lens != null) {
val lensIndex = lenses.indexOf(lens)
lenses.removeAt(lensIndex)
boxes[box] = lenses
}
} else {
val newLens = Pair(label, focalLength.toInt())
val existingLens = lenses.find { (lensLabel) -> lensLabel == label }
if (existingLens != null) {
boxes[box] = lenses.map {
if (it.first == label) {
Pair(it.first, focalLength.toInt())
} else it
}.toMutableList()
} else {
boxes[box] = (lenses + newLens).toMutableList()
}
}
}
return boxes.entries.sumOf { (box, lenses) ->
lenses.sumOf { lens ->
listOf(1 + box, lenses.indexOf(lens) + 1, lens.second).product()
}
}
}
private fun String.hash() = this.fold(0) { value, character -> ((value + character.code) * 17) % 256 }
} | 0 | Kotlin | 0 | 1 | d1f941a3c5bacd126177ace6b9f576c9af07fed6 | 1,796 | advent-of-code-2023 | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.