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/Day07.kt | Kvest | 573,621,595 | false | {"Kotlin": 87988} | import java.util.*
fun main() {
val testInput = readInput("Day07_test")
val testRoot = buildFileSystem(testInput)
val testSizeCache = mutableMapOf<Node, Long>()
check(part1(testRoot, testSizeCache) == 95437L)
check(part2(testRoot, testSizeCache) == 24933642L)
val input = readInput("Day07")
val root = buildFileSystem(input)
val sizeCache = mutableMapOf<Node, Long>()
println(part1(root, sizeCache))
println(part2(root, sizeCache))
}
private const val MAX = 100000L
private fun part1(root: Node, sizeCache: MutableMap<Node, Long>): Long {
var result = 0L
root.visit { node ->
if (node.isDir) {
val size = sizeCache.getOrPut(node, node::size)
if (size < MAX) {
result += size
}
}
}
return result
}
private const val TOTAL_SPACE = 70000000L
private const val TARGET_FREE_SPACE = 30000000L
private fun part2(root: Node, sizeCache: MutableMap<Node, Long>): Long {
val rootSize = sizeCache.getOrPut(root, root::size)
val spaceToFreeUp = TARGET_FREE_SPACE - (TOTAL_SPACE - rootSize)
var result = Long.MAX_VALUE
root.visit { node ->
if (node.isDir) {
val size = sizeCache.getOrPut(node, node::size)
if (size >= spaceToFreeUp && size < result) {
result = size
}
}
}
return result
}
private fun buildFileSystem(commands: List<String>): Node {
val root = Node.Dir()
val navigationStack = LinkedList<Node>()
var i = 0
while (i <= commands.lastIndex) {
val cmd = commands[i++]
when {
cmd.startsWith("$ cd /") -> {
navigationStack.clear()
navigationStack.push(root)
}
cmd.startsWith("$ cd ..") -> navigationStack.pop()
cmd.startsWith("$ cd ") -> {
val destinationName = cmd.substringAfter("$ cd ")
val destination = navigationStack.peek().getChild(destinationName)
navigationStack.push(destination)
}
cmd.startsWith("$ ls") -> {
val targetNode = navigationStack.peek()
while (i <= commands.lastIndex && !commands[i].startsWith("$")) {
val item = commands[i++]
if (item.startsWith("dir")) {
targetNode.addChild(
name = item.substringAfter("dir "),
child = Node.Dir()
)
} else {
targetNode.addChild(
name = item.substringAfter(" "),
child = Node.File(
size = item.substringBefore(" ").toLong()
)
)
}
}
}
}
}
return root
}
sealed interface Node {
val isDir: Boolean
fun getChild(name: String): Node
fun addChild(name: String, child: Node)
fun size(): Long
fun visit(action: (Node) -> Unit)
class Dir : Node {
private val children = mutableMapOf<String, Node>()
override val isDir: Boolean
get() = true
override fun getChild(name: String): Node = children[name] ?: error("Child $name not found")
override fun addChild(name: String, child: Node) {
children[name] = child
}
override fun size(): Long {
return children.values.fold(0) { acc, node -> acc + node.size() }
}
override fun visit(action: (Node) -> Unit) {
children.forEach { it.value.visit(action) }
action(this)
}
}
class File(val size: Long) : Node {
override val isDir: Boolean
get() = false
override fun getChild(name: String): Node = error("getChild is not applicable for File")
override fun addChild(name: String, child: Node) = error("addChild is not applicable for File")
override fun size(): Long = size
override fun visit(action: (Node) -> Unit) {
action(this)
}
}
} | 0 | Kotlin | 0 | 0 | 6409e65c452edd9dd20145766d1e0ea6f07b569a | 4,203 | AOC2022 | Apache License 2.0 |
src/commonMain/kotlin/ai/hypergraph/kaliningraph/sampling/Bijections.kt | breandan | 245,074,037 | false | {"Kotlin": 1482924, "Haskell": 744, "OCaml": 200} | package ai.hypergraph.kaliningraph.sampling
import ai.hypergraph.kaliningraph.choose
import ai.hypergraph.kaliningraph.types.to
import kotlin.math.*
// Bijection between k-combinations and integers
// https://en.wikipedia.org/wiki/Combinatorial_number_system
fun Set<Int>.encode(): Int {
var (k, i, total) = size to 0 to 0
val asArray = toIntArray()
while (i < size) {
val result = asArray[i] choose k
total += result
k -= 1
i += 1
}
return total
}
fun Int.decodeCombo(k: Int): Set<Int> {
var choice: Int = k - 1
while (choice choose k < this) choice++
var N = this
var kk = k
val result = mutableSetOf<Int>()
(choice downTo 0).forEach { ch ->
if (ch choose kk <= N) {
N -= ch choose kk--
result.add(ch)
}
}
return result
}
fun ndBoxUnpair(lengths: List<Int>, index: Int): List<Int> {
val n = lengths.size
val indexes = MutableList(n) { 0 }
var dimensionProduct = 1
for (dimension in (n - 1) downTo 0) {
indexes[dimension] = index / dimensionProduct % lengths[dimension]
dimensionProduct *= lengths[dimension]
}
return indexes
}
fun ndBoxPair(lengths: List<Int>, indexes: List<Int>): Int {
val n = lengths.size
var index = 0
var dimensionProduct = 1
for (dimension in (n - 1) downTo 0) {
index += indexes[dimension] * dimensionProduct
dimensionProduct *= lengths[dimension]
}
return index
}
fun Int.pow(n: Int): Int = when (n) {
0 -> 1
1 -> this
else -> {
var result = this
for (i in 1 until n) {
result *= this
}
result
}
}
/**
* Constructs a bijection between ℕ <-> ℕᵏ using Szudzik's pairing function
* generalized to n-tuples, n.b. optimally compact for hypercubic shells.
*/
fun List<Int>.tupled(): Int {
val n = size
if (n == 0) return 0
val shell = max()
fun recursiveIndex(dim: Int): Int {
val sliceDims = n - dim - 1
val subshellCount = (shell + 1).pow(sliceDims) - shell.pow(sliceDims)
val indexI = this[dim]
return if (indexI == shell) {
subshellCount * shell + ndBoxPair(List(sliceDims) { shell + 1 }, slice(dim + 1 until n))
} else {
subshellCount * indexI + recursiveIndex(dim + 1)
}
}
return shell.pow(n) + recursiveIndex(0)
}
fun Int.untupled(n: Int): List<Int> {
val shell = toDouble().pow(1.0 / n).toInt()
fun recursiveIndexes(dim: Int, remaining: Int): List<Int> =
if (dim == n - 1) {
listOf(shell)
} else {
val sliceDims = n - dim - 1
val subshellCount = (shell + 1).pow(sliceDims) - shell.pow(sliceDims)
val indexI = min(remaining / subshellCount, shell)
if (indexI == shell) {
listOf(shell) + ndBoxUnpair(List(sliceDims) { shell + 1 }, remaining - subshellCount * shell)
} else {
listOf(indexI) + recursiveIndexes(dim + 1, remaining - subshellCount * indexI)
}
}
return recursiveIndexes(0, this - shell.pow(n))
} | 0 | Kotlin | 8 | 100 | c755dc4858ed2c202c71e12b083ab0518d113714 | 2,917 | galoisenne | Apache License 2.0 |
solution/#2 Add Two Numbers/Solution.kt | enihsyou | 116,918,868 | false | {"Java": 179666, "Python": 36379, "Kotlin": 32431, "Shell": 367} | package leetcode.q2.kotlin;
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.Arguments
import org.junit.jupiter.params.provider.MethodSource
/**
* Definition for singly-linked list.
* class ListNode(var `val`: Int = 0) {
* var next: ListNode? = null
* }
*/
class Solution {
class ListNode(var `val`: Int = 0) {
var next: ListNode? = null
}
fun addTwoNumbers(l1: ListNode?, l2: ListNode?): ListNode? {
var carry = false
val sum = ListNode(0)
var p1 = l1
var p2 = l2
var ps = sum
while (p1 != null || p2 != null) {
/*计算两个个位数之和*/
val s = (p1?.`val` ?: 0) + (p2?.`val` ?: 0)
/*赋值到节点里*/
val new_value = ListNode((carry.int + s) % 10)
ps.next = new_value
ps = ps.next!!
/*计算进位*/
carry = (carry.int + s) / 10 == 1
/*移动指针*/
p1?.let { p1 = it.next }
p2?.let { p2 = it.next }
}
if (carry) ps.next = ListNode(1)
return sum.next
}
val Boolean.int
get() = if (this) 1 else 0
}
class SolutionTest {
private val solution = Solution()
/*缺陷 不能把输入当做一定长度的整数,应该是个很长的序列*/
private fun Int.toIntArray() = toString().toCharArray().map { it - '0' }.toIntArray()
private fun IntArray.toListNode() = fold(null) { acc: Solution.ListNode?, i: Int ->
Solution.ListNode(i).also { it.next = acc }
}
private fun Solution.ListNode.collect(): Int {
val array = StringBuilder()
var p: Solution.ListNode? = this
while (p != null) {
array.append(p.`val`)
p = p.next
}
return array.toString().reversed().toInt()
}
@ParameterizedTest(name = "addTwoNumbers({0}, {1}) = {2}")
@MethodSource("provider")
fun addTwoNumbers(node1: Int, node2: Int, output: Int) {
assertThat(solution.addTwoNumbers(
node1.toIntArray().toListNode(),
node2.toIntArray().toListNode())?.collect())
.isEqualTo(output)
}
companion object {
@JvmStatic
fun provider(): List<Arguments> {
return listOf(
Arguments.of(342, 465, 807),
Arguments.of(1342, 465, 1807),
Arguments.of(89751589, 1456471460, 1546223049)
)
}
}
}
| 1 | Java | 0 | 0 | 230325d1dfd666ee53f304edf74c9c0f60f81d75 | 2,563 | LeetCode | MIT License |
app/src/main/kotlin/codes/jakob/aoc/shared/Extensions.kt | loehnertz | 725,944,961 | false | {"Kotlin": 59236} | package codes.jakob.aoc.shared
import java.util.*
fun String.splitByLines(): List<String> = split("\n")
fun String.splitByCharacter(): List<Char> = split("").filterNot { it.isBlank() }.map { it.toSingleChar() }
fun String.splitBySpace(): List<String> = split(" ")
fun Int.isEven(): Boolean = this % 2 == 0
fun Int.isOdd(): Boolean = !isEven()
fun <E> List<E>.middleOrNull(): E? {
return if (this.count().isOdd()) this[this.count() / 2] else null
}
fun <T> Iterable<T>.productOf(selector: (T) -> Int): Int {
var product = 1
for (element in this) product *= selector(element)
return product
}
/**
* Calculates the [triangular number](https://en.wikipedia.org/wiki/Triangular_number) of the given number.
*/
fun Long.triangular(): Long = ((this * (this + 1)) / 2)
fun CharSequence.toSingleChar(): Char {
require(this.count() == 1) { "The given CharSequence has more than one element" }
return this.first()
}
operator fun <T> T.plus(collection: Collection<T>): List<T> {
val result = ArrayList<T>(collection.size + 1)
result.add(this)
result.addAll(collection)
return result
}
fun <T, K> Collection<T>.countBy(keySelector: (T) -> K): Map<K, Int> {
return this.groupingBy(keySelector).eachCount()
}
/**
* Returns any given [Map] with its keys and values reversed (i.e., the keys becoming the values and vice versa).
* Note in case of duplicate values, they will be overridden in the key-set unpredictably.
*/
fun <K, V> Map<K, V>.reversed(): Map<V, K> {
return HashMap<V, K>(this.count()).also { reversedMap: HashMap<V, K> ->
this.entries.forEach { reversedMap[it.value] = it.key }
}
}
fun <E> Stack<E>.peekOrNull(): E? {
return if (this.isNotEmpty()) this.peek() else null
}
fun <E> List<E>.associateByIndex(): Map<Int, E> {
return this.mapIndexed { index, element -> index to element }.toMap()
}
private val NUMBER_PATTERN = Regex("\\d+")
fun String.isNumber(): Boolean = NUMBER_PATTERN.matches(this)
fun <K, V, NK> Map<K, V>.mapKeysMergingValues(
transformKey: (K, V) -> NK,
mergeValues: (V, V) -> V,
): Map<NK, V> {
return this
.asSequence()
.map { (key, value) -> transformKey(key, value) to value }
.groupBy({ it.first }, { it.second })
.mapValues { (_, values) -> values.reduce(mergeValues) }
}
inline fun <T, R> Pair<T, T>.map(block: (T) -> R): Pair<R, R> {
return this.let { (first: T, second: T) ->
block(first) to block(second)
}
}
inline fun <A, B, C, D> Pair<A, B>.map(blockA: (A) -> C, blockB: (B) -> D): Pair<C, D> {
return this.let { (first: A, second: B) ->
blockA(first) to blockB(second)
}
}
fun <E> List<E>.splitInHalf(): Pair<List<E>, List<E>> {
return this.subList(0, this.size / 2) to this.subList(this.size / 2, this.size)
}
fun List<Int>.binaryToDecimal(): Int {
require(this.all { it == 0 || it == 1 }) { "Expected bit string, but received $this" }
return Integer.parseInt(this.joinToString(""), 2)
}
fun Int.bitFlip(): Int {
require(this == 0 || this == 1) { "Expected bit, but received $this" }
return this.xor(1)
}
fun String.toBitString(): List<Int> {
val bits: List<String> = split("").filter { it.isNotBlank() }
require(bits.all { it == "0" || it == "1" }) { "Expected bit string, but received $this" }
return bits.map { it.toInt() }
}
/**
* [Transposes](https://en.wikipedia.org/wiki/Transpose) the given list of nested lists (a matrix, in essence).
*
* This function is adapted from this [post](https://stackoverflow.com/a/66401340).
*/
fun <T> List<List<T>>.transpose(): List<List<T>> {
val result: MutableList<MutableList<T>> = (this.first().indices).map { mutableListOf<T>() }.toMutableList()
this.forEach { columns -> result.zip(columns).forEach { (rows, cell) -> rows.add(cell) } }
return result
}
infix fun <T : Comparable<T>> ClosedRange<T>.fullyContains(other: ClosedRange<T>): Boolean {
return this.start in other && this.endInclusive in other
}
infix fun <T : Comparable<T>> ClosedRange<T>.overlaps(other: ClosedRange<T>): Boolean {
return this.start in other || this.endInclusive in other
}
fun <E> List<E>.toPair(): Pair<E, E> {
require(this.size == 2) { "The given list has to contain exactly two elements, instead found ${this.size}" }
return this[0] to this[1]
}
fun String.parseRange(delimiter: Char = '-'): IntRange {
val (from: Int, to: Int) = this.split(delimiter).map { it.toInt() }
return from..to
}
@Synchronized
fun <K, V> MutableMap<K, V>.getOrCompute(key: K, valueFunction: () -> V): V {
return this[key] ?: valueFunction().also { this[key] = it }
}
fun <T, R> Collection<T>.allUnique(block: (T) -> R): Boolean {
val mapped: List<R> = this.map(block)
return mapped.size == mapped.toSet().size
}
fun <E> Collection<E>.cartesianProduct(): List<Pair<E, E>> {
return this.flatMap { lhs: E -> this.map { rhs: E -> lhs to rhs } }
}
fun Iterable<Int>.multiply(): Int = fold(1) { a, i -> a * i }
fun Iterable<Long>.multiply(): Long = fold(1L) { a, l -> a * l }
fun Char.parseInt(): Int = toString().toInt()
fun <T> String.parseMatrix(block: (Char) -> T): List<List<T>> {
return this.splitByLines().map { it.splitByCharacter().map(block) }
}
fun <T> String.parseGrid(block: (Char) -> T): Grid<T> {
return Grid.fromMatrix(this.parseMatrix(block))
}
fun <T, R> memoize(block: (T) -> R): (T) -> R {
val cache: MutableMap<T, R> = mutableMapOf()
return { input: T ->
cache.getOrPut(input) { block(input) }
}
}
fun IntProgression.middle(): Int = (first + last) / 2
fun LongProgression.middle(): Long = (first + last) / 2
fun <E> Collection<E>.containsTimes(e: E, times: Int): Boolean = count { it == e } == times
fun <T> Iterable<T>.notAll(block: (T) -> Boolean): Boolean = !all(block)
fun Collection<Number>.lowestCommonMultiple(): Long {
/**
* Calculates the "lowest common multiple" of two numbers.
*/
fun lcm(a: Long, b: Long): Long {
/**
* Calculates the "greatest common divisor" of two numbers.
*/
fun gcd(a: Long, b: Long): Long = if (b == 0L) a else gcd(b, a % b)
return a / gcd(a, b) * b
}
return if (this.isNotEmpty() && !this.contains(0L)) {
this.distinct().map { it.toLong() }.reduce { acc, num -> lcm(acc, num) }
} else 0L // LCM is not defined for empty sets or sets containing 0
}
| 0 | Kotlin | 0 | 0 | 6f2bd7bdfc9719fda6432dd172bc53dce049730a | 6,426 | advent-of-code-2023 | MIT License |
archive/103/solve.kt | daniellionel01 | 435,306,139 | false | null | /*
=== #103 Special subset sums: optimum - Project Euler ===
Let S(A) represent the sum of elements in set A of size n. We shall call it a special sum set if for any two non-empty disjoint subsets, B and C, the following properties are true:
S(B) ≠ S(C); that is, sums of subsets cannot be equal.
If B contains more elements than C then S(B) > S(C).
If S(A) is minimised for a given n, we shall call it an optimum special sum set. The first five optimum special sum sets are given below.
n = 1: {1}n = 2: {1, 2}n = 3: {2, 3, 4}n = 4: {3, 5, 6, 7}n = 5: {6, 9, 11, 12, 13}
It seems that for a given optimum set, A = {a1, a2, ... , an}, the next optimum set is of the form B = {b, a1+b, a2+b, ... ,an+b}, where b is the "middle" element on the previous row.
By applying this "rule" we would expect the optimum set for n = 6 to be A = {11, 17, 20, 22, 23, 24}, with S(A) = 117. However, this is not the optimum set, as we have merely applied an algorithm to provide a near optimum set. The optimum set for n = 6 is A = {11, 18, 19, 20, 22, 25}, with S(A) = 115 and corresponding set string: 111819202225.
Given that A is an optimum special sum set for n = 7, find its set string.
NOTE: This problem is related to Problem 105 and Problem 106.
Difficulty rating: 45%
*/
fun solve(x: Int): Int {
return x*2;
}
fun main() {
val a = solve(10);
println("solution: $a");
} | 0 | Kotlin | 0 | 1 | 1ad6a549a0a420ac04906cfa86d99d8c612056f6 | 1,374 | euler | MIT License |
kotlin/structures/QuadTree.kt | polydisc | 281,633,906 | true | {"Java": 540473, "Kotlin": 515759, "C++": 265630, "CMake": 571} | package structures
// https://en.wikipedia.org/wiki/Quadtree
class QuadTree {
class Node {
var count = 0
var topLeft: Node? = null
var topRight: Node? = null
var bottomLeft: Node? = null
var bottomRight: Node? = null
}
var root: Node? = null
// insert point (x,y)
fun insert(x: Int, y: Int) {
root = insert(root, 0, 0, maxx - 1, maxy - 1, x, y)
}
fun insert(node: Node?, ax: Int, ay: Int, bx: Int, by: Int, x: Int, y: Int): Node? {
var node = node
if (ax > x || x > bx || ay > y || y > by) return node
if (node == null) node = Node()
++node.count
if (ax == bx && ay == by) return node
val mx = ax + bx shr 1
val my = ay + by shr 1
node.bottomLeft = insert(node.bottomLeft, ax, ay, mx, my, x, y)
node.topLeft = insert(node.topLeft, ax, my + 1, mx, by, x, y)
node.bottomRight = insert(node.bottomRight, mx + 1, ay, bx, my, x, y)
node.topRight = insert(node.topRight, mx + 1, my + 1, bx, by, x, y)
return node
}
// number of points in [x1,x2] x [y1,y2]
fun count(x1: Int, y1: Int, x2: Int, y2: Int): Int {
return count(root, 0, 0, maxx - 1, maxy - 1, x1, y1, x2, y2)
}
fun count(node: Node?, ax: Int, ay: Int, bx: Int, by: Int, x1: Int, y1: Int, x2: Int, y2: Int): Int {
if (node == null || ax > x2 || x1 > bx || ay > y2 || y1 > by) return 0
if (x1 <= ax && bx <= x2 && y1 <= ay && by <= y2) return node.count
val mx = ax + bx shr 1
val my = ay + by shr 1
var res = 0
res += count(node.bottomLeft, ax, ay, mx, my, x1, y1, x2, y2)
res += count(node.topLeft, ax, my + 1, mx, by, x1, y1, x2, y2)
res += count(node.bottomRight, mx + 1, ay, bx, my, x1, y1, x2, y2)
res += count(node.topRight, mx + 1, my + 1, bx, by, x1, y1, x2, y2)
return res
}
companion object {
const val maxx = 1 shl 30
const val maxy = 1 shl 30
// Usage example
fun main(args: Array<String?>?) {
val t = QuadTree()
t.insert(0, 0)
t.insert(1, 0)
t.insert(2, 0)
t.insert(3, 0)
System.out.println(4 == t.count(0, 0, 3, 0))
}
}
}
| 1 | Java | 0 | 0 | 4566f3145be72827d72cb93abca8bfd93f1c58df | 2,302 | codelibrary | The Unlicense |
app/src/main/kotlin/me/mataha/misaki/solutions/adventofcode/aoc2015/d06/Day.kt | mataha | 302,513,601 | false | {"Kotlin": 92734, "Gosu": 702, "Batchfile": 104, "Shell": 90} | package me.mataha.misaki.solutions.adventofcode.aoc2015.d06
import com.github.h0tk3y.betterParse.grammar.parseToEnd
import me.mataha.misaki.domain.adventofcode.AdventOfCode
import me.mataha.misaki.domain.adventofcode.AdventOfCodeDay
/** See the puzzle's full description [here](https://adventofcode.com/2015/day/6). */
@AdventOfCode("Probably a Fire Hazard", 2015, 6)
class ProbablyAFireHazard : AdventOfCodeDay<List<Instruction>, Int>() {
override fun parse(input: String): List<Instruction> =
LightGridGrammar.parseToEnd(input)
override fun solvePartOne(input: List<Instruction>): Int {
val grid = object : LightGrid() {
override fun turnOn(x: Int, y: Int) = run { this[x, y] = 1 }
override fun turnOff(x: Int, y: Int) = run { this[x, y] = 0 }
override fun toggle(x: Int, y: Int) = run { this[x, y] = this[x, y] xor 1 }
}
return grid.illuminate(input)
}
override fun solvePartTwo(input: List<Instruction>): Int {
val grid = object : LightGrid() {
override fun turnOn(x: Int, y: Int) = run { this[x, y] += 1 }
override fun turnOff(x: Int, y: Int) = run { if (this[x, y] > 0) this[x, y] -= 1 }
override fun toggle(x: Int, y: Int) = run { this[x, y] += 2 }
}
return grid.illuminate(input)
}
}
private fun LightGrid.illuminate(instructions: List<Instruction>): Int {
for (instruction in instructions) {
this.process(instruction)
}
return this.luminosity
}
| 0 | Kotlin | 0 | 0 | 748a5b25a39d01b2ffdcc94f1a99a6fbc8a02685 | 1,534 | misaki | MIT License |
src/test/kotlin/adventofcode/day13/Day13.kt | jwcarman | 573,183,719 | false | {"Kotlin": 183494} | /*
* Copyright (c) 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 adventofcode.day13
import adventofcode.util.isNumeric
import adventofcode.util.readAsString
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals
private const val EMPTY_LIST = "[]"
private const val DIVIDER_PACKET_1 = "[[2]]"
private const val DIVIDER_PACKET_2 = "[[6]]"
class Day13 {
@Test
fun example1() {
assertEquals(13, calculatePart1(readAsString("day13-example.txt")))
}
@Test
fun part1() {
assertEquals(5330, calculatePart1(readAsString("day13.txt")))
}
@Test
fun example2() {
assertEquals(140, calculatePart2(readAsString("day13-example.txt")))
}
@Test
fun part2() {
assertEquals(27648, calculatePart2(readAsString("day13.txt")))
}
private fun comparePackets(left: String, right: String): Int {
when {
left.isEmptyPacketList() && right.isEmptyPacketList() -> return 0
left.isNumeric() && right.isNumeric() -> return left.toInt() - right.toInt()
left.isNumeric() -> return comparePackets("[$left]", right)
right.isNumeric() -> return comparePackets(left, "[$right]")
left.isEmptyPacketList() -> return -1
right.isEmptyPacketList() -> return 1
else -> {
val compare = comparePackets(left.packetListHead(), right.packetListHead())
if (compare == 0) {
return comparePackets(left.packetListTail(), right.packetListTail())
}
return compare
}
}
}
private fun calculatePart1(input: String): Int {
return input.split("\n\n")
.asSequence()
.map { it.split("\n") }
.withIndex()
.filter { comparePackets(it.value[0], it.value[1]) < 0 }
.map { it.index + 1 }
.sum()
}
private fun calculatePart2(input: String): Int {
val lines = ("$DIVIDER_PACKET_1\n$DIVIDER_PACKET_2\n\n$input").lines()
.filter { it.isNotEmpty() }
.sortedWith { l, r -> comparePackets(l, r) }
return (lines.indexOf(DIVIDER_PACKET_1) + 1) * (lines.indexOf(DIVIDER_PACKET_2) + 1)
}
private fun String.isEmptyPacketList(): Boolean = EMPTY_LIST == this
private fun String.indexOfTopLevelComma(): Int {
var level = 0
for (i in indices) {
when (get(i)) {
'[' -> level++
']' -> level--
',' -> {
if (level == 1) {
return i
}
}
}
}
return -1
}
private fun String.packetListHead(): String {
val ndx = indexOfTopLevelComma()
if (ndx == -1) {
return substring(1, length - 1)
}
return substring(1, ndx)
}
private fun String.packetListTail(): String {
val ndx = indexOfTopLevelComma()
if (ndx == -1) {
return EMPTY_LIST
}
return "[${substring(ndx + 1)}"
}
} | 0 | Kotlin | 0 | 0 | d6be890aa20c4b9478a23fced3bcbabbc60c32e0 | 3,662 | adventofcode2022 | Apache License 2.0 |
algorithms_and_data_structure/with_kotlin/algoritms/BinarySearch.kt | ggsant | 423,455,976 | false | {"Dart": 27223, "Kotlin": 6516} | class BinarySearchSolution
fun main() {
print(binarySearch(arrayOf(12, 3, 24, 5, 10, 23, 9), 23))
}
/**
* @param array is an array where the element should be found
* @param key is an element which should be found
* @return index of the element
*/
fun <T : Comparable<T>> binarySearch(array: Array<T>, key: T): Int {
return binarySearchHelper(array, key, 0, array.size - 1)
}
/**
* @param array The array to search
* @param key The element you are looking for
* @param left is the index of the first element at array.
* @param is the index of the last element at array.
* @return the location of the key or -1 if the element is not found
*/
fun <T : Comparable<T>> binarySearchHelper(array: Array<T>, key: T, start: Int, end: Int): Int {
if (start > end) {
return -1
}
val mid = start + (end - start) / 2
return when {
array[mid].compareTo(key) == 0 -> mid
array[mid].compareTo(key) > 0 -> binarySearchHelper(array, key, start, mid - 1)
else -> binarySearchHelper(array, key, mid + 1, end)
}
}
| 0 | Dart | 0 | 1 | 8ebed6dd46cdbdfada6f19610479191bcc37dd22 | 1,068 | algorithms_analysis_and_data_structure | MIT License |
library/src/main/kotlin/com/benmanwaring/permutations/ArrayPermutations.kt | BenManwaring | 254,948,525 | false | null | package com.benmanwaring.permutations
import com.benmanwaring.permutations.iterables.PermutationsIterable
import com.benmanwaring.permutations.iterators.ArrayPermutationsIterator
import com.benmanwaring.permutations.iterators.IncrementalLengthIterator
inline fun <reified T> Array<T>.permutations(length: Int): Iterable<Array<T>> {
return permutations(length, arrayFactory())
}
fun <T> Array<T>.permutations(
length: Int,
arrayFactory: (length: Int, initialValue: T) -> Array<T>
): Iterable<Array<T>> {
if (length < 1) {
return emptyList()
}
return Iterable { ArrayPermutationsIterator(asIterable(), length, arrayFactory) }
}
inline fun <reified T> Array<T>.permutations(range: Iterable<Int>): Iterable<Array<T>> {
return permutations(range, arrayFactory())
}
fun <T> Array<T>.permutations(
range: Iterable<Int>,
arrayFactory: (length: Int, initialValue: T) -> Array<T>
): Iterable<Array<T>> {
return object : Iterable<Array<T>>, PermutationsIterable<Array<T>> {
override fun iterator(): Iterator<Array<T>> {
return IncrementalLengthIterator(this, range)
}
override fun create(length: Int): Iterator<Array<T>> {
return permutations(length, arrayFactory).iterator()
}
}
}
inline fun <reified T> arrayFactory(): (length: Int, initialValue: T) -> Array<T> {
return { length, initialValue -> Array(length) { initialValue } }
}
| 1 | Kotlin | 0 | 0 | a03117de045622723b162c378201bc2705fa7d22 | 1,444 | Permutations | Apache License 2.0 |
src/main/kotlin/com/ginsberg/advent2023/Day02.kt | tginsberg | 723,688,654 | false | {"Kotlin": 112398} | /*
* Copyright (c) 2023 by <NAME>
*/
/**
* Advent of Code 2023, Day 2 - Cube Conundrum
* Problem Description: http://adventofcode.com/2023/day/2
* Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2023/day2/
*/
package com.ginsberg.advent2023
class Day02(input: List<String>) {
private val games: List<Game> = input.map { Game.of(it) }
fun solvePart1(): Int =
games.filter {
it.isPossible(12, 13, 14)
}.sumOf { it.id }
fun solvePart2(): Int =
games.sumOf { it.power() }
private data class Game(val id: Int, val red: Int, val green: Int, val blue: Int) {
fun isPossible(red: Int, green: Int, blue: Int) =
this.red <= red && this.green <= green && this.blue <= blue
fun power() =
red * blue * green
companion object {
fun of(input: String): Game {
val id = input.substringAfter(" ").substringBefore(":").toInt()
val colors = mutableMapOf<String, Int>()
input.substringAfter(":").split(";").forEach { turn ->
turn.split(",").map { it.trim() }.forEach { draw ->
val drawNum = draw.substringBefore(" ").toInt()
val color = draw.substringAfter(" ")
colors[color] = maxOf(drawNum, colors[color] ?: drawNum)
}
}
return Game(id, colors["red"] ?: 0, colors["green"] ?: 0, colors["blue"] ?: 0)
}
}
}
} | 0 | Kotlin | 0 | 12 | 0d5732508025a7e340366594c879b99fe6e7cbf0 | 1,559 | advent-2023-kotlin | Apache License 2.0 |
src/main/kotlin/be/tabs_spaces/advent2021/days/Day03.kt | janvryck | 433,393,768 | false | {"Kotlin": 58803} | package be.tabs_spaces.advent2021.days
import kotlin.math.pow
class Day03 : Day(3) {
override fun partOne(): Any {
val diagnostics = Diagnostics.fromInput(inputList)
return diagnostics.gammaRate * diagnostics.epsilonRate
}
override fun partTwo(): Any {
val diagnostics = Diagnostics.fromInput(inputList)
return diagnostics.oxygenRating() * diagnostics.scrubberRating()
}
class Diagnostics private constructor(private val diagnostics: List<Diagnostic>) {
private val size
get() = diagnostics.size
private val maxGammaRate by lazy { (2.0.pow(maxOccurrencesPerIndex().size) - 1).toInt() }
val gammaRate by lazy { maxOccurrencesPerIndex().decimal }
val epsilonRate by lazy { maxGammaRate - gammaRate }
companion object {
fun fromInput(rawDiagnostics: List<String>) = Diagnostics(rawDiagnostics
.map { diagnostic -> diagnostic.indices.map { diagnostic[it] } }
.map { Diagnostic(it) })
}
private fun occurrencesByIndex() = diagnostics.first().indices.map { idx -> diagnostics.map { it.get(idx) }.groupingBy { it }.eachCount() }
private fun maxOccurrenceForIndex(index: Int) = occurrencesByIndex()[index].toSortedMap(naturalOrder<Char>().reversed()).maxByOrNull { it.value }?.key
private fun maxOccurrencesPerIndex(): Diagnostic = Diagnostic(diagnostics.first().indices.mapNotNull { maxOccurrenceForIndex(it) })
private fun filterByBitValue(index: Int, matching: Boolean = true) = Diagnostics(
diagnostics.filter {
(it.get(index) == maxOccurrenceForIndex(index)) == matching
}
)
fun oxygenRating(): Int {
var filtered = this
(0 until diagnostics.first().size).forEach {
if (filtered.size > 1) {
filtered = filtered.filterByBitValue(it)
}
}
return filtered.diagnostics.first().decimal
}
fun scrubberRating(): Int {
var filtered = this
(0 until diagnostics.first().size).forEach {
if (filtered.size > 1) {
filtered = filtered.filterByBitValue(it, false)
}
}
return filtered.diagnostics.first().decimal
}
}
data class Diagnostic(private val rawDiagnostic: List<Char>) {
val indices
get() = rawDiagnostic.indices
val size
get() = rawDiagnostic.size
val decimal
get() = rawDiagnostic.joinToString("").toInt(2)
fun get(index: Int) = rawDiagnostic[index]
}
} | 0 | Kotlin | 0 | 0 | f6c8dc0cf28abfa7f610ffb69ffe837ba14bafa9 | 2,708 | advent-2021 | Creative Commons Zero v1.0 Universal |
src/Day06.kt | BenHopeITC | 573,352,155 | false | null | fun List<Char>.areUnique(): Boolean {
return this.size == this.toSet().size
}
fun String.firstUniqueSequenceOf(length: Int) = String(this.toCharArray().toList()
.windowed(length)
.first { it.areUnique() }
.toCharArray())
fun main() {
val day = "Day06"
fun part1(input: String) = input.indexOf(input.firstUniqueSequenceOf(4)) + 4
fun part2(input: String) = input.indexOf(input.firstUniqueSequenceOf(14)) + 14
// test if implementation meets criteria from the description, like:
// val testInput = readInputAsText("${day}_test")
// println(part1(testInput))
// check(part1(testInput) == 7)
// test if implementation meets criteria from the description, like:
// val testInput2 = readInputAsText("${day}_test")
// println(part2(testInput2))
// check(part2(testInput2) == 19)
val input = readInputAsText(day)
println(part1(input))
println(part2(input))
check(part1(input) == 1896)
check(part2(input) == 3452)
}
| 0 | Kotlin | 0 | 0 | 851b9522d3a64840494b21ff31d83bf8470c9a03 | 1,000 | advent-of-code-2022-kotlin | Apache License 2.0 |
kotlin/src/2022/Day14_2022.kt | regob | 575,917,627 | false | {"Kotlin": 50757, "Python": 46520, "Shell": 430} | import kotlin.math.sign
private data class Point(val x: Int, val y: Int)
private fun next(p: Point, m: Map<Point, Int>, yMax: Int) : Point? {
if (p.y + 1 >= yMax) return null
for (pt in listOf(Point(p.x, p.y + 1), Point(p.x - 1, p.y + 1), Point(p.x + 1, p.y + 1)))
if (pt !in m) return pt
return null
}
fun main() {
val input = readInput(14).trim().lines()
// 1 -> rock, 2 -> sand, not in map (-1) -> air
val M = mutableMapOf<Point, Int>()
input.forEach {
val pts = it.split(" -> ").map { x ->
val ps = x.split(",")
Point(ps[0].toInt(), ps[1].toInt())
}
for ((pStart, pEnd) in pts.dropLast(1).zip(pts.drop(1))) {
val (xstep, ystep) = (pEnd.x - pStart.x).sign to (pEnd.y - pStart.y).sign
M[pStart] = 1
var p = pStart
while (p != pEnd) {
p = Point(p.x + xstep, p.y + ystep)
M[p] = 1
}
}
}
val yMax = M.maxOf {it.key.y} + 2
// part1
var m = M.toMutableMap()
var cnt = 0
while (true) {
var p = Point(500, 0)
var np = next(p, m, yMax)
while (np != null) {
p = np
np = next(p, m, yMax)
}
if (p.y == yMax - 1) break
cnt += 1
m[p] = 2
}
println(cnt)
// part2
m = M.toMutableMap()
cnt = 0
while (true) {
var p = Point(500, 0)
var np = next(p, m, yMax)
while (np != null) {
p = np
np = next(p, m, yMax)
}
cnt += 1
m[p] = 2
if (p == Point(500, 0)) break
}
println(cnt)
} | 0 | Kotlin | 0 | 0 | cf49abe24c1242e23e96719cc71ed471e77b3154 | 1,667 | adventofcode | Apache License 2.0 |
atcoder/arc156/b.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package atcoder.arc156
fun main() {
var (_, k) = readInts()
val a = readInts().toSet()
val f = (0..a.size).first { it !in a }
var ans = if (f > 0) take(k, f) else 0.toModularUnsafe()
for (x in f..Int.MAX_VALUE) {
ans += take(k - 1, x + 1)
if (x !in a && --k == 0) break
}
println(ans)
}
private fun take(n: Int, m: Int) = cnk(n + m - 1, n)
//typealias Modular = Double; fun Number.toModular() = toDouble(); fun Number.toModularUnsafe() = toDouble()
//typealias ModularArray = DoubleArray; val ModularArray.data; get() = this
@Suppress("NOTHING_TO_INLINE")
private class Modular(val x: Int) {
companion object {
const val M = 998244353; val MOD_BIG_INTEGER = M.toBigInteger()
}
inline operator fun plus(that: Modular) = Modular((x + that.x).let { if (it >= M) it - M else it })
inline operator fun minus(that: Modular) = Modular((x - that.x).let { if (it < 0) it + M else it })
inline operator fun times(that: Modular) = Modular((x.toLong() * that.x % M).toInt())
inline operator fun div(that: Modular) = times(that.inverse())
inline fun inverse() = Modular(x.toBigInteger().modInverse(MOD_BIG_INTEGER).toInt())
override fun toString() = x.toString()
}
private fun Int.toModularUnsafe() = Modular(this)
private fun Int.toModular() = Modular(if (this >= 0) { if (this < Modular.M) this else this % Modular.M } else { Modular.M - 1 - inv() % Modular.M })
private fun Long.toModular() = Modular((if (this >= 0) { if (this < Modular.M) this else this % Modular.M } else { Modular.M - 1 - inv() % Modular.M }).toInt())
private fun java.math.BigInteger.toModular() = Modular(mod(Modular.MOD_BIG_INTEGER).toInt())
private fun String.toModular() = Modular(fold(0L) { acc, c -> (c - '0' + 10 * acc) % Modular.M }.toInt())
private class ModularArray(val data: IntArray) {
operator fun get(index: Int) = data[index].toModularUnsafe()
operator fun set(index: Int, value: Modular) { data[index] = value.x }
}
private inline fun ModularArray(n: Int, init: (Int) -> Modular) = ModularArray(IntArray(n) { init(it).x })
private val factorials = mutableListOf(1.toModularUnsafe())
private fun factorial(n: Int): Modular {
while (n >= factorials.size) factorials.add(factorials.last() * factorials.size.toModularUnsafe())
return factorials[n]
}
private fun cnk(n: Int, k: Int) = factorial(n) / factorial(k) / factorial(n - k)
private fun readLn() = readLine()!!
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 2,478 | competitions | The Unlicense |
src/main/kotlin/leetcode/kotlin/tree/257. Binary Tree Paths.kt | sandeep549 | 251,593,168 | false | null | package leetcode.kotlin.tree
private fun binaryTreePaths(root: TreeNode?): List<String> {
fun dfs(root: TreeNode?): List<String> {
root?.let {
if (it.left == null && it.right == null) return mutableListOf("" + it.`val`)
var l = dfs(it.left).map { "" + root.`val` + "->" + it }
var r = dfs(it.right).map { "" + root.`val` + "->" + it }
return l + r
}
return listOf()
}
return dfs(root)
}
private fun binaryTreePaths2(root: TreeNode?): List<String>? {
val answer = arrayListOf<String>()
fun dfs(root: TreeNode?, path: String, answer: MutableList<String>) {
if (root!!.left == null && root.right == null) answer.add(path + root.`val`)
root.left?.let { dfs(it, path + root.`val` + "->", answer) }
root.right?.let { dfs(it, path + root.`val` + "->", answer) }
}
root?.let { dfs(it, "", answer) }
return answer
}
fun binaryTreePaths3(root: TreeNode?): List<String> {
if (root == null) return emptyList()
if (root.left == null && root.right == null) return listOf(root.`val`.toString())
val left = binaryTreePaths(root.left)
val right = binaryTreePaths(root.right)
return (left + right).map { root.`val`.toString() + "->" + it }
}
fun binaryTreePaths4(root: TreeNode?): List<String> {
return when {
root == null -> emptyList()
root.left == null && root.right == null -> listOf(root.`val`.toString())
else -> (binaryTreePaths(root.left) + binaryTreePaths(root.right)).map { root.`val`.toString() + "->" + it }
}
}
// TODO: do it with iteration
// TODO: calculate exact time complexity
| 0 | Kotlin | 0 | 0 | 9cf6b013e21d0874ec9a6ffed4ae47d71b0b6c7b | 1,662 | kotlinmaster | Apache License 2.0 |
src/Day01.kt | bendh | 573,833,833 | false | {"Kotlin": 11618} | fun main() {
fun part1(input: List<String>): Int {
var max = 0
var temp = 0
input.forEach {
if(it.isNotEmpty()) {
temp += it.toInt()
} else {
max = if (temp > max) temp else max
temp = 0
}
}
return max
}
fun part2(input: List<String>): Int {
var temp = 0
val caloryPerElf = ArrayList<Int>()
input.forEach {
if(it.isNotEmpty()) {
temp += it.toInt()
} else {
caloryPerElf.add(temp)
temp = 0
}
}
caloryPerElf.sort()
return caloryPerElf.takeLast(3).sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readLines("Day01_test")
check(part1(testInput) == 15)
val input = readLines("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | e3ef574441b63a99a99a095086a0bf025b8fc475 | 968 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/main/kotlin/com/leetcode/P235.kt | antop-dev | 229,558,170 | false | {"Kotlin": 695315, "Java": 213000} | package com.leetcode
// https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/
class P235 {
fun lowestCommonAncestor(root: TreeNode?, p: TreeNode?, q: TreeNode?): TreeNode? {
val path1 = path(root!!, p!!)
val path2 = path(root, q!!)
println()
println("path1 = ${path1.contentToString()}, path2 = ${path2.contentToString()}")
for (i in path1.lastIndex downTo 0) {
for (j in path2.lastIndex downTo 0) {
if (path1[i] == path2[j]) return TreeNode(path1[i])
}
}
return null
}
// 재귀의 시작
private fun path(root: TreeNode, target: TreeNode): IntArray {
println()
println("find path = ${target.`val`}")
val list = mutableListOf<Int>()
search(list, root, target.`val`);
return list.toIntArray()
}
// 재귀 (꼬리)
private fun search(list: MutableList<Int>, node: TreeNode?, target: Int): Boolean {
if (node == null) return false
println(" search node = ${node.`val`}")
if (node.`val` == target // 현재 내 노드가 타겟과 같거나
|| search(list, node.left, target) // 내 왼쪽 노드를 탐색해서 참이 나오거나
|| search(list, node.right, target) // 내 오른쪽 노드를 탐색해서 참이 나오거나
) {
list.add(0, node.`val`) // 리스트의 앞에 삽입
return true
}
return false
}
class TreeNode(var `val`: Int = 0) {
var left: TreeNode? = null
var right: TreeNode? = null
}
} | 1 | Kotlin | 0 | 0 | 9a3e762af93b078a2abd0d97543123a06e327164 | 1,634 | algorithm | MIT License |
src/day19/Day19.kt | ritesh-singh | 572,210,598 | false | {"Kotlin": 99540} | package day19
import readInput
private class RobotFactory(lines: List<String>) {
private data class BluePrint(
val id: Int,
val oreRReq: Int, // ore
val clayRReq: Int, // ore
val obsidianRReq: Pair<Int, Int>, // ore and clay
val geodeRReq: Pair<Int, Int> // ore and obsidian
)
private val bluePrints = mutableListOf<BluePrint>()
init {
lines.forEach { line ->
val chunks = line.split(".")
bluePrints.add(
BluePrint(
id = line.substringBefore(":").substringAfter("Blueprint").trim().toInt(),
oreRReq = chunks[0].substringAfter("costs").substringBefore("ore").trim().toInt(),
clayRReq = chunks[1].substringAfter("costs").substringBefore("ore").trim().toInt(),
obsidianRReq = Pair(
chunks[2].substringAfter("costs").substringBefore("ore").trim().toInt(),
chunks[2].substringAfter("and").substringBefore("clay").trim().toInt()
),
geodeRReq = Pair(
chunks[3].substringAfter("costs").substringBefore("ore").trim().toInt(),
chunks[3].substringAfter("and").substringBefore("obsidian").trim().toInt()
)
)
)
}
}
private data class State(
var ore: Int = 0,
var clay: Int = 0,
var obsidian: Int = 0,
var geodes: Int = 0,
var oreRobot: Int = 1,
var clayRobot: Int = 0,
var obsidianRobot: Int = 0,
var geodeRobot: Int = 0,
var time: Int = 24
)
private fun largestGeodeOpened(bluePrint: BluePrint, part1:Boolean): Int {
val queue = ArrayDeque<State>()
queue.addLast(State().copy(time = if (part1) 24 else 32))
var maxGeodes = Int.MIN_VALUE
val visited = hashSetOf<State>()
// bfs on all possible states
while (queue.isNotEmpty()) {
var currState = queue.removeFirst()
if (visited.contains(currState))
continue
visited.add(currState)
if (currState.time <= 0) {
maxGeodes = maxOf(maxGeodes, currState.geodes)
continue
}
// Reduce state by removing robots required per minute
val maxOresRequired = listOf(bluePrint.oreRReq, bluePrint.clayRReq, bluePrint.obsidianRReq.first, bluePrint.geodeRReq.first).max() // find max ores required for a robot
if (currState.oreRobot >= maxOresRequired) { // max ores which can be utilized for building any type of robot per minute
currState = currState.copy(
oreRobot = maxOresRequired
)
}
if (currState.clayRobot >= bluePrint.obsidianRReq.second) { // max clays which can be utilized for building any type of robot per minute
currState = currState.copy(
clayRobot = bluePrint.obsidianRReq.second
)
}
if (currState.obsidianRobot >= bluePrint.geodeRReq.second) { // max obsidian which can be utilized for building any type of robot per minute
currState = currState.copy(
obsidianRobot = bluePrint.geodeRReq.second
)
}
// Reduce state by removing resources not required per minute
if (currState.ore >= currState.time * maxOresRequired - currState.oreRobot * (currState.time - 1)) {
currState = currState.copy(
ore = currState.time * maxOresRequired - currState.oreRobot * (currState.time - 1)
)
}
if (currState.clay >= currState.time * bluePrint.obsidianRReq.second - currState.clayRobot * (currState.time - 1)) {
currState = currState.copy(
clay = currState.time * bluePrint.obsidianRReq.second - currState.clayRobot * (currState.time - 1)
)
}
if (currState.obsidian >= currState.time * bluePrint.geodeRReq.second - currState.obsidianRobot *(currState.time-1)){
currState = currState.copy(
obsidian = currState.time * bluePrint.geodeRReq.second - currState.obsidianRobot * (currState.time - 1)
)
}
queue.addLast( // don't buy any robot, just collect resources
currState.copy(
ore = currState.ore + currState.oreRobot,
clay = currState.clay + currState.clayRobot,
obsidian = currState.obsidian + currState.obsidianRobot,
geodes = currState.geodes + currState.geodeRobot,
time = currState.time - 1
)
)
if (currState.ore >= bluePrint.oreRReq) { // buy ore robot from prev robots and collect resources
queue.addLast(
currState.copy(
ore = currState.ore - bluePrint.oreRReq + currState.oreRobot,
clay = currState.clay + currState.clayRobot,
obsidian = currState.obsidian + currState.obsidianRobot,
geodes = currState.geodes + currState.geodeRobot,
oreRobot = currState.oreRobot + 1,
time = currState.time - 1
)
)
}
if (currState.ore >= bluePrint.clayRReq) { // buy clay robot from prev robots and collect resources
queue.addLast(
currState.copy(
ore = currState.ore - bluePrint.clayRReq + currState.oreRobot,
clay = currState.clay + currState.clayRobot,
obsidian = currState.obsidian + currState.obsidianRobot,
geodes = currState.geodes + currState.geodeRobot,
clayRobot = currState.clayRobot + 1,
time = currState.time - 1
)
)
}
if (currState.ore >= bluePrint.obsidianRReq.first && currState.clay >= bluePrint.obsidianRReq.second) {
queue.addLast( // buy obsidian robot from prev robots and collect resources
currState.copy(
ore = currState.ore - bluePrint.obsidianRReq.first + currState.oreRobot,
clay = currState.clay - bluePrint.obsidianRReq.second + currState.clayRobot,
obsidian = currState.obsidian + currState.obsidianRobot,
geodes = currState.geodes + currState.geodeRobot,
obsidianRobot = currState.obsidianRobot + 1,
time = currState.time - 1
)
)
}
if (currState.ore >= bluePrint.geodeRReq.first && currState.obsidian >= bluePrint.geodeRReq.second) {
queue.addLast( // buy geode robot from prev robots and collect resources
currState.copy(
ore = currState.ore - bluePrint.geodeRReq.first + currState.oreRobot,
obsidian = currState.obsidian - bluePrint.geodeRReq.second + currState.obsidianRobot,
clay = currState.clay + currState.clayRobot,
geodes = currState.geodes + currState.geodeRobot,
geodeRobot = currState.geodeRobot + 1,
time = currState.time - 1
)
)
}
}
return maxGeodes
}
fun answer(part1: Boolean):Int {
if (part1) {
return bluePrints.sumOf {
it.id * largestGeodeOpened(it, true)
}
}
return bluePrints.take(3)
.map {
largestGeodeOpened(it, false)
}.fold(1) { a, b -> a * b }
}
}
fun main() {
fun part1(input: List<String>): Int {
val robotFactory = RobotFactory(lines = input)
return robotFactory.answer(true)
}
fun part2(input: List<String>): Int {
val robotFactory = RobotFactory(lines = input)
return robotFactory.answer(false)
}
val input = readInput("/day19/Day19")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 17fd65a8fac7fa0c6f4718d218a91a7b7d535eab | 8,498 | aoc-2022-kotlin | Apache License 2.0 |
src/main/java/com/booknara/problem/search/binary/KthSmallestElementInSortedMatrixKt.kt | booknara | 226,968,158 | false | {"Java": 1128390, "Kotlin": 177761} | package com.booknara.problem.search.binary
/**
* 378. Kth Smallest Element in a Sorted Matrix (Medium)
* https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/
*/
class KthSmallestElementInSortedMatrixKt {
// T:O((m + n) * log(max value - min value), S:O(1)
fun kthSmallest(matrix: Array<IntArray>, k: Int): Int {
// input check, k is always valid
val row = matrix.size
val col = matrix[0].size
var s = matrix[0][0]
var e = matrix[row - 1][col - 1]
while (s < e) {
val mid = s + (e - s) / 2
val midIndex = find(matrix, mid)
//println("$mid, $midIndex")
if (midIndex < k) {
s = mid + 1
} else {
e = mid
}
}
return e
}
fun find(matrix: Array<IntArray>, mid: Int): Int {
var res = 0
var r = 0
var c = matrix[0].size - 1
while (r < matrix.size && c >= 0) {
if (matrix[r][c] <= mid) {
res += c + 1
r++
} else {
c--
}
}
return res
}
} | 0 | Java | 1 | 1 | 04dcf500ee9789cf10c488a25647f25359b37a53 | 1,015 | playground | MIT License |
src/Day01.kt | meierjan | 572,860,548 | false | {"Kotlin": 20066} | private fun createCaloriesSumArray(input: List<String>) : List<Int> {
val calorieGroups = mutableListOf(mutableListOf<Int>())
for(item in input) {
if (item.isEmpty()) {
calorieGroups.add(mutableListOf())
} else {
calorieGroups.last().add(item.toInt())
}
}
return calorieGroups.map { calGroup ->
calGroup.sumOf { it }
}
}
fun part1(input: List<String>): Int =
createCaloriesSumArray(input)
.max()
fun part2(input: List<String>): Int =
createCaloriesSumArray(input)
.takeLast(3)
.sum()
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_1_test")
check(part1(testInput) == 24000)
val input = readInput("Day01_1")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | a7e52209da6427bce8770cc7f458e8ee9548cc14 | 858 | advent-of-code-kotlin-2022 | Apache License 2.0 |
day-4/src/both/Both.kt | woojiahao | 225,170,972 | false | null | package both
import timeAndAnswer
// Part 1
fun pairInput(i: Int, predicate: (Int, Int) -> Boolean) =
i.toString().zipWithNext { a, b -> predicate(a.toInt(), b.toInt()) }
fun hasRepeating(i: Int) = pairInput(i) { a, b -> a == b }.any { it }
fun isAscending(i: Int) = pairInput(i) { a, b -> a <= b }.all { it }
fun validate(i: Int) = hasRepeating(i) && isAscending(i)
fun solve(lower: Int, upper: Int) = (lower..upper).filter { validate(it) }.size
// Part 2
fun hasValidRepeatGroup(i: Int) = i.toString().groupBy { it }.map { it.value.size == 2 }.any { it }
fun validate2(i: Int) = validate(i) && hasValidRepeatGroup(i)
fun solve2(lower: Int, upper: Int) = (lower..upper).filter { validate2(it) }.size
fun main() {
timeAndAnswer(::solve)
timeAndAnswer(::solve2)
}
| 0 | Kotlin | 0 | 2 | 4c9220a49dbc093fbe7f0d6692fa0390a63e702a | 779 | aoc-19 | MIT License |
app/src/main/kotlin/kotlinadventofcode/2016/2016-01.kt | pragmaticpandy | 356,481,847 | false | {"Kotlin": 1003522, "Shell": 219} | // Originally generated by the template in CodeDAO
package kotlinadventofcode.`2016`
import com.github.h0tk3y.betterParse.combinators.*
import com.github.h0tk3y.betterParse.grammar.*
import com.github.h0tk3y.betterParse.lexer.*
import kotlinadventofcode.Day
import kotlin.math.abs
class `2016-01` : Day {
/**
* After verifying your solution on the AoC site, run `./ka continue` to add a test for it.
*/
override fun runPartOneNoUI(input: String): String {
var state = State(0, 0, CardinalDirection.NORTH)
parseInstructions(input).forEach { state = state.getStateAfter(it) }
return (abs(state.x) + abs(state.y)).toString()
}
/**
* After verifying your solution on the AoC site, run `./ka continue` to add a test for it.
*/
override fun runPartTwoNoUI(input: String): String {
var state = State(0, 0, CardinalDirection.NORTH)
val visited = mutableSetOf(0 to 0)
parseInstructions(input).forEach { instruction ->
val oldState = state
state = state.getStateAfter(instruction)
val allVisitedCoordinates = when (state.direction) {
CardinalDirection.NORTH -> ((oldState.y + 1)..state.y).map { oldState.x to it }
CardinalDirection.EAST -> ((oldState.x + 1)..state.x).map { it to oldState.y }
CardinalDirection.SOUTH -> ((oldState.y - 1) downTo state.y).map { oldState.x to it }
CardinalDirection.WEST -> ((oldState.x - 1) downTo state.x).map { it to oldState.y }
}
allVisitedCoordinates.forEach { coordinate ->
if (visited.contains(coordinate)) {
return (abs(coordinate.first) + abs(coordinate.second)).toString()
} else {
visited.add(coordinate)
}
}
}
throw IllegalStateException("No location visited twice")
}
data class State(val x: Int, val y: Int, val direction: CardinalDirection) {
fun getStateAfter(instruction: Instruction): State {
val newDirection = when (instruction.turn) {
Turn.CLOCKWISE -> when (direction) {
CardinalDirection.NORTH -> CardinalDirection.EAST
CardinalDirection.EAST -> CardinalDirection.SOUTH
CardinalDirection.SOUTH -> CardinalDirection.WEST
CardinalDirection.WEST -> CardinalDirection.NORTH
}
Turn.COUNTERCLOCKWISE -> when (direction) {
CardinalDirection.NORTH -> CardinalDirection.WEST
CardinalDirection.WEST -> CardinalDirection.SOUTH
CardinalDirection.SOUTH -> CardinalDirection.EAST
CardinalDirection.EAST -> CardinalDirection.NORTH
}
}
val newCoordinates = when (newDirection) {
CardinalDirection.NORTH -> x to y + instruction.distance
CardinalDirection.EAST -> x + instruction.distance to y
CardinalDirection.SOUTH -> x to y - instruction.distance
CardinalDirection.WEST -> x - instruction.distance to y
}
return State(newCoordinates.first, newCoordinates.second, newDirection)
}
}
enum class CardinalDirection {
NORTH,
EAST,
SOUTH,
WEST
}
enum class Turn {
CLOCKWISE,
COUNTERCLOCKWISE
}
data class Instruction(val turn: Turn, val distance: Int)
private fun parseInstructions(input: String): List<Instruction> {
val grammar = object : Grammar<List<Instruction>>() {
val commaLit by literalToken(",")
val spaceLit by literalToken(" ")
val rLit by literalToken("R")
val lLit by literalToken("L")
val positiveIntRegex by regexToken("\\d+")
val positiveInt by positiveIntRegex use { text.toInt() }
val turn by (rLit or lLit) map { if (it.text == "R") Turn.CLOCKWISE else Turn.COUNTERCLOCKWISE }
val instruction by (turn and positiveInt) map { Instruction(it.t1, it.t2) }
val separator by commaLit and spaceLit
override val rootParser by separatedTerms(instruction, separator)
}
return grammar.parseToEnd(input)
}
override val defaultInput = """R5, R4, R2, L3, R1, R1, L4, L5, R3, L1, L1, R4, L2, R1, R4, R4, L2, L2, R4, L4, R1, R3, L3, L1, L2, R1, R5, L5, L1, L1, R3, R5, L1, R4, L5, R5, R1, L185, R4, L1, R51, R3, L2, R78, R1, L4, R188, R1, L5, R5, R2, R3, L5, R3, R4, L1, R2, R2, L4, L4, L5, R5, R4, L4, R2, L5, R2, L1, L4, R4, L4, R2, L3, L4, R2, L3, R3, R2, L2, L3, R4, R3, R1, L4, L2, L5, R4, R4, L1, R1, L5, L1, R3, R1, L2, R1, R1, R3, L4, L1, L3, R2, R4, R2, L2, R1, L5, R3, L3, R3, L1, R4, L3, L3, R4, L2, L1, L3, R2, R3, L2, L1, R4, L3, L5, L2, L4, R1, L4, L4, R3, R5, L4, L1, L1, R4, L2, R5, R1, R1, R2, R1, R5, L1, L3, L5, R2"""
} | 0 | Kotlin | 0 | 3 | 26ef6b194f3e22783cbbaf1489fc125d9aff9566 | 5,012 | kotlinadventofcode | MIT License |
kotlin/src/katas/kotlin/leetcode/merge_k_sorted_lists/MergeSortedLists.kt | dkandalov | 2,517,870 | false | {"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221} | package katas.kotlin.leetcode.merge_k_sorted_lists
import katas.kotlin.leetcode.ListNode
import katas.kotlin.leetcode.listNodes
import datsok.shouldEqual
import org.junit.Test
/**
* https://leetcode.com/problems/merge-k-sorted-lists
*/
class MergeSortedListsTests {
@Test fun `merge k sorted linked lists`() {
merge(arrayOf(listNodes(1))) shouldEqual listNodes(1)
merge(arrayOf(listNodes(1, 2))) shouldEqual listNodes(1, 2)
merge(arrayOf(listNodes(1), listNodes(2))) shouldEqual listNodes(1, 2)
merge(arrayOf(listNodes(1, 2), listNodes(3))) shouldEqual listNodes(1, 2, 3)
merge(arrayOf(listNodes(1, 3), listNodes(2))) shouldEqual listNodes(1, 2, 3)
merge(arrayOf(listNodes(1, 4, 5), listNodes(1, 3, 4), listNodes(2, 6))) shouldEqual listNodes(1, 1, 2, 3, 4, 4, 5, 6)
}
}
private fun merge(listNodes: Array<ListNode?>): ListNode? {
fun Array<ListNode?>.removeMin(): ListNode {
var result: ListNode? = null
var index = 0
forEachIndexed { i, node ->
if (node != null) {
if (result == null || node.value < result!!.value) {
result = node
index = i
}
}
}
listNodes[index] = result!!.next
return result!!
}
fun Array<ListNode?>.hasNodes() = any { it != null }
if (!listNodes.hasNodes()) return null
var result = listNodes.removeMin()
result.next = null
while (listNodes.hasNodes()) {
val node = listNodes.removeMin()
node.next = result
result = node
}
return result.reverse()
} | 7 | Roff | 3 | 5 | 0f169804fae2984b1a78fc25da2d7157a8c7a7be | 1,641 | katas | The Unlicense |
src/main/kotlin/se/brainleech/adventofcode/aoc2022/Aoc2022Day09.kt | fwangel | 435,571,075 | false | {"Kotlin": 150622} | package se.brainleech.adventofcode.aoc2022
import se.brainleech.adventofcode.compute
import se.brainleech.adventofcode.readLines
import se.brainleech.adventofcode.verify
import kotlin.math.max
import kotlin.math.min
import kotlin.math.sign
class Aoc2022Day09 {
companion object {
const val DEBUG = false
const val TRACE = false
const val UP = "U"
const val RIGHT = "R"
const val DOWN = "D"
const val LEFT = "L"
fun List<Position>.offset(dx: Int, dy: Int) : List<Position> {
return this.map { Position(it.x + dx, it.y + dy) }.toList()
}
inline fun <T> T.trace(block: (T) -> Unit): T {
if (TRACE) block(this)
return this
}
inline fun <T> T.debug(block: (T) -> Unit): T {
if (DEBUG) block(this)
return this
}
}
data class Rule(val direction: String, val steps: Int) {
companion object {
fun parse(instruction: String) : Rule {
val (direction, steps) = instruction.split(" ")
return Rule(direction, steps.toInt())
}
}
}
data class Position(var x: Int, var y: Int) {
fun move(direction: String) : Position {
when (direction) {
UP -> y --
RIGHT -> x ++
DOWN -> y ++
LEFT -> x --
}
return this
}
private val distance: Int get() = (x * x) + (y * y)
fun follow(leader: Position) : Position {
val offset = Position(leader.x - x, leader.y - y)
if (offset.distance > 2) {
x += offset.x.sign
y += offset.y.sign
}
return this
}
fun cloned() : Position {
return Position(x, y)
}
override fun toString(): String {
return "(x:${x}, y:${y})"
}
}
data class KnotsSpace(private val ropeLength: Int) {
private val rope: MutableList<Position> = mutableListOf()
private val tailVisited: LinkedHashSet<Position> = linkedSetOf()
init {
repeat(ropeLength) { rope.add(Position(0,0)) }
tailVisited.add(rope.last().cloned())
}
fun process(input: List<String>) : Int {
if (input.isEmpty()) return -1
input.forEach { instruction -> move(Rule.parse(instruction)) }
return tailVisits().count()
}
private fun move(rule: Rule) {
repeat(rule.steps) {
rope.first().move(rule.direction)
rope.drop(1).forEachIndexed { index, knot ->
knot.follow(rope[index])
}
tailVisited.add(rope.last().cloned())
}
trace { println("$this\n") }
}
private fun tailVisits(): List<Position> {
return tailVisited.toList()
.debug { println(this); println("Locations visited by the tail: ${tailVisited.count()}\n") }
}
override fun toString(): String {
val minX = min(tailVisited.minOf { it.x }, rope.minOf { it.x })
val minY = min(-5, min(tailVisited.minOf { it.y }, rope.minOf { it.y }))
val visited = tailVisited.map { it.cloned() }.toList().offset(-minX, -minY)
val knots = rope.map { it.cloned() }.toList().offset(-minX, -minY)
val width = max(10, max(visited.maxOf { it.x }, knots.maxOf { it.x })).plus(1)
val height = max(visited.maxOf { it.y }, knots.maxOf { it.y }).plus(1)
val world = ".".repeat(width * height).toCharArray()
visited.onEach {
world[(width * it.y) + it.x] = '#'
}
knots.drop(1).onEachIndexed { index, it ->
world[(width * it.y) + it.x] = (index + 1).digitToChar()
}
world[(width * knots.last().y) + knots.last().x] = 'T'
world[(width * knots.first().y) + knots.first().x] = 'H'
world[(width * visited.first().y) + visited.first().x] = 's'
return world.asSequence().chunked(width).map { it.joinToString("") }.joinToString("\n")
}
}
fun part1(input: List<String>) : Int {
return KnotsSpace(2).process(input)
}
fun part2(input: List<String>) : Int {
return KnotsSpace(10).process(input)
}
}
fun main() {
val solver = Aoc2022Day09()
val prefix = "aoc2022/aoc2022day09"
val testData = readLines("$prefix.test.txt")
val realData = readLines("$prefix.real.txt")
verify(13, solver.part1(testData))
compute({ solver.part1(realData) }, "$prefix.part1 = ")
verify(1, solver.part2(testData))
verify(9, solver.part2(listOf("R 10", "U 10", "L 10", "D 10")))
verify(36, solver.part2(listOf("R 5", "U 8", "L 8", "D 3", "R 17", "D 10", "L 25", "U 20")))
compute({ solver.part2(realData) }, "$prefix.part2 = ")
} | 0 | Kotlin | 0 | 0 | 0bba96129354c124aa15e9041f7b5ad68adc662b | 5,027 | adventofcode | MIT License |
src/main/kotlin/de/tek/adventofcode/y2022/day07/NoSpaceLeftOnDevice.kt | Thumas | 576,671,911 | false | {"Kotlin": 192328} | package de.tek.adventofcode.y2022.day07
import de.tek.adventofcode.y2022.util.readInputLines
abstract class FileSystemElement(val name: String) {
abstract fun getSize(): Int
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is FileSystemElement) return false
if (name != other.name) return false
return true
}
override fun hashCode(): Int {
return name.hashCode()
}
}
class File(name: String, private val size: Int) : FileSystemElement(name) {
override fun getSize() = size
override fun toString(): String {
return "File(name=$name, size=$size)"
}
}
class Directory private constructor(name: String, val parent: Directory?) : FileSystemElement(name),
Iterable<FileSystemElement> {
companion object {
fun newRoot() = Directory("/", null)
}
private val children = mutableMapOf<FileSystemElement, FileSystemElement>()
override fun getSize(): Int = children.keys.sumOf { it.getSize() }
fun getOrCreateSubdirectory(name: String): Directory {
val newSubdirectory = Directory(name, this)
return this.getOrCreateChild(newSubdirectory)
}
private fun <T : FileSystemElement> getOrCreateChild(child: T): T {
return if (children.containsKey(child)) {
children[child]!! as T
} else {
children[child] = child
child
}
}
fun add(file: File): File = getOrCreateChild(file)
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Directory) return false
if (!super.equals(other)) return false
if (parent != other.parent) return false
return true
}
override fun hashCode(): Int {
var result = super.hashCode()
result = 31 * result + (parent?.hashCode() ?: 0)
return result
}
override fun toString(): String {
val depth = getDepth()
val parentDescription = if (parent != null) " parent=${parent.name}," else ""
return "Directory(name=$name,${parentDescription} children=\n" +
"${"\t".repeat(depth + 1)}${children.keys}\n${"\t".repeat(depth)})"
}
private fun getDepth() = generateSequence(this) { it.parent }.count() - 1
override fun iterator(): Iterator<FileSystemElement> = object : Iterator<FileSystemElement> {
private val unvisitedDescendants = mutableListOf(this@Directory as FileSystemElement)
override fun hasNext() = unvisitedDescendants.isNotEmpty()
override fun next(): FileSystemElement {
val next = unvisitedDescendants.removeFirst()
if (next is Directory) {
unvisitedDescendants.addAll(0, next.children.keys)
}
return next
}
}
}
class FileSystem {
val root = Directory.newRoot()
private var currentDirectory = root
fun apply(command: Command) {
when (command.name) {
"cd" -> currentDirectory = when (command.parameter) {
".." -> currentDirectory.parent
?: throw IllegalArgumentException("Root has no parent, cannot change to top level directory!")
"/" -> root
else -> currentDirectory.getOrCreateSubdirectory(command.parameter)
}
"ls" -> {
ListCommand(command.getResults()).apply(currentDirectory)
}
else -> throw NotImplementedError("Unknown command ${command}.")
}
}
}
class Command(val name: String, val parameter: String) {
private val results = mutableListOf<String>()
fun getResults(): List<String> = results.toList()
fun addResult(result: String) = results.add(result)
override fun toString(): String {
return "Command(name='$name', parameter='$parameter', results=${results.joinToString("\n")})"
}
}
class ListCommand(private val results: List<String>) {
fun apply(currentDirectory: Directory) {
val fileResultSyntax = """(\d+) (\S+)""".toRegex()
for (result in results) {
if (result.startsWith("dir")) {
val matchDirectoryResultSyntax = """dir (\S+)""".toRegex().matchEntire(result)
if (matchDirectoryResultSyntax != null) {
val (name) = matchDirectoryResultSyntax.destructured
currentDirectory.getOrCreateSubdirectory(name)
}
} else if (result.matches(fileResultSyntax)) {
val matchFileResultSyntax = fileResultSyntax.matchEntire(result)
if (matchFileResultSyntax != null) {
val (size, name) = matchFileResultSyntax.destructured
currentDirectory.add(File(name, size.toInt()))
}
} else {
throw IllegalArgumentException("Unknown result of list command $result.")
}
}
}
}
fun analyzeLog(input: List<String>): FileSystem {
val fileSystem = FileSystem()
var lastCommand: Command? = null
for (line in input) {
if (line.startsWith("$")) {
if (lastCommand != null) {
fileSystem.apply(lastCommand)
}
val matchCommandSyntax = """^\$\s+([a-z]+)\s*(\S*?)$""".toRegex().matchEntire(line)
if (matchCommandSyntax != null) {
val (name, parameter) = matchCommandSyntax.destructured
lastCommand = Command(name, parameter)
}
} else {
if (lastCommand != null) {
lastCommand.addResult(line)
} else {
throw IllegalArgumentException("First line must be a command!")
}
}
}
if (lastCommand != null) {
fileSystem.apply(lastCommand)
}
return fileSystem
}
fun Directory.subdirectorySizes(): Sequence<Int> =
this.iterator().asSequence().filter { it is Directory }.map { it.getSize() }
fun main() {
val input = readInputLines(FileSystem::class)
fun part1(input: List<String>) =
analyzeLog(input).root.subdirectorySizes().filter { it <= 100000 }.sum()
fun part2(input: List<String>) {
val diskSize = 70000000
val requiredUnusedSpace = 30000000
val root = analyzeLog(input).root
val currentUnusedSpace = diskSize - root.getSize()
val spaceToCleanUp = requiredUnusedSpace - currentUnusedSpace
val result = root.subdirectorySizes().filter { it >= spaceToCleanUp }.min()
println("The update needs $requiredUnusedSpace. Currently, $currentUnusedSpace is unused. The smallest directory to delete has size $result.")
}
println("The sum of all directory sizes individually smaller than 100,000 is ${part1(input)}.")
part2(input)
} | 0 | Kotlin | 0 | 0 | 551069a21a45690c80c8d96bce3bb095b5982bf0 | 6,851 | advent-of-code-2022 | Apache License 2.0 |
src/chapter3/section2/ex9.kt | w1374720640 | 265,536,015 | false | {"Kotlin": 1373556} | package chapter3.section2
import chapter1.section4.factorial
import chapter2.sleep
import chapter2.swap
/**
* 对于N=2、3、4、5和6,画出用N个键可能构造出的所有不同形状的二叉查找树
*
* 解:对于N个不同的键,有N!种插入顺序,可以构造出N!个二叉查找树,
* 但是构造的二叉查找树中会有结构相同的树,需要剔除结构相同的树
* 自定义二叉查找树的比较器,从根节点开始依次比较每个结点,只有当结点结构相同、键相同时才认为二叉查找树相同,
* 对二叉查找树组成的数组排序,然后去除重复的二叉查找树
* 数组中删除重复元素可以参考练习2.5.4
*/
fun ex9(N: Int, delay: Long) {
val allBinaryTree = createAllBinaryTree(N)
val comparator = BinaryTreeComparator()
allBinaryTree.sortWith(comparator)
val array = dedupBinaryTree(allBinaryTree, comparator)
println("N: $N number of binary trees: ${array.size}")
drawBSTArray(array, delay)
}
fun createAllBinaryTree(N: Int): Array<BinarySearchTree<Int, Int>> {
val array = Array(N) { it + 1 }
val list = ArrayList<Array<Int>>()
fullArray(array, 0, list)
check(list.size == factorial(N).toInt())
return Array(list.size) { index ->
BinarySearchTree<Int, Int>().apply {
list[index].forEach { key ->
put(key, 0)
}
}
}
}
/**
* 求长度为N,元素不重复数组的所有全排列
*
* 解:全排列P(N)=N*P(N-1)
* 分别将0,1,2...N-1交换到第一位,对剩余元素求全排列P(N-1),组合成全排列P(N)
* 求全排列P(N-1)时,递归调用(N-1)*P(N-2),直到P(1)只有一种可能性
* 参考链接:https://blog.csdn.net/K346K346/article/details/51154786
*/
fun <T> fullArray(array: Array<T>, start: Int, list: ArrayList<Array<T>>) {
if (start == array.size - 1) {
list.add(array.copyOf())
return
}
for (i in start until array.size) {
array.swap(start, i)
fullArray(array, start + 1, list)
//这里必须将start和i交换回去,否则无法保证全排列完整不重复
array.swap(start, i)
}
}
class BinaryTreeComparator : Comparator<BinarySearchTree<Int, Int>> {
override fun compare(o1: BinarySearchTree<Int, Int>, o2: BinarySearchTree<Int, Int>): Int {
return compare(o1.root, o2.root)
}
fun compare(node1: BinarySearchTree.Node<Int, Int>?, node2: BinarySearchTree.Node<Int, Int>?): Int {
if (node1 == null && node2 == null) return 0
if (node1 == null) return -1
if (node2 == null) return 1
val result1 = node1.key.compareTo(node2.key)
if (result1 != 0) return result1
val result2 = compare(node1.left, node2.left)
if (result2 != 0) return result2
return compare(node1.right, node2.right)
}
}
/**
* 去除重复元素
*/
fun dedupBinaryTree(array: Array<BinarySearchTree<Int, Int>>, comparator: Comparator<BinarySearchTree<Int, Int>>): Array<BinarySearchTree<Int, Int>> {
var delCount = 0
for (i in 1 until array.size) {
if (comparator.compare(array[i], array[i - 1]) == 0) {
delCount++
}
}
if (delCount == 0) return array
val result = array.copyOfRange(0, array.size - delCount)
//从后向前遍历可以重复利用delCount变量,也可以减少部分循环次数
for (i in array.size - 1 downTo 1) {
if (comparator.compare(array[i], array[i - 1]) == 0) {
delCount--
//第一个重复元素前面的元素不需要重新赋值
if (delCount == 0) break
} else {
result[i - delCount] = array[i]
}
}
return result
}
fun <K: Comparable<K>, V: Any> drawBSTArray(array: Array<BinarySearchTree<K, V>>, delay: Long) {
array.forEach { bst ->
drawBST(bst)
sleep(delay)
}
}
fun main() {
var N = 2
val delay = 2000L
repeat(5) {
ex9(N, delay)
N++
}
} | 0 | Kotlin | 1 | 6 | 879885b82ef51d58efe578c9391f04bc54c2531d | 4,036 | Algorithms-4th-Edition-in-Kotlin | MIT License |
year2019/src/main/kotlin/net/olegg/aoc/year2019/day18/Day18.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2019.day18
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.find
import net.olegg.aoc.utils.get
import net.olegg.aoc.utils.set
import net.olegg.aoc.year2019.DayOf2019
import java.util.BitSet
import java.util.PriorityQueue
/**
* See [Year 2019, Day 18](https://adventofcode.com/2019/day/18)
*/
object Day18 : DayOf2019(18) {
override fun first(): Any? {
val map = matrix
val keys = (('a'..'z') + '@')
.associateWith { checkNotNull(map.find(it)) }
val routes = mutableMapOf<Char, MutableMap<Char, Pair<Int, BitSet>>>()
keys.entries.forEach { (key, position) ->
val queue = ArrayDeque(listOf(Triple(position, 0, BitSet(26))))
val visited = mutableSetOf(position)
while (queue.isNotEmpty()) {
val (curr, steps, doors) = queue.removeFirst()
NEXT_4.map { it.step + curr }
.filter { map[it] != '#' }
.filter { it !in visited }
.forEach { next ->
visited += next
when (val char = map[next]!!) {
'.', '#' -> {
queue += Triple(next, steps + 1, doors)
}
in 'a'..'z' -> {
routes.getOrPut(key) { mutableMapOf() }[char] = steps + 1 to doors
queue += Triple(next, steps + 1, doors)
}
in 'A'..'Z' -> {
val newDoors = doors.get(0, 26).apply { set(char - 'A') }
queue += Triple(next, steps + 1, newDoors)
}
}
}
}
}
val queue = PriorityQueue<Config>(1000, compareBy({ -it.keys.cardinality() }, { it.steps }))
queue.add(Config())
val visited = mutableMapOf<Pair<Char, BitSet>, Int>()
var best = Int.MAX_VALUE
while (queue.isNotEmpty()) {
val config = queue.poll()
if (config.steps >= best) {
continue
}
routes[config.char]
.orEmpty()
.asSequence()
.filterNot { config.keys[it.key - 'a'] }
.filter { (_, route) ->
val doors = route.second
return@filter (0..<26).none { doors[it] && !config.keys[it] }
}
.map { (next, route) ->
return@map Config(
char = next,
steps = config.steps + route.first,
keys = config.keys.get(0, 26).apply { set(next - 'a') },
)
}
.filter { it.steps < best }
.filter { it.steps < visited.getOrDefault(it.char to it.keys, Int.MAX_VALUE) }
.forEach {
visited[it.char to it.keys] = it.steps
if (it.keys.cardinality() == 26) {
best = minOf(best, it.steps)
queue.removeIf { config -> config.steps >= best }
} else {
queue.offer(it)
}
}
}
return best
}
override fun second(): Any? {
val map = matrix.map { it.toMutableList() }
val start = checkNotNull(map.find('@'))
(-1..1).forEach { y ->
(-1..1).forEach { x ->
map[start + Vector2D(x, y)] = '#'
}
}
map[start + Vector2D(-1, -1)] = '@'
map[start + Vector2D(-1, 1)] = '$'
map[start + Vector2D(1, -1)] = '%'
map[start + Vector2D(1, 1)] = '&'
val bots = "@$%&".toList()
val keys = (('a'..'z') + bots)
.associateWith { checkNotNull(map.find(it)) }
val routes = mutableMapOf<Char, MutableMap<Char, Pair<Int, BitSet>>>()
keys.entries.forEach { (key, position) ->
val queue = ArrayDeque(listOf(Triple(position, 0, BitSet(26))))
val visited = mutableSetOf(position)
while (queue.isNotEmpty()) {
val (curr, steps, doors) = queue.removeFirst()
NEXT_4.map { it.step + curr }
.filter { map[it] != '#' }
.filter { it !in visited }
.forEach { next ->
visited += next
when (val char = map[next]!!) {
'.', in bots -> {
queue += Triple(next, steps + 1, doors)
}
in 'a'..'z' -> {
routes.getOrPut(key) { mutableMapOf() }[char] = steps + 1 to doors
queue += Triple(next, steps + 1, doors)
}
in 'A'..'Z' -> {
val newDoors = doors.get(0, 26).apply { set(char - 'A') }
queue += Triple(next, steps + 1, newDoors)
}
}
}
}
}
val queue = PriorityQueue<MultiConfig>(1000, compareBy({ -it.keys.cardinality() }, { it.steps }))
val visited = mutableMapOf<Pair<String, BitSet>, Int>()
queue.add(MultiConfig())
var best = Int.MAX_VALUE
while (queue.isNotEmpty()) {
val config = queue.poll()
if (config.steps >= best) {
continue
}
config.bots
.toList()
.flatMap { key -> routes[key].orEmpty().map { Triple(key, it.key, it.value) } }
.asSequence()
.filterNot { config.keys[it.second - 'a'] }
.filter { (_, _, route) ->
val doors = route.second
return@filter (0..<26).none { doors[it] && !config.keys[it] }
}
.map { (curr, next, route) ->
return@map MultiConfig(
bots = config.bots.replace(curr, next),
steps = config.steps + route.first,
keys = config.keys.get(0, 26).apply { set(next - 'a') },
)
}
.filter { it.steps < best }
.filter { it.steps < visited.getOrDefault(it.bots to it.keys, Int.MAX_VALUE) }
.forEach {
visited[it.bots to it.keys] = it.steps
if (it.keys.cardinality() == 26) {
best = minOf(best, it.steps)
queue.removeIf { config -> config.steps >= best }
} else {
queue.offer(it)
}
}
}
return best
}
data class Config(
val char: Char = '@',
val steps: Int = 0,
val keys: BitSet = BitSet(26)
)
data class MultiConfig(
val bots: String = "@$%&",
val steps: Int = 0,
val keys: BitSet = BitSet(26)
)
}
fun main() = SomeDay.mainify(Day18)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 6,130 | adventofcode | MIT License |
src/test/kotlin/dev/shtanko/algorithms/leetcode/BinaryTreePathsTest.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2020 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import java.util.stream.Stream
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.extension.ExtensionContext
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.Arguments
import org.junit.jupiter.params.provider.ArgumentsProvider
import org.junit.jupiter.params.provider.ArgumentsSource
abstract class BinaryTreePathsTest<out T : BinaryTreePathsStrategy>(private val strategy: T) {
private class InputArgumentsProvider : ArgumentsProvider {
override fun provideArguments(context: ExtensionContext?): Stream<out Arguments> = Stream.of(
Arguments.of(
TreeNode(1),
listOf("1"),
),
Arguments.of(
TreeNode(1).apply {
left = TreeNode(2)
},
listOf("1->2"),
),
Arguments.of(
TreeNode(1).apply {
left = TreeNode(2)
right = TreeNode(3)
},
listOf("1->2", "1->3"),
),
Arguments.of(
TreeNode(1).apply {
left = TreeNode(2)
right = TreeNode(3)
left?.right = TreeNode(5)
},
listOf("1->2->5", "1->3"),
),
Arguments.of(
t2(),
listOf("1->2->4", "1->2->5", "1->3->6", "1->3->7"),
),
)
private fun t2(): TreeNode? {
val arr = intArrayOf(1, 2, 3, 4, 5, 6, 7)
val tree: TreeNode? = null
return insertLevelOrder(tree, arr, 0)
}
}
@ParameterizedTest
@ArgumentsSource(InputArgumentsProvider::class)
fun `binary tree paths test`(tree: TreeNode, expected: List<String>) {
val actual = strategy.binaryTreePaths(tree).sorted()
assertEquals(expected, actual)
}
}
class BinaryTreePathsRecursionTest : BinaryTreePathsTest<BinaryTreePathsRecursion>(BinaryTreePathsRecursion())
class BinaryTreePathsBFSQueueTest : BinaryTreePathsTest<BinaryTreePathsBFSQueue>(BinaryTreePathsBFSQueue())
class BinaryTreePathsBFSStackTest : BinaryTreePathsTest<BinaryTreePathsBFSStack>(BinaryTreePathsBFSStack())
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,933 | kotlab | Apache License 2.0 |
src/nativeMain/kotlin/com.qiaoyuang.algorithm/round1/Questions58.kt | qiaoyuang | 100,944,213 | false | {"Kotlin": 338134} | package com.qiaoyuang.algorithm.round1
fun test58() {
printlnResult1("I am a student.")
printlnResult1("I am a student. ")
printlnResult2(charArrayOf('a', 'b', 'c', 'd', 'e', 'f', 'g'), 2)
printlnResult2(charArrayOf('H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'), 6)
}
/**
* Questions 58-1: Reverse all vocabularies in an English statement
*/
private fun String.reverse(): String {
var pointer1 = lastIndex
var pointer2 = lastIndex
val str = this
return buildString {
while (pointer2 >= 0) {
if (str[pointer2] == ' ') {
append(str.substring(pointer2 + 1, pointer1 + 1))
pointer1 = pointer2
while (str[pointer2] == ' ')
pointer2--
} else if (pointer2 == 0) {
append(str.substring(pointer2, pointer1 + 1))
break
} else
pointer2--
}
}
}
private fun printlnResult1(str: String) =
println("Input a str: '$str', the reverse is '${str.reverse()}'")
/**
* Questions 58-2: Input an integer n and a CharArray, put the first nth characters behind on other characters in the CharArray
*/
private fun reverse(array: CharArray, n: Int): CharArray {
val slash = n - 1
var i = 0
var j = slash
while (i < j)
swap(array, i++, j--)
i = n
j = array.lastIndex
while (i < j)
swap(array, i++, j--)
i = 0
j = array.lastIndex
while (i < j)
swap(array, i++, j--)
return array
}
private fun swap(array: CharArray, i: Int, j: Int) {
val temp = array[i]
array[i] = array[j]
array[j] = temp
}
private fun printlnResult2(array: CharArray, n: Int) =
println("Rotate the first ${n}th character of ${array.toList()}, then we can get: ${reverse(array, n)}") | 0 | Kotlin | 3 | 6 | 66d94b4a8fa307020d515d4d5d54a77c0bab6c4f | 1,835 | Algorithm | Apache License 2.0 |
kotlin/src/main/kotlin/io/github/ocirne/aoc/year2015/Day7.kt | ocirne | 327,578,931 | false | {"Python": 323051, "Kotlin": 67246, "Sage": 5864, "JavaScript": 832, "Shell": 68} | package io.github.ocirne.aoc.year2015
import io.github.ocirne.aoc.AocChallenge
class Day7(val lines: List<String>) : AocChallenge(2015, 7) {
override fun part1(): Int {
return run("a")
}
override fun part2(): Int {
val answer1 = part1()
return run("a", answer1.toString())
}
private fun prepareRules(newRuleB : String?): Map<String, Node> {
return lines.map { it.trim().split(" -> ") }
.associate { Pair(it[1], if (it[1] == "b" && newRuleB != null) Node(newRuleB) else Node(it[0])) }
}
fun run(wire: String, newRuleB : String? = null): Int {
val rules = prepareRules(newRuleB)
return Circuit(rules).deduct(wire)
}
internal class Circuit(private val rules: Map<String, Node>) {
internal fun deduct(wire: String): Int {
if (wire.toIntOrNull() != null) {
return wire.toInt()
}
val node = rules[wire]!!
if (node.value != 0) {
return node.value
}
when (node.rule.size) {
1 -> {
node.value = deduct(node.rule[0])
}
2 -> {
val (op, ref) = node.rule
if (op == "NOT") {
node.value = M - 1 - deduct(ref)
}
}
3 -> {
val (ref1, op, ref2) = node.rule
val value1 = deduct(ref1)
val value2 = deduct(ref2)
node.value = when (op) {
"AND" -> value1 and value2
"OR" -> value1 or value2
"LSHIFT" -> value1 shl value2
"RSHIFT" -> value1 shr value2
else -> throw Exception()
}
}
}
return node.value
}
}
internal class Node(tokens: String) {
val rule = tokens.split(' ')
var value : Int = 0
}
companion object {
// 2 ^ 16
const val M = 1 shl 16
}
}
| 0 | Python | 0 | 1 | b8a06fa4911c5c3c7dff68206c85705e39373d6f | 2,148 | adventofcode | The Unlicense |
src/leetcodeProblem/leetcode/editor/en/MultiplyStrings.kt | faniabdullah | 382,893,751 | false | null | //Given two non-negative integers num1 and num2 represented as strings, return
//the product of num1 and num2, also represented as a string.
//
// Note: You must not use any built-in BigInteger library or convert the inputs
//to integer directly.
//
//
// Example 1:
// Input: num1 = "2", num2 = "3"
//Output: "6"
// Example 2:
// Input: num1 = "123", num2 = "456"
//Output: "56088"
//
//
// Constraints:
//
//
// 1 <= num1.length, num2.length <= 200
// num1 and num2 consist of digits only.
// Both num1 and num2 do not contain any leading zero, except the number 0
//itself.
//
// Related Topics Math String Simulation 👍 3398 👎 1336
package leetcodeProblem.leetcode.editor.en
class MultiplyStrings {
fun solution() {
}
//below code will be used for submission to leetcode (using plugin of course)
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
fun multiply(num1: String, num2: String): String {
if ("0" == num1 || "0" == num2)
return "0"
val list = Array(num1.length + num2.length - 1){0}
for (i in num1.length - 1 downTo 0) {
for (j in num2.length - 1 downTo 0) {
list[i + j] += (num1[i] - '0') * (num2[j] - '0')
}
}
for (i in list.size - 1 downTo 1) {
list[i - 1] += list[i] / 10
list[i] %= 10
}
val builder = StringBuilder()
list.forEach {
builder.append(it)
}
return builder.toString()
}
}
//leetcode submit region end(Prohibit modification and deletion)
}
fun main() {}
| 0 | Kotlin | 0 | 6 | ecf14fe132824e944818fda1123f1c7796c30532 | 1,726 | dsa-kotlin | MIT License |
src/Day01.kt | krzysztof-wydrzynski | 572,895,885 | false | {"Kotlin": 1492} | fun main() {
fun sumValuesSeparatedByEnter(input: List<String>): List<Int> =
input.fold(mutableListOf(0)) { resultList, next ->
if (next == "\n" || next.isBlank()) {
resultList.add(0)
resultList
} else {
val last: Int = resultList.removeLast()
resultList.add(last + Integer.valueOf(next))
resultList
}
}
fun part1(input: List<String>) = sumValuesSeparatedByEnter(input).max()
fun part2(input: List<String>) = sumValuesSeparatedByEnter(input).sortedDescending().subList(0, 3).sum()
val testInput = readInput("day01_test")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readInput("day01_input")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f78f576d6334026b66a1e4040149928f7878b5f8 | 844 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/day4.kt | Arch-vile | 572,557,390 | false | {"Kotlin": 132454} | package day4
import aoc.utils.closedRange
import aoc.utils.containsFully
import aoc.utils.hasOverlap
import aoc.utils.readInput
fun part1(): Int {
return readInput("day4-input.txt")
.map { it.split(",") }
.map {
Pair(
toRange(it[0]),
toRange(it[1])
)
}
.filter { containsFullyEither(it.first, it.second) }
.count()
}
fun containsFullyEither(first: ClosedRange<Int>, second: ClosedRange<Int>): Boolean {
return first.containsFully(second) || second.containsFully(first)
}
fun toRange(s: String): ClosedRange<Int> {
val parts = s.split("-")
return closedRange(parts[0].toInt(), parts[1].toInt())
}
fun part2(): Int {
return readInput("day4-input.txt")
.map { it.split(",") }
.map {
Pair(
toRange(it[0]),
toRange(it[1])
)
}
.filter { it.first.hasOverlap(it.second) }
.count()
}
| 0 | Kotlin | 0 | 0 | e737bf3112e97b2221403fef6f77e994f331b7e9 | 994 | adventOfCode2022 | Apache License 2.0 |
src/day20/Day20.kt | easchner | 572,762,654 | false | {"Kotlin": 104604} | package day20
import readInputString
import java.lang.Exception
import kotlin.system.measureNanoTime
data class WorkingNumber(val original: Int, val number: Long)
fun main() {
fun moveItem(coords: MutableList<WorkingNumber>, index: Int) {
val item = coords.find { it.original == index } ?: throw Exception()
val oldIndex = coords.indexOf(item)
var newIndex = (oldIndex + item.number) % (coords.size - 1)
if (newIndex < 0) {
newIndex += coords.size - 1
}
coords.removeAt(oldIndex)
coords.add(newIndex.toInt(), item)
}
fun part1(input: List<String>): Long {
val coords = input.mapIndexed { index, s -> WorkingNumber(index, s.toLong()) }.toMutableList()
for (i in coords.indices) {
moveItem(coords, i)
}
val zeroIndex = coords.indexOfFirst { it.number == 0L } ?: throw Exception()
return coords[((zeroIndex + 1_000L) % coords.size).toInt()].number + coords[((zeroIndex + 2_000L) % coords.size).toInt()].number + coords[((zeroIndex + 3_000L) % coords.size).toInt()].number
}
fun part2(input: List<String>): Long {
val coords = input.mapIndexed { index, s -> WorkingNumber(index, s.toLong() * 811_589_153L) }.toMutableList()
for (x in 0 until 10) {
for (i in coords.indices) {
moveItem(coords, i)
}
}
val zeroIndex = coords.indexOfFirst { it.number == 0L } ?: throw Exception()
return coords[(zeroIndex + 1_000) % coords.size].number + coords[(zeroIndex + 2_000) % coords.size].number + coords[(zeroIndex + 3_000) % coords.size].number
}
val testInput = readInputString("day20/test")
val input = readInputString("day20/input")
check(part1(testInput) == 3L)
val time1 = measureNanoTime { println(part1(input)) }
println("Time for part 1 was ${"%,d".format(time1)} ns")
check(part2(testInput) == 1623178306L)
val time2 = measureNanoTime { println(part2(input)) }
println("Time for part 2 was ${"%,d".format(time2)} ns")
} | 0 | Kotlin | 0 | 0 | 5966e1a1f385c77958de383f61209ff67ffaf6bf | 2,084 | Advent-Of-Code-2022 | Apache License 2.0 |
algorithms/Kotlin/QuickSort/QuickSort.kt | thuva4 | 105,735,897 | false | {"C++": 165979, "Java": 105820, "Python": 78620, "JavaScript": 50450, "C": 35635, "Swift": 22216, "Go": 20412, "C#": 19569, "Ruby": 10966, "Haskell": 6158, "Kotlin": 5787, "Rust": 4612, "Scala": 4198, "Perl": 1926, "Crystal": 1760, "HTML": 1752, "Makefile": 727, "Racket": 406, "Brainfuck": 308, "CSS": 47} | fun printArray(x: IntArray) {
for (i in x.indices)
print(x[i].toString() + " ")
}
fun IntArray.sort(low: Int = 0, high: Int = this.size - 1) {
if (low >= high) return
val middle = partition(low, high)
sort(low, middle - 1)
sort(middle + 1, high)
}
fun IntArray.partition(low: Int, high: Int): Int {
val middle = low + (high - low) / 2
val a = this
swap(a, middle, high)
var storeIndex = low
for (i in low until high) {
if (a[i] < a[high]) {
swap(a, storeIndex, i)
storeIndex++
}
}
swap(a, high, storeIndex)
return storeIndex
}
fun swap(a: IntArray, i: Int, j: Int) {
val temp = a[i]
a[i] = a[j]
a[j] = temp
}
fun main(args: Array<String>) {
println("Enter the number of elements :")
val n = readLine()!!.toInt()
val arr = IntArray(n)
println("Enter the elements.")
for (i in 0 until n) {
arr[i] = readLine()!!.toInt()
}
println("Given array")
printArray(arr)
arr.sort()
println("\nSorted array")
printArray(arr)
}
| 9 | C++ | 571 | 472 | 7da835fe429c30dfb62fcf412ad397d9dd6407b2 | 1,096 | Algorithms | Apache License 2.0 |
kotlin/src/2022/Day10_2022.kt | regob | 575,917,627 | false | {"Kotlin": 50757, "Python": 46520, "Shell": 430} | import kotlin.math.abs
private fun part1(input: List<String>): Int {
var total = 0
var (bound, boundMx) = 20 to 220
var (x, cycle) = 1 to 0
for (s in input) {
val y = if (s == "noop") {
cycle += 1
0
} else {
cycle += 2
s.split(" ")[1].toInt()
}
if (cycle >= bound) {
total += bound * x
bound += 40
}
x += y
if (bound > boundMx) break
}
return total
}
private fun outputAt(i: Int, sprite: Int) : String {
val r = (i - 1) % 40
val ch = if (abs(sprite - r) <= 1) "#" else "."
if (r == 39) return ch + "\n"
return ch
}
private fun part2(input: List<String>){
val output = mutableListOf<String>()
var (x, cycle) = 1 to 0
for (s in input) {
val y = if (s == "noop") {
cycle += 1
output.add(outputAt(cycle, x))
0
} else {
cycle += 2
output.add(outputAt(cycle - 1, x))
output.add(outputAt(cycle, x))
s.split(" ")[1].toInt()
}
x += y
}
println(output.joinToString(""))
}
fun main() {
val input = readInput(10).trim().lines()
println(part1(input))
part2(input)
} | 0 | Kotlin | 0 | 0 | cf49abe24c1242e23e96719cc71ed471e77b3154 | 1,274 | adventofcode | Apache License 2.0 |
src/main/kotlin/com/github/dangerground/aoc2020/Day17.kt | dangerground | 317,439,198 | false | null | package com.github.dangerground.aoc2020
import com.github.dangerground.aoc2020.util.DayInput
import com.github.dangerground.aoc2020.util.World
import kotlin.math.max
fun main() {
val process = Day17(DayInput.asWorld(17))
println("result part 1: ${process.part1()}")
println("result part 2: ${process.part2()}")
}
class Day17(input: World) {
var world = World3D()
var nextWorld = World3D()
var world4 = World4D()
var nextWorld4 = World4D()
init {
val puffer = 6
for (r in 0 until input.getRowCount()) {
for (c in 0 until input.getColumnCount()) {
world.setActive(puffer, r + puffer, c + puffer, input.isChar(r, c, '#'))
world4.setActive(puffer, puffer, r + puffer, c + puffer, input.isChar(r, c, '#'))
}
}
}
fun part1(): Int {
world.print()
val puffer = 6
for (run in 0 until puffer) {
nextTick()
world = nextWorld
nextWorld = World3D()
}
world.print()
return world.countActive()
}
private fun nextTick() {
for (z in 0..world.maxZ + 1) {
for (y in 0..world.maxY + 1) {
for (x in 0..world.maxX + 1) {
val self = world.getCell(z, y, x)
val t = world.countActiveNeighbours(z, y, x)
val active = (self && (t == 2 || t == 3)) || (!self && t == 3)
nextWorld.setActive(z, y, x, active)
}
}
}
}
fun part2(): Int {
world4.print()
nextTick4()
world4.print()
val puffer = 6
for (run in 0 until puffer) {
nextTick4()
world4 = nextWorld4
nextWorld4 = World4D()
}
// world.print()
return world4.countActive()
}
private fun nextTick4() {
for (w in 0..world4.maxW + 1) {
for (z in 0..world4.maxZ + 1) {
for (y in 0..world4.maxY + 1) {
for (x in 0..world4.maxX + 1) {
val self = world4.getCell(w, z, y, x)
val t = world4.countActiveNeighbours(w, z, y, x)
val active = (self && (t == 2 || t == 3)) || (!self && t == 3)
nextWorld4.setActive(w, z, y, x, active)
}
}
}
}
}
}
class World3D() {
val active = mutableMapOf<Int, MutableMap<Int, MutableMap<Int, Boolean>>>()
var maxZ = 0
var maxY = 0
var maxX = 0
fun countActive(): Int {
return active.map { (_, u) ->
u.map { (_, u) ->
u.count { it.value }
}.sum()
}.sum()
}
fun countActiveNeighbours(z: Int, y: Int, x: Int): Int {
var result = 0
for (sz in z - 1..z + 1) {
for (sy in y - 1..y + 1) {
for (sx in x - 1..x + 1) {
if (getCell(sz, sy, sx) && (sz != z || sy != y || sx != x)) {
result++
}
}
}
}
return result
}
fun getCell(z: Int, y: Int, x: Int): Boolean {
if (!active.containsKey(z) || !active[z]!!.containsKey(y) || !active[z]!![y]!!.containsKey(x)) {
return false
}
return active[z]!![y]!![x]!!
}
fun setActive(z: Int, y: Int, x: Int, active: Boolean) {
maxZ = max(maxZ, z)
maxY = max(maxY, y)
maxX = max(maxX, x)
if (!this.active.containsKey(z)) {
this.active[z] = mutableMapOf()
}
if (!this.active[z]!!.containsKey(y)) {
this.active[z]!![y] = mutableMapOf()
}
this.active[z]!![y]!![x] = active
}
fun print() {
active.forEach { (k, v) ->
println("\nz=$k")
v.forEach { (_, u) ->
println(u.map { if (it.value) '#' else '.' }.toCharArray().contentToString())
}
}
}
}
class World4D() {
val active = mutableMapOf<Int, MutableMap<Int, MutableMap<Int, MutableMap<Int, Boolean>>>>()
var maxW = 0
var maxZ = 0
var maxY = 0
var maxX = 0
fun countActive(): Int {
return active.map { (_, u) ->
u.map { (_, u) ->
u.map { (_, u) ->
u.count { it.value }
}.sum()
}.sum()
}.sum()
}
fun countActiveNeighbours(w: Int, z: Int, y: Int, x: Int): Int {
var result = 0
for (sw in w - 1..w + 1) {
for (sz in z - 1..z + 1) {
for (sy in y - 1..y + 1) {
for (sx in x - 1..x + 1) {
if (getCell(sw, sz, sy, sx) && (sw != w || sz != z || sy != y || sx != x)) {
result++
}
}
}
}
}
return result
}
fun getCell(w: Int, z: Int, y: Int, x: Int): Boolean {
if (!active.containsKey(w) || !active[w]!!.containsKey(z) || !active[w]!![z]!!.containsKey(y) || !active[w]!![z]!![y]!!.containsKey(x)) {
return false
}
return active[w]!![z]!![y]!![x]!!
}
fun setActive(w: Int, z: Int, y: Int, x: Int, active: Boolean) {
maxW = max(maxW, w)
maxZ = max(maxZ, z)
maxY = max(maxY, y)
maxX = max(maxX, x)
if (!this.active.containsKey(w)) {
this.active[w] = mutableMapOf()
}
if (!this.active[w]!!.containsKey(z)) {
this.active[w]!![z] = mutableMapOf()
}
if (!this.active[w]!![z]!!.containsKey(y)) {
this.active[w]!![z]!![y] = mutableMapOf()
}
this.active[w]!![z]!![y]!![x] = active
}
fun print() {
active.forEach { (w, v) ->
v.forEach { (z, v) ->
println("\nz=$z, w=$w")
v.forEach { (_, u) ->
println(u.map { if (it.value) '#' else '.' }.toCharArray().contentToString())
}
}
}
}
}
| 0 | Kotlin | 0 | 0 | c3667a2a8126d903d09176848b0e1d511d90fa79 | 6,184 | adventofcode-2020 | MIT License |
src/main/kotlin/com/github/dangerground/aoc2020/Day9.kt | dangerground | 317,439,198 | false | null | package com.github.dangerground.aoc2020
import com.github.dangerground.aoc2020.util.DayInput
class Day9(val input: List<Long>, val checkLast: Int) {
fun isSumOfLast(ptr: Int): Boolean {
val check = input[ptr]
val subList = input.subList(ptr - checkLast, ptr)
subList.forEach { it1 ->
subList.forEach { it2 ->
if (it1 != it2 && it1 + it2 == check) {
return true
}
}
}
return false
}
fun part1(): Long {
for (ptr in checkLast until input.size) {
if (!isSumOfLast(ptr)) {
return input[ptr]
}
}
return -1;
}
fun part2(reference: Long): Long {
val list = mutableListOf<Long>()
for (ptr in input.indices) {
list.clear()
var sum = 0L
for (last in 0..999) {
val element = input[ptr + last]
list.add(element)
sum += element
if (sum > reference) {
break
} else if (sum == reference) {
return firstPlusLast(list)
}
}
}
return -1
}
private fun firstPlusLast(list: MutableList<Long>): Long {
list.sort()
return list.first() + list.last()
}
}
fun main() {
val input = DayInput.asLongList(9)
val day9 = Day9(input, 25)
// part 1
val part1 = day9.part1()
println("result part 1: $part1")
// part2
val part2 = day9.part2(167829540L)
println("result part 2: $part2")
} | 0 | Kotlin | 0 | 0 | c3667a2a8126d903d09176848b0e1d511d90fa79 | 1,643 | adventofcode-2020 | MIT License |
AOC-2023/src/main/kotlin/Day01.kt | sagar-viradiya | 117,343,471 | false | {"Kotlin": 72737} | import utils.splitAtNewLines
object Day01 {
fun day01Part01(input: String): Int {
return input.splitAtNewLines().sumOf {
val firstDigit = it.first(Char::isDigit)
val lastDigit = it.reversed().first(Char::isDigit)
"$firstDigit$lastDigit".toInt()
}
}
fun day01Part02(input: String): Int {
val numbers = buildMap {
listOf(
1 to "one",
2 to "two",
3 to "three",
4 to "four",
5 to "five",
6 to "six",
7 to "seven",
8 to "eight",
9 to "nine",
).forEach { (number, name) ->
put(number.toString(), number)
put(name, number)
}
}
return input.lines()
.map { line ->
val min = numbers.getValue(line.findAnyOf(numbers.keys)!!.second)
val max = numbers.getValue(line.findLastAnyOf(numbers.keys)!!.second)
"$min$max".toInt()
}
.fold(0, Int::plus)
}
}
| 0 | Kotlin | 0 | 0 | 7f88418f4eb5bb59a69333595dffa19bee270064 | 1,129 | advent-of-code | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MinOneBitOperations.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
/**
* 1611. Minimum One Bit Operations to Make Integers Zero
* https://leetcode.com/problems/minimum-one-bit-operations-to-make-integers-zero
*/
fun interface MinOneBitOperations {
operator fun invoke(n: Int): Int
}
class MinOneBitOperationsRecursion : MinOneBitOperations {
/**
* Calculates the minimum number of one-bit operations required to make an integer zero.
*
* @param n The input integer.
* @return The minimum number of one-bit operations.
*/
override fun invoke(n: Int): Int {
if (n == 0) {
return 0
}
var k = 0
var curr = 1
while (curr * 2 <= n) {
curr *= 2
k++
}
return (1 shl k + 1) - 1 - invoke(n xor curr)
}
}
class MinOneBitOperationsIteration : MinOneBitOperations {
/**
* Computes the minimum number of one-bit operations required to make an integer zero.
*
* @param n The integer to perform the operations on.
* @return The minimum number of one-bit operations required.
*/
override fun invoke(n: Int): Int {
var ans = 0
var k = 0
var mask = 1
while (mask <= n) {
if (n and mask != 0) {
ans = (1 shl k + 1) - 1 - ans
}
mask = mask shl 1
k++
}
return ans
}
}
class MinOneBitOperationsGrayCode : MinOneBitOperations {
private companion object {
const val SHIFT_16 = 16
const val SHIFT_8 = 8
const val SHIFT_4 = 4
const val SHIFT_2 = 2
const val SHIFT_1 = 1
}
override fun invoke(n: Int): Int {
return calculateXOR(n, SHIFT_16, SHIFT_8, SHIFT_4, SHIFT_2, SHIFT_1)
}
/**
* Calculates the XOR of a given number with a series of shifts.
*
* @param n The input number for which the XOR is to be calculated.
* @param shifts The array of shift values.
* @return The result of the XOR operation.
*/
private fun calculateXOR(n: Int, vararg shifts: Int): Int {
var result = n
for (shift in shifts) {
result = result xor (result shr shift)
}
return result
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,855 | kotlab | Apache License 2.0 |
Abundant_odd_numbers/Kotlin/src/Abundant.kt | ncoe | 108,064,933 | false | {"D": 425100, "Java": 399306, "Visual Basic .NET": 343987, "C++": 328611, "C#": 289790, "C": 216950, "Kotlin": 162468, "Modula-2": 148295, "Groovy": 146721, "Lua": 139015, "Ruby": 84703, "LLVM": 58530, "Python": 46744, "Scala": 43213, "F#": 21133, "Perl": 13407, "JavaScript": 6729, "CSS": 453, "HTML": 409} | fun divisors(n: Int): List<Int> {
val divs = mutableListOf(1)
val divs2 = mutableListOf<Int>()
var i = 2
while (i * i <= n) {
if (n % i == 0) {
val j = n / i
divs.add(i)
if (i != j) {
divs2.add(j)
}
}
i++
}
divs.addAll(divs2.reversed())
return divs
}
fun abundantOdd(searchFrom: Int, countFrom: Int, countTo: Int, printOne: Boolean): Int {
var count = countFrom
var n = searchFrom
while (count < countTo) {
val divs = divisors(n)
val tot = divs.sum()
if (tot > n) {
count++
if (!printOne || count >= countTo) {
val s = divs.joinToString(" + ")
if (printOne) {
println("$n < $s = $tot")
} else {
println("%2d. %5d < %s = %d".format(count, n, s, tot))
}
}
}
n += 2
}
return n
}
fun main() {
val max = 25
println("The first $max abundant primes are:")
val n = abundantOdd(1, 0, 25, false)
println("\nThe one thousandth abundant odd number is:")
abundantOdd(n, 25, 1000, true)
println("\nThe first abundant odd number above one billion is:")
abundantOdd((1e9 + 1).toInt(), 0, 1, true)
}
| 0 | D | 0 | 4 | c2a9f154a5ae77eea2b34bbe5e0cc2248333e421 | 1,338 | rosetta | MIT License |
src/main/kotlin/days/Day3.kt | hughjdavey | 433,597,582 | false | {"Kotlin": 53042} | package days
import util.Utils.map
import util.Utils.mul
class Day3 : Day(3) {
private val bitLists = inputList.map { it.toCharArray().map { it.toString().toInt() } }
override fun partOne(): Any {
return bitLists
.reduce { sums, list -> sums.mapIndexed { index, i -> i + list[index] } }
.map { sum -> sum > inputList.size / 2 }
.fold("" to "") { (g, e), oneIsMostCommon -> if (oneIsMostCommon) g + 1 to e + 0 else g + 0 to e + 1 }
.map { it.toInt(2) }
.mul()
}
override fun partTwo(): Any {
return Pair(getRating(1), getRating(0))
.map { it.first().joinToString("").toInt(2) }
.mul()
}
// todo make this functional/immutable
private fun getRating(keepIfEqual: Int): List<List<Int>> {
var bit = 0
var bits = bitLists
while (bits.size > 1) {
val ones = bits.map { it[bit] }.count { it == 1 }
val zeroes = bits.size - ones
bits = if (ones == zeroes) {
bits.filter { it[bit] == keepIfEqual }
}
else {
val mostCommon = if (ones > zeroes) 1 else 0
bits.filter { if (keepIfEqual == 1) it[bit] == mostCommon else it[bit] != mostCommon }
}
bit++
}
return bits
}
}
| 0 | Kotlin | 0 | 0 | a3c2fe866f6b1811782d774a4317457f0882f5ef | 1,366 | aoc-2021 | Creative Commons Zero v1.0 Universal |
src/main/kotlin/solutions/day02/Day2.kt | Dr-Horv | 112,381,975 | false | null | package solutions.day02
import solutions.Solver
class Day2: Solver {
override fun solve(input: List<String>, partTwo: Boolean): String {
val rowMapper = if(partTwo) {
this::evenlyDivisible
} else {
this::largestDifference
}
return input
.map(this::toNumbers)
.map(rowMapper)
.sum()
.toString()
}
private fun toNumbers(row: String): List<Int> {
return row.trim().split(Regex("\\s+")).map(String::toInt)
}
private fun largestDifference(row: List<Int>): Int {
var largest = Int.MIN_VALUE
var smallest = Int.MAX_VALUE
for (i in row) {
if(i > largest) {
largest = i
}
if(i < smallest) {
smallest = i
}
}
return largest - smallest
}
private fun evenlyDivisible(row: List<Int>): Int {
for (index1 in row.indices) {
val i = row[index1]
if(i == 0) {
continue
}
for (index2 in index1..row.lastIndex) {
val j = row[index2]
if(j == 0 || i == j) {
continue
}
if(i % j == 0) {
return i / j
}
if(j % i == 0) {
return j / i
}
}
}
throw RuntimeException("Found no evenly divisible numbers")
}
} | 0 | Kotlin | 0 | 2 | 975695cc49f19a42c0407f41355abbfe0cb3cc59 | 1,538 | Advent-of-Code-2017 | MIT License |
UniformCostSearch.kt | malikdawar | 356,954,800 | false | null | package com.example.academy
import org.junit.Test
import java.util.*
class UniformCostSearch(private val numberOfNodes: Int) {
private val priorityQueue: PriorityQueue<Node>
private val settled: MutableSet<Int>
private val distances: IntArray
private val adjacencyMatrix: Array<IntArray>
private val path: LinkedList<Int>
private val superParent: IntArray
private var source = 0
private var destination = 0
private fun uniformCostSearch(adjacencyMatrix: Array<IntArray>?, source: Int, destination: Int): Int {
var evaluationNode: Int
this.source = source
this.destination = destination
for (i in 1..numberOfNodes) {
distances[i] = MAX_VALUE
}
priorityQueue.add(Node(source, 0))
distances[source] = 0
while (!priorityQueue.isEmpty()) {
evaluationNode = nodeWithMinDistanceFromPriorityQueue
println("The eval Node is $evaluationNode")
if (evaluationNode == destination) {
return distances[destination]
}
settled.add(evaluationNode)
addFrontiersToQueue(evaluationNode)
}
return distances[destination]
}
private fun addFrontiersToQueue(evaluationNode: Int) {
for (destination in 1..numberOfNodes) {
if (!settled.contains(destination)) {
if (adjacencyMatrix[evaluationNode][destination] != MAX_VALUE) {
if (distances[destination] > adjacencyMatrix[evaluationNode][destination]
+ distances[evaluationNode]
) {
distances[destination] = (adjacencyMatrix[evaluationNode][destination]
+ distances[evaluationNode])
superParent[destination] = evaluationNode
}
val node: Node = Node(destination, distances[destination])
if (priorityQueue.contains(node)) {
priorityQueue.remove(node)
}
priorityQueue.add(node)
}
}
}
}
private val nodeWithMinDistanceFromPriorityQueue: Int
private get() {
val node = priorityQueue.remove()
return node.node
}
fun printPath() {
path.add(destination)
var found = false
var vertex = destination
while (!found) {
if (vertex == source) {
found = true
continue
}
path.add(superParent[vertex])
vertex = superParent[vertex]
}
println("The Path between $source and $destination is ")
val iterator = path.descendingIterator()
while (iterator.hasNext()) {
print(iterator.next().toString() + "\t")
}
}
@Test
fun test() {
val adjacency_matrix: Array<IntArray>
val number_of_vertices: Int
var source = 0
var destination = 0
val distance: Int
try {
println("Enter the number of vertices")
number_of_vertices = 7
adjacency_matrix = Array(number_of_vertices + 1) { IntArray(number_of_vertices + 1) }
println("Enter the Weighted Matrix for the graph")
for (i in 1..number_of_vertices) {
for (j in 1..number_of_vertices) {
adjacency_matrix[i][j] = 6
if (i == j) {
adjacency_matrix[i][j] = 0
continue
}
if (adjacency_matrix[i][j] == 0) {
adjacency_matrix[i][j] = MAX_VALUE
}
}
}
println("Enter the source ")
source = 1
println("Enter the destination")
destination = 7
val uniformCostSearch = UniformCostSearch(number_of_vertices)
distance = uniformCostSearch.uniformCostSearch(adjacency_matrix, source, destination)
uniformCostSearch.printPath()
println(
"""
The Distance between source $source and destination $destination is $distance"""
)
} catch (inputMismatch: InputMismatchException) {
println("Wrong Input Format")
}
/*outPUT
*
* 0 5 0 3 0 0 0
0 0 1 0 0 0 0
0 0 0 0 6 0 8
0 0 0 0 2 2 0
0 4 0 0 0 0 0
0 0 0 0 0 0 3
0 0 0 0 4 0 0
*
* The Path between 1 and 7 is
1 4 6 7
The Distance between source 1 and destination 7 is 8
*
* */
}
internal inner class Node : Comparator<Node> {
var node = 0
var cost = 0
constructor() {}
constructor(node: Int, cost: Int) {
this.node = node
this.cost = cost
}
override fun compare(node1: Node, node2: Node): Int {
if (node1.cost < node2.cost) return -1
if (node1.cost > node2.cost) return 1
return if (node1.node < node2.node) -1 else 0
}
override fun equals(obj: Any?): Boolean {
if (obj is Node) {
if (this.node == obj.node) {
return true
}
}
return false
}
}
companion object {
const val MAX_VALUE = 999
}
init {
settled = HashSet()
priorityQueue = PriorityQueue(
numberOfNodes, Node()
)
distances = IntArray(numberOfNodes + 1)
path = LinkedList()
adjacencyMatrix = Array(numberOfNodes + 1) { IntArray(numberOfNodes + 1) }
superParent = IntArray(numberOfNodes + 1)
}
} | 0 | Kotlin | 0 | 0 | a13dd335d06bc96d9fb19eed4b89897b8bb181f0 | 5,873 | ArtificialIntelligenceAlgorithms | Apache License 2.0 |
src/main/kotlin/g1101_1200/s1139_largest_1_bordered_square/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1101_1200.s1139_largest_1_bordered_square
// #Medium #Array #Dynamic_Programming #Matrix
// #2023_05_31_Time_224_ms_(100.00%)_Space_49.8_MB_(100.00%)
class Solution {
fun largest1BorderedSquare(grid: Array<IntArray>): Int {
val rightToLeft = arrayOfNulls<IntArray>(grid.size)
val bottomToUp = arrayOfNulls<IntArray>(grid.size)
for (i in grid.indices) {
rightToLeft[i] = grid[i].clone()
bottomToUp[i] = grid[i].clone()
}
val row = grid.size
val col = grid[0].size
for (i in 0 until row) {
for (j in col - 2 downTo 0) {
if (grid[i][j] == 1) {
rightToLeft[i]!![j] = rightToLeft[i]!![j + 1] + 1
}
}
}
for (j in 0 until col) {
for (i in row - 2 downTo 0) {
if (grid[i][j] == 1) {
bottomToUp[i]!![j] = bottomToUp[i + 1]!![j] + 1
}
}
}
var res = 0
for (i in 0 until row) {
for (j in 0 until col) {
val curLen = rightToLeft[i]!![j]
for (k in curLen downTo 1) {
if (bottomToUp[i]!![j] >= k && rightToLeft[i + k - 1]!![j] >= k &&
bottomToUp[i]!![j + k - 1] >= k
) {
if (k > res) {
res = k
}
break
}
}
}
}
return res * res
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,579 | LeetCode-in-Kotlin | MIT License |
Retos/Reto #9 - HETEROGRAMA, ISOGRAMA Y PANGRAMA [Fácil]/kotlin/juant351.kt | mouredev | 581,049,695 | false | {"Python": 3866914, "JavaScript": 1514237, "Java": 1272062, "C#": 770734, "Kotlin": 533094, "TypeScript": 457043, "Rust": 356917, "PHP": 281430, "Go": 243918, "Jupyter Notebook": 221090, "Swift": 216751, "C": 210761, "C++": 164758, "Dart": 159755, "Ruby": 70259, "Perl": 52923, "VBScript": 49663, "HTML": 45912, "Raku": 44139, "Scala": 30892, "Shell": 27625, "R": 19771, "Lua": 16625, "COBOL": 15467, "PowerShell": 14611, "Common Lisp": 12715, "F#": 12710, "Pascal": 12673, "Haskell": 11051, "Assembly": 10368, "Elixir": 9033, "Visual Basic .NET": 7350, "Groovy": 7331, "PLpgSQL": 6742, "Clojure": 6227, "TSQL": 5744, "Zig": 5594, "Objective-C": 5413, "Apex": 4662, "ActionScript": 3778, "Batchfile": 3608, "OCaml": 3407, "Ada": 3349, "ABAP": 2631, "Erlang": 2460, "BASIC": 2340, "D": 2243, "Awk": 2203, "CoffeeScript": 2199, "Vim Script": 2158, "Brainfuck": 1550, "Prolog": 1342, "Crystal": 783, "Fortran": 778, "Solidity": 560, "Standard ML": 525, "Scheme": 457, "Vala": 454, "Limbo": 356, "xBase": 346, "Jasmin": 285, "Eiffel": 256, "GDScript": 252, "Witcher Script": 228, "Julia": 224, "MATLAB": 193, "Forth": 177, "Mercury": 175, "Befunge": 173, "Ballerina": 160, "Smalltalk": 130, "Modula-2": 129, "Rebol": 127, "NewLisp": 124, "Haxe": 112, "HolyC": 110, "GLSL": 106, "CWeb": 105, "AL": 102, "Fantom": 97, "Alloy": 93, "Cool": 93, "AppleScript": 85, "Ceylon": 81, "Idris": 80, "Dylan": 70, "Agda": 69, "Pony": 69, "Pawn": 65, "Elm": 61, "Red": 61, "Grace": 59, "Mathematica": 58, "Lasso": 57, "Genie": 42, "LOLCODE": 40, "Nim": 38, "V": 38, "Chapel": 34, "Ioke": 32, "Racket": 28, "LiveScript": 25, "Self": 24, "Hy": 22, "Arc": 21, "Nit": 21, "Boo": 19, "Tcl": 17, "Turing": 17} | package Reto_09
private val allLetters = listOf<Char>(
'a',
'b',
'c',
'd',
'e',
'f',
'g',
'h',
'i',
'j',
'k',
'l',
'm',
'n',
'o',
'p',
'q',
'r',
's',
't',
'u',
'v',
'w',
'x',
'y',
'z'
)
fun main(args: Array<String>) {
print("Introduzca una cadena de texto para saber si se trata de un heterograma, un isograma o un pangrama: ")
val cadena = readln().toList()
isHeterograma(cadena)
isIsograma(cadena)
isPangrama(cadena)
}
fun isHeterograma(cadena: List<Char>) {
if (cadena.size != cadena.distinct().size) println("La cadena ${String(cadena.toCharArray())} no es un heterograma.")
else println("¡La cadena ${String(cadena.toCharArray())} es un heterograma!")
}
fun isIsograma(cadena: List<Char>) {
var isIsograma: Boolean
// Get a key-value map where each key it's a character at the input chain and the value is the number of appearances of that character.
val aparicionesCaracter =
cadena
.groupingBy { it }
.eachCount()
/* We get a list of all the values (number of appearances) and we compare how distinct they are.
* It should be only 1 type of value for be an isograma.
*/
isIsograma = aparicionesCaracter.values.distinct().count() == 1
if (isIsograma) println("¡La cadena ${String(cadena.toCharArray())} es un isograma de grado ${aparicionesCaracter.values.distinct()}!")
else println("La cadena ${String(cadena.toCharArray())} no es un isograma")
}
fun isPangrama(cadena: List<Char>) {
if(cadena.containsAll(allLetters)) println("¡La cadena ${String(cadena.toCharArray())} es un pangrama!")
else println("La cadena ${String(cadena.toCharArray())} no es un pangrama")
} | 4 | Python | 2,929 | 4,661 | adcec568ef7944fae3dcbb40c79dbfb8ef1f633c | 1,860 | retos-programacion-2023 | Apache License 2.0 |
gcj/y2020/round1b/a.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package gcj.y2020.round1b
private fun solve(): String {
var (x, y) = readInts()
val steps = (x.abs() + y.abs()).countSignificantBits()
return (steps - 1 downTo 0).map { i ->
val dir = DX.indices.maxByOrNull { x * DX[it] + y * DY[it] }!!
x -= DX[dir] shl i; y -= DY[dir] shl i
DIR_ROSE[dir]
}.joinToString("").reversed().takeIf { x == 0 && y == 0 } ?: "IMPOSSIBLE"
}
private val DX = intArrayOf(1, 0, -1, 0)
private val DY = intArrayOf(0, 1, 0, -1)
private const val DIR_ROSE = "ENWS"
fun main() = repeat(readInt()) { println("Case #${it + 1}: ${solve()}") }
private fun Int.countSignificantBits() = Int.SIZE_BITS - Integer.numberOfLeadingZeros(this)
private fun Int.abs() = kotlin.math.abs(this)
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 893 | competitions | The Unlicense |
src/main/kotlin/com/hj/leetcode/kotlin/problem785/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem785
/**
* LeetCode page: [785. Is Graph Bipartite?](https://leetcode.com/problems/is-graph-bipartite/);
*/
class Solution {
/* Complexity:
* Time O(N+E) and Space O(N) where N is the size of graph and E is the size of flattened graph;
*/
fun isBipartite(graph: Array<IntArray>): Boolean {
// Assign an initial, unspecified color to each node
val nodes = graph.indices
val nodeColors = MutableList(graph.size) { Color.Unspecified }
/* Try to color each connected component in two colors. If we can do that, the graph
* is bipartite; otherwise it is not.
*/
for (node in nodes) {
val inColoredComponent = nodeColors[node] != Color.Unspecified
if (inColoredComponent) {
continue
}
val canColorComponent = colorConnectedComponent(node, Color.White, nodeColors, graph)
if (!canColorComponent) {
return false
}
}
return true
}
private enum class Color {
White, Black, Unspecified
}
private fun colorConnectedComponent(
source: Int,
sourceColor: Color,
nodeColors: MutableList<Color>,
graph: Array<IntArray>
): Boolean {
// If the node is colored, check if its color matches the desired color
val isColored = nodeColors[source] != Color.Unspecified
if (isColored) {
return nodeColors[source] == sourceColor
}
// If the node is not colored, color it and further color the component
nodeColors[source] = sourceColor
val neighbourNodes = graph[source]
val neighbourColor = oppositeColor(sourceColor)
for (node in neighbourNodes) {
val canColorComponent = colorConnectedComponent(node, neighbourColor, nodeColors, graph)
if (!canColorComponent) {
return false
}
}
return true
}
private fun oppositeColor(color: Color): Color = when (color) {
Color.White -> Color.Black
Color.Black -> Color.White
Color.Unspecified -> throw IllegalArgumentException()
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 2,234 | hj-leetcode-kotlin | Apache License 2.0 |
code/number_theory/GCD.kt | hakiobo | 397,069,173 | false | null | private fun gcd(p: Int, q: Int): Int {
return if (p < 0) gcd(-p, q)
else if (q < 0) gcd(p, -q)
else if (p == 0) q
else if (q == 0) p
else if (p and 1 == 0 && q and 1 == 0) gcd(p shr 1, q shr 1) shl 1
else if (p and 1 == 0) gcd(p shr 1, q)
else if (q and 1 == 0) gcd(p, q shr 1)
else if (p > q) gcd((p - q) shr 1, q)
else gcd(p, (q - p) shr 1)
}
private fun gcd(p: Long, q: Long): Long {
return if (p < 0) gcd(-p, q)
else if (q < 0) gcd(p, -q)
else if (p == 0L) q
else if (q == 0L) p
else if (p and 1L == 0L && q and 1L == 0L) gcd(p shr 1, q shr 1) shl 1
else if (p and 1L == 0L) gcd(p shr 1, q)
else if (q and 1L == 0L) gcd(p, q shr 1)
else if (p > q) gcd((p - q) shr 1, q)
else gcd(p, (q - p) shr 1)
}
| 0 | Kotlin | 1 | 2 | f862cc5e7fb6a81715d6ea8ccf7fb08833a58173 | 778 | Kotlinaughts | MIT License |
src/main/kotlin/dev/shtanko/algorithms/extensions/Int.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2020 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.extensions
import kotlin.math.sqrt
import kotlin.random.Random
fun interface IntPredicate {
fun accept(i: Int): Boolean
}
val isEven = IntPredicate { it % 2 == 0 }
val Int.isEven: Boolean
get() = this % 2 == 0
fun Int.generateRandomArray(): IntArray {
val array = IntArray(this)
for (i in 0 until this) {
array[i] = Random.nextInt(this)
}
return array
}
fun Int.lessThanZero(): Boolean {
return this < 0
}
fun Int.isPrime(): Boolean {
if (this < 2) return false
val r = sqrt(this.toDouble()).toInt()
for (d in 2..r) if (this % d == 0) return false
return true
}
fun Int.isUgly2(): Boolean {
var n = this
// A non-positive integer cannot be ugly
if (n <= 0) {
return false
}
// Factorize by dividing with permitted factors
for (factor in intArrayOf(2, 3, 5)) {
n = (n to factor).keepDividingWhenDivisible()
}
// Check if the integer is reduced to 1 or not.
return n == 1
}
/**
* Function to check if a number is ugly or not
*/
fun Int.isUgly(): Boolean {
var n = this
prms.map {
n = (n to it).maxDivide()
}
return n == 1
}
private val prms = listOf(2, 3, 5)
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,831 | kotlab | Apache License 2.0 |
src/main/kotlin/com/github/michaelbull/advent2023/day4/Scratchcard.kt | michaelbull | 726,012,340 | false | {"Kotlin": 195941} | package com.github.michaelbull.advent2023.day4
import kotlin.math.pow
private val WHITESPACE_REGEX = "\\s+".toRegex()
private val CARD_REGEX = "Card$WHITESPACE_REGEX(\\d+): (.*) \\| (.*)".toRegex()
private fun String.toNumberSet(): Set<Int> {
return trim()
.split(WHITESPACE_REGEX)
.map(String::toInt)
.toSet()
}
fun String.toScratchCard(): Scratchcard {
val result = requireNotNull(CARD_REGEX.matchEntire(this)) {
"$this must match $CARD_REGEX"
}
val (id, winningNumbers, ownedNumbers) = result.destructured
return Scratchcard(
id = id.toInt(),
winningNumbers = winningNumbers.toNumberSet(),
ownedNumbers = ownedNumbers.toNumberSet(),
)
}
fun Collection<Scratchcard>.toWinningCounts(): List<Int> {
val counts = MutableList(size) { 1 }
for ((index, scratchcard) in withIndex()) {
repeat(scratchcard.winningCount) { offset ->
counts[index + offset + 1] += counts[index]
}
}
return counts
}
data class Scratchcard(
val id: Int,
val winningNumbers: Set<Int>,
val ownedNumbers: Set<Int>,
) {
private val winningOwnedNumbers = ownedNumbers intersect winningNumbers
val winningCount = winningOwnedNumbers.size
fun points(): Int {
return 2 pow winningCount - 1
}
private infix fun Int.pow(exponent: Int): Int {
return toDouble().pow(exponent).toInt()
}
}
| 0 | Kotlin | 0 | 1 | ea0b10a9c6528d82ddb481b9cf627841f44184dd | 1,438 | advent-2023 | ISC License |
src/Day06.kt | ekgame | 573,100,811 | false | {"Kotlin": 20661} | fun main() {
fun solve(input: String, size: Int) = input
.windowed(size)
.mapIndexed { index, sequence -> index to sequence }
.first {
it.second.toCharArray().toSet().size == size
}
.first + size
fun part1(input: String): Int = solve(input, 4)
fun part2(input: String): Int = solve(input, 14)
val testInput = readInput("06.test")
check(part1(testInput[0]) == 5)
check(part1(testInput[1]) == 6)
check(part1(testInput[2]) == 10)
check(part1(testInput[3]) == 11)
check(part2(testInput[0]) == 23)
check(part2(testInput[1]) == 23)
check(part2(testInput[2]) == 29)
check(part2(testInput[3]) == 26)
val input = readInputFull("06")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 2 | 0c2a68cedfa5a0579292248aba8c73ad779430cd | 787 | advent-of-code-2022 | Apache License 2.0 |
Kotlin/sort/RadixSort/src/RadixSort.kt | HarshCasper | 274,711,817 | false | {"C++": 1488046, "Java": 948670, "Python": 703942, "C": 615475, "JavaScript": 228879, "Go": 166382, "Dart": 107821, "Julia": 82766, "C#": 76519, "Kotlin": 40240, "PHP": 5465} | // Function to Implement Radix Sort
// The radix sorting algorithm is an integer sorting algorithm,
// that sorts by grouping numbers by their individual digits (or by their radix).
// It uses each radix/digit as a key, and implements counting sort or
// bucket sort under the hood in order to do the work of sorting.
// Takes an IntArray as arguments and returns a sorted IntArray to the caller function
fun radixSort(original: IntArray): IntArray {
// Array needs to be mutable
var old = original
for (shift in 31 downTo 0) {
val tmp = IntArray(old.size)
// The number of 0s
var j = 0
// Move the 0s to the new array, and the 1s to the old one
for (i in 0 until old.size) {
// If there is a 1 in the bit we are testing, the number will be negative
val move = (old[i] shl shift) >= 0
// If this is the last bit, negative numbers are actually lower
val toBeMoved = if (shift != 0) move else !move
if (toBeMoved) {
tmp[j++] = old[i]
}
else {
// It's a 1, so stick it in the old array for now
old[i - j] = old[i]
}
}
// Copy over the 1s from the old array
for (i in j until tmp.size) {
tmp[i] = old[i - j]
}
old = tmp
}
return old
}
fun main(args: Array<String>) {
print("Enter N: ");
val n= readLine()!!.toInt();
println("Enter array of N integers: ");
val arrays = IntArray(n) { readLine()!!.toInt() }
val array= radixSort(arrays);
print("Array after Radix Sort is: ")
for(i in array){
print("$i ")
}
}
/*
Time Complexity: O(log n)
Sample Input:
Enter N: 5
Enter array of N integers:
3
-1
2
3
4
Sample Output:
Array after Radix Sort is: -1 2 3 3 4
*/
| 2 | C++ | 1,086 | 877 | 4f1e5bdd6d9d899fa354de94740e0aecf5ecd2be | 1,917 | NeoAlgo | MIT License |
src/main/kotlin/g2501_2600/s2559_count_vowel_strings_in_ranges/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2501_2600.s2559_count_vowel_strings_in_ranges
// #Medium #Array #String #Prefix_Sum #2023_07_07_Time_638_ms_(100.00%)_Space_111.2_MB_(25.00%)
class Solution {
fun vowelStrings(words: Array<String>, queries: Array<IntArray>): IntArray {
val vowels = HashSet(listOf('a', 'e', 'i', 'o', 'u'))
val n = words.size
val validWords = IntArray(n)
for (i in 0 until n) {
val startChar = words[i][0]
val endChar = words[i][words[i].length - 1]
validWords[i] = if (vowels.contains(startChar) && vowels.contains(endChar)) 1 else 0
}
val prefix = IntArray(n)
prefix[0] = validWords[0]
for (i in 1 until n) {
prefix[i] = prefix[i - 1] + validWords[i]
}
val output = IntArray(queries.size)
for (i in queries.indices) {
val start = queries[i][0]
val end = queries[i][1]
output[i] = if (start == 0) prefix[end] else prefix[end] - prefix[start - 1]
}
return output
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,057 | LeetCode-in-Kotlin | MIT License |
year2023/day08/part1/src/main/kotlin/com/curtislb/adventofcode/year2023/day08/part1/Year2023Day08Part1.kt | curtislb | 226,797,689 | false | {"Kotlin": 2146738} | /*
--- Day 8: Haunted Wasteland ---
You're still riding a camel across Desert Island when you spot a sandstorm quickly approaching. When
you turn to warn the Elf, she disappears before your eyes! To be fair, she had just finished warning
you about ghosts a few minutes ago.
One of the camel's pouches is labeled "maps" - sure enough, it's full of documents (your puzzle
input) about how to navigate the desert. At least, you're pretty sure that's what they are; one of
the documents contains a list of left/right instructions, and the rest of the documents seem to
describe some kind of network of labeled nodes.
It seems like you're meant to use the left/right instructions to navigate the network. Perhaps if
you have the camel follow the same instructions, you can escape the haunted wasteland!
After examining the maps for a bit, two nodes stick out: `AAA` and `ZZZ`. You feel like `AAA` is
where you are now, and you have to follow the left/right instructions until you reach `ZZZ`.
This format defines each node of the network individually. For example:
```
RL
AAA = (BBB, CCC)
BBB = (DDD, EEE)
CCC = (ZZZ, GGG)
DDD = (DDD, DDD)
EEE = (EEE, EEE)
GGG = (GGG, GGG)
ZZZ = (ZZZ, ZZZ)
```
Starting with `AAA`, you need to look up the next element based on the next left/right instruction
in your input. In this example, start with `AAA` and go right (`R`) by choosing the right element of
`AAA`, `CCC`. Then, `L` means to choose the left element of `CCC`, `ZZZ`. By following the
left/right instructions, you reach `ZZZ` in 2 steps.
Of course, you might not find `ZZZ` right away. If you run out of left/right instructions, repeat
the whole sequence of instructions as necessary: `RL` really means `RLRLRLRLRLRLRLRL...` and so on.
For example, here is a situation that takes 6 steps to reach `ZZZ`:
```
LLR
AAA = (BBB, BBB)
BBB = (AAA, ZZZ)
ZZZ = (ZZZ, ZZZ)
```
Starting at `AAA`, follow the left/right instructions. How many steps are required to reach `ZZZ`?
*/
package com.curtislb.adventofcode.year2023.day08.part1
import com.curtislb.adventofcode.year2023.day08.wasteland.WastelandNetwork
import java.nio.file.Path
import java.nio.file.Paths
/**
* Returns the solution to the puzzle for 2023, day 8, part 1.
*
* @param inputPath The path to the input file for this puzzle.
* @param startNode The node in the network from which you start moving.
* @param goalNode The node in the network that you are trying to reach.
*/
fun solve(
inputPath: Path = Paths.get("..", "input", "input.txt"),
startNode: String = "AAA",
goalNode: String = "ZZZ"
): Long {
val network = WastelandNetwork.fromFile(inputPath.toFile())
return network.distance(startNode) { it == goalNode }
}
fun main() {
println(solve())
}
| 0 | Kotlin | 1 | 1 | 6b64c9eb181fab97bc518ac78e14cd586d64499e | 2,750 | AdventOfCode | MIT License |
2021/src/main/kotlin/aoc2021/day18/Day18.kt | dkhawk | 433,915,140 | false | {"Kotlin": 170350} | package aoc2021.day18
import java.util.LinkedList
import java.util.Queue
import kotlin.math.ceil
import kotlin.math.floor
import kotlin.system.measureTimeMillis
import utils.COLORS
import utils.Input
import utils.NO_COLOR
@OptIn(ExperimentalStdlibApi::class)
class Day18 {
companion object {
fun run() {
val time = measureTimeMillis {
// Day01().part1()
Day18().part1()
}
println("millis: $time")
// Day18().part2()
}
}
val sample = """
[[[0,[5,8]],[[1,7],[9,6]]],[[4,[1,2]],[[1,4],2]]]
[[[5,[2,8]],4],[5,[[9,9],0]]]
[6,[[[6,2],[5,6]],[[7,6],[4,7]]]]
[[[6,[0,7]],[0,9]],[4,[9,[9,0]]]]
[[[7,[6,4]],[3,[1,3]]],[[[5,5],1],9]]
[[6,[[7,3],[3,2]]],[[[3,8],[5,7]],4]]
[[[[5,4],[7,7]],8],[[8,3],8]]
[[9,3],[[9,9],[6,[4,9]]]]
[[2,[[7,7],7]],[[5,8],[[9,3],[0,2]]]]
[[[[5,2],5],[8,[3,7]]],[[5,[7,5]],[4,4]]]
""".trimIndent().split("\n")
private fun part1() {
val input = Input.readAsLines("18")
// val input = sample
val sum = sumAndReduce(input)
println(magnitude(sum))
}
private fun part2() {
val input = Input.readAsLines("18")
// val input = sample
val permutations = permutations(input)
val max = permutations.maxOf {
magnitude(sumAndReduce(it.toList()))
}
println(max)
}
private fun permutations(strings: List<String>): List<Pair<String, String>> {
return strings.mapIndexed { outerIndex, oString ->
strings.mapIndexedNotNull { index, string ->
if (outerIndex == index) {
null
} else {
oString to string
}
}
}.flatten()
}
fun sumAndReduce(input: List<String>): String {
return input.reduce { acc, it ->
reduce(add(acc, it))
}
}
fun reduce(start: String): String {
var current = start
while(true) {
val explodeString = explode(current, useString = true)
// val explodeTree = explode(current, useString = false)
//
// if (explodeString != explodeTree) {
// throw Exception("Expected $explodeString to equal $explodeTree")
// }
current = explodeString ?: (split(current) ?: return current)
}
}
private fun add(first: String, second: String): String = "[$first,$second]"
val doubleDigit = Regex("""\d\d+""")
fun split(s: String): String? {
// println("splitting: $s")
doubleDigit.find(s)?.groups?.get(0)?.let { group ->
val pre = s.substring(0 until group.range.first)
val post = s.substring(group.range.last + 1)
val value = group.value.toInt()
// println("value $value")
val halfValue = value.toDouble() / 2.0
val newLeft = floor(halfValue).toInt()
val newRight = ceil(halfValue).toInt()
val answer = "$pre[$newLeft,$newRight]$post"
// println("split: $answer")
return answer
}
return null
}
fun parse(iterator: BufferedIterator): Element {
val next = iterator.peek()
return when {
next?.isDigit() == true -> {
Value(parseNumber(iterator))
}
next == '[' -> {
parsePair(iterator)
}
else -> {
throw Exception("Unexpected token $next")
}
}
}
fun parsePair(iterator: BufferedIterator): Spair {
val start = iterator.nextChar()
if (start != '[') {
throw Exception("Unexpected token $start")
}
var next = iterator.peek()
val left = if (next?.isDigit() == true) {
val num = parseNumber(iterator)
val sep = iterator.nextChar()
if (sep != ',') {
throw Exception("Unexpected token $sep")
}
Value(num)
} else {
val p = parsePair(iterator)
val sep = iterator.nextChar()
if (sep != ',') {
throw Exception("Unexpected token $sep")
}
p
}
next = iterator.peek()
val right = if (next?.isDigit() == true) {
val num = parseNumber(iterator)
val close = iterator.nextChar()
if (close != ']') {
throw Exception("Unexpected token $close")
}
Value(num)
} else {
val p = parsePair(iterator)
val sep = iterator.nextChar()
if (sep != ']') {
throw Exception("Unexpected token $sep")
}
p
}
return Spair(left, right)
}
fun parseNumber(iterator: BufferedIterator): Int {
var answer = 0
var next : Char? = iterator.nextChar()
while (next?.isDigit() == true) {
answer = answer * 10 + next.digitToInt()
next = iterator.nextCharOrNull()
}
if (next != null && !next.isDigit()) {
iterator.putBack(next)
}
return answer
}
private val pairRegex = Regex("""\[\d+,\d+\]""")
fun explode(input: String, useString: Boolean = false): String? {
return if (useString) {
stringExplode(input)
} else {
val tree = parse(input.getBufferedIterator())
leftValue = -1
rightValue = -1
val newTree = treeExplode(tree)
return newTree?.toString() ?: null
}
}
var leftValue = -1
var rightValue = -1
private fun treeExplode(node: Element, depth: Int = 0): Element? {
if (node is Spair) {
if (depth == 4) {
if (node.first is Value && node.second is Value) {
leftValue = node.first.value
rightValue = node.second.value
return Value(0)
} else {
throw Exception("WTF! Expected two values!")
}
}
val left = treeExplode(node.first, depth + 1)
if (left != null) {
// Replace the left node
val rightNode = if (rightValue > 0) {
val value = rightValue
rightValue = -1
addToFirst(node.second, value)
} else {
node.second
}
return Spair(left, rightNode)
} else {
val right = treeExplode(node.second, depth + 1)
if (right != null) {
val leftNode = if (leftValue > 0) {
val value = leftValue
leftValue = -1
addToLast(node.first, value)
} else {
node.first
}
return Spair(leftNode, right)
}
}
}
return null
}
fun addToFirst(node: Element, value: Int): Element {
return if (value < 0) {
node
} else {
if (node is Value) {
Value(node.value + value)
} else {
Spair(addToFirst((node as Spair).first, value), node.second)
}
}
}
private fun addToLast(node: Element, value: Int): Element {
return if (value < 0) {
node
} else {
if (node is Value) {
Value(node.value + value)
} else {
Spair((node as Spair).first, addToLast((node as Spair).second, value))
}
}
}
fun stringExplode(input: String): String? {
pairRegex.findAll(input).forEach { matchResult ->
matchResult.groups[0]?.let { match ->
val pre = input.substring(0 until match.range.first)
val depth = pre.count { it == '[' } - pre.count { it == ']' }
if (depth > 4) {
throw Exception("depth is greater than 4!")
}
if (depth == 4) {
// println(highlight(match, input))
val post = input.substring(match.range.last + 1)
val values = match.value.drop(1).dropLast(1).split(',').map(String::toInt)
if (values.size != 2) {
throw Exception("WTF!!")
}
val left = values[0]
val right = values[1]
// val preWithHighlights = pre.addToLastDigit(left, true)
// val postWithHighlights = post.addToFirstDigit(right, true)
val newPre = pre.addToLastDigit(left)
val newPost = post.addToFirstDigit(right)
// val highlight =
// preWithHighlights + COLORS.RED.toString() + "0" + NO_COLOR + postWithHighlights
// println(highlight)
return newPre + "0" + newPost
}
} ?: throw Exception("Did not expect to get here!")
}
return null
}
private fun highlight(match: MatchGroup, s: String): String {
val pre = s.substring(0 until match.range.first)
val post = s.substring(match.range.last + 1)
return "$pre${COLORS.LT_RED}${match.value}${NO_COLOR}$post"
}
fun magnitude(snailFishNumberString: String): Int {
val snailFishNumber = parse(snailFishNumberString.getBufferedIterator())
return snailFishNumber.magnitude()
}
}
val firstNumber = Regex("""[^\d]*(\d+).*""")
private fun String.addToFirstDigit(value: Int, highlight: Boolean = false): String {
firstNumber.matchEntire(this)?.let { matchResult ->
val matchGroup = matchResult.groups[1]!!
val newValue = matchGroup.value.toInt() + value
val pre = this.substring(0 until matchGroup.range.first)
val post = this.substring(matchGroup.range.last + 1)
return if (highlight) {
pre + COLORS.LT_CYAN.toString() + newValue.toString() + NO_COLOR + post
} else {
pre + newValue.toString() + post
}
}
return this
}
val lastNumber = Regex(""".*[^\d](\d+)[^\d]+$""")
private fun String.addToLastDigit(value: Int, highlight: Boolean = false): String {
lastNumber.matchEntire(this)?.let { matchResult ->
val matchGroup = matchResult.groups[1]!!
val newValue = matchGroup.value.toInt() + value
val pre = this.substring(0 until matchGroup.range.first)
val post = this.substring(matchGroup.range.last + 1)
return if (highlight) {
pre + COLORS.GREEN.toString() + newValue.toString() + NO_COLOR + post
} else {
pre + newValue.toString() + post
}
}
return this
}
fun String.getBufferedIterator(): BufferedIterator {
return BufferedIterator(iterator())
}
class BufferedIterator(val iterator: CharIterator) : CharIterator() {
constructor(string: String) : this(string.iterator())
val queue : Queue<Char> = LinkedList<Char>()
override fun hasNext(): Boolean {
return queue.isNotEmpty() || iterator.hasNext()
}
override fun nextChar(): Char {
return if (queue.isNotEmpty()) queue.remove() else iterator.next()
}
fun putBack(c: Char) {
queue.add(c)
}
fun nextCharOrNull(): Char? {
return if (queue.isNotEmpty())
queue.remove()
else if (iterator.hasNext())
iterator.next()
else
null
}
fun peek(): Char? {
return if (queue.isNotEmpty())
queue.first()
else if (iterator.hasNext())
iterator.next().also { queue.add(it) }
else
null
}
}
//sealed class Token
//object Open: Token()
//object Comma: Token()
//object Close: Token()
//class NumToken(val value: Int): Token()
sealed class Element {
abstract fun magnitude(): Int
}
data class Value(val value: Int) : Element() {
override fun magnitude(): Int {
return value
}
override fun toString(): String = "$value"
}
data class Spair(val first: Element, val second: Element) : Element() {
override fun magnitude(): Int = (first.magnitude() * 3) + (second.magnitude() * 2)
override fun toString(): String {
return "[$first,$second]"
}
}
| 0 | Kotlin | 0 | 0 | 64870a6a42038acc777bee375110d2374e35d567 | 10,970 | advent-of-code | MIT License |
src/main/kotlin/Day008Idiomatic.kt | ruffCode | 398,923,968 | false | null | import kotlin.time.measureTimedValue
// all credit to @SebastianAigner
object Day008Idiomatic {
val input = PuzzleInput("day008.txt").readText().split(newLine)
@JvmStatic
fun main(args: Array<String>) {
val inst = input.toInstr()
println(
measureTimedValue {
execute(inst)
}.duration.inWholeMicroseconds
)
println(
measureTimedValue {
executeMutably(inst)
}.duration.inWholeMicroseconds
)
println(
measureTimedValue {
Day008.partOne()
}.duration.inWholeMicroseconds
)
println("part two")
println(
measureTimedValue {
generateAllMutations(inst)
.map { mod -> execute(mod) }
.first { state -> state.ip !in inst.indices }
}.also {
it.duration.inWholeMilliseconds
}
)
println(
measureTimedValue {
generateAllMutations(inst)
.map { mod -> executeMutably(mod) }
.first { state -> state.ip !in inst.indices }
}.also {
it.duration.inWholeMilliseconds
}
)
println(
measureTimedValue {
Day008.partTwo()
}.also {
it.duration.inWholeMilliseconds
}
)
}
private fun execute(instructions: List<Inst>): MachineState {
var state = MachineState(0, 0)
val executedIndices = mutableSetOf<Int>()
while (state.ip in instructions.indices) {
val nextInstruction = instructions[state.ip]
state = nextInstruction.action(state)
if (state.ip in executedIndices) return state
executedIndices += state.ip
}
return state
}
private fun List<String>.toInstr(): List<Inst> = map(::Inst)
private fun Inst(s: String): Inst {
val (first, second) = s.split(" ")
val arg = second.toInt()
return when (first) {
"acc" -> Acc(arg)
"jmp" -> Jmp(arg)
"nop" -> Nop(arg)
else -> error("Invalid input")
}
}
private fun generateAllMutations(instructions: List<Inst>): Sequence<List<Inst>> = sequence {
for ((index, instruction) in instructions.withIndex()) {
val newProgram = instructions.toMutableList()
newProgram[index] = when (instruction) {
is Acc -> continue
is Jmp -> Nop(instruction.value)
is Nop -> Jmp(instruction.value)
}
yield(newProgram)
}
}
private fun executeMutably(instructions: List<Inst>): MachineState {
var idx = 0
var acc = 0
val executedIndices = mutableSetOf<Int>()
while (idx in instructions.indices) {
when (val nextInstr = instructions[idx]) {
is Acc -> {
acc += nextInstr.value
idx++
}
is Jmp -> idx += nextInstr.value
is Nop -> idx++
}
if (idx in executedIndices) break
executedIndices += idx
}
return MachineState(idx, acc)
}
}
private data class MachineState(val ip: Int, val acc: Int)
private sealed class Inst(val action: (MachineState) -> MachineState)
private class Nop(val value: Int) : Inst({ MachineState(it.ip + 1, it.acc) })
private class Jmp(val value: Int) : Inst({ MachineState(it.ip + value, it.acc) })
private class Acc(val value: Int) : Inst({ MachineState(it.ip + 1, it.acc + value) })
| 0 | Kotlin | 0 | 0 | 477510cd67dac9653fc61d6b3cb294ac424d2244 | 3,753 | advent-of-code-2020-kt | MIT License |
src/main/kotlin/segtree.kt | AlBovo | 574,593,169 | false | {"Kotlin": 75843} | import kotlin.math.*
class SegmentTree(array: Array<Int>){
private var segment = Array<Int>(0){ 0 }
private var size = 0
private var sizeOfInitialArray = 0
init{
size = 1 shl ceil(log2(array.size.toFloat())).toInt()
sizeOfInitialArray = array.size
segment = Array(size * 2){ 0 }
for(i in array.indices){
segment[i + size] = array[i]
}
for(i in size-1 downTo 1){
segment[i] = segment[i * 2]+segment[i * 2 + 1]
}
}
private fun privateGetSum(node: Int, nodeRangeLeft: Int, nodeRangeRight: Int, queryRangeLeft: Int, queryRangeRight: Int): Int{ // the query range is [queryRangeLeft, queryRangeRight)
if(queryRangeLeft >= nodeRangeRight || queryRangeRight <= nodeRangeLeft){
return 0
}
if(nodeRangeLeft >= queryRangeLeft && nodeRangeRight <= queryRangeRight){
return segment[node]
}
val left = privateGetSum(node * 2, nodeRangeLeft, (nodeRangeLeft + nodeRangeRight) / 2, queryRangeLeft, queryRangeRight)
val right = privateGetSum(node * 2 + 1, (nodeRangeLeft + nodeRangeRight) / 2, nodeRangeRight, queryRangeLeft ,queryRangeRight)
return left + right
}
private fun privateUpdate(nodePosition: Int, value: Int){
var node = nodePosition + size
segment[node] = value
node /= 2
while(node > 0){
segment[node] = segment[node * 2] + segment[node * 2 + 1]
node /= 2
}
}
private fun check(){
for(i in segment.indices){
print(segment[i].toString() + " ")
}
println("")
}
fun getSum(queryLeft: Int, queryRight: Int): Int{
require(queryLeft >= 0 && queryLeft < segment.size){
"Left end is not correct, it must be greater than -1 and less than the size of the segment size"
}
require(queryRight >= 0 && queryRight <= segment.size){
"Right end is not correct, it must be greater than -1 and less than the size of the segment size"
}
require(queryLeft <= queryRight){
"The right end must be greater or equal to the left end"
}
return privateGetSum(1, 1, size, queryLeft, queryRight)
}
fun update(nodePosition: Int, value: Int){
require(nodePosition in 0 until sizeOfInitialArray){
"The node isn't in the segment tree"
}
privateUpdate(nodePosition, value)
check()
}
}
fun main(){
val arr = arrayOf(2, 4, 2, 1, 3, 4, 5)
val seg = SegmentTree(arr)
print(seg.getSum(0, 4))
//seg.update(3, 4)
} | 0 | Kotlin | 0 | 0 | 56a31313c53cc3525d2aa3c29b3a2085b1b1b506 | 2,646 | Compiti | MIT License |
src/main/kotlin/day25.kt | Gitvert | 433,947,508 | false | {"Kotlin": 82286} | fun day25() {
val lines: List<String> = readFile("day25.txt")
day25part1(lines)
day25part2(lines)
}
fun day25part1(lines: List<String>) {
val seaFloor = getSeaFloor(lines)
var noOfMovers: Int
var steps = 0
do {
steps++
noOfMovers = 0
noOfMovers += moveEast(seaFloor)
noOfMovers += moveSouth(seaFloor)
} while (noOfMovers != 0)
val answer = steps
println("25a: $answer")
}
fun day25part2(lines: List<String>) {
val answer = "---"
println("25b: $answer")
}
fun moveEast(seaFloor: Array<CharArray>): Int {
val movers = mutableListOf<Pair<Int, Int>>()
for (i in seaFloor.indices) {
for (j in seaFloor[0].indices) {
if (seaFloor[i][j] == '>') {
if (j == seaFloor[0].size - 1 && seaFloor[i][0] == '.') {
movers.add(Pair(i, j))
} else if (j < seaFloor[0].size - 1 && seaFloor[i][j + 1] == '.') {
movers.add(Pair(i, j))
}
}
}
}
movers.forEach {
seaFloor[it.first][it.second] = '.'
if (it.second == seaFloor[0].size - 1) {
seaFloor[it.first][0] = '>'
} else {
seaFloor[it.first][it.second + 1] = '>'
}
}
return movers.size
}
fun moveSouth(seaFloor: Array<CharArray>): Int {
val movers = mutableListOf<Pair<Int, Int>>()
for (i in seaFloor.indices) {
for (j in seaFloor[0].indices) {
if (seaFloor[i][j] == 'v') {
if (i == seaFloor.size - 1 && seaFloor[0][j] == '.') {
movers.add(Pair(i, j))
} else if (i < seaFloor.size - 1 && seaFloor[i + 1][j] == '.') {
movers.add(Pair(i, j))
}
}
}
}
movers.forEach {
seaFloor[it.first][it.second] = '.'
if (it.first == seaFloor.size - 1) {
seaFloor[0][it.second] = 'v'
} else {
seaFloor[it.first + 1][it.second] = 'v'
}
}
return movers.size
}
fun getSeaFloor(lines: List<String>): Array<CharArray> {
val seaFloor = Array(lines.size) {CharArray(lines[0].length) {' '} }
for (i in lines.indices) {
for (j in 0 until lines[0].length) {
seaFloor[i][j] = lines[i][j]
}
}
return seaFloor
} | 0 | Kotlin | 0 | 0 | 02484bd3bcb921094bc83368843773f7912fe757 | 2,368 | advent_of_code_2021 | MIT License |
src/main/kotlin/com/github/brpeterman/advent2022/RpsSim.kt | brpeterman | 573,059,778 | false | {"Kotlin": 53108} | package com.github.brpeterman.advent2022
class RpsSim {
fun simulateAndScore(plays: List<Pair<String, String>>): Int {
return plays.fold(0, { total, play ->
total + scorePlay(play.first, toPlay(play.second))
})
}
fun strategizeAndScore(plays: List<Pair<String, String>>): Int {
return plays.fold(0, {total, play ->
total + scorePlay(play.first, choosePlay(play.first, play.second))
})
}
fun toPlay(play: String): String {
return when (play) {
ME_ROCK -> ROCK
ME_PAPER -> PAPER
ME_SCISSORS -> SCISSORS
else -> throw IllegalStateException("Unexpected play: ${play}")
}
}
fun choosePlay(opponent: String, outcome: String): String {
if (outcome == WIN) {
return when (opponent) {
ROCK -> PAPER
PAPER -> SCISSORS
SCISSORS -> ROCK
else -> throw IllegalStateException("Unexpected move: ${opponent}")
}
}
if (outcome == LOSE) {
return when (opponent) {
ROCK -> SCISSORS
PAPER -> ROCK
SCISSORS -> PAPER
else -> throw IllegalStateException("Unexpected move: ${opponent}")
}
}
return opponent
}
fun scorePlay(opponent: String, me: String): Int {
var score = SCORES[me]!!
if (opponent == me) {
score += 3
} else if ((opponent == ROCK && me == PAPER) ||
(opponent == PAPER && me == SCISSORS) ||
(opponent == SCISSORS && me == ROCK)) {
score += 6
}
return score
}
companion object {
// I had these in nice typesafe enums and then part 2 showed up 😐
val ROCK = "A"
val PAPER = "B"
val SCISSORS = "C"
val ME_ROCK = "X"
val ME_PAPER = "Y"
val ME_SCISSORS = "Z"
val LOSE = "X"
val WIN = "Z"
val SCORES = mapOf(
Pair(ROCK, 1),
Pair(PAPER, 2),
Pair(SCISSORS, 3))
fun parseInput(input: String): List<Pair<String, String>> {
return input.split("\n")
.filter { it.isNotBlank() }
.map { line ->
val (left, right) = line.split(" ")
Pair(left, right)
}
}
}
}
| 0 | Kotlin | 0 | 0 | 1407ca85490366645ae3ec86cfeeab25cbb4c585 | 2,447 | advent2022 | MIT License |
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[剑指 Offer 03]数组中重复的数字.kt | maoqitian | 175,940,000 | false | {"Kotlin": 354268, "Java": 297740, "C++": 634} | //找出数组中重复的数字。
//
//
//在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请
//找出数组中任意一个重复的数字。
//
// 示例 1:
//
// 输入:
//[2, 3, 1, 0, 2, 5, 3]
//输出:2 或 3
//
//
//
//
// 限制:
//
// 2 <= n <= 100000
// Related Topics 数组 哈希表
// 👍 237 👎 0
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
fun findRepeatNumber(nums: IntArray): Int {
//使用 HashSet 加入元素失败说明当前元素重复
val set = HashSet<Int>()
for (i in 0 until nums.size){
if(!set.add(nums[i])){
return nums[i]
}
}
return -1
}
}
//leetcode submit region end(Prohibit modification and deletion)
| 0 | Kotlin | 0 | 1 | 8a85996352a88bb9a8a6a2712dce3eac2e1c3463 | 944 | MyLeetCode | Apache License 2.0 |
advent/src/test/kotlin/org/elwaxoro/advent/y2020/Dec12.kt | elwaxoro | 328,044,882 | false | {"Kotlin": 376774} | package org.elwaxoro.advent.y2020
import org.elwaxoro.advent.PuzzleDayTester
import kotlin.math.abs
class Dec12 : PuzzleDayTester(12, 2020) {
override fun part1(): Int = parse().sail(1 to 0, true)
override fun part2(): Int = parse().sail(10 to 1, false)
private fun List<Pair<Char, Int>>.sail(initialVector: Pair<Int, Int>, compassModsPosition: Boolean): Int {
var vector = initialVector
var position = 0 to 0
forEach {
when (it.first) {
'F' -> position =
position.first + vector.first * it.second to position.second + vector.second * it.second
'R' -> vector = vector.rotate(it.second)
'L' -> vector = vector.rotate(360 - it.second)
'N' -> if (compassModsPosition) {
position = position.north(it.second)
} else {
vector = vector.north(it.second)
}
'S' -> if (compassModsPosition) {
position = position.south(it.second)
} else {
vector = vector.south(it.second)
}
'E' -> if (compassModsPosition) {
position = position.east(it.second)
} else {
vector = vector.east(it.second)
}
'W' -> if (compassModsPosition) {
position = position.west(it.second)
} else {
vector = vector.west(it.second)
}
}
}
return abs(position.first) + abs(position.second)
}
private fun parse() = load().map {
Pair(it[0], it.substring(1).toInt())
}
private fun Pair<Int, Int>.north(mod: Int) = first to second + mod
private fun Pair<Int, Int>.south(mod: Int) = first to second - mod
private fun Pair<Int, Int>.east(mod: Int) = first + mod to second
private fun Pair<Int, Int>.west(mod: Int) = first - mod to second
private fun Pair<Int, Int>.rotate(rotation: Int) =
when (rotation) {
0 -> this
90 -> second to first * -1
180 -> first * -1 to second * -1
270 -> second * -1 to first
else -> throw IllegalStateException("OMG")
}
}
| 0 | Kotlin | 4 | 0 | 1718f2d675f637b97c54631cb869165167bc713c | 2,319 | advent-of-code | MIT License |
src/main/kotlin/biz/koziolek/adventofcode/year2022/day21/day21.kt | pkoziol | 434,913,366 | false | {"Kotlin": 715025, "Shell": 1892} | package biz.koziolek.adventofcode.year2022.day21
import biz.koziolek.adventofcode.*
import java.util.*
fun main() {
val inputFile = findInput(object {})
val yellingMonkeys = parseYellingMonkeys(inputFile.bufferedReader().readLines())
println("'root' monkey yells: ${findYelledNumber("root", yellingMonkeys)}")
}
sealed interface YellingMonkey : GraphNode {
override val id: String
override fun toGraphvizString(exactXYPosition: Boolean, xyPositionScale: Float) = id
}
data class SpecificNumberYellingMonkey(
override val id: String,
val number: Long,
) : YellingMonkey
data class MathOperationYellingMonkey(
override val id: String,
val operation: Char,
val operand1: String,
val operand2: String,
) : YellingMonkey
fun parseYellingMonkeys(lines: Iterable<String>): List<YellingMonkey> =
lines.map { line ->
Regex("^([a-z]+): (([0-9]+)|(([a-z]+) ([/*+-]) ([a-z]+)))$")
.find(line)
?.let { result ->
val id = result.groups[1]!!.value
if (result.groups[3] != null) {
val number = result.groups[3]!!.value.toLong()
SpecificNumberYellingMonkey(id, number)
} else {
val operand1 = result.groups[5]!!.value
val operation = result.groups[6]!!.value.single()
val operand2 = result.groups[7]!!.value
MathOperationYellingMonkey(id, operation, operand1, operand2)
}
}
?: throw IllegalArgumentException("Cannot parse '$line'")
}
fun findYelledNumber(monkeyID: String, yellingMonkeys: List<YellingMonkey>): Long {
val waitingMonkeys: Stack<String> = Stack()
waitingMonkeys.push(monkeyID)
val monkeyNumbers = hashMapOf<String, Long>()
while (waitingMonkeys.isNotEmpty()) {
val currentMonkeyID = waitingMonkeys.pop()
val currentMonkey = yellingMonkeys.single { it.id == currentMonkeyID }
if (currentMonkey.id in monkeyNumbers) {
continue
}
when (currentMonkey) {
is SpecificNumberYellingMonkey -> {
monkeyNumbers[currentMonkey.id] = currentMonkey.number
}
is MathOperationYellingMonkey -> {
if (currentMonkey.operand1 in monkeyNumbers && currentMonkey.operand2 in monkeyNumbers) {
val number1 = monkeyNumbers[currentMonkey.operand1]!!
val number2 = monkeyNumbers[currentMonkey.operand2]!!
val number = when (currentMonkey.operation) {
'+' -> number1 + number2
'-' -> number1 - number2
'*' -> number1 * number2
'/' -> number1 / number2
else -> throw IllegalArgumentException("Unsupported operation: ${currentMonkey.operation}")
}
monkeyNumbers[currentMonkey.id] = number
} else {
waitingMonkeys.push(currentMonkey.id)
waitingMonkeys.push(currentMonkey.operand1)
waitingMonkeys.push(currentMonkey.operand2)
}
}
}
}
return monkeyNumbers[monkeyID]!!
}
fun findNumberToYell(yellingMonkeys: List<YellingMonkey>): Long {
val monkeyMap = yellingMonkeys.associateBy { it.id }
val rootMonkey = monkeyMap["root"] as MathOperationYellingMonkey
val human = monkeyMap["humn"]!!
val graph: Graph<YellingMonkey, UniDirectionalGraphEdge<YellingMonkey>> = buildGraph {
yellingMonkeys.forEach { monkey ->
if (monkey is MathOperationYellingMonkey) {
add(UniDirectionalGraphEdge(monkey, yellingMonkeys.single { it.id == monkey.operand1 }))
add(UniDirectionalGraphEdge(monkey, yellingMonkeys.single { it.id == monkey.operand2 }))
}
}
}
if (graph.edges.count { it.node1 == human || it.node2 == human } != 1) {
throw UnsupportedOperationException("Human has to be on exactly one edge")
}
val path = graph.findShortestPath(start = rootMonkey, end = human)
var wantedNumber: Long? = null
for (currentMonkey in path) {
if (currentMonkey !is MathOperationYellingMonkey) {
break
}
val knownChildID = if (monkeyMap[currentMonkey.operand1] !in path) {
currentMonkey.operand1
} else {
currentMonkey.operand2
}
val knownValue = findYelledNumber(knownChildID, yellingMonkeys)
val knownIsLeft = (knownChildID == currentMonkey.operand1)
wantedNumber = if (currentMonkey.id == "root") {
knownValue
} else if (currentMonkey.operation == '+') {
wantedNumber!! - knownValue
} else if (currentMonkey.operation == '-') {
if (knownIsLeft) {
knownValue - wantedNumber!!
} else {
wantedNumber!! + knownValue
}
} else if (currentMonkey.operation == '*') {
wantedNumber!! / knownValue
} else if (currentMonkey.operation == '/') {
if (knownIsLeft) {
knownValue / wantedNumber!!
} else {
wantedNumber!! * knownValue
}
} else {
throw IllegalArgumentException("Unknown operation: '${currentMonkey.operation}'")
}
}
if (wantedNumber != null) {
return wantedNumber
} else {
throw IllegalStateException("Human number to yell was not found")
}
}
| 0 | Kotlin | 0 | 0 | 1b1c6971bf45b89fd76bbcc503444d0d86617e95 | 5,651 | advent-of-code | MIT License |
2020/kotlin/day-2/main.kt | waikontse | 330,900,073 | false | null | import util.FileUtils
fun main() {
println ("This is day #2")
val fileUtils = FileUtils("input.txt")
val validPasswordCount = fileUtils.lines
.map {fullLine -> fullLine.split(' ')}
.filter(::isPasswordValid2)
.count()
println ("The total number of correct passwords: $validPasswordCount")
}
fun isPasswordValid(line: List<String>): Boolean {
return isCharWithinCount(getCharCounts(line[2]), getTargetChar(line[1]), getModifiers(line[0]))
}
fun isPasswordValid2(line: List<String>): Boolean {
return isCharWithinPassword(line[2], getTargetChar(line[1]), getModifiers(line[0]))
}
fun isCharWithinCount(charCounts: Map<Char, Int>, char: Char, count: Pair<Int, Int>): Boolean {
val charCount: Int = charCounts.get(char)?: 0
return charCount >= count.first && charCount <= count.second;
}
fun isCharWithinPassword(line: String, char: Char, count: Pair<Int, Int>): Boolean {
val isCharOnPosition1: Boolean = line.get(count.first-1).equals(char);
val isCharOnPosition2: Boolean = line.get(count.second-1).equals(char);
return isCharOnPosition1.xor(isCharOnPosition2)
}
fun getCharCounts(line: String): MutableMap<Char, Int> {
val counts = HashMap<Char, Int>()
line.groupingBy { it }.eachCountTo(counts)
return counts
}
fun getModifiers(line: String): Pair<Int, Int> {
val lowAndHigh = line.split('-')
return Pair(lowAndHigh[0].toInt(), lowAndHigh[1].toInt())
}
fun getTargetChar(line: String): Char {
return line.get(0)
}
| 0 | Kotlin | 0 | 0 | abeb945e74536763a6c72cebb2b27f1d3a0e0ab5 | 1,522 | advent-of-code | Creative Commons Zero v1.0 Universal |
src/day08/Day08.kt | idle-code | 572,642,410 | false | {"Kotlin": 79612} | package day08
import readInput
fun main() {
fun visibilityHorizontally(input: List<List<Int>>, xRange: IntProgression, startVisibility: Int = -1): Array<BooleanArray> {
val mask = Array(input.size) { BooleanArray(input[0].size) { false } }
for (y in 0..input.lastIndex) {
var previousTreeHeight = startVisibility
for (x in xRange) {
val currentHeight = input[y][x]
if (currentHeight > previousTreeHeight) {
mask[y][x] = true
previousTreeHeight = currentHeight
}
}
}
return mask
}
fun visibilityVertically(input: List<List<Int>>, yRange: IntProgression, startVisibility: Int = -1): Array<BooleanArray> {
val mask = Array(input.size) { BooleanArray(input[0].size) { false } }
for (x in 0..input[0].lastIndex) {
var previousTreeHeight = startVisibility
for (y in yRange) {
val currentHeight = input[y][x]
if (currentHeight > previousTreeHeight) {
mask[y][x] = true
previousTreeHeight = currentHeight
}
}
}
return mask
}
fun mergeVisibilityMasks(vararg masks: Array<BooleanArray>): Array<BooleanArray> {
val height = masks[0].lastIndex
val width = masks[0][0].lastIndex
val mergedMask = Array(height + 1) { BooleanArray(width + 1) { false } }
for (m in masks) {
for (y in 0..height) {
for (x in 0..width) {
mergedMask[y][x] = mergedMask[y][x] || m[y][x]
}
}
}
return mergedMask
}
fun countAllVisible(mask: Array<BooleanArray>): Int {
val height = mask.lastIndex
var visibleCount = 0
for (y in 0..height) {
visibleCount += mask[y].count { it }
}
return visibleCount
}
fun calculateLineOfSightVertically(
input: List<List<Int>>,
x: Int,
yRange: IntProgression,
currentTreeHeight: Int
): Int {
var visibleTreeCount = 0
for (yy in yRange) {
if (input[yy][x] >= currentTreeHeight) {
++visibleTreeCount
break
}
++visibleTreeCount
}
return visibleTreeCount
}
fun calculateLineOfSightHorizontally(
input: List<List<Int>>,
xRange: IntProgression,
y: Int,
currentTreeHeight: Int
): Int {
var visibleTreeCount = 0
for (xx in xRange) {
if (input[y][xx] >= currentTreeHeight) {
++visibleTreeCount
break
}
++visibleTreeCount
}
return visibleTreeCount
}
fun calculateScenicScore(input: List<List<Int>>, x: Int, y: Int): Int {
val currentTreeHeight = input[y][x]
val visibleToLeft = calculateLineOfSightHorizontally(input, x-1 downTo 0, y, currentTreeHeight)
val visibleToRight = calculateLineOfSightHorizontally(input, x+1..input[y].lastIndex, y, currentTreeHeight)
val visibleToTop = calculateLineOfSightVertically(input, x, y - 1 downTo 0, currentTreeHeight)
val visibleToBottom = calculateLineOfSightVertically(input, x, y+1 ..input.lastIndex, currentTreeHeight)
return visibleToRight * visibleToLeft * visibleToBottom * visibleToTop
}
fun maxScenicScore(input: List<List<Int>>): Int {
var maxScore = 0
for (y in 0..input.lastIndex) {
for (x in 0..input[y].lastIndex) {
val scenicScore = calculateScenicScore(input, y, x)
if (scenicScore > maxScore)
maxScore = scenicScore
}
}
return maxScore
}
fun part1(rawInput: List<String>): Int {
val input = rawInput.map { it.map { char -> char.digitToInt() } }
val maskFromLeft = visibilityHorizontally(input, 0..input[0].lastIndex)
val maskFromRight = visibilityHorizontally(input, input[0].lastIndex downTo 0)
val maskFromTop = visibilityVertically(input, 0..input.lastIndex)
val maskFromBottom = visibilityVertically(input, input.lastIndex downTo 0)
val mergedMask = mergeVisibilityMasks(maskFromLeft, maskFromRight, maskFromTop, maskFromBottom)
return countAllVisible(mergedMask)
}
fun part2(rawInput: List<String>): Int {
val input = rawInput.map { it.map { char -> char.digitToInt() } }
return maxScenicScore(input)
}
val testInput = readInput("sample_data", 8)
println(part1(testInput))
check(part1(testInput) == 21)
val mainInput = readInput("main_data", 8)
println(part1(mainInput))
check(part1(mainInput) == 1798)
println(part2(testInput))
check(part2(testInput) == 8)
println(part2(mainInput))
check(part2(mainInput) == 259308)
}
| 0 | Kotlin | 0 | 0 | 1b261c399a0a84c333cf16f1031b4b1f18b651c7 | 4,996 | advent-of-code-2022 | Apache License 2.0 |
app/src/main/java/com/betulnecanli/kotlindatastructuresalgorithms/SortingAlgorithms/OnSortingAlgorithms/BubbleSort.kt | betulnecanli | 568,477,911 | false | {"Kotlin": 167849} | package com.betulnecanli.kotlindatastructuresalgorithms.SortingAlgorithms.OnSortingAlgorithms
/*One of the simplest sorts is the bubble sort. The bubble sort repeatedly compares
adjacent values and swaps them, if needed, to perform the sort. The larger values in
the set will, therefore, bubble up to the end of the collection.*/
/*Bubble sort has a best time complexity of O(n) if it’s already sorted, and a worst and
average time complexity of O(n²), making it one of the least appealing sorts.*/
fun <T : Comparable<T>> ArrayList<T>.bubbleSort(showPasses : Boolean = true){
//1
if(this.size < 2) return
//2
for (end in (1 until this.size).reversed()){
var swapped = false
//3
for(current in 0 until end){
if(this[current] > this[current + 1]){
//4
this.swapAt(current, current + 1 )
swapped = true
}
}
//5
if(showPasses) println(this)
//6
if(!swapped) return
}
}
/*1. There’s no need to sort the collection when it has less than two elements. One
element is sorted by itself; zero elements don’t require an order.
2. A single-pass will bubble the largest value to the end of the collection. Every pass
needs to compare one less value than in the previous pass, so you shorten the
array by one with each pass.
3. This loop performs a single pass starting from the first element and going up
until the last element not already sorted. It compares every element with the
adjacent value.
4. Next, the algorithm swaps the values if needed and marks this in swapped. This is
important later because it’ll allow you to exit the sort as early as you can detect
the list is sorted.
5. This prints out how the list looks after each pass. This step has nothing to do
with the sorting algorithm, but it will help you visualize how it works. You can
remove it (and the function parameter) after you understand the sorting
algorithm.
6. If no values were swapped this pass, the collection is assumed sorted, and you
can exit early.
*/
| 2 | Kotlin | 2 | 40 | 70a4a311f0c57928a32d7b4d795f98db3bdbeb02 | 2,360 | Kotlin-Data-Structures-Algorithms | Apache License 2.0 |
src/main/kotlin/Day15.kt | chjaeggi | 728,738,815 | false | {"Kotlin": 87254} | import utils.execFileByLine
private enum class Operation(value: String) {
ADD("="), REMOVE("-")
}
private data class Lens(
val label: String,
val focalLength: Int,
)
private data class LensOperation(
val lens: Lens,
val operation: Operation,
val boxNo: Int
)
class Day15 {
private val boxes = mutableMapOf<Int,ArrayDeque<Lens>>()
fun solveFirst(): Int {
var res = -1
execFileByLine(15) {
res = it.split(",").sumOf { it.elfHash() }
}
return res
}
fun solveSecond(): Int {
repeat(256) {
boxes[it] = ArrayDeque()
}
val lensOperations = mutableListOf<LensOperation>()
execFileByLine(15) {
val res = it.split(",")
res.forEach {
val lensLabel = it.substringBefore("=").substringBefore("-")
val focalLength = if (it.contains("=")) it.substringAfter("=").toInt() else -1
val operation = if (it.contains("-")) Operation.REMOVE else Operation.ADD
val boxNo = lensLabel.elfHash()
lensOperations.add(LensOperation(Lens(lensLabel, focalLength), operation, boxNo))
}
lensOperations.forEach {
if (it.operation == Operation.ADD) {
addLens(it.boxNo, it.lens)
} else {
removeLens(it.boxNo, it.lens)
}
}
}
return boxes.map {
if (it.value.isNotEmpty()) {
focusingPowerPerBox(it.key)
} else {
0
}
}.sum()
}
private fun String.elfHash(): Int {
var current = 0
forEach {
current += it.code
current *= 17
current %= 256
}
return current
}
private fun removeLens(boxNo: Int, lens: Lens) {
for ((index, element) in boxes[boxNo]!!.withIndex()) {
if (element.label == lens.label) {
boxes[boxNo]!!.removeAt(index)
break
}
}
}
private fun addLens(boxNo: Int, lens: Lens) {
for ((index, element) in boxes[boxNo]!!.withIndex()) {
if (element.label == lens.label) {
boxes[boxNo]!![index] = lens
return
}
}
boxes[boxNo]!!.addLast(lens)
}
private fun focusingPowerPerBox(boxNo: Int): Int {
var power = 0
for ((index, element) in boxes[boxNo]!!.withIndex()) {
power += (boxNo + 1) * (index + 1) * element.focalLength
}
return power
}
} | 0 | Kotlin | 1 | 1 | a6522b7b8dc55bfc03d8105086facde1e338086a | 2,659 | aoc2023 | Apache License 2.0 |
kotlin/692.Top K Frequent Words(前K个高频单词).kt | learningtheory | 141,790,045 | false | {"Python": 4025652, "C++": 1999023, "Java": 1995266, "JavaScript": 1990554, "C": 1979022, "Ruby": 1970980, "Scala": 1925110, "Kotlin": 1917691, "Go": 1898079, "Swift": 1827809, "HTML": 124958, "Shell": 7944} | /**
<p>Given a non-empty list of words, return the <i>k</i> most frequent elements.</p>
<p>Your answer should be sorted by frequency from highest to lowest. If two words have the same frequency, then the word with the lower alphabetical order comes first.</p>
<p><b>Example 1:</b><br />
<pre>
<b>Input:</b> ["i", "love", "leetcode", "i", "love", "coding"], k = 2
<b>Output:</b> ["i", "love"]
<b>Explanation:</b> "i" and "love" are the two most frequent words.
Note that "i" comes before "love" due to a lower alphabetical order.
</pre>
</p>
<p><b>Example 2:</b><br />
<pre>
<b>Input:</b> ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], k = 4
<b>Output:</b> ["the", "is", "sunny", "day"]
<b>Explanation:</b> "the", "is", "sunny" and "day" are the four most frequent words,
with the number of occurrence being 4, 3, 2 and 1 respectively.
</pre>
</p>
<p><b>Note:</b><br>
<ol>
<li>You may assume <i>k</i> is always valid, 1 ≤ <i>k</i> ≤ number of unique elements.</li>
<li>Input words contain only lowercase letters.</li>
</ol>
</p>
<p><b>Follow up:</b><br />
<ol>
<li>Try to solve it in <i>O</i>(<i>n</i> log <i>k</i>) time and <i>O</i>(<i>n</i>) extra space.</li>
</ol>
</p><p>给一非空的单词列表,返回前 <em>k </em>个出现次数最多的单词。</p>
<p>返回的答案应该按单词出现频率由高到低排序。如果不同的单词有相同出现频率,按字母顺序排序。</p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong> ["i", "love", "leetcode", "i", "love", "coding"], k = 2
<strong>输出:</strong> ["i", "love"]
<strong>解析:</strong> "i" 和 "love" 为出现次数最多的两个单词,均为2次。
注意,按字母顺序 "i" 在 "love" 之前。
</pre>
<p> </p>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong> ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], k = 4
<strong>输出:</strong> ["the", "is", "sunny", "day"]
<strong>解析:</strong> "the", "is", "sunny" 和 "day" 是出现次数最多的四个单词,
出现次数依次为 4, 3, 2 和 1 次。
</pre>
<p> </p>
<p><strong>注意:</strong></p>
<ol>
<li>假定 <em>k</em> 总为有效值, 1 ≤ <em>k</em> ≤ 集合元素数。</li>
<li>输入的单词均由小写字母组成。</li>
</ol>
<p> </p>
<p><strong>扩展练习:</strong></p>
<ol>
<li>尝试以 <em>O</em>(<em>n</em> log <em>k</em>) 时间复杂度和 <em>O</em>(<em>n</em>) 空间复杂度解决。</li>
</ol>
<p>给一非空的单词列表,返回前 <em>k </em>个出现次数最多的单词。</p>
<p>返回的答案应该按单词出现频率由高到低排序。如果不同的单词有相同出现频率,按字母顺序排序。</p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong> ["i", "love", "leetcode", "i", "love", "coding"], k = 2
<strong>输出:</strong> ["i", "love"]
<strong>解析:</strong> "i" 和 "love" 为出现次数最多的两个单词,均为2次。
注意,按字母顺序 "i" 在 "love" 之前。
</pre>
<p> </p>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong> ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], k = 4
<strong>输出:</strong> ["the", "is", "sunny", "day"]
<strong>解析:</strong> "the", "is", "sunny" 和 "day" 是出现次数最多的四个单词,
出现次数依次为 4, 3, 2 和 1 次。
</pre>
<p> </p>
<p><strong>注意:</strong></p>
<ol>
<li>假定 <em>k</em> 总为有效值, 1 ≤ <em>k</em> ≤ 集合元素数。</li>
<li>输入的单词均由小写字母组成。</li>
</ol>
<p> </p>
<p><strong>扩展练习:</strong></p>
<ol>
<li>尝试以 <em>O</em>(<em>n</em> log <em>k</em>) 时间复杂度和 <em>O</em>(<em>n</em>) 空间复杂度解决。</li>
</ol>
**/
class Solution {
fun topKFrequent(words: Array<String>, k: Int): List<String> {
}
} | 0 | Python | 1 | 3 | 6731e128be0fd3c0bdfe885c1a409ac54b929597 | 4,593 | leetcode | MIT License |
src/Day16.kt | matusekma | 572,617,724 | false | {"Kotlin": 119912, "JavaScript": 2024} | import java.util.StringJoiner
import kotlin.math.max
class RatedVertex(
val name: String,
val rate: Int,
var edges: Set<RatedVertex> = setOf()
)
class Edge(val v1: RatedVertex, val v2: RatedVertex, val weight: Int)
class ParseResult(val vertex: RatedVertex, val neighbors: Set<String>)
class Day16 {
var pressure = 0
fun part1(input: List<String>): Int {
val vertexes = mutableMapOf<String, RatedVertex>()
val notZeroVertexes = mutableMapOf<String, RatedVertex>()
val vertexNeighbors = mutableMapOf<String, Set<String>>()
val zeroValves = mutableSetOf<String>()
for (line in input) {
val parseResult = parseLine(line)
val vertex = parseResult.vertex
vertexes[vertex.name] = vertex
vertexNeighbors[vertex.name] = parseResult.neighbors
if (vertex.rate > 0 || vertex.name == "AA") {
notZeroVertexes[vertex.name] = vertex
}
}
for (vertex in vertexes.values) {
vertex.edges =
vertexNeighbors[vertex.name]!!.filter { !zeroValves.contains(it) }.map { vertexes[it]!! }.toSet()
}
val graph = mutableMapOf<String, MutableList<Edge>>()
for (vertex in notZeroVertexes.values) {
for (otherVertex in notZeroVertexes.values) {
if (vertex != otherVertex && otherVertex.name != "AA") {
val edge = Edge(vertex, otherVertex, dijkstra(vertex, otherVertex, vertexes.values.toList()))
if (graph[vertex.name] != null) graph[vertex.name]!!.add(edge) else graph[vertex.name] = mutableListOf(edge)
}
}
}
DFS(0, graph, "AA", 0, 30, setOf(), false)
return pressure
}
private fun DFS(
p: Int,
graph: MutableMap<String, MutableList<Edge>>,
v: String,
time: Int,
maxTime: Int,
discovered: Set<String>,
part2: Boolean
) {
pressure = max(pressure, p)
for (edge in graph[v]!!) {
val v2 = edge.v2
val dist = edge.weight
// if `v2` is not yet discovered
if (!discovered.contains(v2.name) && time + dist + 1 < maxTime) {
DFS(
p + (maxTime - time - dist - 1) * v2.rate,
graph,
v2.name,
time + dist + 1,
maxTime,
discovered.union(listOf(v2.name)),
part2
)
}
}
if (part2) {
DFS(p, graph, "AA", 0, maxTime, discovered, false)
}
}
fun parseLine(line: String): ParseResult {
val destructuredRegex =
"Valve ([A-Z]{2}) has flow rate=([0-9]+); tunnels? leads? to valves? (.*)".toRegex()
return destructuredRegex.matchEntire(line)
?.destructured
?.let { (name, rate, valves) ->
ParseResult(RatedVertex(name, rate.toInt()), valves.split(", ").toSet())
}
?: throw IllegalArgumentException("Bad input '$line'")
}
fun part2(input: List<String>): Int {
val vertexes = mutableMapOf<String, RatedVertex>()
val notZeroVertexes = mutableMapOf<String, RatedVertex>()
val vertexNeighbors = mutableMapOf<String, Set<String>>()
val zeroValves = mutableSetOf<String>()
for (line in input) {
val parseResult = parseLine(line)
val vertex = parseResult.vertex
vertexes[vertex.name] = vertex
vertexNeighbors[vertex.name] = parseResult.neighbors
if (vertex.rate > 0 || vertex.name == "AA") {
notZeroVertexes[vertex.name] = vertex
}
}
for (vertex in vertexes.values) {
vertex.edges =
vertexNeighbors[vertex.name]!!.filter { !zeroValves.contains(it) }.map { vertexes[it]!! }.toSet()
}
val graph = mutableMapOf<String, MutableList<Edge>>()
for (vertex in notZeroVertexes.values) {
for (otherVertex in notZeroVertexes.values) {
if (vertex != otherVertex && otherVertex.name != "AA") {
val edge = Edge(vertex, otherVertex, dijkstra(vertex, otherVertex, vertexes.values.toList()))
if (graph[vertex.name] != null) graph[vertex.name]!!.add(edge) else graph[vertex.name] = mutableListOf(edge)
}
}
}
DFS(0, graph, "AA", 0, 26, setOf(), true)
return pressure
}
private fun dijkstra(startNode: RatedVertex, endNode: RatedVertex, vertexList: List<RatedVertex>): Int {
val distances = mutableMapOf<RatedVertex, Int>()
distances[startNode] = 0
val q = mutableSetOf<RatedVertex>()
for (vertex in vertexList) {
if (vertex != startNode) distances[vertex] = Int.MAX_VALUE
q.add(vertex)
}
while (q.isNotEmpty()) {
val v = q.minBy { distances[it]!! }
q.remove(v)
for (neighbor in v.edges) {
if (q.contains(neighbor)) {
val alt = distances[v]!! + 1
if (alt < distances[neighbor]!!) {
distances[neighbor] = alt
}
}
}
if (v == endNode) {
distances[endNode]!!
}
}
return distances[endNode]!!
}
}
fun main() {
val input = readInput("input16_1")
println(Day16().part1(input))
println(Day16().part2(input))
} | 0 | Kotlin | 0 | 0 | 744392a4d262112fe2d7819ffb6d5bde70b6d16a | 5,661 | advent-of-code | Apache License 2.0 |
src/main/kotlin/day9.kt | gautemo | 725,273,259 | false | {"Kotlin": 79259} | import shared.*
fun main() {
val input = Input.day(9)
println(day9A(input))
println(day9B(input))
}
fun day9A(input: Input): Long {
val sequences = input.lines.map { Sequence(it.toLongs().toMutableList()) }
sequences.forEach { it.addNextValue() }
return sequences.sumOf { it.values.last() }
}
fun day9B(input: Input): Long {
val sequences = input.lines.map { Sequence(it.toLongs().toMutableList()) }
sequences.forEach { it.addPreviousValue() }
return sequences.sumOf { it.values[0] }
}
class Sequence(val values: MutableList<Long>) {
fun addNextValue() {
if(values.all { it == 0L }) {
values.add(0)
} else {
val subSequence = Sequence(values.zipWithNext().map { it.second - it.first }.toMutableList())
subSequence.addNextValue()
values.add(values.last() + subSequence.values.last())
}
}
fun addPreviousValue() {
if(values.all { it == 0L }) {
values.add(0, 0)
} else {
val subSequence = Sequence(values.zipWithNext().map { it.second - it.first }.toMutableList())
subSequence.addPreviousValue()
values.add(0, values[0] - subSequence.values[0])
}
}
} | 0 | Kotlin | 0 | 0 | 6862b6d7429b09f2a1d29aaf3c0cd544b779ed25 | 1,248 | AdventOfCode2023 | MIT License |
src/main/java/com/barneyb/aoc/aoc2021/day06/Lanternfish.kt | barneyb | 553,291,150 | false | {"Kotlin": 184395, "Java": 104225, "HTML": 6307, "JavaScript": 5601, "Shell": 3219, "CSS": 1020} | package com.barneyb.aoc.aoc2021.day06
import com.barneyb.aoc.util.Solver
fun main() {
Solver.execute(
::parse,
{ nDays(it, 80) },
{ nDays(it, 256) },
)
}
fun parse(input: String): LongArray {
val hist = LongArray(9)
input.trim()
.split(',')
.map(String::toInt)
.forEach {
hist[it] = hist[it] + 1 // += is a compile error?!
}
return hist
}
fun nDays(hist: LongArray, n: Int): Long {
var curr = hist
for (i in 1..n) {
val next = curr.clone()
for (j in next.indices) {
when (j) {
6 -> next[j] = curr[j + 1] + curr[0]
8 -> next[j] = curr[0]
else -> next[j] = curr[j + 1]
}
}
curr = next
}
return curr.sum()
}
| 0 | Kotlin | 0 | 0 | 8b5956164ff0be79a27f68ef09a9e7171cc91995 | 817 | aoc-2022 | MIT License |
src/main/java/challenges/cracking_coding_interview/bit_manipulation/flip_bit_to_win/QuestionD.kt | ShabanKamell | 342,007,920 | false | null | package challenges.cracking_coding_interview.bit_manipulation.flip_bit_to_win
/**
* You have an integer, and you can flip exactly one bit from a 0 to a 1.
* Write code to find the length of the longest sequence of ls you could create.
* EXAMPLE
* Input: 1775 (or: 11011101111) Output: 8
*/
object QuestionD {
private fun flipBit(a: Int): Int {
/* If all 1s, this is already the longest sequence. */
var a = a
if (a.inv() == 0) return Integer.BYTES * 8
var currentLength = 0
var previousLength = 0
var maxLength = 1 // We can always have a sequence of at least one 1
while (a != 0) {
if (a and 1 == 1) {
currentLength++
} else if (a and 1 == 0) {
/* Update to 0 (if next bit is 0) or currentLength (if next bit is 1). */
previousLength = if (a and 2 == 0) 0 else currentLength
currentLength = 0
}
maxLength = Math.max(previousLength + currentLength + 1, maxLength)
a = a ushr 1
}
return maxLength
}
@JvmStatic
fun main(args: Array<String>) {
val cases = arrayOf(
intArrayOf(-1, 32),
intArrayOf(Int.MAX_VALUE, 32),
intArrayOf(-10, 31),
intArrayOf(0, 1),
intArrayOf(1, 2),
intArrayOf(15, 5),
intArrayOf(1775, 8)
)
for (c in cases) {
val x = flipBit(c[0])
val r = c[1] == x
println(c[0].toString() + ": " + x + ", " + c[1] + " " + r)
}
}
} | 0 | Kotlin | 0 | 0 | ee06bebe0d3a7cd411d9ec7b7e317b48fe8c6d70 | 1,614 | CodingChallenges | Apache License 2.0 |
app/src/main/kotlin/com/jamjaws/adventofcode/xxiii/day/Day10.kt | JamJaws | 725,792,497 | false | {"Kotlin": 30656} | package com.jamjaws.adventofcode.xxiii.day
import com.jamjaws.adventofcode.xxiii.readInput
import java.awt.Polygon
class Day10 {
fun part1(text: List<String>): Int {
val (xStart, yStart) = getStartCoordinate(text)
val start = Pipe(xStart, yStart, PipeType.START)
val loop = getPipeLoop(start, text)
return loop.count() / 2
}
fun part2(text: List<String>): Int {
val (xStart, yStart) = getStartCoordinate(text)
val start = Pipe(xStart, yStart, PipeType.START)
val loop = getPipeLoop(start, text)
val polygon = Polygon(loop.map(Pipe::x).toIntArray(), loop.map(Pipe::y).toIntArray(), loop.size)
val loopTiles = text.flatMapIndexed { y: Int, line: String -> line.indices.mapNotNull { x -> Pair(x, y) } }
.filter { (x, y) -> polygon.intersects(x - 0.5, y - 0.5, 1.0, 1.0) }
val enclosedByTheLoop = loopTiles.filterNot { tile -> loop.any { tile == it.coordinate } }
return enclosedByTheLoop.size
}
private fun getPipeLoop(
start: Pipe,
text: List<String>
) = generateSequence(start) {
it.getNext(text)
}.takeWhile {
it == start || it.pipeType != PipeType.START
}.toList()
private fun getStartCoordinate(text: List<String>): Pair<Int, Int> =
text.indexOfFirst { line -> line.contains(PipeType.START.char) }
.let { y -> text[y].indexOfFirst { it == PipeType.START.char } to y }
enum class PipeType(val char: Char) {
NS('|'),
EW('-'),
NE('L'),
NW('J'),
SW('7'),
SE('F'),
GROUND('.'),
START('S');
companion object {
fun of(char: Char) = entries.first { it.char == char }
val toNorth = listOf(NS, SE, SW)
val toEast = listOf(EW, NW, SW)
val toSouth = listOf(NS, NE, NW)
val toWest = listOf(EW, NE, SE)
}
}
class Pipe(val x: Int, val y: Int, val pipeType: PipeType, private val from: Pair<Int, Int>? = null) {
constructor(coordinate: Pair<Int, Int>, sketch: List<String>, from: Pipe?) : this(
coordinate.first,
coordinate.second,
PipeType.of(sketch[coordinate.second][coordinate.first]),
from?.coordinate,
)
val coordinate get() = Pair(x, y)
fun getNext(sketch: List<String>): Pipe =
when (pipeType) {
PipeType.NS -> sequenceOf(n, s).next(sketch)
PipeType.EW -> sequenceOf(e, w).next(sketch)
PipeType.NE -> sequenceOf(n, e).next(sketch)
PipeType.NW -> sequenceOf(n, w).next(sketch)
PipeType.SW -> sequenceOf(s, w).next(sketch)
PipeType.SE -> sequenceOf(s, e).next(sketch)
PipeType.START -> {
sequence {
yield(Pipe(n, sketch, this@Pipe).takeIf { it.pipeType in PipeType.toNorth })
yield(Pipe(e, sketch, this@Pipe).takeIf { it.pipeType in PipeType.toEast })
yield(Pipe(s, sketch, this@Pipe).takeIf { it.pipeType in PipeType.toSouth })
yield(Pipe(w, sketch, this@Pipe).takeIf { it.pipeType in PipeType.toWest })
}.filterNotNull()
.first()
}
PipeType.GROUND -> throw IllegalStateException("should never go here")
}
private fun Sequence<Pair<Int, Int>>.next(sketch: List<String>): Pipe =
map { Pipe(it, sketch, this@Pipe) }.first { it.coordinate != from }
private val n get() = Pair(x, y - 1)
private val s get() = Pair(x, y + 1)
private val e get() = Pair(x + 1, y)
private val w get() = Pair(x - 1, y)
}
}
fun main() {
val answer1 = Day10().part1(readInput("Day10"))
println(answer1)
val answer2 = Day10().part2(readInput("Day10"))
println(answer2)
}
| 0 | Kotlin | 0 | 0 | e2683305d762e3d96500d7268e617891fa397e9b | 3,976 | advent-of-code-2023 | MIT License |
src/test/kotlin/nl/dirkgroot/adventofcode/year2022/Day03Test.kt | dirkgroot | 317,968,017 | false | {"Kotlin": 187862} | package nl.dirkgroot.adventofcode.year2022
import io.kotest.core.spec.style.StringSpec
import io.kotest.matchers.shouldBe
import nl.dirkgroot.adventofcode.util.*
private fun solution1(input: String) = input.lineSequence()
.splitCompartments()
.totalPriorityOfOverlappingItems()
private fun Sequence<String>.splitCompartments() = this
.map { it.chunked(it.length / 2) }
.map { it.map { compartment -> compartment.toSet() } }
private fun solution2(input: String) = input.lineSequence()
.splitGroups()
.totalPriorityOfOverlappingItems()
private fun Sequence<String>.splitGroups() = this
.chunked(3)
.map { it.map { rucksack -> rucksack.toSet() } }
private fun Sequence<List<Set<Char>>>.totalPriorityOfOverlappingItems() = this
.map { it.reduce { acc, rucksack -> acc.intersect(rucksack) } }
.map { it.single() }
.sumOf { if (it >= 'a') it - 'a' + 1 else it - 'A' + 27 }
//===============================================================================================\\
private const val YEAR = 2022
private const val DAY = 3
class Day03Test : StringSpec({
"example part 1" { ::solution1 invokedWith exampleInput shouldBe 157 }
"part 1 solution" { ::solution1 invokedWith input(YEAR, DAY) shouldBe 7903 }
"example part 2" { ::solution2 invokedWith exampleInput shouldBe 70 }
"part 2 solution" { ::solution2 invokedWith input(YEAR, DAY) shouldBe 2548 }
})
private val exampleInput =
"""
vJrwpWtwJgWrhcsFMMfFFhFp
jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL
PmmdzqPrVvPwwTWBwg
wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn
ttgJtRGJQctTZtZT
CrZsJsPPZsGzwwsLwLmpwMDw
""".trimIndent()
| 1 | Kotlin | 1 | 1 | ffdffedc8659aa3deea3216d6a9a1fd4e02ec128 | 1,676 | adventofcode-kotlin | MIT License |
src/Day01.kt | patrickwilmes | 572,922,721 | false | {"Kotlin": 6337} | typealias ElvesWithTotalCalories = List<List<Int>>
fun main() {
val calculateCaloriesCarriedByAllElves: (List<String>) -> ElvesWithTotalCalories = {
it.fold(mutableListOf(mutableListOf<Int>())) { acc, item ->
if (item.isBlank()) {
acc.add(mutableListOf())
} else {
acc.last().add(item.toInt())
}
acc
}
}
fun part1(input: List<String>): Int {
val elvesCalories = calculateCaloriesCarriedByAllElves(input)
return elvesCalories.maxOfOrNull {
it.sum()
} ?: 0
}
fun part2(input: List<String>): Int {
return calculateCaloriesCarriedByAllElves(input)
.map { it.sum() }
.sortedDescending()
.subList(0, 3)
.sum()
}
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 162c8f1b814805285e10ea4e3ab944c21e8be4c5 | 910 | advent-of-code-2022 | Apache License 2.0 |
dcp_kotlin/src/main/kotlin/dcp/day282/day282.kt | sraaphorst | 182,330,159 | false | {"C++": 577416, "Kotlin": 231559, "Python": 132573, "Scala": 50468, "Java": 34742, "CMake": 2332, "C": 315} | package dcp.day282
// day282.kt
// By <NAME>, 2020.
typealias Triplet = Triple<Int, Int, Int>
/**
* Find the first Pythagorean triplet (in lexicographic order) in a collection of integers.
* This is a triple (a, b, c) such that:
* 1. a, b, c > 0 and a < b
* 2. a^2 + b^2 = c^2.
*/
fun Collection<Int>.findPythagoreanTriplet(): Triplet? {
if (size < 3)
return null
// First square everything and sort to avoid having to repeatedly square.
// Only positive integers can make up a Pythagorean triple by definition.
val sortedSquares = filter{it > 0}.map{it * it to it}.sortedBy(Pair<Int,Int>::first)
// Now iterate O(N^2) to see if we can find a triplet, and return the first one.
for (i in 0 until (sortedSquares.size - 2))
for (j in (i + 1) until (sortedSquares.size - 1)) {
val hypotenuse = sortedSquares.find { it.first == sortedSquares[i].first + sortedSquares[j].first }
if (hypotenuse != null)
return Triplet(sortedSquares[i].second, sortedSquares[j].second, hypotenuse.second)
}
return null
}
| 0 | C++ | 1 | 0 | 5981e97106376186241f0fad81ee0e3a9b0270b5 | 1,112 | daily-coding-problem | MIT License |
src/Day03.kt | arhor | 572,349,244 | false | {"Kotlin": 36845} | fun main() {
val input = readInput {}
println("Part 1: " + solvePuzzle1(input))
println("Part 2: " + solvePuzzle2(input))
}
private fun solvePuzzle1(input: List<String>): Int {
return input.sumOf { line ->
val l = line.substring(0, line.length / 2)
val r = line.substring(line.length / 2, line.length)
ALPHABET.indexOf(l.first { it in r })
}
}
private fun solvePuzzle2(input: List<String>): Int {
return input.chunked(3).sumOf { (s1, s2, s3) ->
ALPHABET.indexOf(s1.first { it in s2 && it in s3 })
}
}
| 0 | Kotlin | 0 | 0 | 047d4bdac687fd6719796eb69eab2dd8ebb5ba2f | 564 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/com/ginsberg/advent2022/Day21.kt | tginsberg | 568,158,721 | false | {"Kotlin": 113322} | /*
* Copyright (c) 2022 by <NAME>
*/
/**
* Advent of Code 2022, Day 21 - Monkey Math
* Problem Description: http://adventofcode.com/2022/day/21
* Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2022/day21/
*/
package com.ginsberg.advent2022
class Day21(input: List<String>) {
private val monkeys: Set<Monkey> = parseInput(input)
private val root: Monkey = monkeys.first { it.name == "root" }
fun solvePart1(): Long =
root.yell()
fun solvePart2(): Long =
root.calculateHumanValue()
private fun parseInput(input: List<String>): Set<Monkey> {
val monkeyCache: Map<String, Monkey> = input.map { Monkey(it) }.associateBy { it.name }
monkeyCache.values.filterIsInstance<FormulaMonkey>().forEach { monkey ->
monkey.left = monkeyCache.getValue(monkey.leftName)
monkey.right = monkeyCache.getValue(monkey.rightName)
}
return monkeyCache.values.toSet()
}
private interface Monkey {
val name: String
fun yell(): Long
fun findHumanPath(): Set<Monkey>
fun calculateHumanValue(humanPath: Set<Monkey> = findHumanPath(), incoming: Long = 0L): Long
companion object {
operator fun invoke(row: String): Monkey {
val name = row.substringBefore(":")
return if (row.length == 17) {
FormulaMonkey(name, row.substring(6..9), row.substringAfterLast(" "), row[11])
} else {
NumberMonkey(name, row.substringAfter(" ").toLong())
}
}
}
}
private class NumberMonkey(
override val name: String,
val number: Long
) : Monkey {
override fun yell(): Long = number
override fun findHumanPath(): Set<Monkey> =
if (name == "humn") setOf(this) else emptySet()
override fun calculateHumanValue(humanPath: Set<Monkey>, incoming: Long): Long =
if (name == "humn") incoming else number
}
private class FormulaMonkey(
override val name: String,
val leftName: String,
val rightName: String,
val op: Char
) : Monkey {
lateinit var left: Monkey
lateinit var right: Monkey
override fun calculateHumanValue(humanPath: Set<Monkey>, incoming: Long): Long =
if (name == "root") {
if (left in humanPath) left.calculateHumanValue(humanPath, right.yell())
else right.calculateHumanValue(humanPath, left.yell())
} else if (left in humanPath) {
left.calculateHumanValue(humanPath, incoming leftAntiOp right.yell()) // Negate
} else {
right.calculateHumanValue(humanPath, incoming rightAntiOp left.yell()) // Negate
}
override fun findHumanPath(): Set<Monkey> {
val leftPath = left.findHumanPath()
val rightPath = right.findHumanPath()
return if (leftPath.isNotEmpty()) leftPath + this
else if (rightPath.isNotEmpty()) rightPath + this
else emptySet()
}
override fun yell(): Long =
left.yell() op right.yell()
private infix fun Long.op(right: Long): Long =
when (op) {
'+' -> this + right
'-' -> this - right
'*' -> this * right
else -> this / right
}
private infix fun Long.leftAntiOp(right: Long): Long =
when (op) {
'+' -> this - right
'-' -> this + right
'*' -> this / right
else -> this * right
}
private infix fun Long.rightAntiOp(right: Long): Long =
when (op) {
'+' -> this - right
'-' -> right - this
'*' -> this / right
else -> right / this
}
}
}
| 0 | Kotlin | 2 | 26 | 2cd87bdb95b431e2c358ffaac65b472ab756515e | 3,971 | advent-2022-kotlin | Apache License 2.0 |
src/graphs/weighted/DirectedWeightedGraph.kt | ArtemBotnev | 136,745,749 | false | {"Kotlin": 79256, "Shell": 292} | package graphs.weighted
/**
* Model of directed weighted graph
*/
class DirectedWeightedGraph<T>(maxVertexCount: Int, infinity: Long)
: WeightedGraph<T>(maxVertexCount, infinity) {
override fun addEdge(first: T, second: T, weight: Long): Boolean {
val values = vertexList.map { it.value }
val start = values.indexOf(first)
val end = values.indexOf(second)
if (start < 0 || end < 0) return false
adjMatrix[start][end] = weight
return true
}
/**
* finds shortest path from particular vertex to each vertex of this graph
* Dijkstra’s algorithm
*
* @param from - the value of the vertex from which the path should begin
* @return list of Pair which represent shortest paths
* @throws NotSuchVertexException - in case the vertex with value @from hasn't been found
*/
@Throws(NotSuchVertexException::class)
fun shortestPath(from: T): List<Pair<List<T>, Long>>? {
// list of all paths from start vertex
val pathList = mutableListOf<Path<T>>()
val startVertexIndex = vertexList.map { it.value }.indexOf(from)
// startVertexIndex is already visited
var visitedVerticesCount = 1
if (startVertexIndex < 0) throw NotSuchVertexException()
// vertex form which begin part of full path in particular moment
var parentVertex = vertexList[startVertexIndex].also { it.wasVisited = true }
// fill path list
for (i in 0 until currentVertexCount) {
val weight = adjMatrix[startVertexIndex][i]
// add new path from start vertex to list
pathList.add(Path(parentVertex, vertexList[i].value, weight))
}
// till all vertices will be visited
while (visitedVerticesCount < currentVertexCount) {
val shortestPathIndex = getMinWeightVertexIndex(startVertexIndex, pathList)
val shortestPath = pathList[shortestPathIndex]
if (shortestPath.weight >= infinity) {
return null
} else {
// assign vertex that is start of shortest path as parent vertex
parentVertex = vertexList[shortestPathIndex]
}
parentVertex.wasVisited = true
visitedVerticesCount++
adjustPaths(pathList, parentVertex, shortestPath)
}
// flags reset
vertexList.forEach { it.wasVisited = false }
// building result
// exclude path start vertex to itself
pathList.removeAt(startVertexIndex)
return pathList.map { it.report() }
}
/**
* finds index of vertex which has shortest path from start vertex to it
* and hasn't visited yet
*
* @param startVertexIndex - index of start vertex
* @param paths - list of paths from start vertex to each vertex in this graph
* @return - index of found vertex in adj matrix
*/
private fun getMinWeightVertexIndex(
startVertexIndex: Int, paths: MutableList<Path<T>>
): Int {
var minWeight = infinity
var minIndex = 0
for (i in 0 until currentVertexCount) {
// skip start vertex
if (startVertexIndex == i) continue
if (!vertexList[i].wasVisited && paths[i].weight < minWeight) {
minWeight = paths[i].weight
minIndex = i
}
}
return minIndex
}
/**
* updates paths according to info about new visited vertex
*
* @param paths - list of all paths from start vertex
* @param currentVertex - vertex that has just visited
* @param previousPath - previous shortest path
*/
private fun adjustPaths(
paths: MutableList<Path<T>>,
currentVertex: Vertex<T>,
previousPath: Path<T>) {
val parentIndex = vertexList.indexOf(currentVertex)
val startToParentWeight = previousPath.weight
for (i in 0 until currentVertexCount) {
if (vertexList[i].wasVisited) continue
val currentToDist = adjMatrix[parentIndex][i]
val startToDist = startToParentWeight + currentToDist
val path = paths[i].weight
if (startToDist < path) {
// update path
paths[i].run {
addVertices(previousPath.pathPoints)
addVertex(currentVertex)
weight = startToDist
}
}
}
}
/**
* Represents shortest path from start vertex to vertex in the graph
*
* @param startVertex - vertex from that path is beginning
* @param destination - destination vertex value
* @param weight - summary weight from startVertex to vertex of this Path
*/
private inner class Path<T>(private val startVertex: Vertex<T>, private val destination: T, var weight: Long) {
val pathPoints = mutableListOf<Vertex<T>>()
private var currentVertex: Vertex<T>
init {
currentVertex = startVertex
}
/**
* adds new vertex through which the path lies
*/
fun addVertex(vertex: Vertex<T>) {
currentVertex = vertex
pathPoints.add(vertex)
}
/**
* adds all previous vertices through which the path lies
*/
fun addVertices(vertices: List<Vertex<T>>) {
vertices.forEach {
if (!pathPoints.contains(it)) pathPoints.add(it)
}
}
/**
* converts Path to Pair<List<T>, Long> - all vertices through which the path lies
* and its weight
*/
fun report(): Pair<List<T>, Long> {
val res = mutableListOf(startVertex.value)
.apply { addAll(pathPoints.map { it.value }) }
.apply { add(destination) }
return res to weight
}
override fun toString() ="$startVertex->${pathPoints.joinToString("") { "$it->" } }" +
"$destination $weight"
}
} | 0 | Kotlin | 0 | 0 | 530c02e5d769ab0a49e7c3a66647dd286e18eb9d | 6,113 | Algorithms-and-Data-Structures | MIT License |
src/main/kotlin/com/eric/leetcode/MaxAreaOfIsland.kt | wanglikun7342 | 163,727,208 | false | {"Kotlin": 172132, "Java": 27019} | package com.eric.leetcode
class MaxAreaOfIsland {
private lateinit var grid: Array<IntArray>
private lateinit var seen: Array<BooleanArray>
private var count = 0
var dr = intArrayOf(1, -1, 0, 0)
var dc = intArrayOf(0, 0, 1, -1)
private fun getArea(r: Int, c: Int): Int {
count++
if (r < 0 || r >= grid.size || c < 0 || c >= grid[0].size ||
seen[r][c] || grid[r][c] == 0)
return 0
seen[r][c] = true
return 1 + getArea(r + 1, c) + getArea(r - 1, c) + getArea(r, c - 1) + getArea(r, c + 1)
}
fun maxAreaOfIsland(grid: Array<IntArray>): Int {
this.grid = grid
seen = Array(grid.size) { BooleanArray(grid[0].size) }
var ans = 0
for (r in grid.indices) {
for (c in grid[0].indices) {
count = 0
ans = maxOf(ans, getArea(r, c))
println("r: $r, c: $c, count: $count")
}
}
return ans
}
fun maxAreaOfIsland2(grid: Array<IntArray>): Int {
this.grid = grid
seen = Array(grid.size) { BooleanArray(grid[0].size) }
var queue = mutableListOf<IntArray>()
var ans = 0
for (r in grid.indices) {
for (c in grid[0].indices) {
if (!seen[r][c] && grid[r][c] == 1) {
var shape = 0
seen[r][c] = true
queue.add(intArrayOf(r, c))
while (queue.isNotEmpty()) {
var node = queue.removeAt(0)
var rIndex = node[0]
var cIndex = node[1]
shape++
for (k in 0..3) {
val nr = rIndex + dr[k]
val nc = cIndex + dc[k]
if (nr in grid.indices &&
nc in grid[0].indices &&
grid[nr][nc] == 1 && !seen[nr][nc]) {
queue.add(intArrayOf(nr, nc))
seen[nr][nc] = true
}
}
}
ans = maxOf(ans, shape)
}
}
}
return ans
}
}
fun main(args: Array<String>) {
val grid = arrayOf(
intArrayOf(0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0),
intArrayOf(0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0),
intArrayOf(0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0),
intArrayOf(0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0),
intArrayOf(0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0),
intArrayOf(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0),
intArrayOf(0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0),
intArrayOf(0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0))
val grid2 = arrayOf(intArrayOf(1, 1))
val maxAreaOfIsland = MaxAreaOfIsland()
println("result: " + maxAreaOfIsland.maxAreaOfIsland2(grid))
} | 0 | Kotlin | 2 | 8 | d7fb5ff5a0a64d9ce0a5ecaed34c0400e7c2c89c | 3,096 | Leetcode-Kotlin | Apache License 2.0 |
src/year2022/day22/Day22.kt | kingdongus | 573,014,376 | false | {"Kotlin": 100767} | package year2022.day22
import Point2D
import readInputFileByYearAndDay
import readTestFileByYearAndDay
import year2022.day22.Orientation.*
import kotlin.math.max
import kotlin.math.min
enum class Orientation(val direction: Point2D, val facing: Int) {
UP(Point2D(0, -1), 3),
DOWN(Point2D(0, 1), 1),
LEFT(Point2D(-1, 0), 2),
RIGHT(Point2D(1, 0), 0);
fun turnRight(): Orientation =
when (this) {
UP -> RIGHT
RIGHT -> DOWN
DOWN -> LEFT
else -> UP
}
fun turnLeft(): Orientation =
when (this) {
UP -> LEFT
LEFT -> DOWN
DOWN -> RIGHT
else -> UP
}
}
val OPEN_TILE = '.'
val SOLID_TILE = '#'
val WRAP_TILE = ' '
fun tokenizeInstructions(instructions: String): List<String> {
var buffer = ""
val result = mutableListOf<String>()
for (c in instructions.split("")) {
when (c) {
"" -> continue
"L", "R" -> {
if (buffer.isNotBlank()) {
result.add(buffer)
buffer = ""
}
result.add(c)
}
else -> buffer += c
}
}
if (buffer.isNotBlank()) result.add(buffer)
return result
}
fun main() {
fun walkFlat(field: Array<String>, startPosition: Point2D, orientation: Orientation, numSteps: Int): Point2D {
val fieldDimensionX = field[0].length
val fieldDimensionY = field.size
var (x, y) = startPosition
repeat(numSteps) {
var newX = x + orientation.direction.x
var newY = y + orientation.direction.y
if (newX < 0) newX = max(field[y].lastIndexOf(OPEN_TILE), field[y].lastIndexOf(SOLID_TILE))
else if (newX >= fieldDimensionX) newX = min(field[y].indexOf(OPEN_TILE), field[y].indexOf(SOLID_TILE))
if (newY < 0) {
// search in column from bottom (fieldDimensionY-1)
for (i in field.indices.reversed()) {
if (field[i][x] != WRAP_TILE) {
newY = i
break
}
}
} else if (newY >= fieldDimensionY) {
// search in column from top (0)
for (i in field.indices)
if (field[i][x] != WRAP_TILE) {
newY = i
break
}
}
// if newX, newY is a wrap tile, search for the first non-wrap tile, factoring in direction
if (field[newY][newX] == WRAP_TILE) {
if (orientation.direction.x > 0) {
newX = min(field[y].indexOf(OPEN_TILE), field[y].indexOf(SOLID_TILE))
} else if (orientation.direction.x < 0) {
newX = max(field[y].lastIndexOf(OPEN_TILE), field[y].lastIndexOf(SOLID_TILE))
} else if (orientation.direction.y > 0) {
for (i in field.indices)
if (field[i][x] != WRAP_TILE) {
newY = i
break
}
} else if (orientation.direction.y < 0) {
for (i in field.indices.reversed()) {
if (field[i][x] != WRAP_TILE) {
newY = i
break
}
}
}
}
// only update if we ultimately ended up on a free tile
if (field[newY][newX] == OPEN_TILE) {
x = newX
y = newY
}
}
return Point2D(x, y)
}
fun parseMap(input: List<String>): Array<String> {
val fieldLines = input.takeWhile { it.isNotBlank() }
val fieldDimensionX = fieldLines.maxOf { it.length }
return fieldLines.map { it.padEnd(fieldDimensionX, ' ') }.toTypedArray()
}
fun part1(input: List<String>): Int {
val parsedMapByRow = parseMap(input)
val tokenizedInstructions = tokenizeInstructions(input.last())
var y = 0
var x = parsedMapByRow[0].indexOf(OPEN_TILE)
var orientation = RIGHT
tokenizedInstructions.forEach {
when (it) {
"L" -> orientation = orientation.turnLeft()
"R" -> orientation = orientation.turnRight()
else -> {
val newPos = walkFlat(parsedMapByRow, Point2D(x, y), orientation, it.toInt())
x = newPos.x
y = newPos.y
}
}
}
return ((y + 1) * 1000) + (4 * (x + 1)) + orientation.facing
}
// 21
// 3
// 54
// 6
data class CubeFace(val topLeft: Point2D)
// overlay map with cube faces
// hardcoded for part 2
val faceDim = 50
val face1 = CubeFace(topLeft = Point2D(faceDim * 2, 0))
val face2 = CubeFace(topLeft = Point2D(faceDim, 0))
val face3 = CubeFace(topLeft = Point2D(faceDim, faceDim))
val face4 = CubeFace(topLeft = Point2D(faceDim, faceDim * 2))
val face5 = CubeFace(topLeft = Point2D(0, faceDim * 2))
val face6 = CubeFace(topLeft = Point2D(0, faceDim * 3))
val faces = listOf(face1, face2, face3, face4, face5, face6)
val top = 0
val left = 0
val right = faceDim - 1
val bottom = faceDim - 1
fun startAtTopKeepX(p: Point2D) = Point2D(p.x, top)
fun startAtTopTransformX(p: Point2D) = Point2D(p.y, top)
fun startAtBottomKeepX(p: Point2D) = Point2D(p.x, bottom)
fun startAtBottomTransformX(p: Point2D) = Point2D(p.y, bottom)
fun startAtLeftTransformXtoY(p: Point2D) = Point2D(left, p.x)
fun startAtLeftKeepY(p: Point2D) = Point2D(left, p.y)
fun startAtLeftInvertY(p: Point2D) = Point2D(left, faceDim - p.y - 1) // might be off by one
fun startAtRightInvertY(p: Point2D) = Point2D(right, faceDim - p.y - 1) // might be off by one
fun startAtRightKeepY(p: Point2D) = Point2D(right, p.y)
fun startAtRightTransformXToY(p: Point2D) = Point2D(right, p.x) // might be off by one
// (a,b):(c,d, e) if we exit face a in direction b, enter face c facing direction d transforming coordinates using function e
val transformationRules = mapOf(
(face1 to UP) to Triple(face6, UP, ::startAtBottomKeepX),
(face1 to RIGHT) to Triple(face4, LEFT, ::startAtRightInvertY),
(face1 to DOWN) to Triple(face3, LEFT, ::startAtRightTransformXToY),
(face1 to LEFT) to Triple(face2, LEFT, ::startAtRightKeepY),
(face2 to UP) to Triple(face6, RIGHT, ::startAtLeftTransformXtoY), // ??
(face2 to RIGHT) to Triple(face1, RIGHT, ::startAtLeftKeepY),
(face2 to DOWN) to Triple(face3, DOWN, ::startAtTopKeepX),
(face2 to LEFT) to Triple(face5, RIGHT, ::startAtLeftInvertY), // flipped
(face3 to UP) to Triple(face2, UP, ::startAtBottomKeepX),
(face3 to RIGHT) to Triple(face1, UP, ::startAtBottomTransformX),
(face3 to DOWN) to Triple(face4, DOWN, ::startAtTopKeepX),
(face3 to LEFT) to Triple(face5, DOWN, ::startAtTopTransformX),
(face4 to UP) to Triple(face3, UP, ::startAtBottomKeepX),
(face4 to RIGHT) to Triple(face1, LEFT, ::startAtRightInvertY),
(face4 to DOWN) to Triple(face6, LEFT, ::startAtRightTransformXToY), // probably ok
(face4 to LEFT) to Triple(face5, LEFT, ::startAtRightKeepY),
(face5 to UP) to Triple(face3, RIGHT, ::startAtLeftTransformXtoY),
(face5 to RIGHT) to Triple(face4, RIGHT, ::startAtLeftKeepY),
(face5 to DOWN) to Triple(face6, DOWN, ::startAtTopKeepX),
(face5 to LEFT) to Triple(face2, RIGHT, ::startAtLeftInvertY),
(face6 to UP) to Triple(face5, UP, ::startAtBottomKeepX),
(face6 to RIGHT) to Triple(face4, UP, ::startAtBottomTransformX),
(face6 to DOWN) to Triple(face1, DOWN, ::startAtTopKeepX),
(face6 to LEFT) to Triple(face2, DOWN, ::startAtTopTransformX),
)
fun isOutOfCubeFaceBounds(p: Point2D): Boolean =
p.x < 0 || p.y < 0 || p.y >= faceDim || p.x >= faceDim
fun walkCube(
startFace: CubeFace,
startPosition: Point2D,
orientation: Orientation,
numSteps: Int,
slicedFaces: Map<CubeFace, List<String>>
): Triple<Point2D, Orientation, CubeFace> {
var currentPosition = startPosition
var currentOrientation = orientation
var currentCubeFace = startFace
repeat(numSteps) {
val newPosition = currentPosition + currentOrientation.direction
if (isOutOfCubeFaceBounds(newPosition)) {
val stuff = transformationRules[currentCubeFace to currentOrientation]
val newFace = stuff!!.first
val positionOnNewFace = stuff.third.invoke(newPosition)
val slice = slicedFaces[newFace]
// only update if we ultimately ended up on a free tile
if (slice!![positionOnNewFace.y][positionOnNewFace.x] == OPEN_TILE) {
currentCubeFace = newFace
currentOrientation = stuff.second
currentPosition = positionOnNewFace
}
} else {
val slice = slicedFaces[currentCubeFace]
// only update if we ultimately ended up on a free tile
if (slice!![newPosition.y][newPosition.x] == OPEN_TILE) {
currentPosition = newPosition
}
}
}
return Triple(currentPosition, currentOrientation, currentCubeFace)
}
fun part2(input: List<String>): Int {
val parsedMapByRow = parseMap(input)
// one string array per cube face
val slicedFaces = faces.map { it.topLeft }
.map { it.x to parsedMapByRow.drop(it.y).take(faceDim) }
.map { xAndLines ->
val (x, lines) = xAndLines
lines.map { it.substring(x until x + faceDim) }
}.mapIndexed { index, strings -> faces[index] to strings }
.toMap()
// quick check that we got no off-by-1 errors
slicedFaces.values.onEach { if (it.any { line -> line.contains(" ") }) throw Exception(" oh no") }
val tokenizedInstructions = tokenizeInstructions(input.last())
// start position: top left of face 2 hardcoded
var currentCubeFace = face2
var orientation = RIGHT
var position = Point2D(0, 0)
tokenizedInstructions.forEach {
when (it) {
"L" -> orientation = orientation.turnLeft()
"R" -> orientation = orientation.turnRight()
else -> {
val (newPos, newOrientation, newFace) = walkCube(
currentCubeFace,
position,
orientation,
it.toInt(),
slicedFaces
)
position = newPos
orientation = newOrientation
currentCubeFace = newFace
}
}
}
// transform local cube face coordinates into global coordinates
return ((position.y + currentCubeFace.topLeft.y + 1) * 1000) + (4 * (position.x + currentCubeFace.topLeft.x + 1)) + orientation.facing
}
val testInput = readTestFileByYearAndDay(2022, 22)
check(part1(testInput) == 6032)
// check(part2(testInput) == 5031) // I ignore this one since the layout differs, too much headache
val input = readInputFileByYearAndDay(2022, 22)
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | aa8da2591310beb4a0d2eef81ad2417ff0341384 | 11,789 | advent-of-code-kotlin | Apache License 2.0 |
src/main/kotlin/com/hj/leetcode/kotlin/problem706/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem706
import java.util.*
/**
* LeetCode page: [706. Design HashMap](https://leetcode.com/problems/design-hashmap/);
*/
class MyHashMap() {
private var buckets = Array(8) { LinkedList<Pair<Int, Int>>() }
private var totalEntries = 0
fun get(key: Int): Int {
return buckets[hash(key)]
.firstOrNull { it.first == key }
?.second
?: -1
}
private fun hash(key: Int): Int {
return key % buckets.size
}
fun put(key: Int, value: Int) {
remove(key)
buckets[hash(key)].add(Pair(key, value))
totalEntries++
adaptBucketsSize()
}
fun remove(key: Int) {
buckets[hash(key)]
.removeAll { it.first == key }
.let { if (it) totalEntries-- }
adaptBucketsSize()
}
private fun adaptBucketsSize() {
when {
totalEntries < buckets.size / 4 -> shrinkBuckets()
totalEntries > buckets.size * 3 / 4 -> expandBuckets()
}
}
private fun shrinkBuckets() {
val oldBuckets = buckets
buckets = Array(buckets.size / 2) { LinkedList<Pair<Int, Int>>() }
copyEntriesFrom(oldBuckets)
}
private fun copyEntriesFrom(oldBuckets: Array<LinkedList<Pair<Int, Int>>>) {
for (bucket in oldBuckets) {
for (entry in bucket) {
buckets[hash(entry.first)].add(entry)
}
}
}
private fun expandBuckets() {
val oldBuckets = buckets
buckets = Array(buckets.size * 2) { LinkedList<Pair<Int, Int>>() }
copyEntriesFrom(oldBuckets)
}
}
/**
* Your MyHashMap object will be instantiated and called as such:
* var obj = MyHashMap()
* obj.put(key,value)
* var param_2 = obj.get(key)
* obj.remove(key)
*/ | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 1,831 | hj-leetcode-kotlin | Apache License 2.0 |
src/main/kotlin/com/hj/leetcode/kotlin/problem718/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem718
/**
* LeetCode page: [718. Maximum Length of Repeated Subarray](https://leetcode.com/problems/maximum-length-of-repeated-subarray/);
*/
class Solution {
/* Complexity:
* Time O(MN) and Space O(1) where M and N are the size of nums1 and nums2;
*/
fun findLength(nums1: IntArray, nums2: IntArray): Int {
var maxLength = 0
slideTargetByTailOverDestination(
target = nums1,
destination = nums2
) { overlapLength, startIndexByTarget, startIndexByDestination ->
val currMaxLength = findMaxLengthHavingSameElements(
first = nums1,
second = nums2,
lengthOfScope = overlapLength,
startIndexOfFirst = startIndexByTarget,
startIndexOfSecond = startIndexByDestination
)
maxLength = maxOf(maxLength, currMaxLength)
}
slideTargetByTailOverDestination(
target = nums2,
destination = nums1
) { overlapLength, startIndexByTarget, startIndexByDestination ->
val currMaxLength = findMaxLengthHavingSameElements(
first = nums2,
second = nums1,
lengthOfScope = overlapLength,
startIndexOfFirst = startIndexByTarget,
startIndexOfSecond = startIndexByDestination
)
maxLength = maxOf(maxLength, currMaxLength)
}
return maxLength
}
private fun slideTargetByTailOverDestination(
target: IntArray,
destination: IntArray,
sideEffectPerOverlap: (
overlapLength: Int,
startIndexByTarget: Int,
startIndexByDestination: Int
) -> Unit
) {
for (index in destination.indices) {
val overlapLength = minOf(index + 1, target.size)
val startIndexByTarget = target.size - overlapLength
val startIndexByDestination = index - overlapLength + 1
sideEffectPerOverlap(overlapLength, startIndexByTarget, startIndexByDestination)
}
}
private fun findMaxLengthHavingSameElements(
first: IntArray,
second: IntArray,
lengthOfScope: Int,
startIndexOfFirst: Int,
startIndexOfSecond: Int
): Int {
var maxLength = 0
var currMaxLength = 0
for (index in 0 until lengthOfScope) {
val num1 = first[startIndexOfFirst + index]
val num2 = second[startIndexOfSecond + index]
if (num1 == num2) {
currMaxLength++
maxLength = maxOf(maxLength, currMaxLength)
} else {
currMaxLength = 0
}
}
return maxLength
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 2,804 | hj-leetcode-kotlin | Apache License 2.0 |
src/main/kotlin/io/dp/MinimumAsciiDeleteTwoStrings.kt | jffiorillo | 138,075,067 | false | {"Kotlin": 434399, "Java": 14529, "Shell": 465} | package io.dp
import io.utils.runTests
// https://leetcode.com/problems/minimum-ascii-delete-sum-for-two-strings/
class MinimumAsciiDeleteTwoStrings {
fun execute(initial: String, goal: String): Int {
val dp = Array(initial.length + 1) { row ->
IntArray(goal.length + 1) { col ->
when {
row == 0 && col != 0 -> (0 until col).fold(0) { acc, index -> acc + goal[index].toInt() }
row != 0 && col == 0 -> (0 until row).fold(0) { acc, index -> acc + initial[index].toInt() }
else -> 0
}
}
}
initial.forEachIndexed { row, initialValue ->
goal.forEachIndexed { col, goalValue ->
dp[row + 1][col + 1] =
if (initialValue == goalValue) dp[row][col]
else minOf(dp[row][col] + initialValue.toInt() + goalValue.toInt(), dp[row + 1][col] + goalValue.toInt(), dp[row][col + 1] + initialValue.toInt())
}
}
return dp[initial.length][goal.length]
}
}
fun main() {
runTests(listOf(
Triple("sea", "eat", 231),
Triple("delete", "leet", 403)
)) { (initial, goal, value) -> value to MinimumAsciiDeleteTwoStrings().execute(initial, goal) }
} | 0 | Kotlin | 0 | 0 | f093c2c19cd76c85fab87605ae4a3ea157325d43 | 1,165 | coding | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/Permutations.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import java.util.Collections
import java.util.LinkedList
fun interface Permutations {
fun permute(nums: IntArray): List<List<Int>>
}
class PermutationsBacktracking : Permutations {
override fun permute(nums: IntArray): List<List<Int>> {
// init output list
val output: MutableList<List<Int>> = LinkedList()
// convert nums into list since the output is a list of lists
val numsList: MutableList<Int> = ArrayList()
for (num in nums) numsList.add(num)
val n = nums.size
backtrack(n, numsList, output, 0)
return output
}
private fun backtrack(
n: Int,
nums: List<Int>,
output: MutableList<List<Int>>,
first: Int,
) {
// if all integers are used up
if (first == n) output.add(ArrayList(nums))
for (i in first until n) {
// place i-th integer first
// in the current permutation
Collections.swap(nums, first, i)
// use next integers to complete the permutations
backtrack(n, nums, output, first + 1)
// backtrack
Collections.swap(nums, first, i)
}
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,829 | kotlab | Apache License 2.0 |
src/Day06.kt | zuevmaxim | 572,255,617 | false | {"Kotlin": 17901} | private fun solve(input: List<String>, k: Int): Int {
val s = input[0]
for (i in 0 until s.length - k) {
if (s.substring(i, i + k).toSet().size == k) {
return i + k
}
}
return -1
}
private fun part1(input: List<String>) = solve(input, 4)
private fun part2(input: List<String>) = solve(input, 14)
fun main() {
val testInput = readInput("Day06_test")
check(part1(testInput) == 7)
check(part2(testInput) == 19)
val input = readInput("Day06")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 34356dd1f6e27cc45c8b4f0d9849f89604af0dfd | 557 | AOC2022 | Apache License 2.0 |
src/Day01.kt | KyleMcB | 573,097,895 | false | {"Kotlin": 1762} | import kotlin.math.max
fun main() {
val input = readInput("Day01")
println("solution to puzzle 1 ${solution1(input)}")
println("solution to puzzle 2 ${solution2(input)}")
}
// list of numbers with an extra new line to seperate groups
// I need to sum the groups and find the greatest
fun solution1(input: List<String>): Int {
var maxValueSoFar = Int.MIN_VALUE
input.fold(0) { acc: Int, s: String ->
if (s.isBlank()) {
maxValueSoFar = max(maxValueSoFar, acc)
0
} else {
acc + s.toInt()
}
}
return maxValueSoFar
} // I decided to go for a semi functional approach
//I need to keep track of the top three this time so I will just keep track of all of them
//then sort and take the top three
fun solution2(input: List<String>):Int {
val list = mutableListOf<Int>()
input.fold(0) {acc: Int, s: String ->
if (s.isBlank()) {
list.add(acc)
0
} else {
acc + s.toInt()
}
}
list.sort()
val last = list.lastIndex
return list[last] + list[last-1] + list[last-2]
} | 0 | Kotlin | 0 | 0 | d3ad4cf2940507207276f5e5ed2eb1149300802f | 1,125 | 2022-AOC | Apache License 2.0 |
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[100]相同的树.kt | maoqitian | 175,940,000 | false | {"Kotlin": 354268, "Java": 297740, "C++": 634} | //给定两个二叉树,编写一个函数来检验它们是否相同。
//
// 如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。
//
// 示例 1:
//
// 输入: 1 1
// / \ / \
// 2 3 2 3
//
// [1,2,3], [1,2,3]
//
//输出: true
//
// 示例 2:
//
// 输入: 1 1
// / \
// 2 2
//
// [1,2], [1,null,2]
//
//输出: false
//
//
// 示例 3:
//
// 输入: 1 1
// / \ / \
// 2 1 1 2
//
// [1,2,1], [1,1,2]
//
//输出: false
//
// Related Topics 树 深度优先搜索
// 👍 559 👎 0
//leetcode submit region begin(Prohibit modification and deletion)
/**
* Example:
* var ti = TreeNode(5)
* var v = ti.`val`
* Definition for a binary tree node.
* class TreeNode(var `val`: Int) {
* var left: TreeNode? = null
* var right: TreeNode? = null
* }
*/
class Solution {
fun isSameTree(p: TreeNode?, q: TreeNode?): Boolean {
//递归比较比较 时间复杂度 O(n)
//递归结束条件
if(p == null && q == null) {
return true
}else if(p == null || q == null){
return false
}else if(p.`val` != q.`val`){
return false
}else{
return isSameTree(p.left,q.left) && isSameTree(p.right,q.right)
}
//逻辑处理 进入下层循环
}
}
//leetcode submit region end(Prohibit modification and deletion)
| 0 | Kotlin | 0 | 1 | 8a85996352a88bb9a8a6a2712dce3eac2e1c3463 | 1,559 | MyLeetCode | Apache License 2.0 |
src/main/kotlin/Day20.kt | dlew | 75,886,947 | false | null | import java.util.*
class Day20 {
companion object {
fun findLowest(input: String) = merge(parse(input))[0].endInclusive + 1
fun count(input: String, max: Long): Long {
val merged = merge(parse(input))
val betweenRanges = merged.slidingWindow(2).fold(0L, { count, ranges ->
count + (ranges[1].start - ranges[0].endInclusive - 1)
})
val extra = Math.max(max - merged.last().endInclusive, 0)
return betweenRanges + extra
}
private fun parse(input: String) = input.split('\n')
.map {
val split = it.split('-')
LongRange(split[0].toLong(), split[1].toLong())
}
private fun merge(ranges: List<LongRange>)
= ranges.sortedBy { it.start }
.fold(ArrayList<LongRange>(), { merged, range ->
if (merged.size != 0 && merged.last().endInclusive + 1 >= range.start) {
val last = merged.last()
if (last.endInclusive > range.endInclusive) {
merged
} else {
merged.removeAt(merged.size - 1)
merged.add(LongRange(last.start, range.endInclusive))
merged
}
} else {
merged.add(range)
merged
}
})
}
} | 0 | Kotlin | 2 | 12 | 527e6f509e677520d7a8b8ee99f2ae74fc2e3ecd | 1,261 | aoc-2016 | MIT License |
src/test/kotlin/de/tek/adventofcode/y2022/day02/RockPaperScissorsTest.kt | Thumas | 576,671,911 | false | {"Kotlin": 192328} | package de.tek.adventofcode.y2022.day02
import de.tek.adventofcode.y2022.day02.Choice.Rock as Rock
import de.tek.adventofcode.y2022.day02.Choice.Paper as Paper
import de.tek.adventofcode.y2022.day02.Choice.Scissors as Scissors
import de.tek.adventofcode.y2022.day02.Result.Win as Win
import de.tek.adventofcode.y2022.day02.Result.Lose as Lose
import de.tek.adventofcode.y2022.day02.Result.Draw as Draw
import io.kotest.core.spec.style.StringSpec
import io.kotest.data.blocking.forAll
import io.kotest.data.row
import io.kotest.inspectors.forAll
import io.kotest.matchers.shouldBe
class ChoiceTest : StringSpec({
"score" {
forAll(
row(Rock, 1),
row(Paper, 2),
row(Scissors, 3)
) { choice, expectedScore ->
choice.score shouldBe expectedScore
}
}
"scoreAgainst" {
forAll(
row(Rock, Rock, 3),
row(Rock, Paper, 0),
row(Rock, Scissors, 6),
row(Paper, Rock, 6),
row(Paper, Paper, 3),
row(Paper, Scissors, 0),
row(Scissors, Rock, 0),
row(Scissors, Paper, 6),
row(Scissors, Scissors, 3),
) { a, b, expectedScore ->
(a playAgainst b).score shouldBe expectedScore
}
}
"choiceToResultIn" {
forAll(
row(Rock, Draw, Rock),
row(Rock, Lose, Paper),
row(Rock, Win, Scissors),
row(Paper, Win, Rock),
row(Paper, Draw, Paper),
row(Paper, Lose, Scissors),
row(Scissors, Lose, Rock),
row(Scissors, Win, Paper),
row(Scissors, Draw, Scissors),
) { choice, result, expectedChoice ->
choice.choiceToResultIn(result) shouldBe expectedChoice
}
}
})
class GameTest : StringSpec({
"scenarios" {
listOf(
arrayOf(Rock, Rock, Rock, Rock) to 8,
arrayOf(Rock, Paper, Paper, Rock, Scissors, Scissors) to 15
).map { convertToListOfMoves(*it.first) to it.second }
.forAll { (moves, expectedScore) ->
moves.play().otherScore shouldBe expectedScore
}
}
})
fun convertToListOfMoves(vararg choices: Choice): List<Pair<Choice, Choice>> {
if (choices.size.mod(2) != 0) {
throw IllegalArgumentException("Number of choices must be even.")
}
return choices.asList().chunked(2) { Move(it[0], it[1]) }
}
class AlternativeMove : StringSpec( {
"scenarios" {
listOf(
"A Y" to Move(Rock, Rock),
"B X" to Move(Paper, Rock),
"C Z" to Move(Scissors, Rock)
).forAll { (input, expectedMove) ->
input.toAlternativeMove() shouldBe expectedMove
}
}
}) | 0 | Kotlin | 0 | 0 | 551069a21a45690c80c8d96bce3bb095b5982bf0 | 2,861 | advent-of-code-2022 | Apache License 2.0 |
app/src/main/kotlin/day10/Day10.kt | W3D3 | 572,447,546 | false | {"Kotlin": 159335} | package day10
import common.InputRepo
import common.readSessionCookie
import common.solve
import util.splitIntoPair
data class AddExecution(var cycles: Int, val arg: Int) {
fun cycle() {
cycles--
}
}
fun main(args: Array<String>) {
val day = 10
val input = InputRepo(args.readSessionCookie()).get(day = day)
solve(day, input, ::solveDay10Part1, ::solveDay10Part2)
}
fun solveDay10Part1(input: List<String>): Int {
var x = 1
var cycle = 1
val executionList = mutableListOf<AddExecution>()
var sum = 0
val cmds = input.map { it.splitIntoPair(" ") }.toMutableList()
var i = 0
while (executionList.filter { it.cycles >= 0 }.isNotEmpty() || i < cmds.size) {
sum += signalStrengthOnCorrectCyle(x, cycle)
if (i < cmds.size) {
val (cmd, arg) = cmds[i]
if (cmd == "addx") {
executionList.add(AddExecution(1, arg.toInt()))
cmds.add(i + 1, "fakenoop" to "")
}
}
val toExecute = executionList.filter { it.cycles == 0 }
toExecute.forEach { x += it.arg }
executionList.forEach { it.cycle() }
cycle++
i++
}
println("$cycle | X: $x |")
return sum
}
fun signalStrengthOnCorrectCyle(x: Int, cycle: Int): Int {
println("$cycle | X: $x |")
if (cycle == 20 || (cycle - 20) % 40 == 0) {
println("!!!! $cycle | X: $x |")
return x * cycle
}
return 0
}
fun solveDay10Part2(input: List<String>): Long {
var x = 1
var cycle = 1
val executionList = mutableListOf<AddExecution>()
val cmds = input.map { it.splitIntoPair(" ") }.toMutableList()
var i = 0
while (i < 6 * 40) {
if (i < cmds.size) {
val (cmd, arg) = cmds[i]
if (cmd == "addx") {
executionList.add(AddExecution(1, arg.toInt()))
cmds.add(i + 1, "fakenoop" to "")
}
}
// CRT code here
crtDraw(x, i)
val toExecute = executionList.filter { it.cycles == 0 }
toExecute.forEach { x += it.arg }
executionList.forEach { it.cycle() }
cycle++
i++
}
return 0
}
fun crtDraw(x: Int, cycle: Int) {
if (cycle % 40 == 0) {
println()
}
if (setOf(x - 1, x, x + 1).contains(cycle % 40)) {
print("█")
} else {
print(" ")
}
} | 0 | Kotlin | 0 | 0 | 34437876bf5c391aa064e42f5c984c7014a9f46d | 2,412 | AdventOfCode2022 | Apache License 2.0 |
src/main/java/Exercise11.kt | cortinico | 317,667,457 | false | null | fun main() {
val input: List<CharArray> =
object {}
.javaClass
.getResource("input-11.txt")
.readText()
.split("\n")
.map(String::toCharArray)
var array1 = Array(input.size) { i -> CharArray(input[i].size) { j -> input[i][j] } }
var array2 = Array(input.size) { i -> CharArray(input[i].size) { ' ' } }
var occupiedPlaces: Int
do {
var countedChanges = 0
occupiedPlaces = 0
for (i in array1.indices) {
for (j in array1[i].indices) {
array2[i][j] =
when (array1[i][j]) {
'.' -> '.'
'#' -> {
if (countOccupied(array1, i, j, '#') >= 4) {
countedChanges++
'L'
} else {
occupiedPlaces++
'#'
}
}
// L
else -> {
if (countOccupied(array1, i, j, '#') <= 0) {
countedChanges++
occupiedPlaces++
'#'
} else {
'L'
}
}
}
}
}
array1 = array2
array2 = Array(input.size) { i -> CharArray(input[i].size) { ' ' } }
} while (countedChanges != 0)
println(occupiedPlaces)
}
fun countOccupied(array: Array<CharArray>, i: Int, j: Int, target: Char) =
listOf(
i - 1 to j,
i - 1 to j - 1,
i - 1 to j + 1,
i to j - 1,
i to j + 1,
i + 1 to j,
i + 1 to j - 1,
i + 1 to j + 1,
)
.asSequence()
.filter { it.first >= 0 }
.filter { it.first < array.size }
.filter { it.second >= 0 }
.filter { it.second < array[0].size }
.count { array[it.first][it.second] == target }
| 1 | Kotlin | 0 | 4 | a0d980a6253ec210433e2688cfc6df35104aa9df | 2,150 | adventofcode-2020 | MIT License |
src/Day10.kt | anisch | 573,147,806 | false | {"Kotlin": 38951} | fun getSignalStrength(cycles: Int, registerX: Int) =
if (cycles % 40 == 20) cycles * registerX
else 0
fun main() {
fun part1(input: List<String>): Int {
var cycles = 0
var regX = 1
var signalSum = 0
input.forEach { ins ->
if (ins == "noop") {
signalSum += getSignalStrength(++cycles, regX)
} else {
signalSum += getSignalStrength(++cycles, regX)
signalSum += getSignalStrength(++cycles, regX)
regX += ins.split(" ")[1].toInt()
}
}
return signalSum
}
fun part2(input: List<String>): String {
val crt = StringBuilder()
var cycles = 0
var regX = 1
input.forEach { ins ->
val sprite = regX - 1..regX + 1
if (ins == "noop") {
crt.append(if (cycles++ % 40 in sprite) "#" else ".")
} else {
crt.append(if (cycles++ % 40 in sprite) "#" else ".")
crt.append(if (cycles++ % 40 in sprite) "#" else ".")
regX += ins.split(" ")[1].toInt()
}
}
return crt.chunked(40).joinToString("\n") { it }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day10_test")
val input = readInput("Day10")
check(part1(testInput) == 13140)
println(part1(input))
val testResultPart2 = """
##..##..##..##..##..##..##..##..##..##..
###...###...###...###...###...###...###.
####....####....####....####....####....
#####.....#####.....#####.....#####.....
######......######......######......####
#######.......#######.......#######.....
""".trimIndent()
check(part2(testInput) == testResultPart2)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 4f45d264d578661957800cb01d63b6c7c00f97b1 | 1,916 | Advent-of-Code-2022 | Apache License 2.0 |
src/main/kotlin/co/csadev/advent2020/Day08.kt | gtcompscientist | 577,439,489 | false | {"Kotlin": 252918} | /*
* Copyright (c) 2021 by <NAME>
*/
package co.csadev.advent2020
class Day08(input: List<String>) {
data class Instruction(var instr: String, val movement: Int, var count: Int = 0) {
val inc: Int
get() = when (instr) {
"acc" -> movement
else -> 0
}
val move: Int
get() = when (instr) {
"jmp" -> movement
else -> 1
}
}
private val instructionMap =
input.map { i ->
i.split(" ").let { instr ->
Instruction(
instr[0],
instr[1].replace("+", "").toInt()
)
}
}
fun solvePart1(): Int {
var acc = 0
var pos = 0
var lastInstruction = instructionMap[pos]
while (lastInstruction.count < 1) {
acc += lastInstruction.inc
pos += lastInstruction.move
lastInstruction.count++
lastInstruction = instructionMap[pos]
}
return acc
}
fun solvePart2(): Int = instructionMap.indices.asSequence().mapNotNull { idx ->
when (instructionMap[idx].instr) {
"jmp" -> checkMap(instructionMap.map { it.copy() }.toMutableList().also { it[idx].instr = "nop" })
"nop" -> checkMap(instructionMap.map { it.copy() }.toMutableList().also { it[idx].instr = "jmp" })
else -> null
}
}.first()
private fun checkMap(instrMap: List<Instruction>): Int? {
var acc = 0
var pos = 0
var lastInstruction = instrMap[pos]
while (lastInstruction.count < 1) {
acc += lastInstruction.inc
pos += lastInstruction.move
if (pos >= instrMap.size) {
return acc
}
lastInstruction.count++
lastInstruction = instrMap[pos]
}
return null
}
}
| 0 | Kotlin | 0 | 1 | 43cbaac4e8b0a53e8aaae0f67dfc4395080e1383 | 1,954 | advent-of-kotlin | Apache License 2.0 |
src/main/kotlin/dp/AlphaCombin.kt | yx-z | 106,589,674 | false | null | package dp
import util.get
// given a = 1, b = 2, c = 3, ..., z = 26
// and a number (as a string), determine the number of ways to interpret this number into alphabets
// ex. 123 == [12, 3] -> lc
// == [1, 2, 3] -> abc
// == [1, 23] -> aw
// so we should return 3
// note that no leading 0s are allowed
// ex. 102 == [10, 2] -> jb
// (!= [1, 02])
// so we should return 1
// ex. 0123 == []
// so we should return 0 since there is no valid interpretation
fun main(args: Array<String>) {
println(alphaCombin("123"))
println(alphaCombin("102"))
println(alphaCombin("0123"))
}
fun alphaCombin(n: String): Int {
val len = n.length
// dp(i): # of interpretations for n[i until len]
// dp(i) = 1 if (i >= len - 1)
// note that for empty strings, there is still one interpretation: empty string
// = dp(i + 1) + dp(i + 2) if (isValid(n[i..i+1]) && isValid(n[i])) ex. [1, 2, ...]
// = dp(i + 1) if (isValid(n[i])) ex. [9, 0, ...] 9 is valid but not 90
// = 0 o/w, i.e. !isValid(n[i]) ex. [0, ...]
// memoization structure: 1d array
// space complexity: O(n)
val dp = IntArray(len + 1) { 1 }
// time complexity: O(n)
// evaluation order: i from len down to 0, i.e. right to left
for (i in len - 2 downTo 0) {
// dependency: dp[i] depends on later two terms dp[i + 1] and dp[i + 2]
dp[i] = if (isValid(n[i..i]) && isValid(n[i..i + 1])) {
dp[i + 1] + dp[i + 2]
} else if (isValid(n[i..i])) {
dp[i + 1]
} else {
0
}
}
return dp[0]
}
// assume O(1) operation
fun isValid(n: String) = !n.startsWith('0') && Integer.parseInt(n) in 1..26 | 0 | Kotlin | 0 | 1 | 15494d3dba5e5aa825ffa760107d60c297fb5206 | 1,615 | AlgoKt | MIT License |
src/main/kotlin/com/kishor/kotlin/algo/algorithms/dynamicprogramming/Fibbonacci.kt | kishorsutar | 276,212,164 | false | null | package com.kishor.kotlin.algo.algorithms.dynamicprogramming
fun main() {
val table = mutableMapOf<Int, Long>()
table.put(0, 1)
table.put(1, 1)
println("Fibbo recursion ${fibbonacciRecursion(30)}")
println("Fibbo Memoization ${fibonacciMemoization(100, table)}")
println("Fibbo Tabbulation ${fibonacciTabulation(100, table)}")
}
// recursion
fun fibbonacciRecursion(n: Int): Int{
if (n == 0) return 1
if (n == 1) return 1
return fibbonacciRecursion(n - 1) + fibbonacciRecursion(n - 2)
}
// top down approach with hashmap
fun fibonacciMemoization(n: Int, table: MutableMap<Int, Long>): Long {
if (n == 0) return 1
if (n == 1) return 1
if (!table.containsKey(n))
table[n] = fibonacciMemoization(n-1, table)+fibonacciMemoization(n-2,table)
return table[n]!!
}
// bottom up approach with tabulation
fun fibonacciTabulation(n: Int, table: MutableMap<Int, Long>): Long {
for (i in 2..n) {
table[i] = table[i-1]!! + table[i-2]!!
}
return table[n]!!
}
| 0 | Kotlin | 0 | 0 | 6672d7738b035202ece6f148fde05867f6d4d94c | 1,035 | DS_Algo_Kotlin | MIT License |
day11/kotlin/RJPlog/day2311_1_2.kt | mr-kaffee | 720,687,812 | false | {"Rust": 223627, "Kotlin": 46100, "Python": 39390, "Shell": 3369, "Haskell": 3122, "Dockerfile": 2236, "Gnuplot": 1678, "C++": 980, "HTML": 592, "CMake": 314} | import java.io.File
import kotlin.math.*
fun day11(in1: Int): Long {
var expansionValue = 1
if (in1 == 2) {
expansionValue = 1000000 - 1
}
var universe: String = ""
var xDim = 0
var yDim = 0
var galaxyMap = mutableMapOf<Int, Pair<Int, Int>>()
var galaxyCount = 1
File("day2311_puzzle_input.txt").forEachLine {
universe += it
xDim = it.length
var line = it
for (i in 0..line.length - 1) {
if (line[i] == '#') {
galaxyMap.put(galaxyCount, Pair(i, yDim))
galaxyCount += 1
}
}
yDim += 1
// expand universe in yDim:
if (!line.contains('#')) {
yDim += expansionValue
}
}
// determine at which xDim the universe will expand:
var xDimExpandCount = mutableListOf<Int>()
for (i in 0..xDim - 1) {
if (!universe.chunked(xDim).map { it[i] }.contains('#')) {
xDimExpandCount.add(i)
}
}
for (key in galaxyMap.keys) {
for (i in xDimExpandCount.size - 1 downTo 0) {
if (galaxyMap.getValue(key).first > xDimExpandCount[i]) {
galaxyMap.put(
key,
Pair(galaxyMap.getValue(key).first + (expansionValue), galaxyMap.getValue(key).second)
)
}
}
}
var result = 0L
for ((key, value) in galaxyMap) {
for ((key2, value2) in galaxyMap) {
if (key != key2) {
result += (abs(value2.second - value.second) + abs(value2.first - value.first)).toLong()
}
}
}
return result / 2
}
fun main() {
var t1 = System.currentTimeMillis()
var solution1 = day11(1)
var solution2 = day11(2)
// print solution for part 1
println("*******************************")
println("--- Day 11: Cosmic Expansion ---")
println("*******************************")
println("Solution for part1")
println(" $solution1 ")
println()
// print solution for part 2
println("*******************************")
println("Solution for part2")
println(" $solution2 ")
println()
t1 = System.currentTimeMillis() - t1
println("puzzle solved in ${t1} ms")
}
| 0 | Rust | 2 | 0 | 5cbd13d6bdcb2c8439879818a33867a99d58b02f | 1,913 | aoc-2023 | MIT License |
src/main/kotlin/net/devromik/poly/Polynomial.kt | devromik | 53,753,715 | false | null | package net.devromik.poly
import net.devromik.poly.utils.COMPLEX_ZERO
import net.devromik.poly.utils.Complex
import net.devromik.poly.utils.times
import java.lang.Math.max
/**
* @author <NAME> */
class Polynomial(val coeffs: DoubleArray) {
init {
require(coeffs.size > 0)
}
// ****************************** //
fun setCoeff(i: Int, c: Double) {
coeffs[i] = c
}
fun coeff(i: Int): Double = coeffs[i]
val coeffCount: Int get() = coeffs.size
val degree: Int get() = coeffCount - 1
fun at(x: Double): Double {
if (coeffCount == 1) {
return coeff(0)
}
var r = coeff(coeffCount - 1)
for (i in coeffCount - 2 downTo 0) {
r = r * x + coeff(i)
}
return r
}
override fun toString(): String {
return coeffs.reversed().mapIndexed {
i, c ->
when {
c.compareTo(0.0) == 0 -> "-"
i < degree - 1 -> if (c.compareTo(1.0) == 0) "X^${degree - i}" else "$c * X^${degree - i}"
i == degree - 1 -> if (c.compareTo(1.0) == 0) "X" else "$c * X"
else -> "$c"
}
}.filter { it != "-" }.joinToString(separator = " + ")
}
}
/* ****** Sum ****** */
operator fun Polynomial.plus(addend: Polynomial): Polynomial {
val (min, max) = if (coeffCount > addend.coeffCount) addend.to(this) else this.to(addend)
return Polynomial(DoubleArray(
max.coeffCount,
{ if (it < min.coeffCount) min.coeff(it) + max.coeff(it) else max.coeff(it) }))
}
operator fun Polynomial.plus(addend: Double): Polynomial {
val sumCoeffs = coeffs.copyOf()
sumCoeffs[0] += addend
return Polynomial(sumCoeffs)
}
operator fun Double.plus(addend: Polynomial): Polynomial {
return addend + this
}
/* ****** Product ****** */
operator fun Polynomial.times(factor: Double): Polynomial = Polynomial(coeffs * factor)
operator fun Double.times(factor: Polynomial): Polynomial = factor * this
operator fun Polynomial.times(factor: Polynomial): Polynomial {
val productCoeffs = DoubleArray(degree + factor.degree + 1, { 0.0 })
for (i in 0..degree) {
for (j in 0..factor.degree) {
productCoeffs[i + j] += coeff(i) * factor.coeff(j)
}
}
return Polynomial(productCoeffs)
}
fun Polynomial.multFFT(factor: Polynomial): Polynomial {
val maxCoeffCount = max(coeffCount, factor.coeffCount);
var auxiliaryCoeffCount = 1
while (auxiliaryCoeffCount < maxCoeffCount) {
if (auxiliaryCoeffCount > Int.MAX_VALUE / 4) {
throw IllegalArgumentException("Overflow")
}
auxiliaryCoeffCount = auxiliaryCoeffCount.shl(1)
}
auxiliaryCoeffCount = auxiliaryCoeffCount.shl(1);
val a = Array(
auxiliaryCoeffCount,
{ if (it < coeffCount) Complex(coeff(it)) else COMPLEX_ZERO })
fft(a, false)
val b = Array(
auxiliaryCoeffCount,
{ if (it < factor.coeffCount) Complex(factor.coeff(it)) else COMPLEX_ZERO })
fft(b, false)
for (i in 0..auxiliaryCoeffCount - 1) {
a[i] *= b[i]
}
fft(a, true)
return Polynomial(DoubleArray(degree + factor.degree + 1, { a[it].re }))
} | 0 | Kotlin | 0 | 0 | ff340e0284d1756502d66e84106853416521aa6f | 3,287 | poly | MIT License |
src/Day11.kt | frozbiz | 573,457,870 | false | {"Kotlin": 124645} | import javax.script.ScriptEngineManager
class Monkey (
var items: MutableList<Long> = mutableListOf(),
val operation: (Long) -> Long,
val testNum: Int,
private val throwToMonkey: Pair<Int,Int>
) {
var itemsExamined = 0
var manageWorry = {worry: Long -> worry/3}
fun examineItems(monkeyList: List<Monkey>) {
itemsExamined += items.size
for (item in items) {
val newItem = manageWorry(operation(item))
val monkeyIx = if ((newItem % testNum) == 0L) throwToMonkey.first else throwToMonkey.second
monkeyList[monkeyIx].items.add(newItem)
}
items.clear()
}
override fun toString(): String {
return "Monkey: currentItems=$items, totalExamined=$itemsExamined"
}
companion object {
private fun doMath(equation: String): Long {
return if ('*' in equation) {
equation.split('*').fold(1) { acc, s -> acc * s.trim().toInt() }
} else if ('+' in equation) {
equation.split('+').fold(0) { acc, s -> acc + s.trim().toInt() }
} else {
throw IllegalArgumentException("Dunno what to do here.")
}
}
fun monkeyFromInput(input: List<String>): Monkey {
val startingItems = input[1].split(':').last().split(',').map { it.trim().toLong() }.toMutableList()
val operationString = input[2].split('=').last()
val testNum = input[3].split(' ').last().trim().toInt()
val trueIx = input[4].split(' ').last().trim().toInt()
val falseIx = input[5].split(' ').last().trim().toInt()
return Monkey(startingItems, { old -> doMath(operationString.replace("old", "$old")) }, testNum, Pair(trueIx, falseIx))
}
}
}
fun main() {
fun List<Monkey>.print() {
for ((ix, monkey) in this.withIndex()) {
println("Monkey $ix: ${monkey.items.joinToString(", ")}")
}
}
fun List<Monkey>.printVerbose() {
for ((ix, monkey) in this.withIndex()) {
println("Monkey $ix: $monkey")
}
}
fun part1(input: List<String>): Int {
var nextMonkey = input
val monkeyList = mutableListOf<Monkey>()
while (nextMonkey.isNotEmpty()) {
val monkey = Monkey.monkeyFromInput(nextMonkey)
monkeyList.add(monkey)
nextMonkey = if (7 > nextMonkey.size) emptyList() else nextMonkey.subList(7,nextMonkey.size)
}
for (ix in 1..20) {
for (monkey in monkeyList) {
monkey.examineItems(monkeyList)
}
if (ix <= 10 || ix % 5 == 0) {
println("After round $ix, the monkeys are holding items with these worry levels:")
monkeyList.print()
}
}
println()
println("Final State:")
monkeyList.printVerbose()
return monkeyList.sortedBy { -it.itemsExamined }.take(2).fold(1) {acc, monkey -> acc * monkey.itemsExamined }
}
fun part2(input: List<String>): Long {
var nextMonkey = input
val monkeyList = mutableListOf<Monkey>()
var monkeyProduct = 1
while (nextMonkey.isNotEmpty()) {
val monkey = Monkey.monkeyFromInput(nextMonkey)
monkeyList.add(monkey)
monkeyProduct *= monkey.testNum
nextMonkey = if (7 > nextMonkey.size) emptyList() else nextMonkey.subList(7,nextMonkey.size)
}
for (monkey in monkeyList) {
monkey.manageWorry = { it % monkeyProduct }
}
for (ix in 1..10000) {
for (monkey in monkeyList) {
monkey.examineItems(monkeyList)
}
if (ix == 1 || ix == 20 || ix % 1000 == 0) {
println("After round $ix, the monkey list looks like:")
monkeyList.printVerbose()
}
}
println()
println("Final State:")
monkeyList.printVerbose()
return monkeyList.sortedBy { -it.itemsExamined }.take(2).fold(1L) {acc, monkey -> acc * monkey.itemsExamined }
}
// test if implementation meets criteria from the description, like:
val testInput = listOf(
"Monkey 0:\n",
" Starting items: 79, 98\n",
" Operation: new = old * 19\n",
" Test: divisible by 23\n",
" If true: throw to monkey 2\n",
" If false: throw to monkey 3\n",
"\n",
"Monkey 1:\n",
" Starting items: 54, 65, 75, 74\n",
" Operation: new = old + 6\n",
" Test: divisible by 19\n",
" If true: throw to monkey 2\n",
" If false: throw to monkey 0\n",
"\n",
"Monkey 2:\n",
" Starting items: 79, 60, 97\n",
" Operation: new = old * old\n",
" Test: divisible by 13\n",
" If true: throw to monkey 1\n",
" If false: throw to monkey 3\n",
"\n",
"Monkey 3:\n",
" Starting items: 74\n",
" Operation: new = old + 3\n",
" Test: divisible by 17\n",
" If true: throw to monkey 0\n",
" If false: throw to monkey 1\n",
)
check(part1(testInput) == 10605)
check(part2(testInput) == 2713310158)
val input = readInput("day11")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 4feef3fa7cd5f3cea1957bed1d1ab5d1eb2bc388 | 5,377 | 2022-aoc-kotlin | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.