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/Day14.kt | ostersc | 572,991,552 | false | {"Kotlin": 46059} | import kotlin.math.sign
enum class ContentType { Air, Rock, Sand, Hole }
data class Point(var x: Int, var y: Int) {
fun down(): Point {
return this.copy(y = y + 1)
}
fun diagLeft(): Point {
return this.copy(x = x - 1, y = y + 1)
}
fun diagRight(): Point {
return this.copy(x = x + 1, y = y + 1)
}
}
class CaveGrid(var hole: Point = Point(500, 0), var contents: MutableMap<Point, ContentType>) {
var minX = 0
var maxX = 0
var maxY = 0
init {
contents.put(hole, ContentType.Hole)
}
fun isInVoid(point: Point): Boolean {
return point.x < minX || point.x > maxX || point.y > maxY || point.y < 0
}
fun updateExtents() {
minX = contents.keys.minOf { p -> p.x }
maxX = contents.keys.maxOf { p -> p.x }
maxY = contents.keys.maxOf { p -> p.y }
}
override fun toString(): String {
var result = ""
for (y in 0..maxY) {
for (x in minX..maxX) {
val p = Point(x, y)
if (contents.contains(p)) {
when (contents.get(p)) {
ContentType.Air -> result += "."
ContentType.Rock -> result += "#"
ContentType.Sand -> result += "o"
ContentType.Hole -> result += "+"
null -> {}
}
} else {
result += "."
}
}
result += "\n"
}
return result
}
fun dropSand(): Boolean {
var s = hole.copy()
while (!isInVoid(s)) {
if (contents.getOrDefault(s.down(), ContentType.Air) == ContentType.Air) {
s = s.down()
} else if (contents.getOrDefault(s.diagLeft(), ContentType.Air) == ContentType.Air) {
s = s.diagLeft()
} else if (contents.getOrDefault(s.diagRight(), ContentType.Air) == ContentType.Air) {
s = s.diagRight()
} else {
break
}
}
if (!isInVoid(s) && s != hole) {
contents.put(s, ContentType.Sand)
return true
}
return false
}
companion object {
fun of(input: List<String>): CaveGrid {
val c = CaveGrid(contents = mutableMapOf<Point, ContentType>())
for (line in input) {
val points = line.split("->")
points.zipWithNext().forEach {
val start = Point(
it.first.split(",").first().trim().toInt(),
it.first.split(",").last().trim().toInt()
)
val end = Point(
it.second.split(",").first().trim().toInt(),
it.second.split(",").last().trim().toInt()
)
c.addRockLine(start, end)
}
}
return c
}
}
fun addRockLine(start: Point, end: Point) {
contents.put(start, ContentType.Rock)
contents.put(end, ContentType.Rock)
val dx = (end.x - start.x).sign
val dy = (end.y - start.y).sign
var next = start.copy().apply { x += dx; y += dy }
while (next != end) {
contents.put(next, ContentType.Rock)
next = next.copy().apply { x += dx; y += dy }
}
updateExtents()
}
}
fun main() {
fun part1(input: List<String>): Int {
val cave = CaveGrid.of(input)
while (cave.dropSand()) {
//println(cave)
}
return cave.contents.filterValues { it.equals(ContentType.Sand) }.size
}
fun part2(input: List<String>): Int {
val cave = CaveGrid.of(input)
val start = Point(cave.minX - cave.maxY, cave.maxY + 2)
val end = Point(cave.maxX + cave.maxY, cave.maxY + 2)
cave.addRockLine(start, end)
while (cave.dropSand()) {
//println(cave)
}
return cave.contents.filterValues { it.equals(ContentType.Sand) }.size + 1
}
val testInput = readInput("Day14_test")
check(part1(testInput) == 24)
check(part2(testInput) == 93)
val input = readInput("Day14")
val part1 = part1(input)
println(part1)
check(part1 == 1406)
val part2 = part2(input)
println(part2)
check(part2 == 20870)
} | 0 | Kotlin | 0 | 1 | 3eb6b7e3400c2097cf0283f18b2dad84b7d5bcf9 | 4,449 | advent-of-code-2022 | Apache License 2.0 |
src/Day9/December9.kt | Nandi | 47,216,709 | false | null | package Day9
import org.jgrapht.experimental.permutation.CollectionPermutationIter
import org.jgrapht.graph.DefaultWeightedEdge
import org.jgrapht.graph.SimpleWeightedGraph
import java.nio.file.Files
import java.nio.file.Paths
import java.util.stream.Stream
/**
* todo: visualize
*
* Every year, Santa manages to deliver all of his presents in a single night.
*
* Part 1
*
* This year, however, he has some new locations to visit; his elves have provided him the distances between every
* pair of locations. He can start and end at any two (different) locations he wants, but he must visit each location
* exactly once. What is the shortest distance he can travel to achieve this?
*
* Part 2
*
* The next year, just to show off, Santa decides to take the route with the longest distance instead.
*
* He can still start and end at any two (different) locations he wants, and he still must visit each location exactly
* once.
*
* Created by Simon on 10/12/2015.
*/
class December9 {
val cityGraph: SimpleWeightedGraph<String, DefaultWeightedEdge> = SimpleWeightedGraph(DefaultWeightedEdge::class.java)
fun createGraph() {
val lines = loadFile("src/Day9/9.dec_input.txt")
for (line in lines) {
val (cities, weight) = line.split(" = ")
if (cities !is String) return
val(start, end) = cities.split(" to ")
cityGraph.addVertex(start)
cityGraph.addVertex(end)
cityGraph.setEdgeWeight(cityGraph.addEdge(start, end), weight.toDouble());
}
var min = Double.MAX_VALUE;
var minPath = listOf<String>()
var max = 0.0
var maxPath = listOf<String>()
val itertator = CollectionPermutationIter<String>(cityGraph.vertexSet())
while (itertator.hasNext()) {
val permutation = itertator.nextArray
var len = 0.0
for (i in 0..(permutation.size - 2)) {
val edge = cityGraph.getEdge(permutation[i], permutation[i + 1])
len += cityGraph.getEdgeWeight(edge)
}
if (len < min) {
min = len
minPath = permutation
}
if (len > max) {
max = len
maxPath = permutation
}
}
println("The shortest distance was $min through $minPath")
println("The longest distance was $max through $maxPath")
}
fun loadFile(path: String): Stream<String> {
val input = Paths.get(path);
val reader = Files.newBufferedReader(input);
return reader.lines();
}
}
fun main(args: Array<String>) {
December9().createGraph()
} | 0 | Kotlin | 0 | 0 | 34a4b4c0926b5ba7e9b32ca6eeedd530f6e95bdc | 2,705 | adventofcode | MIT License |
src/main/kotlin/day23/part2/Part2.kt | bagguley | 329,976,670 | false | null | package day23.part2
fun main() {
println("Start")
val t1 = System.currentTimeMillis()
val nodes = createNodes()
var ptr = nodes.first()
println("Run")
for (i in 1..10_000_000) {
addAfter(take3(ptr), ptr)
ptr = ptr.nextNode
}
val one = nodes.find { n -> n.value == 1 }!!
val t2 = System.currentTimeMillis()
println("Time " + (t2-t1))
val a = one.nextNode.value.toLong()
val b = one.nextNode.nextNode.value.toLong()
println(a)
println(b)
println(a*b)
}
fun createNodes(): List<Node> {
val cups = "389547612".map { it.toString().toInt() }.toMutableList()
val nodeMap = mutableMapOf<Int,Node>()
val nodes = mutableListOf<Node>()
for (p in 10..1_000_000) {
cups.add(p)
}
for (c in cups) {
val node = Node(c)
nodes.add(node)
nodeMap[c] = node
}
val cupsSize = cups.size
nodes.windowed(2, 1).forEach { (a,b) -> a.nextNode = b ; b.previousNode = a}
nodes.first().previousNode = nodes.last()
nodes.last().nextNode = nodes.first()
nodes.forEach { n -> n.nextNumber = nodeMap[next(n.value, cupsSize)]!!}
nodes.forEach { n -> n.previousNumber = nodeMap[prev(n.value, cupsSize)]!! }
return nodes
}
fun next(num: Int, cupsSize: Int): Int {
val x = (num + 1) % (cupsSize + 1)
return if (x == 0) 1 else x
}
fun prev(num: Int, cupsSize: Int): Int {
val x = num - 1
return if (x == 0) cupsSize else x
}
fun take3(ptr: Node): Pair<Node, Node> {
val first = ptr.nextNode
val last = first.nextNode.nextNode
val after = last.nextNode
ptr.nextNode = after
after.previousNode = ptr
return Pair(first, last)
}
fun addAfter(taken: Pair<Node, Node>, current: Node) {
val takenValues = listOf(taken.first.value, taken.first.nextNode.value, taken.second.value)
var addAfterNode = current.previousNumber
while (takenValues.contains(addAfterNode.value)) {
addAfterNode = addAfterNode.previousNumber
}
val addBeforeNode = addAfterNode.nextNode
addAfterNode.nextNode = taken.first
taken.first.previousNode = addAfterNode
addBeforeNode.previousNode = taken.second
taken.second.nextNode = addBeforeNode
}
| 0 | Kotlin | 0 | 0 | 6afa1b890924e9459f37c604b4b67a8f2e95c6f2 | 2,235 | adventofcode2020 | MIT License |
src/Day04.kt | Fedannie | 572,872,414 | false | {"Kotlin": 64631} | fun main() {
fun parseInput(input: String): List<IntRange> {
return input.split(',')
.map { it.split('-').map { it.toInt() } }
.sortedWith(compareBy<List<Int>> { it[0] }.thenByDescending { it[1] - it[0] })
.map { it[0] .. it[1] }
}
fun part1(input: List<String>): Int {
return input.map(::parseInput).count { pair -> pair[1].last in pair[0] }
}
fun part2(input: List<String>): Int {
return input.map(::parseInput).count { pair -> pair[0].last >= pair[1].first }
}
val testInput = readInputLines("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInputLines(4)
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 1d5ac01d3d2f4be58c3d199bf15b1637fd6bcd6f | 700 | Advent-of-Code-2022-in-Kotlin | Apache License 2.0 |
src/main/kotlin/g0801_0900/s0835_image_overlap/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g0801_0900.s0835_image_overlap
// #Medium #Array #Matrix #2023_03_27_Time_163_ms_(100.00%)_Space_35.3_MB_(100.00%)
class Solution {
fun largestOverlap(img1: Array<IntArray>, img2: Array<IntArray>): Int {
val bits1 = bitwise(img1)
val bits2 = bitwise(img2)
val n = img1.size
var res = 0
for (hori in -1 * n + 1 until n) {
for (veti in -1 * n + 1 until n) {
var curOverLapping = 0
if (veti < 0) {
for (i in -1 * veti until n) {
curOverLapping += if (hori < 0) {
Integer.bitCount(
bits1[i] shl -1 * hori and bits2[i - -1 * veti]
)
} else {
Integer.bitCount(bits1[i] shr hori and bits2[i - -1 * veti])
}
}
} else {
for (i in 0 until n - veti) {
curOverLapping += if (hori < 0) {
Integer.bitCount(bits1[i] shl -1 * hori and bits2[veti + i])
} else {
Integer.bitCount(bits1[i] shr hori and bits2[veti + i])
}
}
}
res = Math.max(res, curOverLapping)
}
}
return res
}
private fun bitwise(img: Array<IntArray>): IntArray {
val bits = IntArray(img.size)
for (i in img.indices) {
var cur = 0
for (j in img[0].indices) {
cur = cur * 2 + img[i][j]
}
bits[i] = cur
}
return bits
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,748 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/Excercise16.kt | underwindfall | 433,989,850 | false | {"Kotlin": 55774} | private val input =
getInputAsTest("16")[0].map { it.digitToInt(16).toString(2).padStart(4, '0') }.joinToString("")
private fun part1() {
var i = 0
fun next(n: Int) = input.substring(i, i + n).toInt(2).also { i += n }
var ans = 0
fun parse(maxLen: Int = Int.MAX_VALUE, maxPackets: Int = Int.MAX_VALUE) {
val start = i
var numPackets = 0
while (++numPackets <= maxPackets && i - start < maxLen) {
val v = next(3)
ans += v
print("[$v")
when (next(3)) {
4 -> {
while (next(1) == 1) next(4)
next(4)
}
else ->
when (next(1)) {
0 -> parse(maxLen = next(15))
1 -> parse(maxPackets = next(11))
}
}
print("]")
}
}
parse(maxPackets = 1)
println("----------------------------------------")
println("Part1 $ans ")
}
private fun part2() {
var i = 0
fun next(n: Int) = input.substring(i, i + n).toInt(2).also { i += n }
fun parse(maxLen: Int = Int.MAX_VALUE, maxPackets: Int = Int.MAX_VALUE, type: Int = -1): Long {
val start = i
var numPackets = 0
val res = ArrayList<Long>()
while (++numPackets <= maxPackets && i - start < maxLen) {
val v = next(3)
print("[$v")
val t = next(3)
when (t) {
4 -> {
var cur = 0L
while (next(1) == 1) cur = (cur shl 4) + next(4)
cur = (cur shl 4) + next(4)
res += cur
}
else ->
when (next(1)) {
0 -> res += parse(maxLen = next(15), type = t)
1 -> res += parse(maxPackets = next(11), type = t)
}
}
print("]")
}
return when (type) {
-1 -> {
require(res.size == 1)
res[0]
}
0 -> res.sum()
1 -> res.fold(1L, Long::times)
2 -> res.minOrNull()!!
3 -> res.maxOrNull()!!
5 -> {
require(res.size == 2)
if (res[0] > res[1]) 1L else 0L
}
6 -> {
require(res.size == 2)
if (res[0] < res[1]) 1L else 0L
}
7 -> {
require(res.size == 2)
if (res[0] == res[1]) 1L else 0L
}
else -> error("type=$type")
}
}
val ans = parse(maxPackets = 1)
println("----------------------------------------")
println("Part2 $ans")
}
fun main() {
part1()
part2()
}
| 0 | Kotlin | 0 | 0 | 4fbee48352577f3356e9b9b57d215298cdfca1ed | 2,339 | advent-of-code-2021 | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/WordDictionary.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import dev.shtanko.algorithms.ALPHABET_LETTERS_COUNT
/**
* 211. Design Add and Search Words Data Structure
* @see <a href="https://leetcode.com/problems/design-add-and-search-words-data-structure/">Source</a>
*/
interface WordDictionary {
fun addWord(word: String)
fun search(word: String): Boolean
}
class WordDictionaryImpl : WordDictionary {
private val children: Array<WordDictionaryImpl?> = Array(ALPHABET_LETTERS_COUNT) { null }
private var isEndOfWord = false
// Adds a word into the data structure.
override fun addWord(word: String) {
var curr: WordDictionaryImpl? = this
for (c in word.toCharArray()) {
if (curr?.children?.get(c.code - 'a'.code) == null) {
curr?.children?.set(c.code - 'a'.code, WordDictionaryImpl())
}
curr = curr?.children?.get(c.code - 'a'.code)
}
curr?.isEndOfWord = true
}
// Returns if the word is in the data structure.
// A word could contain the dot character '.' to represent any one letter.
override fun search(word: String): Boolean {
var curr: WordDictionaryImpl = this
for (i in word.indices) {
val c: Char = word[i]
if (c == '.') {
for (ch in curr.children) {
if (ch != null && ch.search(word.substring(i + 1))) {
return true
}
}
return false
}
if (curr.children[c.code - 'a'.code] == null) {
return false
}
curr = curr.children[c.code - 'a'.code] ?: return false
}
return curr.isEndOfWord
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,346 | kotlab | Apache License 2.0 |
src/main/kotlin/com/hj/leetcode/kotlin/problem636/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem636
/**
* LeetCode page: [636. Exclusive Time of Functions](https://leetcode.com/problems/exclusive-time-of-functions/);
*/
class Solution {
/* Complexity:
* Time O(M+L) and Space O(M+N+K) where
* M is the size of logs,
* L is the flat length of logs,
* N equals n,
* K is the max length of log in logs;
*/
fun exclusiveTime(n: Int, logs: List<String>): IntArray {
val functionCalls = FunctionCalls(IntArray(n), ArrayDeque(), 0)
for (logStr in logs) {
val log = logOf(logStr)
functionCalls.update(log)
}
return functionCalls.exclusiveTimePerId
}
private class FunctionCalls(
val exclusiveTimePerId: IntArray,
val uncompletedIdStack: ArrayDeque<Int>,
var lastExecutionStart: Int
)
private fun logOf(logStr: String): Log {
val (functionIdStr, typeStr, timestampStr) = logStr.split(":")
val functionId = functionIdStr.toInt()
val type = when (typeStr) {
"start" -> LogType.Start
"end" -> LogType.End
else -> throw IllegalArgumentException()
}
val timestamp = timestampStr.toInt()
return Log(functionId, type, timestamp)
}
private data class Log(val functionId: Int, val type: LogType, val timestamp: Int)
private enum class LogType { Start, End }
private fun FunctionCalls.update(log: Log) {
when (log.type) {
LogType.Start -> updateForStartLog(log)
LogType.End -> updateForEndLog(log)
}
}
private fun FunctionCalls.updateForStartLog(log: Log) {
require(log.type == LogType.Start)
if (uncompletedIdStack.isEmpty()) {
uncompletedIdStack.addFirst(log.functionId)
lastExecutionStart = log.timestamp
} else {
val executedId = uncompletedIdStack.first()
val duration = log.timestamp - lastExecutionStart
exclusiveTimePerId[executedId] += duration
uncompletedIdStack.addFirst(log.functionId)
lastExecutionStart = log.timestamp
}
}
private fun FunctionCalls.updateForEndLog(log: Log) {
require(log.type == LogType.End)
val executedId = uncompletedIdStack.first()
check(executedId == log.functionId)
val duration = log.timestamp - lastExecutionStart + 1
exclusiveTimePerId[executedId] += duration
uncompletedIdStack.removeFirst()
lastExecutionStart = log.timestamp + 1
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 2,595 | hj-leetcode-kotlin | Apache License 2.0 |
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2016/2016-16.kt | ferinagy | 432,170,488 | false | {"Kotlin": 787586} | package com.github.ferinagy.adventOfCode.aoc2016
import java.util.*
fun main() {
println("Part1:")
println(solve2(testInput1, 20))
println(solve2(input, 272))
println()
println("Part2:")
println(solve2(input, 35651584))
}
private fun solve2(input: String, length: Int): String {
val bits = BitSet(length / 64 + 1)
input.forEachIndexed { index, c -> bits.set(index, c == '1') }
var size = input.length
while (size < length) {
size = bits.grow(size)
}
size = length
while (size % 2 == 0) {
size = bits.checkSum(size)
}
return buildString {
for (i in 0 until size) {
if (bits.get(i)) append('1') else append('0')
}
}
}
private fun BitSet.grow(size: Int): Int {
set(size, false)
for (i in 0 until size) {
val bit = get(size - i - 1)
set(size + 1 + i, !bit)
}
return size * 2 + 1
}
private fun BitSet.checkSum(size: Int): Int {
val newSize = size / 2
for (i in 0 until newSize) {
val new = get(2 * i) == get(2 * i + 1)
set(i, new)
}
return size / 2
}
private const val testInput1 = """10000"""
private const val input = """10111011111001111"""
| 0 | Kotlin | 0 | 1 | f4890c25841c78784b308db0c814d88cf2de384b | 1,223 | advent-of-code | MIT License |
src/day10/Day10.kt | gr4cza | 572,863,297 | false | {"Kotlin": 93944} | package day10
import readInput
fun main() {
val importantCycles = listOf(20, 60, 100, 140, 180, 220)
fun checkImportantCycle(currentCycle: Int, registerX: Int): Int {
if (currentCycle in importantCycles) {
return registerX * currentCycle
}
return 0
}
fun part1(input: List<String>): Int {
var registerX = 1
var currentCycle = 1
var cycleSum = 0
input.forEach {
if (it == "noop") {
cycleSum += checkImportantCycle(currentCycle, registerX)
currentCycle++
} else {
val (_, xChange) = it.split(" ")
cycleSum += checkImportantCycle(currentCycle, registerX)
currentCycle++
cycleSum += checkImportantCycle(currentCycle, registerX)
currentCycle++
registerX += xChange.toInt()
}
}
return cycleSum
}
fun drawAPixel(pixels: List<MutableList<Char>>, c: Char, pixelPos: Int) {
pixels[pixelPos / 40][pixelPos % 40] = c
}
fun drawPixel(pixels: List<MutableList<Char>>, currentCycle: Int, registerX: Int) {
val pixelPos = currentCycle - 1
if (pixelPos % 40 in registerX - 1..registerX + 1) {
drawAPixel(pixels, '#', pixelPos)
} else {
drawAPixel(pixels, '.', pixelPos)
}
}
fun part2(input: List<String>) {
var registerX = 1
var currentCycle = 1
val pixels = List(6) { MutableList(40) { ' ' } }
input.forEach {
if (it == "noop") {
drawPixel(pixels, currentCycle, registerX)
currentCycle++
} else {
val (_, xChange) = it.split(" ")
drawPixel(pixels, currentCycle, registerX)
currentCycle++
drawPixel(pixels, currentCycle, registerX)
currentCycle++
registerX += xChange.toInt()
}
}
pixels.forEach {
println(it)
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("day10/Day10_test")
println(part1(testInput))
check(part1(testInput) == 13140)
val input = readInput("day10/Day10")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | ceca4b99e562b4d8d3179c0a4b3856800fc6fe27 | 2,379 | advent-of-code-kotlin-2022 | Apache License 2.0 |
year2020/src/main/kotlin/net/olegg/aoc/year2020/day14/Day14.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2020.day14
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.year2020.DayOf2020
/**
* See [Year 2020, Day 14](https://adventofcode.com/2020/day/14)
*/
object Day14 : DayOf2020(14) {
private val PATTERN = "^mem\\[(\\d+)] = (\\d+)$".toRegex()
override fun first(): Any? {
val memory = mutableMapOf<Long, Long>()
var mask = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
lines.forEach { line ->
when {
line.startsWith("mask") -> {
mask = line.substringAfter(" = ")
}
line.startsWith("mem") -> {
PATTERN.findAll(line).forEach {
val (address, value) = it.groupValues.drop(1).mapNotNull { token -> token.toLongOrNull() }
val bitValue = value.toString(2).padStart(36, '0')
memory[address] = bitValue.zip(mask) { a, b -> if (b == 'X') a else b }
.joinToString(separator = "")
.toLong(2)
}
}
}
}
return memory.values.sum()
}
override fun second(): Any? {
val memory = mutableMapOf<Long, Long>()
var mask = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
lines.forEach { line ->
when {
line.startsWith("mask") -> {
mask = line.substringAfter(" = ")
}
line.startsWith("mem") -> {
PATTERN.findAll(line).forEach {
val (address, value) = it.groupValues.drop(1).mapNotNull { token -> token.toLongOrNull() }
val bitValue = address.toString(2).padStart(36, '0')
val count = mask.count { c -> c == 'X' }
(0..<(1 shl count)).forEach { unmasked ->
val submask = unmasked.toString(2).padStart(count, '0')
var meetX = 0
val newAddress = bitValue.zip(mask) { b, m ->
when (m) {
'0' -> b
'1' -> 1
'X' -> {
submask[meetX].also { meetX++ }
}
else -> b
}
}
.joinToString(separator = "")
.toLong(2)
memory[newAddress] = value
}
}
}
}
}
return memory.values.sum()
}
}
fun main() = SomeDay.mainify(Day14)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 2,270 | adventofcode | MIT License |
src/main/aoc2022/Day5.kt | nibarius | 154,152,607 | false | {"Kotlin": 963896} | package aoc2022
class Day5(input: List<String>) {
/**
* A list of all stacks, the top of each stack is position 0 in each stack.
*/
private val stacks = parseStacks(input.first().split("\n"))
/**
* List of instructions, first entry is how many to move, second from index and last to index.
*/
private val instructions = input.last().split("\n").map {
val res = "move (\\d+) from (\\d) to (\\d)".toRegex().find(it)!!.groupValues
listOf(res[1].toInt(), res[2].toInt() - 1, res[3].toInt() - 1)
}
/**
* Parse the stack part of the input. Each stack takes up 4 characters of the input. Example line:
* [B] [L] [J]
* 12341234123412341234123412341234
*
* Second character in the chunk for each stack holds the container name.
*/
private fun parseStacks(stacks: List<String>): List<MutableList<Char>> {
val numStacks = stacks.last().trim().substringAfterLast(" ").toInt()
val ret = List(numStacks) { mutableListOf<Char>() }
stacks.dropLast(1).map { layer ->
layer.chunked(4).forEachIndexed { index, s ->
if (s.isNotBlank()) {
ret[index].add(s[1])
}
}
}
return ret
}
/**
* Solve the problem by either moving all containers at once (same order as in 'from' stack) or
* one at a time (reverse order as in 'from' stack).
*/
private fun solve(oneAtATime: Boolean): String {
instructions.forEach { (n, from, to) ->
// Remove items from 'from' and put them in a new list in the same order.
val toMove = MutableList(n) { stacks[from].removeAt(0) }
.apply { if (oneAtATime) this.reverse() } // Reverse if needed
stacks[to].addAll(0, toMove)
}
return stacks.joinToString("") { it.first().toString() }
}
fun solvePart1(): String {
return solve(true)
}
fun solvePart2(): String {
return solve(false)
}
} | 0 | Kotlin | 0 | 6 | f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22 | 2,059 | aoc | MIT License |
src/main/kotlin/day13/Day13.kt | vitalir2 | 572,865,549 | false | {"Kotlin": 89962} | package day13
import Challenge
import product
object Day13 : Challenge(13) {
override fun part1(input: List<String>): Int {
val packetPairs = parseInput(input)
val inRightOrderIndices = mutableSetOf<Int>()
packetPairs.forEachIndexed { index, pair -> if (isPairInTheRightOrder(pair)) inRightOrderIndices.add(index+1) }
return inRightOrderIndices.sum()
}
override fun part2(input: List<String>): Any {
val dividerPackets = listOf(
PacketData(PacketData.Value.List(PacketData.Value.List(PacketData.Value.Number(2)))),
PacketData(PacketData.Value.List(PacketData.Value.List(PacketData.Value.Number(6)))),
)
val sortedPackets = input
.filter(String::isNotBlank)
.map(::parsePacketData)
.toMutableList().apply { addAll(dividerPackets) }
.toList()
.sortedWith { left, right -> isValuesInRightOrder(left.value, right.value) }
.reversed()
return sortedPackets
.mapIndexed { index, packetData -> index + 1 to packetData }
.toMap()
.filterValues(dividerPackets::contains)
.map(Map.Entry<Int, PacketData>::key)
.product()
}
private fun parseInput(input: List<String>): List<Pair<PacketData, PacketData>> {
return input
.filter(String::isNotBlank)
.chunked(2)
.map(::parsePacketPair)
}
private fun parsePacketPair(input: List<String>): Pair<PacketData, PacketData> {
return input
.map(::parsePacketData)
.let { (first, second) -> first to second }
}
private fun parsePacketData(input: String): PacketData {
return PacketData(parsePacketValue(input, mutableListOf()) as PacketData.Value.List)
}
/**
* [1,2,3] -> PacketData(List(Number(1),Number(2),Number(3))
*
* [1,[1],2] -> PacketData(List(Number(1),List(Number(1)),Number(2)
*
* [] -> PacketData(List())
*
* [1] -> PacketData(List(Number(1))
*
* [[[9]]] -> PacketData(List(List(List(Number(9))))
*
* [1,2,3,4,[5,6,[7,8,9]]]
* -> List(Number(1),Number(2),Number(3),Number(4),List(Number(5),Number(6),List(Number(7),Number(8),Number(9)))
*
*/
private fun parsePacketValue(
input: String,
parentList: MutableList<PacketData.Value>,
): PacketData.Value {
val input = input.removeSurrounding(prefix = "[", suffix = "]")
val list = mutableListOf<PacketData.Value>()
val listStartIndices = ArrayDeque<Int>()
var currentIndex = 0
while (currentIndex != input.length) {
when (input[currentIndex]) {
'[' -> {
listStartIndices.addFirst(currentIndex)
}
']' -> {
val listStartIndex = listStartIndices.removeFirst()
if (listStartIndices.isEmpty()) {
parsePacketValue(input.substring(listStartIndex..currentIndex), list)
}
}
',' -> {
// Ignore
}
in '0'..'9' -> {
if (listStartIndices.isEmpty()) {
val numberString = StringBuilder()
while (input.getOrNull(currentIndex) != null && input[currentIndex].isDigit()) {
numberString.append(input[currentIndex])
currentIndex++
}
currentIndex--
list.add(PacketData.Value.Number(numberString.toString().toInt()))
}
}
else -> error("Invalid char")
}
currentIndex++
}
val result = PacketData.Value.List(list)
parentList.add(result)
return result
}
private fun isPairInTheRightOrder(pair: Pair<PacketData, PacketData>): Boolean {
val (first, second) = pair.toList().map(PacketData::value)
return isValuesInRightOrder(first, second).toBooleanOrNull()!!
}
private fun isValuesInRightOrder(left: PacketData.Value, right: PacketData.Value): Int {
return when {
left is PacketData.Value.Number && right is PacketData.Value.Number ->
right.value.compareTo(left.value)
left is PacketData.Value.List && right is PacketData.Value.List -> {
val values = left.value.zip(right.value)
var isInRightOrder = 0
for (value in values) {
val result = isValuesInRightOrder(value.first, value.second)
if (result != 0) {
isInRightOrder = result
break
}
}
if (isInRightOrder == 0) right.value.size.compareTo(left.value.size) else isInRightOrder
}
left is PacketData.Value.Number && right is PacketData.Value.List -> {
isValuesInRightOrder(PacketData.Value.List(listOf(left)), right)
}
left is PacketData.Value.List && right is PacketData.Value.Number -> {
isValuesInRightOrder(left, PacketData.Value.List(listOf(right)))
}
else -> error("Impossible case")
}
}
private fun Int.toBooleanOrNull(): Boolean? = when {
this > 0 -> true
this < 0 -> false
else -> null
}
private data class PacketData(
val value: Value.List,
) {
sealed interface Value {
data class Number(val value: Int) : Value {
override fun toString(): String {
return "$value"
}
}
data class List(val value: kotlin.collections.List<Value>) : Value {
constructor(single: Value) : this(listOf(single))
override fun toString(): String {
return "[${value.joinToString(",")}]"
}
}
}
}
}
| 0 | Kotlin | 0 | 0 | ceffb6d4488d3a0e82a45cab3cbc559a2060d8e6 | 6,152 | AdventOfCode2022 | Apache License 2.0 |
src/aoc2023/Day06.kt | dayanruben | 433,250,590 | false | {"Kotlin": 79134} | package aoc2023
import checkValue
import readInput
fun main() {
val (year, day) = "2023" to "Day06"
fun countWays(times: List<Long>, distances: List<Long>) =
times.mapIndexed { index, time ->
(1L until time).map {
it * (time - it)
}.count {
it > distances[index]
}.toLong()
}.reduce { acc, i -> acc * i }
fun part1(input: List<String>): Long {
val (times, distances) = input.map { line ->
line.split("\\s+".toRegex()).drop(1).map { it.toLong() }
}
return countWays(times, distances)
}
fun part2(input: List<String>): Long {
val (times, distances) = input.map { line ->
listOf(line.split(":").last().replace("\\s+".toRegex(), "").toLong())
}
return countWays(times, distances)
}
val testInput = readInput(name = "${day}_test", year = year)
val input = readInput(name = day, year = year)
checkValue(part1(testInput), 288)
println(part1(input))
checkValue(part2(testInput), 71503)
println(part2(input))
} | 1 | Kotlin | 2 | 30 | df1f04b90e81fbb9078a30f528d52295689f7de7 | 1,141 | aoc-kotlin | Apache License 2.0 |
src/Day18.kt | a-glapinski | 572,880,091 | false | {"Kotlin": 26602} | import utils.Coordinate3D
import utils.readInputAsLines
fun main() {
val input = readInputAsLines("day18_input_test")
val cubes = input.map { it.split(',') }
.map { (x, y, z) -> Coordinate3D(x.toInt(), y.toInt(), z.toInt()) }.toSet()
fun part1() = cubes.sumOf { cube -> cube.neighbours().count { it !in cubes } }
println(part1())
fun part2(): Int {
val xBounds = (cubes.minOf { it.x } - 1)..(cubes.maxOf { it.x } + 1)
val yBounds = (cubes.minOf { it.y } - 1)..(cubes.maxOf { it.y } + 1)
val zBounds = (cubes.minOf { it.z } - 1)..(cubes.maxOf { it.z } + 1)
val toVisit = mutableListOf(Coordinate3D(xBounds.first, yBounds.first, zBounds.first))
val visited = mutableSetOf<Coordinate3D>()
var surfaceArea = 0
while (toVisit.isNotEmpty()) {
val current = toVisit.removeFirst()
if (current !in visited) {
current.neighbours()
.filter { (x, y, z) -> x in xBounds && y in yBounds && z in zBounds }
.forEach { if (it in cubes) surfaceArea++ else toVisit.add(it) }
visited.add(current)
}
}
return surfaceArea
}
println(part2())
} | 0 | Kotlin | 0 | 0 | c830d23ffc2ab8e9a422d015ecd413b5b01fb1a8 | 1,241 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/CountSubmatricesWithAllOnes.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
/**
* 1504. Count Submatrices With All Ones
* @see <a href="https://leetcode.com/problems/count-submatrices-with-all-ones/">Source</a>
*/
fun interface CountSubmatricesWithAllOnes {
fun numSubmat(mat: Array<IntArray>): Int
}
class CountSubmatricesWithAllOnesStack : CountSubmatricesWithAllOnes {
override fun numSubmat(mat: Array<IntArray>): Int {
val m: Int = mat.size
val n: Int = mat[0].size
var res = 0
for (up in 0 until m) {
val h = IntArray(n) { 1 }
for (down in up until m) {
for (k in 0 until n) h[k] = h[k] and mat[down][k]
res += countOneRow(h)
}
}
return res
}
private fun countOneRow(a: IntArray): Int {
var res = 0
var length = 0
for (i in a.indices) {
length = if (a[i] == 0) 0 else length + 1
res += length
}
return res
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,589 | kotlab | Apache License 2.0 |
src/main/java/challenges/educative_grokking_coding_interview/top_k_elements/_5/KthLargestElement.kt | ShabanKamell | 342,007,920 | false | null | package challenges.educative_grokking_coding_interview.top_k_elements._5
import challenges.util.PrintHyphens
import java.util.*
/**
Find the kth largest element in an unsorted array.
Note: We need to find the kth largest element in the sorted order, not the kth distinct element.
https://www.educative.io/courses/grokking-coding-interview-patterns-java/g79o2467JpG
*/
internal object KthLargestElement {
private fun findKthLargest(array: IntArray, k: Int): Int {
val kNumbersMinHeap = PriorityQueue { n1: Int, n2: Int -> n1 - n2 }
// Put first k elements in the min heap
for (i in 0 until k) kNumbersMinHeap.add(array[i])
// Go through the remaining elements of the array, if the element from the array is greater than the
// top (smallest) element of the heap, remove the top element from heap and add the element from array
for (i in k until array.size) {
if (array[i] > kNumbersMinHeap.peek()) {
kNumbersMinHeap.poll()
kNumbersMinHeap.add(array[i])
}
}
// The root of the heap has the Kth largest element
return kNumbersMinHeap.peek()
}
@JvmStatic
fun main(args: Array<String>) {
// Driver code
val inputs = arrayOf(
intArrayOf(1, 5, 12, 2, 11, 9, 7, 30, 20),
intArrayOf(23, 13, 17, 19, 10),
intArrayOf(3, 2, 5, 6, 7),
intArrayOf(1, 4, 6, 0, 2),
intArrayOf(1, 2, 3, 4, 5, 6, 7)
)
val K = intArrayOf(3, 4, 5, 1, 7)
for (i in K.indices) {
print(i + 1)
print(".\tInput array: " + Arrays.toString(inputs[i]))
print(", K: " + K[i])
println(
"""
kth largest element: ${findKthLargest(inputs[i], K[i])}"""
)
System.out.println(PrintHyphens.repeat("-", 100))
}
}
} | 0 | Kotlin | 0 | 0 | ee06bebe0d3a7cd411d9ec7b7e317b48fe8c6d70 | 1,913 | CodingChallenges | Apache License 2.0 |
src/main/kotlin/days/Day05.kt | TheMrMilchmann | 433,608,462 | false | {"Kotlin": 94737} | /*
* Copyright (c) 2021 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package days
import utils.*
import kotlin.math.absoluteValue
import kotlin.math.sign
fun main() {
data class Point(val x: Int, val y: Int)
data class Segment(val start: Point, val end: Point)
fun Point.diff(other: Point, selector: (Point) -> Int): IntRange =
minOf(selector(this), selector(other))..maxOf(selector(this), selector(other))
val segments = readInput().map { it.split(" -> ") }
.map { (start, end) ->
Segment(
start.split(",").let { (x, y) -> Point(x.toInt(), y.toInt()) },
end.split(",").let { (x, y) -> Point(x.toInt(), y.toInt()) }
)
}
fun part1(): Int {
val grid = Array(segments.maxOf { maxOf(it.start.y, it.end.y) } + 1) {
IntArray( segments.maxOf { maxOf(it.start.x, it.end.x) } + 1)
}
for (segment in segments) {
if (segment.start.x == segment.end.x) {
segment.start.diff(segment.end, Point::y).forEach { y ->
grid[y][segment.start.x]++
}
} else if (segment.start.y == segment.end.y) {
segment.start.diff(segment.end, Point::x).forEach { x ->
grid[segment.start.y][x]++
}
}
}
return grid.flatMap { it.filter { it > 1 } }.count()
}
fun part2(): Int {
val grid = Array(segments.maxOf { maxOf(it.start.y, it.end.y) } + 1) {
IntArray( segments.maxOf { maxOf(it.start.x, it.end.x) } + 1)
}
for (segment in segments) {
val dX = (segment.end.x - segment.start.x).sign
val dY = (segment.end.y - segment.start.y).sign
for (t in 0..maxOf((segment.start.x - segment.end.x).absoluteValue, (segment.start.y - segment.end.y).absoluteValue)) {
grid[segment.start.y + t * dY][segment.start.x + t * dX]++
}
}
return grid.flatMap { it.filter { it > 1 } }.count()
}
println("Part 1: ${part1()}")
println("Part 2: ${part2()}")
} | 0 | Kotlin | 0 | 1 | dfc91afab12d6dad01de552a77fc22a83237c21d | 3,185 | AdventOfCode2021 | MIT License |
src/main/problem4/solution2.kt | lorenzo-piersante | 515,177,846 | false | {"Kotlin": 15798, "Java": 4893} | package problem4
import java.util.Scanner
private fun isPalindrome(n : Int) : Boolean {
val straight = n.toString()
val reversed = straight.reversed()
return straight == reversed
}
private fun getPreviousPalindrome(n : Int) : Int {
var prev = n
while (! isPalindrome(prev)) prev--
return prev
}
private fun is3DigitTermsProduct(n : Int) : Boolean {
for (i in 111..999) {
for (j in 111..999) {
if (i * j == n) return true
}
}
return false
}
/**
* this solution is way better, in fact we use the nested loops only to find the product terms only for palindrome nums
* the optimization seems to be enough to pass tests
*/
fun largestPalindromeProductV2(input : Int) : Int {
var candidate = getPreviousPalindrome(input - 1)
while (! is3DigitTermsProduct(candidate)) {
candidate = getPreviousPalindrome(candidate - 1)
}
return candidate
}
fun main() {
val sc = Scanner(System.`in`)
val numberOfInputs = sc.nextInt()
for (i in 0 until numberOfInputs) {
val input = sc.nextInt()
val result = largestPalindromeProductV2(input)
println(result)
}
}
| 0 | Kotlin | 0 | 0 | 6159bb49cdfe94310a34edad138de2998352f1c2 | 1,184 | HackerRank-ProjectEuler | MIT License |
core-kotlin-modules/core-kotlin-collections-map/src/test/kotlin/com/baeldung/maptransform/MapTransformUnitTest.kt | Baeldung | 260,481,121 | false | {"Kotlin": 1476024, "Java": 43013, "HTML": 4883} | package com.baeldung.maptransform
import org.junit.Test
import kotlin.test.assertEquals
class MapTransformUnitTest {
@Test
fun `transform map using mapValues() method`() {
val map = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4, "five" to 5)
val transformedMap = map.mapValues { it.value * 2 }
assertEquals(mapOf("one" to 2, "two" to 4, "three" to 6, "four" to 8, "five" to 10), transformedMap)
}
@Test
fun `transform map using filterKeys() method`() {
val map1 = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4, "five" to 5)
val map2 = mapOf(1 to 1, 2 to 2, 3 to 3, 4 to 4, 5 to 5)
val transformedMap1 = map1.filterKeys { it != "three" }
val transformedMap2 = map2.filterKeys { it % 2 == 0 }
assertEquals(mapOf("one" to 1, "two" to 2, "four" to 4, "five" to 5), transformedMap1)
assertEquals(mapOf(2 to 2, 4 to 4), transformedMap2)
}
@Test
fun `transform map using mapKeys() method`() {
val map = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4, "five" to 5)
val transformedMap = map.mapKeys { it.key.uppercase() }
assertEquals(mapOf("ONE" to 1, "TWO" to 2, "THREE" to 3, "FOUR" to 4, "FIVE" to 5), transformedMap)
}
@Test
fun `transform map using associate() method`() {
val originalList = listOf("one", "two", "three", "four", "five")
val transformedMap = originalList.associate { it to it.length }
assertEquals(mapOf("one" to 3, "two" to 3, "three" to 5, "four" to 4, "five" to 4), transformedMap)
}
@Test
fun `transform map using map() method`() {
val map = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4, "five" to 5)
val transformedMap = map.map { it.key.uppercase() to it.value * 10 }.toMap()
assertEquals(mapOf("ONE" to 10, "TWO" to 20, "THREE" to 30, "FOUR" to 40, "FIVE" to 50), transformedMap)
}
@Test
fun `transform map using flatMap() method`() {
val map = mapOf("one" to listOf(1, 2), "two" to listOf(3, 4, 5), "three" to listOf(6, 7, 8, 9))
val flattenedList = map.flatMap { (key, value) -> value.map { key to it } }
val grouped = flattenedList.groupBy({ it.first }, { it.second })
assertEquals("{one=[1, 2], two=[3, 4, 5], three=[6, 7, 8, 9]}", grouped.toString())
}
} | 10 | Kotlin | 273 | 410 | 2b718f002ce5ea1cb09217937dc630ff31757693 | 2,392 | kotlin-tutorials | MIT License |
Kotlin/heap_sort_in_kotlin.kt | iam-abbas | 213,309,115 | false | null | var heapSize = 0
fun left(i: Int): Int {
return 2 * i
}
fun right(i: Int): Int {
return 2 * i + 1
}
fun swap(A: Array<Int>, i: Int, j: Int) {
var temp = A[i]
A[i] = A[j]
A[j] = temp
}
fun max_heapify(A: Array<Int>, i: Int) {
var l = left(i);
var r = right(i);
var largest: Int;
if ((l <= heapSize - 1) && (A[l] > A[i])) {
largest = l;
} else
largest = i
if ((r <= heapSize - 1) && (A[r] > A[l])) {
largest = r
}
if (largest != i) {
swap(A, i, largest);
max_heapify(A, largest);
}
}
fun buildMaxheap(A: Array<Int>) {
heapSize = A.size
for (i in heapSize / 2 downTo 0) {
max_heapify(A, i)
}
}
fun heap_sort(A: Array<Int>) {
buildMaxheap(A)
for (i in A.size - 1 downTo 1) {
swap(A, i, 0)
heapSize = heapSize - 1
max_heapify(A, 0)
}
}
fun main(arg: Array<String>) {
print("Enter no. of elements :")
var n = readLine()!!.toInt()
println("Enter elements : ")
var A = Array(n, { 0 })
for (i in 0 until n)
A[i] = readLine()!!.toInt()
heap_sort(A)
println("Sorted array is : ")
for (i in 0 until n)
print("${A[i]} ")
}
| 3 | C++ | 383 | 215 | d04aa8fd9a1fa290266dde96afe9b90ee23c5a92 | 1,225 | cs-algorithms | MIT License |
kotlin/problems/src/solution/LinkProblems.kt | lunabox | 86,097,633 | false | {"Kotlin": 146671, "Python": 38767, "JavaScript": 19188, "Java": 13966} | package solution
import data.structure.ListNode
class LinkProblems {
/**
* https://leetcode-cn.com/problems/merge-k-sorted-lists/
*/
fun mergeKLists(lists: Array<ListNode?>): ListNode? {
var currentNode = Array<ListNode?>(lists.size) { null }
var result: ListNode? = null
var current: ListNode? = null
lists.forEachIndexed { index, listNode ->
currentNode[index] = listNode
}
currentNode = currentNode.filterNotNull().toTypedArray()
while (currentNode.isNotEmpty()) {
var m = currentNode[0]
var minIndex = 0
currentNode.forEachIndexed { index, listNode ->
if (listNode!!.`val` < m!!.`val`) {
m = listNode
minIndex = index
}
}
if (current == null) {
result = m
current = result
} else {
current.next = m
current = current.next
}
currentNode[minIndex] = currentNode[minIndex]?.next
currentNode = currentNode.filterNotNull().toTypedArray()
current?.next = null
}
return result
}
/**
* https://leetcode-cn.com/problems/add-two-numbers-ii/
*/
fun addTwoNumbers(l1: ListNode?, l2: ListNode?): ListNode? {
val h1 = ListNode(0)
h1.next = l1
val h2 = ListNode(0)
h2.next = l2
val reverseList: (ListNode) -> Unit = {
var current = it.next
it.next = null
while (current != null) {
val pointer = current
current = current.next
if (it.next == null) {
it.next = pointer
pointer.next = null
} else {
pointer.next = it.next
it.next = pointer
}
}
}
reverseList(h1)
reverseList(h2)
var n1 = h1.next
var n2 = h2.next
val ans = ListNode(0)
var cur: ListNode? = null
var carry = 0
while (n1 != null && n2 != null) {
val n = n1.`val` + n2.`val` + carry
carry = n / 10
if (ans.next == null) {
ans.next = ListNode(n % 10)
cur = ans.next
} else {
cur!!.next = ListNode(n % 10)
cur = cur.next
}
n1 = n1.next
n2 = n2.next
}
while (n1 != null) {
cur!!.next = ListNode((n1.`val` + carry) % 10)
carry = (n1.`val` + carry) / 10
cur = cur.next
n1 = n1.next
}
while (n2 != null) {
cur!!.next = ListNode((n2.`val` + carry) % 10)
carry = (n2.`val` + carry) / 10
cur = cur.next
n2 = n2.next
}
if (carry > 0) {
cur!!.next = ListNode(carry)
}
reverseList(ans)
return ans.next
}
/**
* https://leetcode-cn.com/problems/shan-chu-lian-biao-de-jie-dian-lcof/
*/
fun deleteNode(head: ListNode?, `val`: Int): ListNode? {
val ans = ListNode(0)
ans.next = head
var before = ans
var current = ans.next
while (current != null) {
if (current.`val` == `val`) {
before.next = current.next
current.next = null
break
}
before = current
current = current.next
}
return ans.next
}
/**
* https://leetcode-cn.com/problems/convert-binary-number-in-a-linked-list-to-integer/
*/
fun getDecimalValue(head: ListNode?): Int {
var len = 0
var cur = head
var ans = 0
while (cur != null) {
len++
cur = cur.next
}
cur = head
var carry = (1).shl(len - 1)
while (cur != null) {
ans += carry * cur.`val`
carry = carry.shr(1)
cur = cur.next
}
return ans
}
/**
*
*/
fun addTwoNumbers2(l1: ListNode?, l2: ListNode?): ListNode? {
val h1 = ListNode(0)
h1.next = l1
val h2 = ListNode(0)
h2.next = l2
var n1 = h1.next
var n2 = h2.next
val ans = ListNode(0)
var cur: ListNode? = null
var carry = 0
while (n1 != null && n2 != null) {
val n = n1.`val` + n2.`val` + carry
carry = n / 10
if (ans.next == null) {
ans.next = ListNode(n % 10)
cur = ans.next
} else {
cur!!.next = ListNode(n % 10)
cur = cur.next
}
n1 = n1.next
n2 = n2.next
}
while (n1 != null) {
cur!!.next = ListNode((n1.`val` + carry) % 10)
carry = (n1.`val` + carry) / 10
cur = cur.next
n1 = n1.next
}
while (n2 != null) {
cur!!.next = ListNode((n2.`val` + carry) % 10)
carry = (n2.`val` + carry) / 10
cur = cur.next
n2 = n2.next
}
if (carry > 0) {
cur!!.next = ListNode(carry)
}
return ans.next
}
/**
* https://leetcode-cn.com/problems/partition-list/
*/
fun partition(head: ListNode?, x: Int): ListNode? {
val littleList = ListNode(0)
val bigList = ListNode(0)
var current = head
var littleCurrent = littleList
var bigCurrent = bigList
while (current != null) {
val temp = current
current = current.next
temp.next = null
if (temp.`val` < x) {
littleCurrent.next = temp
littleCurrent = littleCurrent.next!!
} else {
bigCurrent.next = temp
bigCurrent = bigCurrent.next!!
}
}
littleCurrent.next = bigList.next
return littleList.next
}
/**
* https://leetcode-cn.com/problems/fan-zhuan-lian-biao-lcof/
*/
fun reverseList(head: ListNode?): ListNode? {
val ans: ListNode = ListNode(0)
var current = head
while (current != null) {
val temp = current
current = current.next
temp.next = ans.next
ans.next = temp
}
return ans.next
}
/**
* https://leetcode-cn.com/problems/he-bing-liang-ge-pai-xu-de-lian-biao-lcof/
*/
fun mergeTwoLists(l1: ListNode?, l2: ListNode?): ListNode? {
var cur1 = l1
var cur2 = l2
val ans = ListNode(0)
var cur: ListNode = ans
while (cur1 != null || cur2 != null) {
if (cur2 == null || (cur1 != null && cur1.`val` <= cur2.`val`)) {
cur.next = cur1
cur1 = cur1!!.next
cur = cur.next!!
cur.next = null
} else if (cur1 == null || cur1.`val` > cur2.`val`) {
cur.next = cur2
cur2 = cur2.next
cur = cur.next!!
cur.next = null
}
}
return ans.next
}
/**
<<<<<<< HEAD
* https://leetcode-cn.com/problems/palindrome-linked-list-lcci/
*/
fun isPalindrome(head: ListNode?): Boolean {
var cur = head
var listLength = 0
while (cur != null) {
listLength++
cur = cur.next
}
cur = head
var count = listLength / 2
val left = ListNode(0)
while (count > 0 && cur != null) {
count--
val temp = cur
cur = cur.next
temp.next = left.next
left.next = temp
}
var curLeft = left.next
var curRight = cur
if (listLength % 2 == 1) {
curRight = cur!!.next
}
while (curLeft != null && curRight != null) {
if (curLeft.`val` != curRight.`val`) {
return false
}
curLeft = curLeft.next
curRight = curRight.next
}
return true
}
/**
* https://leetcode-cn.com/problems/kth-node-from-end-of-list-lcci/
*/
fun kthToLast(head: ListNode?, k: Int): Int {
var cur = head
var listLength = 0
while (cur != null) {
listLength++
cur = cur.next
}
val pos = listLength - k + 1
cur = head
listLength = 0
while (cur != null) {
listLength++
if (listLength == pos) {
return cur.`val`
}
cur = cur.next
}
return 0
}
/**
* https://leetcode-cn.com/problems/middle-of-the-linked-list/
*/
fun middleNode(head: ListNode?): ListNode? {
var listLength = 0
var current = head
while (current != null) {
listLength++
current = current.next
}
val middle = listLength / 2 + 1
current = head
listLength = 0
while (current != null) {
listLength++
if (listLength == middle) {
return current
}
current = current.next
}
return null
}
/**
* https://leetcode-cn.com/problems/linked-list-components/
*/
fun numComponents(head: ListNode?, G: IntArray): Int {
var ans = 0
var current = head
var inList = false
while (current != null) {
if (current.`val` in G) {
if (!inList) {
inList = true
ans++
}
} else {
inList = false
}
current = current.next
}
return ans
}
/**
* https://leetcode-cn.com/problems/remove-duplicate-node-lcci/
*/
fun removeDuplicateNodes(head: ListNode?): ListNode? {
val buffer = HashSet<Int>()
var current = head
var before: ListNode? = null
while (current != null) {
if (current.`val` in buffer) {
before!!.next = current.next
current = before
} else {
buffer.add(current.`val`)
}
before = current
current = current.next
}
return head
}
} | 0 | Kotlin | 0 | 0 | cbb2e3ad8f2d05d7cc54a865265561a0e391a9b9 | 10,550 | leetcode | Apache License 2.0 |
src/day04/Day04_part2.kt | seastco | 574,758,881 | false | {"Kotlin": 72220} | package day04
import readLines
fun main() {
fun part2(pairs: List<String>): Int {
var total = 0
// e.g. 10-15,3-10
for (pair in pairs) {
// ["10-15", "3-10"]
val assignments = pair.split(",")
// [10,15]
val assignment1 = assignments[0].split("-").map { string -> string.toInt() }
// [3,10]
val assignment2 = assignments[1].split("-").map { string -> string.toInt() }
// find the assignment with the first starting point
// first == [3,10], second == [10,15]
val firstAssignment = if (assignment1[0] <= assignment2[0]) assignment1 else assignment2
val secondAssignment = if (assignment1[0] <= assignment2[0]) assignment2 else assignment1
// now, check for overlap by comparing 10 >= 10
total += if (firstAssignment[1] >= secondAssignment[0]) 1 else 0
}
return total
}
println(part2(readLines("day04/test")))
println(part2(readLines("day04/input")))
}
| 0 | Kotlin | 0 | 0 | 2d8f796089cd53afc6b575d4b4279e70d99875f5 | 1,060 | aoc2022 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/DecodeMessage.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import dev.shtanko.algorithms.ALPHABET_LETTERS_COUNT
import java.util.stream.Collectors
/**
* 2325. Decode the Message
* https://leetcode.com/problems/decode-the-message/
*/
fun interface DecodeMessage {
operator fun invoke(key: String, message: String): String
}
class DecodeMessageBruteForce : DecodeMessage {
override operator fun invoke(key: String, message: String): String {
val m: MutableMap<Char, Char> = HashMap()
m[' '] = ' '
var to = 'a'
for (from in key.toCharArray()) {
if (!m.containsKey(from)) {
m[from] = to++
}
}
return message.chars().mapToObj { c -> m[c.toChar()].toString() + "" }.collect(Collectors.joining(""))
}
}
class DecodeMessageSB : DecodeMessage {
override operator fun invoke(key: String, message: String): String {
val table = CharArray(ALPHABET_LETTERS_COUNT)
var index = 0
for (c in key.toCharArray()) {
if (index < ALPHABET_LETTERS_COUNT && c != ' ' && table[c.code - 'a'.code].code == 0) {
table[c.code - 'a'.code] = (index + 'a'.code).toChar()
index++
}
}
val sb = StringBuilder()
for (c in message.toCharArray()) {
sb.append(if (c == ' ') ' ' else table[c.code - 'a'.code])
}
return sb.toString()
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,026 | kotlab | Apache License 2.0 |
src/Day15.kt | fonglh | 573,269,990 | false | {"Kotlin": 48950, "Ruby": 1701} | import kotlin.math.absoluteValue
fun main() {
val inputLineRegex = """Sensor at x=([-\d]+), y=([-\d]+): closest beacon is at x=([-\d]+), y=([-\d]+)""".toRegex()
data class SensorData(val sensorPos: Pair<Int, Int>, val beaconPos: Pair<Int, Int>, val distance: Int)
fun manhattanDistance(p1: Pair<Int, Int>, p2: Pair<Int, Int>): Int {
return (p1.first-p2.first).absoluteValue + (p1.second-p2.second).absoluteValue
}
// min and max X coordinates which are relevant
fun findLeftRightLimits(allSensorData: List<SensorData>): Pair<Int, Int> {
var minX = Int.MAX_VALUE
var maxX = Int.MIN_VALUE
allSensorData.forEach {
val sensorMinX = it.sensorPos.first - it.distance
val sensorMaxX = it.sensorPos.first + it.distance
if (sensorMinX < minX)
minX = sensorMinX
if (sensorMaxX > maxX)
maxX = sensorMaxX
}
return Pair(minX, maxX)
}
fun countBeaconsInRow(allSensorData: List<SensorData>, targetRow: Int): Int {
var beacons = mutableSetOf<Pair<Int, Int>>()
allSensorData.forEach {
if (it.beaconPos.second == targetRow)
beacons.add(it.beaconPos)
}
return beacons.size
}
fun getPerimeterPoints(sensor: SensorData, limit: Int): Set<Pair<Int, Int>> {
var perimeterPoints = mutableSetOf<Pair<Int, Int>>()
// top to right
for (deltaX in 0..(sensor.distance+1)) {
val deltaY = -(sensor.distance+1 - deltaX)
val perimeterX = sensor.sensorPos.first + deltaX
val perimeterY = sensor.sensorPos.second + deltaY
if (perimeterX in 0..limit && perimeterY in 0..limit) {
perimeterPoints.add(Pair(perimeterX, perimeterY))
}
}
// right to bottom
for (deltaX in (sensor.distance+1) downTo 0) {
val deltaY = sensor.distance+1 - deltaX
val perimeterX = sensor.sensorPos.first + deltaX
val perimeterY = sensor.sensorPos.second + deltaY
if (perimeterX in 0..limit && perimeterY in 0..limit) {
perimeterPoints.add(Pair(perimeterX, perimeterY))
}
}
// bottom to left
for (deltaX in 0 downTo -(sensor.distance+1)) {
val deltaY = sensor.distance+1 + deltaX
val perimeterX = sensor.sensorPos.first + deltaX
val perimeterY = sensor.sensorPos.second + deltaY
if (perimeterX in 0..limit && perimeterY in 0..limit) {
perimeterPoints.add(Pair(perimeterX, perimeterY))
}
}
//left to top
for (deltaX in -(sensor.distance+1)..0) {
val deltaY = -(sensor.distance+1 + deltaX)
val perimeterX = sensor.sensorPos.first + deltaX
val perimeterY = sensor.sensorPos.second + deltaY
if (perimeterX in 0..limit && perimeterY in 0..limit) {
perimeterPoints.add(Pair(perimeterX, perimeterY))
}
}
return perimeterPoints
}
fun part1(input: List<String>, targetRow: Int): Int {
var allSensorData = mutableListOf<SensorData>()
input.forEach {
val (sensorX, sensorY, beaconX, beaconY) = inputLineRegex.matchEntire(it)
?.destructured
?: throw IllegalArgumentException("Incorrect input line $it")
val sensorPos = Pair(sensorX.toInt(), sensorY.toInt())
val beaconPos = Pair(beaconX.toInt(), beaconY.toInt())
val distance = manhattanDistance(sensorPos, beaconPos)
allSensorData.add(SensorData(sensorPos, beaconPos, distance))
}
val leftRightLimits = findLeftRightLimits(allSensorData)
val beaconsInRow = countBeaconsInRow(allSensorData, targetRow)
var count = 0
for (x in leftRightLimits.first..leftRightLimits.second) {
val checkPos = Pair(x, targetRow)
if (allSensorData.any { manhattanDistance(it.sensorPos, checkPos) <= it.distance }) {
count++
}
}
return count - beaconsInRow
}
fun part2(input: List<String>, maxSearchCoord: Int): Long {
var allSensorData = mutableListOf<SensorData>()
input.forEach {
val (sensorX, sensorY, beaconX, beaconY) = inputLineRegex.matchEntire(it)
?.destructured
?: throw IllegalArgumentException("Incorrect input line $it")
val sensorPos = Pair(sensorX.toInt(), sensorY.toInt())
val beaconPos = Pair(beaconX.toInt(), beaconY.toInt())
val distance = manhattanDistance(sensorPos, beaconPos)
allSensorData.add(SensorData(sensorPos, beaconPos, distance))
}
allSensorData.forEach {sensor: SensorData ->
val searchPoints = getPerimeterPoints(sensor, maxSearchCoord)
searchPoints.forEach { candidatePos: Pair<Int, Int> ->
if (allSensorData.none { manhattanDistance(it.sensorPos, candidatePos) <= it.distance }) {
println(candidatePos)
return (candidatePos.first.toLong() * 4000000.toLong() + candidatePos.second.toLong())
}
}
}
return 0
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day15_test")
check(part1(testInput, 10) == 26)
check(part2(testInput, 20) == 56000011.toLong())
val input = readInput("Day15")
println(part1(input, 2000000))
println(part2(input, 4000000))
}
| 0 | Kotlin | 0 | 0 | ef41300d53c604fcd0f4d4c1783cc16916ef879b | 5,665 | advent-of-code-2022 | Apache License 2.0 |
CelebrityMashup.kts | breun | 294,154,833 | false | null | import java.io.File
// Models
data class Mashup(
val mashupName: String,
val overlap: Int,
val originalNames: Pair<String, String>
)
// Functions
fun readNamesFromTxtFiles(path: String): List<String> =
File(path)
.listFiles { _, name -> name.endsWith(".txt") }
.flatMap { it.readLines() }
fun calculateMashups(names: List<String>, minimumOverlap: Int): List<Mashup> =
cartesianProduct(names, names)
.filterNot { it.first == it.second }
.mapNotNull { findBestMashup(it, minimumOverlap) }
fun <T> cartesianProduct(list1: Iterable<T>, list2: Iterable<T>): Iterable<Pair<T, T>> =
list1.flatMap { first -> list2.map { second -> first to second } }
fun findBestMashup(originalNames: Pair<String, String>, minimumOverlap: Int): Mashup? {
val first = originalNames.first.toLowerCase()
val second = originalNames.second.toLowerCase()
// Maximum overlap cannot be more than the minimum length of the strings.
// Subtract one from that minimum to avoid mashups where one name completely contains the other, because those aren't funny.
val maxOverlap = minOf(first.length, second.length) - 1
var overlap = maxOverlap
while (overlap >= minimumOverlap) {
val overlapString = second.take(overlap)
if (first.endsWith(overlapString)) {
return Mashup(
mashupName = originalNames.first + originalNames.second.drop(overlap),
originalNames = originalNames,
overlap = overlap
)
}
overlap--
}
return null
}
fun printMashups(mashups: List<Mashup>) {
mashups.forEach { println("${it.mashupName} ${it.originalNames} [${it.overlap}]") }
println("")
println("Found ${mashups.size} celebrity mashups")
}
// Action!
val names = readNamesFromTxtFiles(path = ".")
val mashups = calculateMashups(names, minimumOverlap = 3) // Really short overlaps don't make for good mashups
printMashups(mashups.sortedBy { it.mashupName }) | 0 | Kotlin | 0 | 0 | 741f038625de1bf835c8ed58320fad45c39439cb | 2,013 | celebrity-mashups | Apache License 2.0 |
src/main/kotlin/days/aoc2021/Day4.kt | bjdupuis | 435,570,912 | false | {"Kotlin": 537037} | package days.aoc2021
import days.Day
class Day4 : Day(2021, 4) {
override fun partOne(): Any {
return parseInput(inputList).calculateFirstWinner()
}
override fun partTwo(): Any {
return parseInput(inputList).calculateLastWinner()
}
fun parseInput(input: List<String>): BingoGame {
val numbers = input.first().split(',').map { it.toInt() }
val boards = mutableListOf<BingoBoard>()
input.drop(1).filter { it.isNotBlank() }.chunked(5).let { boardLines ->
boardLines.forEach {
boards.add(BingoBoard(it))
}
}
return BingoGame(numbers, boards)
}
class BingoGame(private val numbers: List<Int>, private val boards: List<BingoBoard>) {
fun calculateFirstWinner(): Int {
numbers.forEach { number ->
boards.forEach { board ->
board.playNumber(number)
if (board.isWinner()) {
return number * board.calculateWinningScore()
}
}
}
throw Exception("No winner found")
}
fun calculateLastWinner(): Int {
var winners = 0
numbers.forEach { number ->
boards.forEach { board ->
if (!board.isWinner()) {
board.playNumber(number)
if (board.isWinner()) {
if (++winners == boards.size) {
return number * board.calculateWinningScore()
}
}
}
}
}
throw Exception("No winner found")
}
}
class BingoBoard(input: List<String>) {
private var board : Array<Array<Pair<Int,Boolean>>>
init {
val list = mutableListOf<Array<Pair<Int,Boolean>>>()
input.forEach { s ->
s.trim().split("\\s+".toRegex()).take(5).let { list ->
list.map {
it.toInt()
}
}.map {
Pair(it, false)
}.toTypedArray().let {
list.add(it)
}
}
board = list.toTypedArray()
}
fun playNumber(number: Int): Boolean {
board.forEach { row ->
for (i in row.indices) {
if (row[i].first == number) {
row[i] = Pair(row[i].first, true)
return true
}
}
}
return false
}
fun isWinner(): Boolean {
var winner: Boolean
for (i in board.indices) {
val row = board[i]
winner = true
for (j in row.indices) {
if (!board[i][j].second) {
winner = false
break
}
}
if (winner) {
return true
}
}
for (i in board[0].indices) {
winner = true
for (j in board.indices) {
if (!board[j][i].second) {
winner = false
break
}
}
if (winner) {
return true
}
}
return false
}
fun calculateWinningScore(): Int {
var sum = 0
board.forEach { row ->
row.filter { !it.second }.sumBy { it.first }.let { sum += it }
}
return sum
}
}
} | 0 | Kotlin | 0 | 1 | c692fb71811055c79d53f9b510fe58a6153a1397 | 3,811 | Advent-Of-Code | Creative Commons Zero v1.0 Universal |
src/main/kotlin/com/hj/leetcode/kotlin/problem47/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem47
/**
* LeetCode page: [47. Permutations II](https://leetcode.com/problems/permutations-ii/);
*/
class Solution {
/* Complexity:
* Time O(N * N!) and Aux_Space O(N) where N is the size of nums;
*/
fun permuteUnique(nums: IntArray): List<List<Int>> {
val frequencyPerNum = getFrequencyPerNum(nums)
val uniquePermutations = mutableListOf<List<Int>>()
addUniquePermutations(frequencyPerNum, nums.size, uniquePermutations)
return uniquePermutations
}
private fun getFrequencyPerNum(nums: IntArray): MutableMap<Int, Int> {
val frequency = hashMapOf<Int, Int>()
for (num in nums) {
frequency[num] = frequency.getOrDefault(num, 0) + 1
}
return frequency
}
private fun addUniquePermutations(
frequencyPerNum: MutableMap<Int, Int>,
length: Int,
container: MutableList<List<Int>>,
accList: MutableList<Int> = mutableListOf(),
) {
val hasCompleted = accList.size == length
if (hasCompleted) {
val copy = accList.toList()
container.add(copy)
return
}
for ((num, freq) in frequencyPerNum) {
if (freq > 0) {
frequencyPerNum[num] = freq - 1
accList.add(num)
addUniquePermutations(frequencyPerNum, length, container, accList)
accList.removeAt(accList.lastIndex)
frequencyPerNum[num] = freq
}
}
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 1,557 | hj-leetcode-kotlin | Apache License 2.0 |
src/chapter3/section5/ex16.kt | w1374720640 | 265,536,015 | false | {"Kotlin": 1373556} | package chapter3.section5
import chapter3.section4.LinearProbingHashST
import extensions.formatDouble
import kotlin.math.abs
/**
* 为SparseVector添加一个sum()方法,接受一个SparseVector对象作为参数并将两者相加的结果返回为一个SparseVector对象
* 请注意:你需要使用delete()方法来处理向量中的一项变为0的情况(请特别注意精度)
*
* 解:向量相加等于对应位置的数相加
*/
class SparseVector(val st: LinearProbingHashST<Int, Double> = LinearProbingHashST()) {
fun size(): Int {
return st.size()
}
fun put(index: Int, value: Double) {
st.put(index, value)
}
fun get(index: Int): Double {
return st.get(index) ?: 0.0
}
fun dot(array: Array<Double>): Double {
var sum = 0.0
for (index in st.keys()) {
sum += get(index) * array[index]
}
return sum
}
fun sum(vector: SparseVector): SparseVector {
val newST = LinearProbingHashST<Int, Double>()
for (index in st.keys()) {
newST.put(index, st.get(index)!!)
}
for (index in vector.st.keys()) {
val value = vector.st.get(index)!!
val sum = (st.get(index) ?: 0.0) + value
// 浮点数相加可能产生误差,当和的绝对值小于指定精度时,认为和为0
if (abs(sum) < 0.00000001) {
newST.delete(index)
} else {
newST.put(index, sum)
}
}
return SparseVector(newST)
}
}
fun main() {
val a = arrayOf(
arrayOf(0.0, 0.9, 0.0, 0.0, 0.0),
arrayOf(0.0, 0.0, 0.36, 0.36, 0.18),
arrayOf(0.0, 0.0, 0.0, 0.9, 0.0),
arrayOf(0.9, 0.0, 0.0, 0.0, 0.0),
arrayOf(0.47, 0.0, 0.47, 0.0, 0.0)
)
val b = arrayOf(
arrayOf(0.1, 0.2, 0.0, 0.4, 0.0),
arrayOf(0.0, 0.36, -0.36, 0.36, 0.0),
arrayOf(0.0, 0.0, 0.0, -0.9, 0.0),
arrayOf(0.1, 0.0, 0.0, 0.0, 0.0),
arrayOf(0.0, 0.0, -0.47, 0.2, 0.0)
)
val x = arrayOf(0.05, 0.04, 0.36, 0.37, 0.19)
val sparseVectorArrayA = Array(a.size) {
SparseVector().apply {
for (i in a[it].indices) {
if (a[it][i] != 0.0) {
put(i, a[it][i])
}
}
}
}
val sparseVectorArrayB = Array(b.size) {
SparseVector().apply {
for (i in b[it].indices) {
if (b[it][i] != 0.0) {
put(i, b[it][i])
}
}
}
}
println("a•x = ")
for (i in sparseVectorArrayA.indices) {
println(formatDouble(sparseVectorArrayA[i].dot(x), 4))
}
println()
for (i in sparseVectorArrayA.indices) {
println("a[${i}]+b[${i}]=")
val result = sparseVectorArrayA[i].sum(sparseVectorArrayB[i])
println(result.st.keys().joinToString { "${it}:${formatDouble(result.st.get(it)!!, 3) }"})
}
} | 0 | Kotlin | 1 | 6 | 879885b82ef51d58efe578c9391f04bc54c2531d | 3,051 | Algorithms-4th-Edition-in-Kotlin | MIT License |
Strategy.kt | kgw78 | 671,116,967 | false | null | // Strategy Pattern Example
// ソートアルゴリズムのStrategyインターフェース
interface SortStrategy {
fun sort(numbers: IntArray): IntArray
}
// バブルソートアルゴリズム
class BubbleSortStrategy : SortStrategy {
override fun sort(numbers: IntArray): IntArray {
val sortedArray = numbers.clone()
val n = sortedArray.size
for (i in 0 until n) {
for (j in 0 until n - i - 1) {
if (sortedArray[j] > sortedArray[j + 1]) {
val temp = sortedArray[j]
sortedArray[j] = sortedArray[j + 1]
sortedArray[j + 1] = temp
}
}
}
return sortedArray
}
}
// クイックソートアルゴリズム
class QuickSortStrategy : SortStrategy {
override fun sort(numbers: IntArray): IntArray {
if (numbers.size <= 1) return numbers
val pivot = numbers[numbers.size / 2]
val equal = numbers.filter { it == pivot }.toIntArray()
val less = numbers.filter { it < pivot }.toIntArray()
val greater = numbers.filter { it > pivot }.toIntArray()
return sort(less) + equal + sort(greater)
}
}
// ソートを実行するコンテキストクラス
class SortContext(private val strategy: SortStrategy) {
fun executeSort(numbers: IntArray): IntArray {
return strategy.sort(numbers)
}
}
fun main() {
val numbers = intArrayOf(9, 3, 7, 1, 5)
// バブルソートを用いたソート
val bubbleSortStrategy = BubbleSortStrategy()
val bubbleSortContext = SortContext(bubbleSortStrategy)
val sortedWithBubbleSort = bubbleSortContext.executeSort(numbers)
println("バブルソートの結果: ${sortedWithBubbleSort.joinToString()}")
// クイックソートを用いたソート
val quickSortStrategy = QuickSortStrategy()
val quickSortContext = SortContext(quickSortStrategy)
val sortedWithQuickSort = quickSortContext.executeSort(numbers)
println("クイックソートの結果: ${sortedWithQuickSort.joinToString()}")
}
| 0 | Kotlin | 0 | 0 | 24b8993c533373ffdfab4e56fe1bb4e59a6933b0 | 2,104 | kotlin-design-patterns | MIT License |
src/day07/Day07.kt | cmargonis | 573,161,233 | false | {"Kotlin": 15730} | package day07
import readInput
import java.util.LinkedList
private const val DIRECTORY = "./day07"
private const val COMMAND = "$"
private const val SPACE_NEEDED_FOR_UPDATE = 30000000
fun main() {
fun traverseFileSystem(node: Node, action: (node: Node) -> Unit) {
if (node is Node.Directory) node.children.forEach { traverseFileSystem(it, action) }
action.invoke(node)
}
fun performCommand(line: List<String>, fileSystem: FileSystemTree) {
if (line[1] == "cd") {
val argument = line[2]
if (argument == "..") {
fileSystem.moveOneUp()
} else {
fileSystem.moveToOrCreate(argument)
}
}
}
fun constructFileSystem(input: List<String>): FileSystemTree {
val fileSystem = FileSystemTree()
input.drop(1).forEach {
val line = it.split(" ")
if (it.startsWith(COMMAND)) {
performCommand(line, fileSystem)
} else if (it.startsWith("dir")) {
fileSystem.createDir(line.last())
} else {
fileSystem.createFile(size = line.first().toInt(), name = line.last())
}
}
fileSystem.moveToRoot()
return fileSystem
}
fun part1(input: List<String>): Int {
val fileSystem = constructFileSystem(input)
val directories: MutableList<Node.Directory> = mutableListOf()
traverseFileSystem(fileSystem.currentWorkingDirectory) {
if (it is Node.Directory && it.name != "/") directories.add(it)
}
return directories.filter { it.getTotalSize() <= 100000 }.sumOf { it.getTotalSize() }
}
fun part2(input: List<String>): Int {
val fileSystem = constructFileSystem(input)
val directories: MutableList<Node.Directory> = mutableListOf()
traverseFileSystem(fileSystem.currentWorkingDirectory) {
if (it is Node.Directory && it.name != "/") directories.add(it)
}
val spaceToEmpty = SPACE_NEEDED_FOR_UPDATE - fileSystem.freeSpace
return directories.filter { it.getTotalSize() >= spaceToEmpty }.minBy { it.getTotalSize() }.getTotalSize()
}
val input = readInput("${DIRECTORY}/Day07")
println(part1(input))
check(part1(input) == 1908462)
println(part2(input))
check(part2(input) == 3979145)
}
class FileSystemTree {
private val totalDiskSpace: Int = 70000000
val freeSpace: Int
get() {
moveToRoot()
return totalDiskSpace - currentWorkingDirectory.getTotalSize()
}
var currentWorkingDirectory: Node.Directory = Node.Directory(mutableListOf(), "/")
private set
fun moveToOrCreate(dirName: String) {
val tmpDir = currentWorkingDirectory.moveToDirectory(dirName)
currentWorkingDirectory = tmpDir ?: currentWorkingDirectory.createDirectory(dirName)
}
fun moveOneUp() {
if (currentWorkingDirectory.parent != null) {
currentWorkingDirectory = currentWorkingDirectory.parent!!
}
}
fun createDir(dirName: String) {
if (currentWorkingDirectory.children.find { it.name == dirName } != null) error("Directory $dirName already exists!")
currentWorkingDirectory.createDirectory(dirName)
}
fun createFile(size: Int, name: String) {
if (currentWorkingDirectory.children.find { it.name == name } != null) error("File $name already exists!")
currentWorkingDirectory.createFile(size = size, name = name)
}
fun moveToRoot() {
while (currentWorkingDirectory.parent != null) {
currentWorkingDirectory = currentWorkingDirectory.parent!!
}
}
private val tree: LinkedList<Node> = LinkedList()
init {
tree.add(currentWorkingDirectory)
}
}
sealed class Node(open val name: String, open val parent: Directory? = null) {
abstract fun getTotalSize(): Int
data class Directory(
val children: MutableList<Node>,
override val name: String,
override val parent: Directory? = null
) : Node(name, parent) {
override fun getTotalSize(): Int = children.sumOf { it.getTotalSize() }
fun moveToDirectory(dirName: String): Directory? =
children.filterIsInstance<Directory>().firstOrNull() { it.name == dirName }
fun createDirectory(name: String): Directory {
val directory = Directory(mutableListOf(), name, this)
children.add(directory)
return directory
}
fun createFile(size: Int, name: String): File {
val file = File(name, size)
children.add(file)
return file
}
}
data class File(override val name: String, val size: Int) : Node(name) {
override fun getTotalSize(): Int = size
}
}
| 0 | Kotlin | 0 | 0 | bd243c61bf8aae81daf9e50b2117450c4f39e18c | 4,869 | kotlin-advent-2022 | Apache License 2.0 |
src/chapter3/section2/ex6.kt | w1374720640 | 265,536,015 | false | {"Kotlin": 1373556} | package chapter3.section2
import chapter3.section1.testOrderedST
import extensions.random
/**
* 为二叉查找树添加一个方法height()来计算树的高度
* 实现两种方案:一种使用递归(用时为线性级别,所需空间和树高度成正比)
* 一种模仿size()在每个结点种添加一个变量(所需空间为线性级别,查询耗时为常数)
*/
fun <K : Comparable<K>, V : Any> BinarySearchTree<K, V>.height(): Int {
if (isEmpty()) return 0
return height(root!!)
}
fun <K : Comparable<K>, V : Any> height(node: BinarySearchTree.Node<K, V>): Int {
var leftHeight = 0
var rightHeight = 0
if (node.left != null) {
leftHeight = height(node.left!!)
}
if (node.right != null) {
rightHeight = height(node.right!!)
}
return maxOf(leftHeight, rightHeight) + 1
}
/**
* 继承BinarySearchTree和BinarySearchTree.Node,在put方法种将所有结点替换为HeightNode
* 在put、deleteMin、deleteMax、delete方法中重新计算路径上子树的高度
*/
class BinarySearchTreeHeight<K : Comparable<K>, V : Any> : BinarySearchTree<K, V>() {
class HeightNode<K : Comparable<K>, V : Any>(key: K,
value: V,
left: Node<K, V>? = null,
right: Node<K, V>? = null,
count: Int = 1,
var height: Int = 1) : Node<K, V>(key, value, left, right, count)
override fun put(key: K, value: V) {
if (root == null) {
//将父类默认的Node替换为HeightNode
root = HeightNode(key, value)
} else {
put(root!!, key, value)
}
}
override fun put(node: Node<K, V>, key: K, value: V) {
when {
node.key > key -> {
if (node.left == null) {
node.left = HeightNode(key, value)
} else {
put(node.left!!, key, value)
}
}
node.key < key -> {
if (node.right == null) {
node.right = HeightNode(key, value)
} else {
put(node.right!!, key, value)
}
}
else -> node.value = value
}
node.count = size(node.left) + size(node.right) + 1
if (node is HeightNode) {
calculateHeight(node)
}
}
fun height(): Int {
return height(root)
}
private fun height(node: Node<K, V>?): Int {
return if (node is HeightNode) {
node.height
} else 0
}
private fun calculateHeight(node: HeightNode<K, V>) {
node.height = maxOf(height(node.left), height(node.right)) + 1
}
override fun deleteMin(node: Node<K, V>): Node<K, V>? {
val result = super.deleteMin(node)
if (result is HeightNode) {
calculateHeight(result)
}
return result
}
override fun deleteMax(node: Node<K, V>): Node<K, V>? {
val result = super.deleteMax(node)
if (result is HeightNode) {
calculateHeight(result)
}
return result
}
override fun delete(node: Node<K, V>, key: K): Node<K, V>? {
val result = super.delete(node, key)
if (result is HeightNode) {
calculateHeight(result)
}
return result
}
}
fun main() {
testOrderedST(BinarySearchTreeHeight())
val array = Array(100) { random(10000) }
val st1 = BinarySearchTree<Int, Int>()
val st2 = BinarySearchTreeHeight<Int, Int>()
array.forEach {
st1.put(it, 0)
st2.put(it, 0)
}
println("st1.height=${st1.height()}")
println("st2.height=${st2.height()}")
st1.deleteMin()
st1.deleteMax()
st2.deleteMin()
st2.deleteMax()
println("st1.height=${st1.height()}")
println("st2.height=${st2.height()}")
repeat(40) {
val index = random(array.size)
val key = array[index]
if (st1.contains(key)) {
st1.delete(key)
st2.delete(key)
}
}
println("st1.height=${st1.height()}")
println("st2.height=${st2.height()}")
Array(100) { random(10000) }.forEach {
st1.put(it, 0)
st2.put(it, 0)
}
println("st1.height=${st1.height()}")
println("st2.height=${st2.height()}")
} | 0 | Kotlin | 1 | 6 | 879885b82ef51d58efe578c9391f04bc54c2531d | 4,518 | Algorithms-4th-Edition-in-Kotlin | MIT License |
src/y2022/Day01.kt | a3nv | 574,208,224 | false | {"Kotlin": 34115, "Java": 1914} | package y2022
import utils.readInput
fun main() {
fun foldIt(input: List<String>): List<Int> {
return input.fold(mutableListOf(0)) { acc, next ->
if (next.isNotBlank()) acc[acc.lastIndex] = next.toInt() + acc.last() else acc.add(0) // this is the first argument - operation
acc // this is the second argument - accumulator
}
}
fun part1(input: List<String>): Int {
return foldIt(input).max()
}
fun part2(input: List<String>): Int {
return foldIt(input).sorted().takeLast(3).sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("y2022","Day01_test")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
println(part1(testInput))
println(part2(testInput))
val input = readInput("y2022","Day01")
check(part1(input) == 68787)
check(part2(input) == 198041)
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | ab2206ab5030ace967e08c7051becb4ae44aea39 | 995 | advent-of-code-kotlin | Apache License 2.0 |
src/y2022/Day02.kt | Yg0R2 | 433,731,745 | false | null | package y2022
import DayX
import y2022.Day02.Results.DRAW
import y2022.Day02.Results.LOOS
import y2022.Day02.Results.WIN
import y2022.Day02.Signals.PAPER
import y2022.Day02.Signals.ROCK
import y2022.Day02.Signals.SCISSORS
class Day02 : DayX<Int>(15, 12) {
/**
* A, X => Rock (1 point)
* B, Y => Paper (2 points)
* C, Z => Scissors (3 points)
*
* Loos: 0 points
* Draw: 3 points
* Win: 6 points
*/
override fun part1(input: List<String>): Int =
input.sumOf {
val opponent = Signals.getByShape(it[0])
val me = Signals.getByShape(it[2])
val outcome = when (opponent) {
ROCK -> {
when (me) {
ROCK -> DRAW
PAPER -> WIN
SCISSORS -> LOOS
}
}
PAPER -> {
when (me) {
ROCK -> LOOS
PAPER -> DRAW
SCISSORS -> WIN
}
}
SCISSORS -> {
when (me) {
ROCK -> WIN
PAPER -> LOOS
SCISSORS -> DRAW
}
}
}
outcome.point + me.point
}
/**
* A => Rock (1 point)
* B => Paper (2 points)
* C => Scissors (3 points)
*
* X => Loos (0 points)
* Y => Draw (3 points)
* Z => Win (6 points)
*/
override fun part2(input: List<String>): Int =
input.sumOf {
val opponent = Signals.getByShape(it[0])
val outcome = Results.getByOutcome(it[2])
val me = when (opponent) {
ROCK -> {
when (outcome) {
LOOS -> SCISSORS
DRAW -> ROCK
WIN -> PAPER
}
}
PAPER -> {
when (outcome) {
LOOS -> ROCK
DRAW -> PAPER
WIN -> SCISSORS
}
}
SCISSORS -> {
when (outcome) {
LOOS -> PAPER
DRAW -> SCISSORS
WIN -> ROCK
}
}
}
outcome.point + me.point
}
private enum class Results(
val point: Int,
val outcome: Char
) {
LOOS(0, 'X'),
DRAW(3, 'Y'),
WIN(6, 'Z');
companion object {
fun getByOutcome(outcome: Char) =
values().firstOrNull {
it.outcome == outcome
} ?: throw IllegalArgumentException("Not found outcome for $outcome")
}
}
private enum class Signals(
val point: Int,
vararg val shapes: Char
) {
ROCK(1, 'A', 'X'),
PAPER(2, 'B', 'Y'),
SCISSORS(3, 'C', 'Z');
companion object {
fun getByShape(shape: Char): Signals =
values().firstOrNull {
it.shapes.contains(shape)
} ?: throw IllegalArgumentException("Not found signal for $shape")
}
}
}
| 0 | Kotlin | 0 | 0 | d88df7529665b65617334d84b87762bd3ead1323 | 3,371 | advent-of-code | Apache License 2.0 |
src/Day06.kt | sbaumeister | 572,855,566 | false | {"Kotlin": 38905} | fun main() {
fun part1(input: List<String>): Int {
val chars = input.first().toCharArray().toList()
repeat(chars.size) { i ->
val endIdx = i + 4
if (chars.subList(i, endIdx).distinct().size == 4) {
return endIdx
}
}
return 0
}
fun part2(input: List<String>): Int {
val chars = input.first().toCharArray().toList()
repeat(chars.size) { i ->
val endIdx = i + 14
if (chars.subList(i, endIdx).distinct().size == 14) {
return endIdx
}
}
return 0
}
val testInput = readInput("Day06_test")
check(part1(testInput) == 10)
check(part2(testInput) == 29)
val input = readInput("Day06")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | e3afbe3f4c2dc9ece1da7cf176ae0f8dce872a84 | 831 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/djei/balltree/BallTree.kt | Djei | 492,503,847 | false | {"Kotlin": 19152} | package com.djei.balltree
import java.util.*
class BallTree(
points: List<Point>,
private val distance: (Point, Point) -> Double,
maxDepth: Int
) {
val root: BallTreeNode = BallTreeNode(points, distance, maxDepth)
init {
val queue = LinkedList<BallTreeNode>()
queue.push(root)
while (queue.isNotEmpty()) {
val node = queue.pop()
val childs = node.split()
node.childs = childs
if (childs.first != null) {
queue.push(childs.first)
}
if (childs.second != null) {
queue.push(childs.second)
}
}
}
fun getKNearestNeighbours(target: Point, k: Int): List<Point> {
val result = PriorityQueue(compareBy<Pair<Point, Double>> { it.second }.reversed())
computeKNearestNeighbours(target, k, result, root)
return result.map { it.first }
}
fun getPointsWithinRange(target: Point, range: Double): List<Point> {
val result = mutableListOf<Point>()
computePointsWithinRange(target, range, result, root)
return result
}
private fun computeKNearestNeighbours(
target: Point,
k: Int,
neighbours: PriorityQueue<Pair<Point, Double>>,
ballTreeNode: BallTreeNode
) {
if (skipBallTreeNodeKNearestNeighbours(target, k, neighbours, ballTreeNode)) {
return
} else if (ballTreeNode.childs.first == null && ballTreeNode.childs.second == null) {
ballTreeNode.points.forEach {
val distanceToTarget = distance(target, it)
if (neighbours.count() < k) {
// neighbours collection has not yet reached threshold k, always add points
neighbours.add(Pair(it, distanceToTarget))
} else if (distanceToTarget < neighbours.peek().second) {
// neighbours collection has reached threshold k, only add point if it is closer than the furthest
neighbours.add(Pair(it, distanceToTarget))
// then remove point that is the furthest away
neighbours.poll()
}
}
} else {
val child1 = ballTreeNode.childs.first
val child2 = ballTreeNode.childs.second
if (child1 != null && child2 == null) {
computeKNearestNeighbours(target, k, neighbours, child1)
} else if (child1 == null && child2 != null) {
computeKNearestNeighbours(target, k, neighbours, child2)
} else if (child1 != null && child2 != null) {
listOf(child1, child2)
.sortedBy { distance(target, it.centroid) }
.forEach {
computeKNearestNeighbours(target, k, neighbours, it)
}
}
}
}
private fun skipBallTreeNodeKNearestNeighbours(
target: Point,
k: Int,
neighbours: PriorityQueue<Pair<Point, Double>>,
ballTreeNode: BallTreeNode
): Boolean {
return if (neighbours.count() == k) {
// ball tree node can be skipped if all its points are further than our current furthest neighbour
// this is where search speed can be gained, skipping nodes and their content from needing to be searched
distance(target, ballTreeNode.centroid) - ballTreeNode.radius >= neighbours.peek().second
} else {
// never skip ball tree node if neighbours collection has not yet reached threshold k
false
}
}
private fun computePointsWithinRange(
target: Point,
range: Double,
pointsWithinRange: MutableList<Point>,
ballTreeNode: BallTreeNode
) {
if (skipBallTreeNodeWithinRange(target, range, ballTreeNode)) {
return
} else if (ballTreeNode.childs.first == null && ballTreeNode.childs.second == null) {
ballTreeNode.points.forEach {
if (distance(target, it) <= range) {
pointsWithinRange.add(it)
}
}
} else {
val child1 = ballTreeNode.childs.first
val child2 = ballTreeNode.childs.second
if (child1 != null && child2 == null) {
computePointsWithinRange(target, range, pointsWithinRange, child1)
} else if (child1 == null && child2 != null) {
computePointsWithinRange(target, range, pointsWithinRange, child2)
} else if (child1 != null && child2 != null) {
listOf(child1, child2)
.sortedBy { distance(target, it.centroid) }
.forEach {
computePointsWithinRange(target, range, pointsWithinRange, it)
}
}
}
}
private fun skipBallTreeNodeWithinRange(target: Point, range: Double, ballTreeNode: BallTreeNode): Boolean {
return distance(target, ballTreeNode.centroid) - ballTreeNode.radius > range
}
} | 0 | Kotlin | 0 | 0 | dbd801c2189c9b67a3904c7be33b9b055216babb | 5,120 | balltree | MIT License |
src/Day05.kt | vonElfvin | 572,857,181 | false | {"Kotlin": 11658} | fun main() {
fun solve(input: List<String>, reversed: Boolean): String {
val boxRegex = "[A-Z]".toRegex()
val boxes: MutableMap<Int, List<Pair<Int, Char>>> = mutableMapOf()
var row = 0
do {
val rowBoxes = boxRegex.findAll(input[row]).toList().map { Pair((it.range.first - 1) / 4 + 1, it.value[0]) }
if (rowBoxes.isNotEmpty()) boxes[row] = rowBoxes
row += 1
} while (input[row] != "")
row += 1
val piles: MutableMap<Int, List<Char>> = mutableMapOf()
boxes.entries.reversed().forEach { (_, row) ->
row.forEach { (pileNumber, letter) ->
piles[pileNumber] = (piles[pileNumber] ?: emptyList()) + letter
}
}
do {
val instruction = input[row]
val numbers = "\\d+".toRegex().findAll(instruction).toList().map { it.value.toInt() }
val (quantity, from, to) = numbers
val move = piles[from]!!.takeLast(quantity)
piles[to] = piles[to]!! + if (reversed) move.reversed() else move
piles[from] = piles[from]!!.dropLast(quantity)
row += 1
} while (row < input.size)
return piles.values.map { it.last() }.joinToString("")
}
val input = readInput("Day05")
println(solve(input, true))
println(solve(input, false))
} | 0 | Kotlin | 0 | 0 | 6210f23f871f646fcd370ec77deba17da4196efb | 1,373 | Advent-of-Code-2022 | Apache License 2.0 |
src/main/java/leetcode/searchmatrix2/Solution.kt | thuytrinh | 106,045,038 | false | null | package leetcode.searchmatrix2
sealed class Result
object Found : Result()
data class NotFoundYet(val maxIndex: Int) : Result()
/**
* https://leetcode.com/problems/search-a-2d-matrix-ii/description/
*/
class Solution {
// a = [7, 8, 11, 15, 15], target = 12
private fun IntArray.bs(
left: Int = 0, // left = 3
right: Int = size - 1, // right = 2
target: Int // target = 12
): Result {
if (left > right) {
return NotFoundYet(right)
}
val middle = (left + right) / 2 // middle = 3
val m = this[middle] // m = 15
return when {
m == target -> Found // false
m < target -> bs(middle + 1, right, target) // false
else -> bs(left, middle - 1, target) // true
}
}
fun searchMatrix(matrix: Array<IntArray>, target: Int): Boolean {
if (matrix.isEmpty() || matrix.first().isEmpty()) {
return false
}
var rightIndex = matrix.first().size - 1
matrix.takeWhile { it.first() <= target }
.forEach {
val r = it.bs(right = rightIndex, target = target)
when (r) {
is Found -> return true
is NotFoundYet -> rightIndex = r.maxIndex
}
}
return false
}
}
| 0 | Kotlin | 0 | 1 | 23da0286a88f855dcab1999bcd7174343ccc1164 | 1,213 | algorithms | MIT License |
src/main/kotlin/com/groundsfam/advent/y2021/d10/Day10.kt | agrounds | 573,140,808 | false | {"Kotlin": 281620, "Shell": 742} | package com.groundsfam.advent.y2021.d10
import com.groundsfam.advent.DATAPATH
import com.groundsfam.advent.timed
import kotlin.io.path.div
import kotlin.io.path.useLines
val syntaxScores = mapOf(
')' to 3,
']' to 57,
'}' to 1197,
'>' to 25137,
)
val autocompleteScores = mapOf(
')' to 1,
']' to 2,
'}' to 3,
'>' to 4,
)
val openToClose = mapOf(
'(' to ')',
'[' to ']',
'{' to '}',
'<' to '>',
)
fun findIllegalChar(line: String): Int? {
val stack = ArrayDeque<Char>()
line.forEach { c ->
if (c in openToClose.keys) {
stack.add(c)
} else {
val expectedChar = stack.removeLastOrNull()
?.let { openToClose[it] }
if (c != expectedChar) {
return syntaxScores[c]
}
}
}
return null
}
fun scoreCompletion(line: String): Long {
val stack = ArrayDeque<Char>()
line.forEach { c ->
if (c in openToClose.keys) {
stack.add(c)
} else {
stack.removeLast()
}
}
var score = 0L
while (stack.isNotEmpty()) {
score *= 5
score += autocompleteScores[openToClose[stack.removeLast()]!!]!!
}
return score
}
fun main() = timed {
var totalSyntaxScore = 0
val completionScores = mutableListOf<Long>()
(DATAPATH / "2021/day10.txt").useLines { lines ->
lines.forEach { line ->
val syntaxScore = findIllegalChar(line)
if (syntaxScore != null) {
totalSyntaxScore += syntaxScore
} else {
completionScores.add(scoreCompletion(line))
}
}
}
println("Part one: $totalSyntaxScore")
completionScores.sorted()[completionScores.size / 2]
.also { println("Part two: $it") }
}
| 0 | Kotlin | 0 | 1 | c20e339e887b20ae6c209ab8360f24fb8d38bd2c | 1,832 | advent-of-code | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/RestoreTheArray.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import dev.shtanko.algorithms.DECIMAL
import dev.shtanko.algorithms.MOD
import kotlin.math.min
/**
* 1416. Restore The Array
* @see <a href="https://leetcode.com/problems/restore-the-array/">Source</a>
*/
fun interface RestoreTheArray {
fun numberOfArrays(s: String, k: Int): Int
}
/**
* Approach 1: Dynamic Programming (Top Down)
*/
class RestoreTheArrayTopDown : RestoreTheArray {
override fun numberOfArrays(s: String, k: Int): Int {
val m: Int = s.length
val dp = IntArray(m + 1)
return dfs(dp, 0, s, k)
}
// Number of possible splits for substring s[start ~ m-1].
private fun dfs(dp: IntArray, start: Int, s: String, k: Int): Int {
// If we have already updated dp[start], return it.
if (dp[start] != 0) return dp[start]
// There is only 1 split for an empty string.
if (start == s.length) return 1
// Number can't have leading zeros.
if (s[start] == '0') return 0
// For all possible starting number, add the number of arrays
// that can be printed as the remaining string to count.
var count = 0
for (end in start until s.length) {
val currNumber = s.substring(start, end + 1)
if (currNumber.toLong() > k) break
count = (count + dfs(dp, end + 1, s, k)) % MOD
}
// Update dp[start] so we don't recalculate it later.
dp[start] = count
return count
}
}
/**
* Approach 2: Dynamic Programming (Bottom Up)
*/
class RestoreTheArrayBottomUp : RestoreTheArray {
override fun numberOfArrays(s: String, k: Int): Int {
val m: Int = s.length
// dp[i] records the number of arrays that can be printed as
// the prefix substring s[0 ~ i - 1]
val dp = IntArray(m + 1)
// Empty string has 1 valid split.
dp[0] = 1
// Iterate over every digit, for each digit s[start]
for (start in 0 until m) {
if (s[start] == '0') continue
// Iterate over ending digit end and find all valid numbers
// s[start ~ end].
for (end in start until m) {
val currNumber: String = s.substring(start, end + 1)
if (currNumber.toLong() > k) break
// If s[start ~ end] is valid, increment dp[end + 1] by dp[start].
dp[end + 1] = (dp[end + 1] + dp[start]) % MOD
}
}
return dp[m]
}
}
class RestoreTheArrayMemoization : RestoreTheArray {
override fun numberOfArrays(s: String, k: Int): Int {
val dp = arrayOfNulls<Int>(s.length) // dp[i] is number of ways to print valid arrays from string s start at i
return dfs(s, k.toLong(), 0, dp)
}
private fun dfs(s: String, k: Long, i: Int, dp: Array<Int?>): Int {
if (i == s.length) return 1 // base case -> Found a valid way
if (s[i] == '0') return 0 // all numbers are in range [1, k] and there are no leading zeros ->
// So numbers starting with 0 mean invalid!
if (dp[i] != null) return dp[i] ?: -1
var ans = 0
var num: Long = 0
for (j in i until s.length) {
num = num * DECIMAL + s[j].code.toLong() - '0'.code.toLong() // num is the value of the substring s[i..j]
if (num > k) break // num must be in range [1, k]
ans += dfs(s, k, j + 1, dp)
ans %= MOD
}
return ans.also { dp[i] = it }
}
}
class RestoreTheArrayDP : RestoreTheArray {
override fun numberOfArrays(s: String, k: Int): Int {
val mod = MOD
val n: Int = s.length
val dp = IntArray(n + 1)
dp[0] = 1
// dp[i] = count of possible arrays for i length string
for (i in 1..n) {
var ans = 0
val start = n - i // reading string from end
// taking min because we can have maximum 9-digit number
for (j in start until min(n, start + 9)) {
val num = s.substring(start, j + 1)
if (num[0] == '0') continue
val value = num.toInt()
ans = if (value <= k) { // if number is valid
(ans + dp[n - j - 1]) % mod
} else {
// if current number is greater than k , then number formed after this number
// also greater than k , so break loop
break
}
}
dp[i] = ans % mod
}
return dp[s.length] // return answer for n len string
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 5,222 | kotlab | Apache License 2.0 |
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[145]二叉树的后序遍历.kt | maoqitian | 175,940,000 | false | {"Kotlin": 354268, "Java": 297740, "C++": 634} | import java.util.*
import kotlin.collections.ArrayList
//给定一个二叉树,返回它的 后序 遍历。
//
// 示例:
//
// 输入: [1,null,2,3]
// 1
// \
// 2
// /
// 3
//
//输出: [3,2,1]
//
// 进阶: 递归算法很简单,你可以通过迭代算法完成吗?
// Related Topics 栈 树
// 👍 511 👎 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 postorderTraversal(root: TreeNode?): List<Int> {
//方法一 深度优先 后序遍历 左右中
var res = ArrayList<Int>()
// dfs(root,res)
//
// return res
//方法二
val result = LinkedList<Int>()
val stack = LinkedList<TreeNode>()
stack.push(root)
while (!stack.isEmpty()) {
val node = stack.removeFirst()
if (null != node) {
result.addFirst(node.`val`)
stack.addFirst(node.left)
stack.addFirst(node.right)
}
}
return result
}
private fun dfs(root: TreeNode?,res:ArrayList<Int>) {
//递归结束条件
if (root == null) return
//逻辑处理进入下层循环
if (root.left != null) dfs(root.left, res)
if (root.right != null) dfs(root.right, res)
res.add(root.`val`)
//数据reverse
}
}
//leetcode submit region end(Prohibit modification and deletion)
| 0 | Kotlin | 0 | 1 | 8a85996352a88bb9a8a6a2712dce3eac2e1c3463 | 1,654 | MyLeetCode | Apache License 2.0 |
src/main/kotlin/com/github/davio/aoc/y2022/Day10.kt | Davio | 317,510,947 | false | {"Kotlin": 405939} | package com.github.davio.aoc.y2022
import com.github.davio.aoc.general.Day
import com.github.davio.aoc.general.call
import com.github.davio.aoc.general.getInputReader
import kotlin.system.measureTimeMillis
fun main() {
println(Day10.getResultPart1())
measureTimeMillis {
println(Day10.getResultPart2())
}.call { println("Took $it ms") }
}
/**
* See [Advent of Code 2022 Day X](https://adventofcode.com/2022/day/X#part2])
*/
object Day10 : Day() {
private sealed class Command(val cyclesNeeded: Int)
private object Noop : Command(1)
private data class AddX(val amount: Int) : Command(2)
private object Cpu {
private var cyclesUsed = 0
var currentCommand: Command? = null
val busy: Boolean get() = currentCommand != null
fun performCycle(currentX: Int): Int {
val command = currentCommand!!
cyclesUsed++
val newX = when (command) {
is Noop -> {
currentX
}
is AddX -> if (cyclesUsed == command.cyclesNeeded) {
currentX + command.amount
} else {
currentX
}
}
if (cyclesUsed == command.cyclesNeeded) {
currentCommand = null
cyclesUsed = 0
}
return newX
}
}
private fun parseCommand(line: String): Command =
if (line.startsWith("addx")) {
AddX(line.split(" ")[1].toInt())
} else Noop
fun getResultPart1(): Int {
var x = 1
return getInputReader().use { reader ->
generateSequence(1) { it + 1 }.takeWhile { Cpu.busy || reader.ready() }.map { cycle ->
if (!Cpu.busy) {
val command = parseCommand(reader.readLine())
Cpu.currentCommand = command
}
val newX = Cpu.performCycle(x)
val signalStrength = if ((cycle - 20) % 40 == 0) {
cycle * x
} else {
0
}
x = newX
signalStrength
}.sum()
}
}
fun getResultPart2(): Int {
var x = 1
val crt = Array(6) { BooleanArray(40) { false } }
return getInputReader().use { reader ->
generateSequence(1) { it + 1 }.takeWhile { Cpu.busy || reader.ready() }.map { cycle ->
val rowIndex = (cycle - 1) / 40
val pixelIndex = (cycle - 1) % 40
if (!Cpu.busy) {
val command = parseCommand(reader.readLine())
Cpu.currentCommand = command
}
val newX = Cpu.performCycle(x)
crt[rowIndex][pixelIndex] = pixelIndex in (x - 1..x + 1)
drawCrt(crt)
x = newX
0
}.sum()
}
}
private fun drawCrt(crt: Array<BooleanArray>) {
println("=".repeat(crt[0].size))
(0..crt.lastIndex).forEach { y ->
(0..crt[0].lastIndex).forEach { x ->
if (crt[y][x]) print("#") else print(".")
}
println()
}
}
}
| 1 | Kotlin | 0 | 0 | 4fafd2b0a88f2f54aa478570301ed55f9649d8f3 | 3,271 | advent-of-code | MIT License |
platform/ml-impl/src/com/intellij/internal/ml/models/local/LocalRandomForestModel.kt | JetBrains | 2,489,216 | false | null | package com.intellij.internal.ml.models.local
import com.intellij.internal.ml.DecisionFunction
import com.intellij.internal.ml.FeaturesInfo
import com.intellij.internal.ml.completion.CompletionRankingModelBase
private class Tree(val thresholds: List<Double>,
val values: List<Double>,
val features: List<Int>,
val left: List<Int>,
val right: List<Int>) {
private fun traverse(node: Int, featuresValues: DoubleArray): Double {
assert (node != -1)
return if (left[node] != -1) {
val featureId = features[node]
val featureValue = featuresValues[featureId]
val threshold = thresholds[node]
if (featureValue <= threshold) {
traverse(left[node], featuresValues)
}
else {
traverse(right[node], featuresValues)
}
}
else {
values[node]
}
}
fun predict(featuresValues: DoubleArray): Double {
return traverse(0, featuresValues)
}
}
private class TreesModel {
private val trees: ArrayList<Tree> = ArrayList()
fun addTree(thresholds: List<Double>,
values: List<Double>,
features: List<Int>,
left: List<Int>,
right: List<Int>) {
trees.add(Tree(thresholds, values, features, left, right))
}
fun predict(featuresValues: DoubleArray?): Double {
if (featuresValues == null) return 0.0
val koef = 1.0 / trees.size
val sum = trees.stream()
.mapToDouble { it.predict(featuresValues) }
.sum()
return sum * koef
}
}
class LocalRandomForestModel private constructor(metadata: FeaturesInfo, private val treesModel: TreesModel)
: CompletionRankingModelBase(metadata) {
override fun predict(features: DoubleArray?): Double = treesModel.predict(features)
companion object {
fun loadModel(modelText: String, metadata: FeaturesInfo): DecisionFunction {
val forest = readTreesModel(modelText)
return LocalRandomForestModel(metadata, forest)
}
private fun readTreesModel(modelText: String): TreesModel {
val reader = modelText.reader().buffered()
val treesModel = TreesModel()
val numberOfTrees = reader.readLine().toInt()
for (i in 0 until numberOfTrees) {
val left = reader.readLine().split(" ").map { it.toInt() }
val right = reader.readLine().split(" ").map { it.toInt() }
val thresholds = reader.readLine().split(" ").map { it.toDouble() }
val features = reader.readLine().split(" ").map { it.toInt() }
val values = reader.readLine().split(" ").map { it.toDouble() }
treesModel.addTree(thresholds, values, features, left, right)
}
return treesModel
}
}
} | 251 | null | 5,079 | 16,158 | 831d1a4524048aebf64173c1f0b26e04b61c6880 | 2,726 | intellij-community | Apache License 2.0 |
src/Day04_2.kt | FuKe | 433,722,611 | false | {"Kotlin": 19825} | import models.BingoPlate
fun main() {
val rawInput: List<String> = readInput("Day04.txt")
val numbersToDrawn: List<Int> = rawInput[0].split(",").map { it.toInt() }
val bingoPlates: List<BingoPlate> = parseBingoPlates(rawInput)
val (winningNumber, lastPlateToWin) = play(numbersToDrawn, bingoPlates)
val score = winningNumber * lastPlateToWin.sumOfUnmarkedNumbers()
println("Last plate to win: \n")
println(lastPlateToWin)
println()
println("Score: $score")
}
private fun play(numbersToDraw: List<Int>, plates: List<BingoPlate>): Pair<Int, BingoPlate> {
var winningPlates: List<Pair<Int, BingoPlate>> = emptyList()
numbersToDraw.forEach { num ->
plates.forEach { plate ->
if (!plate.hasCompleteColumn() && !plate.hasCompleteRow()) {
if (plate.plateHasNumber(num)) {
plate.markNumber(num)
}
if (plate.hasCompleteColumn() || plate.hasCompleteRow()) {
winningPlates = winningPlates + Pair(num, plate)
}
}
}
}
return winningPlates.last()
}
| 0 | Kotlin | 0 | 0 | 1cfe66aedd83ea7df8a2bc26c453df257f349b0e | 1,139 | advent-of-code-2021 | Apache License 2.0 |
day02/kotlin/gysel/src/main/kotlin/Main.kt | rdmueller | 158,926,869 | false | null | import java.util.concurrent.atomic.AtomicInteger
fun main(args: Array<String>) {
/*
part one
*/
val exactlyTwo = AtomicInteger(0)
val exactlyThree = AtomicInteger(0)
openStream().reader().useLines { lines: Sequence<String> ->
lines.map(::groupByCharacter)
.forEach {
if (it.containsValue(2))
exactlyTwo.incrementAndGet()
if (it.containsValue(3))
exactlyThree.incrementAndGet()
}
}
println("Exactly two: $exactlyTwo")
println("Exactly three: $exactlyThree")
println("Checksum: ${exactlyTwo.get() * exactlyThree.get()}")
/*
part two
*/
val lines = openStream().reader().readLines()
calculateCombinations(lines)
.filter { numberOfChangedCharacters(it) == 1 }
.forEach { pair ->
println("found correct box id: $pair")
val commonCharacters = pair.first.toCharArray()
.zip(pair.second.toCharArray())
.filter { it.first == it.second }
.map { it.first }
.joinToString("")
println("common characters are: $commonCharacters")
}
}
fun groupByCharacter(input: String): Map<Char, Int> {
return input.toCharArray().toList()
.groupingBy { it }.eachCount()
}
fun calculateCombinations(values: List<String>): Sequence<Pair<String, String>> {
val lastIndex = values.size - 1
// combine two Ranges into a List<List<Pair>> and then flatten() them
return (0..(lastIndex - 1)).asSequence().map { left ->
((left + 1)..lastIndex).map { right ->
values[left] to values[right]
}
}.flatten()
}
fun numberOfChangedCharacters(pair: Pair<String, String>): Int {
val (a, b) = pair
if (a.length != b.length) throw IllegalStateException("Strings need to be of equals size!")
return a.toCharArray().zip(b.toCharArray()).count { it.first != it.second }
}
// object {} is a little hack as Java needs a class to open a resource from the classpath
private fun openStream() = object {}::class.java.getResourceAsStream("/day02.txt") | 26 | HTML | 18 | 19 | 1a0e6d89d5594d4e6e132172abea78b41be3850b | 2,251 | aoc-2018 | MIT License |
solutions/src/MiniumSizeSubArraySum.kt | JustAnotherSoftwareDeveloper | 139,743,481 | false | {"Kotlin": 305071, "Java": 14982} | import kotlin.math.min
/**
* https://leetcode.com/problems/minimum-size-subarray-sum/
*/
class MiniumSizeSubArraySum {
fun minSubArrayLen(s: Int, nums: IntArray) : Int {
if (nums.isEmpty()) {
return 0
}
var minLength : Int? = null
var lower = 0
var upper = 0
var sumAtLower = IntArray(nums.size)
var sumUpper = IntArray(nums.size)
val totalSum = nums.sum()
for(i in nums.indices) {
if (i == 0) {
sumAtLower[0] = nums[0]
}
else {
sumAtLower[i]=nums[i]+sumAtLower[i-1]
}
}
for (i in nums.lastIndex downTo 0) {
if (i == nums.lastIndex) {
sumUpper[i] = nums[i]
}
else {
sumUpper[i] = nums[i]+sumUpper[i+1]
}
}
while (lower in 0..upper && upper < nums.size) {
val sum = when {
lower == 0 -> {
sumAtLower[upper]
}
upper == nums.lastIndex -> {
sumUpper[lower]
}
else -> {
totalSum - (sumAtLower[lower-1]+sumUpper[upper+1])
}
}
if (sum >= s) {
minLength = minOf(1 + (upper- lower), minLength ?: Int.MAX_VALUE)
lower++
}
else {
upper++
}
}
return minLength ?: 0
}
} | 0 | Kotlin | 0 | 0 | fa4a9089be4af420a4ad51938a276657b2e4301f | 1,535 | leetcode-solutions | MIT License |
bin/main/solutions/CHK/CheckoutSolution.kt | DPNT-Sourcecode | 749,496,960 | false | {"Kotlin": 37004, "Shell": 2184} | package solutions.CHK
object CheckoutSolution {
val prices = hashMapOf(
"A" to 50,
"B" to 30,
"C" to 20,
"D" to 15,
"E" to 40,
"F" to 10,
"G" to 20,
"H" to 10,
"I" to 35,
"J" to 60,
"K" to 80,
"L" to 90,
"M" to 15,
"N" to 40,
"O" to 10,
"P" to 50,
"Q" to 30,
"R" to 50,
"S" to 30,
"T" to 20,
"U" to 40,
"V" to 50,
"W" to 20,
"X" to 90,
"Z" to 50,
"Y" to 10
)
const val PRICE_A = 50
const val PRICE_B = 30
const val PRICE_C = 20
const val PRICE_D = 15
const val PRICE_E = 40
const val PRICE_F = 10
const val A_OFFER3 = 130
const val A_OFFER5 = 200
const val B_OFFER2 = 45
fun checkout(skus: String): Int {
if (skus.any { !listOf('A', 'B', 'C', 'D', 'E', 'F').contains(it) }) {
return -1
}
// calculating As
val offerA5 = calculateOffer(
PRICE_A,
skus.count { it == 'A' } * PRICE_A,
5,
A_OFFER5
)
val offerA3 = calculateOffer(
PRICE_A,
offerA5.second,
3,
A_OFFER3
)
val totalA = offerA5.first + offerA3.first + offerA3.second
// calculating Es
val offerE = calculateOffer(
PRICE_E,
skus.count { it == 'E' } * PRICE_E,
2,
1
)
val adjustedBCount = skus.count { it == 'B' } - offerE.first
// calculating Bs
val newB = calculateOffer(
PRICE_B,
adjustedBCount * PRICE_B,
2,
B_OFFER2
)
val totalB = newB.first + newB.second
// calculating Fs
val offerF = calculateOffer(
PRICE_F,
skus.count { it == 'F' } * PRICE_F,
3,
1
)
val totalF = (skus.count { it == 'F' } * PRICE_F) - (offerF.first * PRICE_F)
return totalA +
(if (totalB <= 0) 0 else totalB) +
(skus.count { it == 'C' } * PRICE_C) +
(skus.count { it == 'D' } * PRICE_D) +
(skus.count { it == 'E' } * PRICE_E) +
totalF
}
private fun calculateOffer(
price: Int,
total: Int,
multiplier: Int,
offer: Int
) : Pair<Int, Int> {
val leftover = total % (price * multiplier)
val reduced = ((total - leftover) / (price * multiplier)) * offer
return Pair(reduced, leftover)
}
}
| 0 | Kotlin | 0 | 0 | 2955860e9436e1b06d5a895c1418d8f1c588a938 | 2,594 | CHK-dkni01 | Apache License 2.0 |
src/main/kotlin/adventofcode/y2021/Day03.kt | Tasaio | 433,879,637 | false | {"Kotlin": 117806} | import adventofcode.applyToEachColumn
import adventofcode.binaryStringToInt
fun main() {
val day = Day03()
println(day.part1())
day.reset()
println(day.part2())
}
class Day03 : Y2021Day(3) {
private val input = fetchInput()
override fun part1(): Number? {
val gamma = input.applyToEachColumn {
if (it.count { it == '1' } > it.count { it == '0' }) '1' else '0'
}
val epsilon = input.applyToEachColumn {
if (it.count { it == '1' } > it.count { it == '0' }) '0' else '1'
}
return gamma.binaryStringToInt() * epsilon.binaryStringToInt()
}
override fun part2(): Number? {
val skipOxy = Array(input.size) { false }
val skipCo2 = Array(input.size) { false }
for (i in 0 until input[0].length) {
var countOxy = 0
var countCo2 = 0
input.indices.forEach {
if (!skipOxy[it]) countOxy += if (input[it][i] == '1') 1 else -1
if (!skipCo2[it]) countCo2 += if (input[it][i] == '1') 1 else -1
}
if (skipOxy.count { it } < input.size - 1) {
input.indices.forEach {
val skipBit = if (countOxy >= 0) '0' else '1'
if (input[it][i] == skipBit) {
skipOxy[it] = true
}
}
}
if (skipCo2.count { it } < input.size - 1) {
input.indices.forEach {
val skipBit = if (countCo2 >= 0) '1' else '0'
if (input[it][i] == skipBit) {
skipCo2[it] = true
}
}
}
}
val oxy = input[ skipOxy.indexOf(false) ]
val co2 = input[ skipCo2.indexOf(false) ]
return Integer.parseInt(oxy, 2) * Integer.parseInt(co2, 2)
}
}
| 0 | Kotlin | 0 | 0 | cc72684e862a782fad78b8ef0d1929b21300ced8 | 1,897 | adventofcode2021 | The Unlicense |
google/2019/qualification_round/3/main.kt | seirion | 17,619,607 | false | {"C++": 801740, "HTML": 42242, "Kotlin": 37689, "Python": 21759, "C": 3798, "JavaScript": 294} | import java.math.BigInteger
import java.util.*
fun main(args: Array<String>) {
val t = readLine()!!.toInt()
(1..t).forEach {
print("Case #$it: ")
solve()
}
}
val ZERO = BigInteger("0")
fun solve() {
val out = ArrayList<BigInteger>()
var prev = BigInteger("0")
var next = BigInteger("0")
readLine()
readLine()!!.split("\\s".toRegex()).map(::BigInteger).forEach { now ->
if (prev == ZERO) { // 0
out.add(now)
} else if (next == ZERO) { // not determined
if (prev == now) {
out.add(now)
} else {
val p = gcd(prev, now)
out.add(p)
determine(out)
next = now.divide(p)
}
} else {
out.add(next)
next = now.divide(next)
}
prev = now
}
out.add(next)
val m = TreeMap<BigInteger, Char>()
TreeSet<BigInteger>(out).forEachIndexed { i, v -> m[v] = 'A' + i }
out.forEach { print(m[it]) }
println("")
}
fun determine(out: ArrayList<BigInteger>) {
for (i in out.size - 2 downTo 0) {
out[i] = out[i].divide(out[i + 1])
}
}
fun gcd(a: BigInteger, b: BigInteger): BigInteger {
val c = a.mod(b)
return if (c == BigInteger("0")) b else gcd(b, c)
}
| 0 | C++ | 4 | 4 | a59df98712c7eeceabc98f6535f7814d3a1c2c9f | 1,321 | code | Apache License 2.0 |
src/main/kotlin/day06/boats.kt | cdome | 726,684,118 | false | {"Kotlin": 17211} | package day06
import java.io.File
import kotlin.math.ceil
import kotlin.math.sqrt
fun main() {
races()
singleRace()
}
private fun races() {
val file = File("src/main/resources/day06-boats").readLines()
val times = file[0].split(":")[1].trim().split(" ").filter { it.isNotBlank() }.map { it.toLong() }
val distances = file[1].split(":")[1].trim().split(" ").filter { it.isNotBlank() }.map { it.toLong() }
times.indices
.map { possibilities(times[it], distances[it]) }
.reduce(Int::times)
.let { println("Multiple races possibilities: $it") }
}
private fun singleRace() {
val file = File("src/main/resources/day06-boats").readLines()
val time = file[0].split(":")[1].replace(" ", "").toLong()
val distance = file[1].split(":")[1].replace(" ", "").toLong()
println("Single race possibilities: ${possibilities(time, distance)}")
}
private fun possibilities(t: Long, d: Long): Int {
val base = (t - sqrt(t * t - 4 * d.toDouble())) / 2
val lowerLimit = if (base == ceil(base)) base + 1 else ceil(base)
return (t - 2 * lowerLimit + 1).toInt()
} | 0 | Kotlin | 0 | 0 | 459a6541af5839ce4437dba20019b7d75b626ecd | 1,119 | aoc23 | The Unlicense |
src/main/kotlin/wtf/log/xmas2021/day/day16/Day16.kt | damianw | 434,043,459 | false | {"Kotlin": 62890} | package wtf.log.xmas2021.day.day16
import wtf.log.xmas2021.Day
import wtf.log.xmas2021.util.collect.removeFirst
import wtf.log.xmas2021.util.math.toBits
import wtf.log.xmas2021.util.math.toInt
import wtf.log.xmas2021.util.math.toLong
import java.io.BufferedReader
import java.util.*
/**
* It would be better to use a BitSet or BigInteger but collections are so much easier to deal with.
*/
object Day16 : Day<Packet, Int, Long> {
override fun parseInput(reader: BufferedReader): Packet {
val bits = reader.readLine().flatMap { it.digitToInt(16).toBits().takeLast(4) }
return parsePacket(ArrayDeque(bits))
}
private fun parsePacket(queue: Deque<Boolean>): Packet {
val version = queue.removeFirst(3).toInt()
when (val typeId = queue.removeFirst(3).toInt()) {
4 -> {
val valueBits = mutableListOf<Boolean>()
do {
val shouldContinue = queue.removeFirst()
valueBits += queue.removeFirst(4)
} while (shouldContinue)
return Literal(
version = version,
value = valueBits.toLong(),
)
}
else -> {
val isCountType = queue.removeFirst()
if (isCountType) {
val packetCount = queue.removeFirst(11).toInt()
val subPackets = (0 until packetCount).map { parsePacket(queue) }
return Operator(
version = version,
type = Operator.Type.fromId(typeId),
subPackets = subPackets,
)
} else {
val packetLength = queue.removeFirst(15).toInt()
val startingSize = queue.size
val endingSize = startingSize - packetLength
val subPackets = mutableListOf<Packet>()
while (queue.size > endingSize) {
subPackets += parsePacket(queue)
}
return Operator(
version = version,
type = Operator.Type.fromId(typeId),
subPackets = subPackets,
)
}
}
}
}
override fun part1(input: Packet): Int = input.versionSum()
override fun part2(input: Packet): Long = input.evaluate()
}
sealed class Packet {
abstract val version: Int
abstract fun versionSum(): Int
abstract fun evaluate(): Long
}
data class Literal(
override val version: Int,
val value: Long,
) : Packet() {
override fun versionSum(): Int = version
override fun evaluate(): Long = value
}
data class Operator(
override val version: Int,
val type: Type,
val subPackets: List<Packet>,
) : Packet() {
override fun versionSum(): Int = version + subPackets.sumOf { it.versionSum() }
override fun evaluate(): Long = type.evaluate(subPackets.map { it.evaluate() })
enum class Type(val id: Int) {
SUM(0) {
override fun evaluate(values: List<Long>): Long = values.reduce(Long::plus)
},
PRODUCT(1) {
override fun evaluate(values: List<Long>): Long = values.reduce(Long::times)
},
MINIMUM(2) {
override fun evaluate(values: List<Long>): Long = values.minOf { it }
},
MAXIMUM(3) {
override fun evaluate(values: List<Long>): Long = values.maxOf { it }
},
GREATER_THAN(5) {
override fun evaluate(values: List<Long>): Long {
require(values.size == 2)
return if (values[0] > values[1]) 1L else 0L
}
},
LESS_THAN(6) {
override fun evaluate(values: List<Long>): Long {
require(values.size == 2)
return if (values[0] < values[1]) 1L else 0L
}
},
EQUAL_TO(7) {
override fun evaluate(values: List<Long>): Long {
require(values.size == 2)
return if (values[0] == values[1]) 1L else 0L
}
},
;
abstract fun evaluate(values: List<Long>): Long
companion object {
private val mapping: Map<Int, Type> = values().associateBy { it.id }
fun fromId(id: Int): Type = mapping.getValue(id)
}
}
}
| 0 | Kotlin | 0 | 0 | 1c4c12546ea3de0e7298c2771dc93e578f11a9c6 | 4,480 | AdventOfKotlin2021 | BSD Source Code Attribution |
advent2022/src/main/kotlin/year2022/Day10.kt | bulldog98 | 572,838,866 | false | {"Kotlin": 132847} | package year2022
import AdventDay
import kotlin.math.absoluteValue
class Day10 : AdventDay(2022, 10) {
class Screen(
val rows: Array<BooleanArray> =
(0 until 6)
.map { BooleanArray(40) { false } }
.toTypedArray()
) {
override fun toString(): String =
rows.joinToString("\n") { row ->
val range = (0..39)
range.joinToString("") { if (row[it]) "#" else "."}
}
}
sealed class Instruction(val cyclesNeeded: Int) {
companion object {
fun from(input: String): Instruction = when {
input == "noop" -> Noop
input.startsWith("addx ") -> AddX(input.split(" ")[1].toInt())
else -> error("should not happen")
}
}
}
data object Noop : Instruction(1)
class AddX(val v: Int) : Instruction(2) {
override fun toString(): String = "AddX($v)"
}
data class State(val program: List<Instruction>, val x: Int = 1, val cycle: Int = 0, val commandAlreadyRunningForCycles: Int = 0) {
fun tick() = when (val c = program.firstOrNull()) {
is Noop -> copy(cycle = cycle + 1, program = program.drop(1))
is AddX -> if (commandAlreadyRunningForCycles == c.cyclesNeeded - 1) {
copy(
x = x + c.v,
cycle = cycle + 1,
commandAlreadyRunningForCycles = 0,
program = program.drop(1)
)
} else {
copy(
cycle = cycle + 1,
commandAlreadyRunningForCycles = commandAlreadyRunningForCycles + 1,
)
}
null -> this
}
}
override fun part1(input: List<String>): Int {
val program = input.map { Instruction.from(it) }
var state = State(program)
var result = 0
while (state.cycle < 220) {
val next = state.tick()
if (next == state) {
break
}
if (next.cycle % 40 == 20) {
result += next.cycle * state.x
}
state = next
}
return result
}
override fun part2(input: List<String>): String {
val program = input.map { Instruction.from(it) }
val screen = Screen()
var state = State(program)
while (state.cycle < 240) {
val next = state.tick()
val row = state.cycle / 40
val pixel = state.cycle % 40
if ((state.x - pixel).absoluteValue in (-1..1)) {
screen.rows[row][pixel] = true
}
state = next
}
return screen.toString()
}
}
fun main() = Day10().run() | 0 | Kotlin | 0 | 0 | 02ce17f15aa78e953a480f1de7aa4821b55b8977 | 2,811 | advent-of-code | Apache License 2.0 |
src/main/kotlin/kt/kotlinalgs/app/dynprog/Knapsack.ws.kts | sjaindl | 384,471,324 | false | null | package com.sjaindl.kotlinalgsandroid.dynprog
// https://www.geeksforgeeks.org/0-1-knapsack-problem-dp-10/
class KnapSack {
// [60, 100, 120]
fun calculateKnapsack(values: IntArray, weights: IntArray, maxWeight: Int): Int {
val cache: MutableMap<Memo, Int> = mutableMapOf()
println("cache.size")
//val cache: Array<IntArray> = Array(weights.size) { IntArray(weights.size) }
println(cache.size)
if (values.isEmpty()) return 0
return calculateKnapsack(values, weights, maxWeight, 0, 0, 0, cache)
}
private fun calculateKnapsack(
values: IntArray, // [60, 100, 120]
weights: IntArray, // [10, 20, 30]
maxWeight: Int, // 50
index: Int, // 0
weight: Int, // 0
value: Int, // 0
cache: MutableMap<Memo, Int>
//cache: Array<IntArray>
): Int {
if (index >= values.size) return value
val memo = Memo(index, weight)
cache[memo]?.let {
//println(cache[index][weight])
//if (cache[index][weight] != 0) {
//return cache[index][weight]
return it
}
// include index or not
val newWeight = weight + weights[index] // 50
val newValue = value + values[index] // 220
var bestValue = value
if (newWeight <= maxWeight) {
bestValue =
calculateKnapsack(values, weights, maxWeight, index + 1, newWeight, newValue, cache)
}
bestValue = Math.max(
bestValue,
calculateKnapsack(values, weights, maxWeight, index + 1, weight, value, cache)
)
//cache[index][weight] = bestValue
cache[memo] = bestValue
return bestValue
}
data class Memo(val index: Int, val weight: Int)
}
val knapsack = KnapSack()
val result = knapsack.calculateKnapsack(intArrayOf(60, 100, 120), intArrayOf(10, 20, 30), 50)
println(result)
// 19:25 - 19:55
/*
input: int[] weights, int[] values, maxWeight
output: int (max value)
example:
values: [60, 100, 120]
weights: [10, 20, 30]
maxW: 50
-> 220 (100 + 120 with W 50)
BF:
loop thr values:
2 branches:
include, if (<= max weight)
don't include
update, if value > curMax
O(2^n), O(N) if recursively
Opt.:
Dynamic Programming
cache max value after index
*/
| 0 | Java | 0 | 0 | e7ae2fcd1ce8dffabecfedb893cb04ccd9bf8ba0 | 2,352 | KotlinAlgs | MIT License |
src/questions/SurroundedRegions.kt | realpacific | 234,499,820 | false | null | package questions
import _utils.UseCommentAsDocumentation
import utils.shouldBe
/**
* Given an `m x n` matrix board containing 'X' and 'O',
* capture all regions that are 4-directionally surrounded by 'X'.
* A region is captured by flipping all 'O's into 'X's in that surrounded region.
*
* [Source](https://leetcode.com/problems/surrounded-regions/)
*/
@UseCommentAsDocumentation
private fun solve(board: Array<CharArray>) {
val borderOs = mutableListOf<Pair<Int, Int>>()
val nonBorderOs = mutableSetOf<Pair<Int, Int>>()
val m = board.lastIndex
val n = board[0].lastIndex
for (row in 0..m) {
for (col in 0..n) {
if (board[row][col] == 'O') {
if (row == 0 || row == m || col == 0 || col == n) {
// Collect all the Os in the borders
borderOs.add(row to col)
} else {
// Collect all the inside Os
nonBorderOs.add(row to col)
}
}
}
}
traverseFromBorderOsAndRemoveConnected(board, borderOs, nonBorderOs)
}
private fun traverseFromBorderOsAndRemoveConnected(
board: Array<CharArray>,
borderOs: List<Pair<Int, Int>>,
nonBorderOs: MutableSet<Pair<Int, Int>>
) {
val connected = mutableSetOf<Pair<Int, Int>>() // collect location of Os that are connected to border Os
borderOs.forEach {
isConnectedToBorderOsOrNull(board, it, it.first + 1 to it.second, connected)
isConnectedToBorderOsOrNull(board, it, it.first to it.second + 1, connected)
isConnectedToBorderOsOrNull(board, it, it.first - 1 to it.second, connected)
isConnectedToBorderOsOrNull(board, it, it.first to it.second - 1, connected)
}
// Now that we have all the Os that are connected to the border
nonBorderOs.forEach {
if (it.first == 0 || it.first == board.lastIndex || it.second == 0 || it.second == board[0].lastIndex) {
return@forEach // ignore Os at the borders
} else if (!connected.contains(it)) {
board[it.first][it.second] = 'X' // if not connected to border, then flip it
}
}
}
private fun isConnectedToBorderOsOrNull(
board: Array<CharArray>,
src: Pair<Int, Int>,
dest: Pair<Int, Int>,
connected: MutableSet<Pair<Int, Int>>
) {
if (dest.first > board.lastIndex || dest.first < 0 || dest.second > board[0].lastIndex || dest.second < 0) {
return
}
if (connected.contains(dest)) {
return // already seen, no need to traverse
}
// These two are connected and since this is called from the bordering Os,
// so [src] & [dest] are also connected to border Os
if (board[src.first][src.second] == 'O' && board[dest.first][dest.second] == 'O') {
connected.add(dest)
isConnectedToBorderOsOrNull(board, dest, dest.first + 1 to dest.second, connected)
isConnectedToBorderOsOrNull(board, dest, dest.first to dest.second + 1, connected)
isConnectedToBorderOsOrNull(board, dest, dest.first - 1 to dest.second, connected)
isConnectedToBorderOsOrNull(board, dest, dest.first to dest.second - 1, connected)
}
}
fun main() {
run {
val board = arrayOf(
// 0 1 2 3
charArrayOf('X', 'X', 'X', 'X'), // o
charArrayOf('X', 'O', 'O', 'X'), // 1
charArrayOf('X', 'X', 'O', 'X'), // 2
charArrayOf('X', 'O', 'X', 'X') // 3
)
val expected = arrayOf(
charArrayOf('X', 'X', 'X', 'X'),
charArrayOf('X', 'X', 'X', 'X'),
charArrayOf('X', 'X', 'X', 'X'),
charArrayOf('X', 'O', 'X', 'X')
)
solve(board)
board.forEachIndexed { index, chars ->
chars shouldBe expected[index]
}
}
run {
val board = arrayOf(
charArrayOf('X', 'O', 'X', 'O', 'X', 'O'),
charArrayOf('O', 'X', 'O', 'X', 'O', 'X'),
charArrayOf('X', 'O', 'X', 'O', 'X', 'O'),
charArrayOf('O', 'X', 'O', 'X', 'O', 'X')
)
val expected =
arrayOf(
charArrayOf('X', 'O', 'X', 'O', 'X', 'O'),
charArrayOf('O', 'X', 'X', 'X', 'X', 'X'),
charArrayOf('X', 'X', 'X', 'X', 'X', 'O'),
charArrayOf('O', 'X', 'O', 'X', 'O', 'X')
)
solve(board)
board.forEachIndexed { index, chars ->
chars shouldBe expected[index]
}
}
run {
val board =
arrayOf(
charArrayOf('X', 'O', 'X', 'X'),
charArrayOf('O', 'X', 'O', 'X'),
charArrayOf('X', 'O', 'X', 'O'),
charArrayOf('O', 'X', 'O', 'X'),
charArrayOf('X', 'O', 'X', 'O'),
charArrayOf('O', 'X', 'O', 'X')
)
val expected =
arrayOf(
charArrayOf('X', 'O', 'X', 'X'),
charArrayOf('O', 'X', 'X', 'X'),
charArrayOf('X', 'X', 'X', 'O'),
charArrayOf('O', 'X', 'X', 'X'),
charArrayOf('X', 'X', 'X', 'O'),
charArrayOf('O', 'X', 'O', 'X')
)
solve(board)
board.forEachIndexed { index, chars ->
println("at index $index")
chars shouldBe expected[index]
}
}
} | 4 | Kotlin | 5 | 93 | 22eef528ef1bea9b9831178b64ff2f5b1f61a51f | 5,410 | algorithms | MIT License |
src/main/kotlin/solutions/Day14RegolithReservoir.kt | aormsby | 571,002,889 | false | {"Kotlin": 80084} | package solutions
import models.Coord2d
import models.Grid
import utils.Input
import utils.Solution
// run only this day
fun main() {
Day14RegolithReservoir()
}
class Day14RegolithReservoir : Solution() {
private val rock = '#'
private val sand = 'o'
private val sandSpout = '+'
private val air = ' '
init {
begin("Day 14 - Regolith Reservoir")
val input = Input.parseTo2dList<Coord2d>(filename = "/d14_cave_scan.txt", delimiter = " -> ")
val cave = buildCave(input)
val sol1 = simulateSandToResting(cave, hasFloor = false)
output("Resting Sand", sol1)
val sol2 = simulateSandToResting(cave, hasFloor = true)
output("Sand Spout Blocked", sol2 + sol1)
}
// system for simulating seeping sand
private fun simulateSandToResting(cave: Grid<Char>, hasFloor: Boolean): Int {
val sandSpoutPos = Coord2d(0, cave.g.first().indexOf(sandSpout))
var grainsDropped = 0
var infiniteSpill = false
while (infiniteSpill.not()) {
val grain = sandSpoutPos.copy()
var fell = true
// single grain falling
while (fell) {
fell = grain.fallIn(cave)
//part 1 end
if (fell && hasFloor.not() && grain.x == cave.g.size - 2) {
infiniteSpill = true
break
} else if (!fell) {
cave[grain] = sand
grainsDropped++
// part 2 end
if (hasFloor && grain == sandSpoutPos) {
infiniteSpill = true
break
}
}
}
}
return grainsDropped
}
// check 3 points beneath grain and fall into first open, return false if resting
private fun Coord2d.fallIn(cave: Grid<Char>): Boolean {
val beneath = listOf(
Coord2d(x + 1, y),
Coord2d(x + 1, y - 1),
Coord2d(x + 1, y + 1)
)
// check positions and fall
beneath.forEach { c ->
if (cave[c] == air) {
x = c.x
y = c.y
return true
}
}
// didn't fall
return false
}
private fun buildCave(scan: List<List<Coord2d>>): Grid<Char> {
// arbitrary size, position normalizer so I don't have to grow list
val caveSize = Coord2d(360, 360)
val caveNorm = Coord2d(0, 500 - ((caveSize.x / 2) + 1))
// empty cave
val cave = Grid(g = MutableList(size = caveSize.y) { MutableList(size = caveSize.x) { air } })
// set sand point
cave[Coord2d(0, 500) - caveNorm] = sandSpout
// add rocks
scan.forEach { line ->
line.windowed(2).forEach { pair ->
val start = pair.first().reversed() - caveNorm
val end = pair.last().reversed() - caveNorm
cave[start.rangeTo(end)] = rock
}
}
//trim
var trimSize = cave.g.takeLastWhile { line -> line.filterNot { it == air }.isEmpty() }.size
while (trimSize > 1) {
cave.g.removeLast()
trimSize--
}
// add floor
cave.g.add(MutableList(size = cave.g.last().size - 1) { rock })
return cave
}
}
| 0 | Kotlin | 0 | 0 | 1bef4812a65396c5768f12c442d73160c9cfa189 | 3,404 | advent-of-code-2022 | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/NumberOfArithmeticSlices.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
/**
* 446. Arithmetic Slices II - Subsequence
* @see <a href="https://leetcode.com/problems/arithmetic-slices-ii-subsequence/">Source</a>
*/
fun interface NumberOfArithmeticSlices {
operator fun invoke(nums: IntArray): Int
}
class NumberOfArithmeticSlicesBruteForce : NumberOfArithmeticSlices {
private var size = 0
private var ans = 0
override operator fun invoke(nums: IntArray): Int {
size = nums.size
ans = 0
val cur: MutableList<Long> = ArrayList()
dfs(0, nums, cur)
return ans
}
private fun dfs(dep: Int, nums: IntArray, cur: MutableList<Long>) {
if (dep == size) {
if (cur.size < 3) {
return
}
val diff = cur[1] - cur[0]
for (i in 1 until cur.size) {
if (cur[i] - cur[i - 1] != diff) {
return
}
}
ans++
return
}
dfs(dep + 1, nums, cur)
cur.add(nums[dep].toLong())
dfs(dep + 1, nums, cur)
cur.remove(nums[dep].toLong())
}
}
class NumberOfArithmeticSlicesDP : NumberOfArithmeticSlices {
override operator fun invoke(nums: IntArray): Int {
val size: Int = nums.size
var ans: Long = 0
val cnt: Array<MutableMap<Int, Int>> = Array(size) { mutableMapOf() }
for (i in 0 until size) {
cnt[i] = HashMap(i)
for (j in 0 until i) {
val delta = nums[i] - nums[j]
val sum = cnt[j].getOrDefault(delta, 0)
val origin = cnt[i].getOrDefault(delta, 0)
cnt[i][delta] = origin + sum + 1
ans += sum.toLong()
}
}
return ans.toInt()
}
}
class NumberOfArithmeticSlicesDP2 : NumberOfArithmeticSlices {
override operator fun invoke(nums: IntArray): Int {
val size: Int = nums.size
var ans = 0
val dp: Array<HashMap<Long, Int>> = Array(size) { HashMap() }
for (i in 0 until size) dp[i] = HashMap()
for (i in 1 until size) {
for (j in 0 until i) {
val diff = nums[i].toLong() - nums[j].toLong()
val cnt = dp[j].getOrDefault(diff, 0)
dp[i][diff] = dp[i].getOrDefault(diff, 0) + cnt + 1
ans += cnt
}
}
return ans
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 3,037 | kotlab | Apache License 2.0 |
src/main/kotlin/File08.kt | andrewrlee | 319,095,151 | false | null | import Challenge08.Operation.*
import java.io.File
import java.nio.charset.StandardCharsets.UTF_8
private class Challenge08 {
enum class Operation { acc, jmp, nop }
enum class Mode { ALLOW_MODIFY, NO_MODIFY }
data class Instruction(val index: Int, val op: Operation, val value: Int) {
constructor(index: Int, line: String) : this(
index,
valueOf(line.substring(0, 3)),
line.substring(3).trim().toInt()
)
val accContr: Int get() = if (op == acc) value else 0
val nextIndex: Int get() = if (op == jmp) index + value else index + 1
}
val instructions =
File("src/main/resources/08-input.txt").readLines(UTF_8).withIndex().map { Instruction(it.index, it.value) }
fun findBeforeLoop(current: Instruction, seen: List<Instruction> = listOf(current)): List<Instruction> {
if (instructions.size < current.nextIndex) return seen
val next = instructions[current.nextIndex]
return if (seen.contains(next)) seen else findBeforeLoop(next, seen + next)
}
fun findAnswer1v1(): Int = findBeforeLoop(instructions[0]).map { it.accContr }.sum()
private fun findModifiedSolution(current: Instruction, seen: List<Instruction>, mode: Mode) =
if (mode == Mode.NO_MODIFY) null else when (current.op) {
acc -> null
jmp -> current.copy(op = nop).let { findWorking(it, Mode.NO_MODIFY, seen) }
nop -> current.copy(op = jmp).let { findWorking(it, Mode.NO_MODIFY, seen) }
}
fun findWorking(current: Instruction, mode: Mode, seen: List<Instruction> = listOf(current)): List<Instruction>? {
findModifiedSolution(current, seen, mode)?.let { return it }
if (instructions.size <= current.nextIndex) return seen
val next = instructions[current.nextIndex]
return if (seen.contains(next)) return null else findWorking(next, mode, seen + next)
}
fun findAnswer2v1(): Int = findWorking(instructions[0], Mode.ALLOW_MODIFY)?.map { it.accContr }?.sum() ?: 0
fun solve() {
println(findAnswer1v1())
println(findAnswer2v1())
}
}
fun main() = Challenge08().solve() | 0 | Kotlin | 0 | 0 | a9c21a6563f42af7fada3dd2e93bf75a6d7d714c | 2,183 | adventOfCode2020 | MIT License |
src/Day01.kt | xabgesagtx | 572,139,500 | false | {"Kotlin": 23192} | fun main() {
fun readCalories(input: List<String>): List<Int> {
return input.fold(mutableListOf(mutableListOf<Int>())) {
acc, line ->
if (line.isBlank()) {
acc.add(mutableListOf())
} else {
acc.last().add(line.toInt())
}
acc
}
.filter { it.isNotEmpty() }
.map { it.sum() }
}
fun part1(input: List<String>): Int {
return readCalories(input).max()
}
fun part2(input: List<String>): Int {
return readCalories(input)
.sortedDescending()
.take(3)
.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 976d56bd723a7fc712074066949e03a770219b10 | 968 | advent-of-code-2022 | Apache License 2.0 |
src/day09/Day09_1.kt | ritesh-singh | 572,210,598 | false | {"Kotlin": 99540} | package day09
import readInput
import kotlin.math.abs
fun main() {
data class Position(val row: Int, val col: Int)
val size = 5000
val middle = size / 2
var head = Position(row = middle, col = middle)
var tail = Position(row = middle, col = middle)
var answer = 1
val visited = hashSetOf<Position>()
fun update() {
if (visited.contains(tail)) return
++answer
visited.add(tail)
}
fun moveTail(direction:String) {
// horizontal
if (head.row == tail.row) {
if (abs(head.col - tail.col) < 2) return
tail = if (head.col > tail.col) { // right
tail.copy(col = tail.col + 1)
} else { // left
tail.copy(col = tail.col - 1)
}
update()
return
}
// vertical
if (head.col == tail.col) {
if (abs(head.row - tail.row) < 2) return
tail = if (head.row < tail.row) { // up
tail.copy(row = tail.row - 1)
} else { // down
tail.copy(row = tail.row + 1)
}
update()
return
}
// diagonal
if (abs(head.row - tail.row) < 2 && abs(head.col - tail.col) < 2) return
// if (direction == "U" || direction == "D"){
// if (abs(head.row - tail.row) < 2) return
// }
//
//
// if (direction == "R" || direction == "L"){
// if (abs(head.col - tail.col) < 2) return
// }
// up
if (head.row < tail.row) {
if (head.col > tail.col) { // right
tail = tail.copy(
row = tail.row - 1,
col = tail.col + 1
)
update()
return
}
// left
tail = tail.copy(
row = tail.row - 1,
col = tail.col - 1
)
update()
return
}
// diagonal - down
if (head.col > tail.col) { // right
tail = tail.copy(
row = tail.row + 1,
col = tail.col + 1
)
update()
return
}
// left
tail = tail.copy(
row = tail.row + 1,
col = tail.col - 1
)
update()
}
fun part1(input: List<String>): Int {
head = Position(middle, middle)
tail = Position(middle, middle)
answer = 1
visited.clear()
visited.add(tail)
input.forEach {
val (direction, step) = it.split(" ").map { it.trim() }
var stepCount = step.toInt()
while (stepCount > 0) {
when (direction) {
"R" -> {
head = head.copy(col = head.col + 1)
}
"L" -> {
head = head.copy(col = head.col - 1)
}
"U" -> {
head = head.copy(row = head.row - 1)
}
"D" -> {
head = head.copy(row = head.row + 1)
}
}
moveTail(direction)
--stepCount
}
}
return answer
}
val testInput = readInput("/day09/Day09_test")
println(part1(testInput))
println("----------------------------------------")
val input = readInput("/day09/Day09")
println(part1(input))
}
| 0 | Kotlin | 0 | 0 | 17fd65a8fac7fa0c6f4718d218a91a7b7d535eab | 3,583 | aoc-2022-kotlin | Apache License 2.0 |
src/main/year_2017/day02/day03.kt | rolf-rosenbaum | 572,864,107 | false | {"Kotlin": 80772} | package year_2017.day02
import readInput
fun part1(input: List<String>): Int = input.map { line ->
line.split(" ").map { it.toInt() }.sortedDescending()
}.sumOf { it.first() - it.last() }
fun part2(input: List<String>): Int = input.map { line ->
line.split(" ").map { it.toInt() }.sortedDescending()
}.sumOf { line ->
line.findDivisionResult()
}
fun main() {
val input = readInput("main/year_2017/day02/Day02")
println(part1(input))
println(part2(input))
}
fun List<Int>.findDivisionResult(): Int {
forEachIndexed { index, candidate ->
(index + 1 until size).forEach {
if (candidate % this[it] == 0) return candidate / this[it]
}
}
error("no even division found")
}
| 0 | Kotlin | 0 | 2 | 59cd4265646e1a011d2a1b744c7b8b2afe482265 | 736 | aoc-2022 | Apache License 2.0 |
src/Day17.kt | azat-ismagilov | 573,217,326 | false | {"Kotlin": 75114} | private val List<List<Boolean>>.height: Int
get() = this.indexOfLast { line -> line.any { it } }
data class Block(val data: List<List<Boolean>>) {
fun intersects(other: List<List<Boolean>>): Boolean = data.zip(other).any { (firstLine, secondLine) ->
firstLine.zip(secondLine).any { (bitFirst, bitSecond) ->
bitFirst and bitSecond
}
}
val hSize: Int
get() = data.size
val vSize: Int
get() = data.first().size
companion object {
fun of(input: String) = Block(input.split('\n').map { line -> line.map { it == '#' } })
}
}
data class MovableBlock(val block: Block, val positionX: Int, val positionY: Int) {
fun move(direction: BlockDirection, shaft: List<List<Boolean>>): MovableBlock {
val newBlock = this.copy(
positionX = positionX + when (direction) {
BlockDirection.LEFT -> -1
BlockDirection.RIGHT -> 1
}
)
if (!newBlock.intersects(shaft))
return newBlock
return this
}
fun moveDown(shaft: List<List<Boolean>>): MovableBlock? {
val newBlock = this.copy(
positionY = positionY - 1
)
if (!newBlock.intersects(shaft))
return newBlock
return null
}
fun intersects(shaft: List<List<Boolean>>): Boolean {
if (positionX < 0 || positionX + block.vSize > shaft.first().size) {
return true
}
if (positionY < 0 || positionY + block.hSize > shaft.size) {
return true
}
val cutOut =
shaft.subList(positionY, positionY + block.hSize).map { it.subList(positionX, positionX + block.vSize) }
return block.intersects(cutOut)
}
fun applyToShaft(shaft: MutableList<MutableList<Boolean>>) {
for (y in 0 until block.hSize)
for (x in 0 until block.vSize)
if (block.data[y][x])
shaft[y + positionY][x + positionX] = true
}
}
enum class BlockDirection {
LEFT, RIGHT
}
fun main() {
val day = 17
val shapes = listOf(
"""
####
""".trimIndent(),
"""
.#.
###
.#.
""".trimIndent(),
"""
###
..#
..#
""".trimIndent(),
"""
#
#
#
#
""".trimIndent(),
"""
##
##
""".trimIndent()
).map { Block.of(it) }
fun prepareInput(input: List<String>): List<BlockDirection> = input.first().map {
when (it) {
'<' -> BlockDirection.LEFT
else -> BlockDirection.RIGHT
}
}
fun <T> List<T>.getCyclic(index: Int) = this[index % size]
fun part1(input: List<String>, shaftSize: Int, rocksCount: Int): Int {
val moves = prepareInput(input)
val shaft = mutableListOf<MutableList<Boolean>>()
var currentMove = 0
var requiredRocks = rocksCount
var rockIndex = 0
while (requiredRocks > 0) {
val shape = shapes.getCyclic(rockIndex++)
val neededDefaultPosition = shaft.height + 4
while (shaft.size < neededDefaultPosition + shape.hSize)
shaft.add(MutableList(shaftSize) { false })
var movableBlock = MovableBlock(shape, 2, neededDefaultPosition)
while (true) {
movableBlock = movableBlock.move(moves.getCyclic(currentMove++), shaft)
movableBlock = movableBlock.moveDown(shaft) ?: break
}
movableBlock.applyToShaft(shaft)
--requiredRocks
}
return shaft.height + 1
}
fun part2(input: List<String>, shaftSize: Int, rocksCount: Long): Long {
val moves = prepareInput(input)
val shaft = mutableListOf<MutableList<Boolean>>()
var currentMove = 0
val prevAttempts = mutableMapOf<Triple<List<List<Boolean>>, Int, Int>, Pair<Int, Int>>()
var requiredRocks = rocksCount
var fakeHeight = 0L
var rockIndex = 0
while (requiredRocks > 0) {
val shape = shapes.getCyclic(rockIndex++)
val neededDefaultPosition = shaft.height + 4
while (shaft.size < neededDefaultPosition + shape.hSize)
shaft.add(MutableList(shaftSize) { false })
var movableBlock = MovableBlock(shape, 2, neededDefaultPosition)
while (true) {
movableBlock = movableBlock.move(moves.getCyclic(currentMove++), shaft)
movableBlock = movableBlock.moveDown(shaft) ?: break
}
movableBlock.applyToShaft(shaft)
val myCurrentResult = Triple(
shaft.take(shaft.height).takeLast(5), rockIndex % shapes.size, currentMove % moves.size
)
--requiredRocks
if (myCurrentResult in prevAttempts) {
val (prevRockIndex, prevHeight) = prevAttempts[myCurrentResult]!!
val d = requiredRocks / (rockIndex - prevRockIndex)
requiredRocks -= d * (rockIndex - prevRockIndex)
fakeHeight += d * (shaft.height - prevHeight)
prevAttempts.clear()
}
prevAttempts[myCurrentResult] = Pair(rockIndex, shaft.height)
}
return shaft.height + fakeHeight + 1
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day${day}_test")
check(part1(testInput, 7, 2022) == 3068)
check(part2(testInput, 7, 1000000000000) == 1514285714288)
val input = readInput("Day${day}")
println(part1(input, 7, 2022))
println(part2(input, 7, 1000000000000))
}
| 0 | Kotlin | 0 | 0 | abdd1b8d93b8afb3372cfed23547ec5a8b8298aa | 5,791 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/Day04.kt | ssiegler | 572,678,606 | false | {"Kotlin": 76434} | package day04
import utils.readInput
fun part1(filename: String): Int =
readInput(filename).map(String::pairOfAssignments).count { (first, second) ->
second in first || first in second
}
fun part2(filename: String): Int =
readInput(filename).map(String::pairOfAssignments).count(Pair<Assignment, Assignment>::overlap)
private fun Pair<Assignment, Assignment>.overlap() =
first.first <= second.last && second.first <= first.last
typealias Assignment = IntRange
private operator fun Assignment.contains(other: Assignment) =
contains(other.first) && contains(other.last)
private fun String.assignment(): Assignment = split("-").map { it.toInt() }.run { first()..last() }
private fun String.pairOfAssignments(): Pair<Assignment, Assignment> =
split(",").map { it.assignment() }.run { first() to last() }
private const val filename = "Day04"
fun main() {
println(part1(filename))
println(part2(filename))
}
| 0 | Kotlin | 0 | 0 | 9133485ca742ec16ee4c7f7f2a78410e66f51d80 | 952 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/com/ab/advent/day05/Models.kt | battagliandrea | 574,137,910 | false | {"Kotlin": 27923} | package com.ab.advent.day05
import java.util.Stack
typealias Stacks = List<Stack<Crate>>
typealias CrateMover = (src: Stack<Crate>, dst: Stack<Crate>, count: Int) -> Unit
data class Movement(val count: Int, val sourceId: Int, val destinationId: Int)
data class Crate(val id: Char)
class Crane(private val stacks: Stacks, private val move: CrateMover) {
val message: String get() = stacks.map { it.peek().id }.joinToString("")
fun move(movements: List<Movement>) = movements.forEach(::move)
private fun move(movement: Movement) = with(movement) { move(stacks[sourceId - 1], stacks[destinationId - 1], count) }
}
object Parser {
private const val FIELD_SIZE = 4
private val newline = System.lineSeparator()
private val movementRegex = Regex("move (\\d+) from (\\d+) to (\\d+)")
fun parse(input: String): Pair<() -> Stacks, List<Movement>> {
val (crane, movement) = input.split(newline.repeat(2)).map { it.split(newline) }
return { parseStacks(crane) } to movement.filter { it.isNotEmpty() }.map(::parseMovement)
}
private fun parseMovement(input: String) =
movementRegex.find(input)?.groupValues?.let { Movement(it[1].toInt(), it[2].toInt(), it[3].toInt()) } ?: throw IllegalArgumentException()
private fun parseStacks(input: List<String>): List<Stack<Crate>> {
val lines = input.reversed().drop(1)
return (1..input.last().length step FIELD_SIZE).map { index ->
lines.fold(Stack<Crate>()) { stack, item ->
stack.apply { item.getOrNull(index)?.takeUnless { it == ' ' }?.let { push(Crate(it)) } }
}
}
}
}
| 0 | Kotlin | 0 | 0 | cb66735eea19a5f37dcd4a31ae64f5b450975005 | 1,644 | Advent-of-Kotlin | Apache License 2.0 |
letcode/src/main/java/daily/LeetCode309.kt | chengw315 | 343,265,699 | false | null | package daily
fun main() {
val solution = Solution309()
//10
val i8 = solution.maxProfit(intArrayOf(8,6,4,3,3,2,3,5,8,3,8,2,6))
//13
val i7 = solution.maxProfit(intArrayOf(1,7,2,4,11))
//6
val i4 = solution.maxProfit(intArrayOf(3, 3, 5, 0, 0, 3, 1, 4))
//3
val i = solution.maxProfit(intArrayOf(1, 2, 3, 0, 2))
//3
val i2 = solution.maxProfit(intArrayOf(1, 4, 2))
//1
val i3 = solution.maxProfit(intArrayOf(2, 1, 2, 0, 1))
//6
val i5 = solution.maxProfit(intArrayOf(1, 4, 2, 7))
//10
val i6 = solution.maxProfit(intArrayOf(1, 2, 7, 4, 11))
}
/**
* 买卖股票的最佳时期(含冰冻期)
*/
class Solution309 {
fun maxProfit(prices: IntArray): Int {
if(prices.size < 2) {
return 0
}
if(prices.size == 2) {
return if(prices[1] - prices[0] > 0) prices[1] - prices[0] else 0
}
var result = 0
var hold = false
var freeze = false
var buy = 0
var i = 0
while (i < prices.size - 3) {
if(freeze) {
freeze = false
i++
continue
}
//空仓,观望:明天跌 或 明天涨但后天有抄底的机会
if(!hold && (downTomorrow(prices,i)
|| dltTomorrow(prices, i) <= dltTomorrow(prices,i+2) && dltTomorrow(prices,i) + dltTomorrow(prices,i+1) <= 0)) {
i++
continue
}
//空仓,买
if(!hold) {
buy = prices[i++]
hold = true
continue
}
//持仓,卖:明天跌而且后天没涨回来 或 明天涨但后天有抄底的机会
if(hold && (
downTomorrow(prices,i) && dltTomorrow(prices,i) + dltTomorrow(prices,i+1) <= 0
|| upTomorrow(prices,i) && dltTomorrow(prices, i) <= dltTomorrow(prices,i+2) && dltTomorrow(prices,i) + dltTomorrow(prices,i+1) <= 0
)) {
hold = false
freeze = true
result += prices[i++] - buy
continue
}
//观望
i++
}
//最后三天的决策
//持仓,只能卖一次,最高那天卖
if(hold) {
result += Math.max(prices[prices.size - 3], Math.max(prices[prices.size - 2],prices[prices.size - 1])) - buy
} else if(freeze) {
//空仓冰冻期 Math.max(第三天-第二天,0)
result += Math.max(dltTomorrow(prices,prices.size-2),0)
} else {
//空仓,Math.max(第二天-第一天,第三天 - 前两天中低的一天,0)
val best = prices[prices.size - 1] - Math.min(prices[prices.size - 2], prices[prices.size - 3])
result += Math.max(prices[prices.size-2] - prices[prices.size - 3],Math.max(best,0))
}
return result
}
private fun dltTomorrow(prices: IntArray, i: Int) = prices[i + 1] - prices[i]
private fun upTomorrow(prices: IntArray, i: Int): Boolean {
return prices[i + 1] > prices[i]
}
private fun downTomorrow(prices: IntArray, i: Int): Boolean {
return prices[i + 1] <= prices[i]
}
} | 0 | Java | 0 | 2 | 501b881f56aef2b5d9c35b87b5bcfc5386102967 | 3,340 | daily-study | Apache License 2.0 |
src/main/kotlin/days/aoc2022/Day11.kt | bjdupuis | 435,570,912 | false | {"Kotlin": 537037} | package days.aoc2022
import days.Day
class Day11 : Day(2022, 11) {
override fun partOne(): Any {
return calculateTopTwoMonkeysMonkeyBusinessAfterRounds(inputList, 20, true)
}
override fun partTwo(): Any {
return calculateTopTwoMonkeysMonkeyBusinessAfterRounds(inputList, 10000, false)
}
fun calculateTopTwoMonkeysMonkeyBusinessAfterRounds(input: List<String>, rounds: Int, decreaseWorryLevel: Boolean): Long {
val monkeyBusiness = parseMonkeyBusiness(input, decreaseWorryLevel)
repeat(rounds) {
monkeyBusiness.monkeys.forEach { monkey ->
monkey.doMonkeyThings()
}
}
monkeyBusiness.monkeys.forEachIndexed { i, monkey -> println("Monkey $i looked at ${monkey.itemsInspected} items") }
return monkeyBusiness.monkeys.map { it.itemsInspected.toLong() }.sortedDescending().take(2).reduce { acc, i -> acc * i }
}
private fun parseMonkeyBusiness(input: List<String>, decreaseWorryLevel: Boolean): MonkeyBusiness {
var index = 0
val monkeyBusiness = MonkeyBusiness(decreaseWorryLevel)
var moduloFactor = 1
while (index in input.indices) {
index++ // skip monkey "name"
val itemList = input[index++].split(": ").last().split(", ").map { it.toLong() }
val operation = input[index++].split(" Operation: new = old ").last().split(" ")?.let { parts ->
Pair(parts[0], parts[1])
}
val divisor = input[index++].split(" ").last().toInt()
moduloFactor *= divisor
val trueDestination = input[index++].split(" ").last().toInt()
val falseDestination = input[index++].split(" ").last().toInt()
index++ // blank
monkeyBusiness.addMonkey(itemList, { worryLevel: Long ->
val operand = if (operation?.second == "old") worryLevel else operation?.second?.toLong() ?: throw IllegalStateException()
when (operation?.first) {
"+" -> worryLevel + operand
"*" -> worryLevel * operand
else -> throw IllegalStateException()
}
}, { worryLevel: Long ->
if (worryLevel % divisor == 0L) {
trueDestination
} else {
falseDestination
}
} )
}
monkeyBusiness.moduloFactor = moduloFactor
return monkeyBusiness
}
class MonkeyBusiness(private val decreaseWorryLevel: Boolean) {
val monkeys = mutableListOf<Monkey>()
var moduloFactor: Int = 1
fun throwToMonkey(item: Long, monkeyIndex: Int) {
monkeys[monkeyIndex].items.add(item)
}
fun addMonkey(items: List<Long>, operation: (Long) -> Long, determineDestination: (Long) -> Int) {
val monkey = Monkey(operation, determineDestination)
monkey.items.addAll(items)
monkeys.add(monkey)
}
inner class Monkey(
private val operation: (Long) -> Long,
private val determinateDestination: (Long) -> Int
) {
val items = mutableListOf<Long>()
var itemsInspected = 0
fun doMonkeyThings() {
while(items.isNotEmpty()) {
itemsInspected++
val item = items.removeAt(0)
val newWorryLevel: Long = operation.invoke(item).let { if (decreaseWorryLevel) it / 3 else it % moduloFactor }
throwToMonkey(newWorryLevel, determinateDestination(newWorryLevel))
}
}
}
}
} | 0 | Kotlin | 0 | 1 | c692fb71811055c79d53f9b510fe58a6153a1397 | 3,710 | Advent-Of-Code | Creative Commons Zero v1.0 Universal |
year2023/day08/part2/src/main/kotlin/com/curtislb/adventofcode/year2023/day08/part2/Year2023Day08Part2.kt | curtislb | 226,797,689 | false | {"Kotlin": 2146738} | /*
--- Part Two ---
The sandstorm is upon you and you aren't any closer to escaping the wasteland. You had the camel
follow the instructions, but you've barely left your starting position. It's going to take
significantly more steps to escape!
What if the map isn't for people - what if the map is for ghosts? Are ghosts even bound by the laws
of spacetime? Only one way to find out.
After examining the maps a bit longer, your attention is drawn to a curious fact: the number of
nodes with names ending in `A` is equal to the number ending in `Z`! If you were a ghost, you'd
probably just start at every node that ends with `A` and follow all of the paths at the same time
until they all simultaneously end up at nodes that end with `Z`.
For example:
```
LR
11A = (11B, XXX)
11B = (XXX, 11Z)
11Z = (11B, XXX)
22A = (22B, XXX)
22B = (22C, 22C)
22C = (22Z, 22Z)
22Z = (22B, 22B)
XXX = (XXX, XXX)
```
Here, there are two starting nodes, `11A` and `22A` (because they both end with `A`). As you follow
each left/right instruction, use that instruction to simultaneously navigate away from both nodes
you're currently on. Repeat this process until all of the nodes you're currently on end with `Z`.
(If only some of the nodes you're on end with `Z`, they act like any other node and you continue as
normal.) In this example, you would proceed as follows:
- Step 0: You are at `11A` and `22A`.
- Step 1: You choose all of the left paths, leading you to `11B` and `22B`.
- Step 2: You choose all of the right paths, leading you to `11Z` and `22C`.
- Step 3: You choose all of the left paths, leading you to `11B` and `22Z`.
- Step 4: You choose all of the right paths, leading you to `11Z` and `22B`.
- Step 5: You choose all of the left paths, leading you to `11B` and `22C`.
- Step 6: You choose all of the right paths, leading you to `11Z` and `22Z`.
So, in this example, you end up entirely on nodes that end in `Z` after 6 steps.
Simultaneously start on every node that ends with `A`. How many steps does it take before you're
only on nodes that end with `Z`?
*/
package com.curtislb.adventofcode.year2023.day08.part2
import com.curtislb.adventofcode.common.number.leastCommonMultiple
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 2.
*
* @param inputPath The path to the input file for this puzzle.
* @param isStart Returns `true` if a ghost starts on the given `node`.
* @param isGoal Returns `true` if the given `node` is one that all ghosts are trying to reach.
*/
fun solve(
inputPath: Path = Paths.get("..", "input", "input.txt"),
isStart: (node: String) -> Boolean = { it.last() == 'A' },
isGoal: (node: String) -> Boolean = { it.last() == 'Z' }
): Long {
val network = WastelandNetwork.fromFile(inputPath.toFile())
val distances = network.nodes.filter(isStart).map { network.distance(it, isGoal) }
return leastCommonMultiple(distances)
}
fun main() {
println(solve())
}
| 0 | Kotlin | 1 | 1 | 6b64c9eb181fab97bc518ac78e14cd586d64499e | 3,069 | AdventOfCode | MIT License |
src/main/java/com/gitlab/lae/intellij/jump/Tree.kt | laech | 294,076,464 | false | {"Kotlin": 17491} | package com.gitlab.lae.intellij.jump
data class TreePath<out K>(val keys: List<K>)
operator fun <K> TreePath<K>.plus(key: K) = TreePath(keys + key)
sealed class Tree<out K, out V>
data class TreeLeaf<out V>(val value: V) : Tree<Nothing, V>() {
override fun toString() = "TreeLeaf($value)"
}
data class TreeNode<out K, out V>(val nodes: List<Pair<K, Tree<K, V>>>) : Tree<K, V>() {
constructor(vararg nodes: Pair<K, Tree<K, V>>) : this(nodes.toList())
override fun toString() = "TreeNode(\n ${nodes.joinToString(",\n").replace("\n", "\n ")}\n)"
}
val emptyPath = TreePath<Nothing>(emptyList())
val emptyTree = TreeNode<Nothing, Nothing>(emptyList())
fun <V> treeOf(items: Collection<V>, nodeSize: Int): Tree<Int, V> =
join(items.map(::TreeLeaf).toList(), nodeSize)
private fun <V> join(nodes: Collection<Tree<Int, V>>, nodeSize: Int): Tree<Int, V> =
when {
nodeSize < 1 -> throw IllegalArgumentException("nodeSize=$nodeSize")
nodes.size <= 1 -> nodes.firstOrNull() ?: emptyTree
nodes.size <= nodeSize ->
nodes.withIndex().map { (index, value) -> index to value }.let(::TreeNode)
else ->
nodes
.asSequence()
.chunked(nodeSize)
.map { join(it, nodeSize) }
.let { join(it.toList(), nodeSize) }
}
fun <K, V, R> Tree<K, V>.mapKey(mapper: (K) -> R): Tree<R, V> =
when (this) {
is TreeLeaf -> this
is TreeNode ->
nodes.map { (key, value) -> mapper(key) to value.mapKey(mapper) }.let(::TreeNode)
}
fun <K, V> Tree<K, V>.asSequence(path: TreePath<K> = emptyPath): Sequence<Pair<TreePath<K>, V>> =
when (this) {
is TreeLeaf -> sequenceOf(path to value)
is TreeNode -> nodes.asSequence().flatMap { (key, value) -> value.asSequence(path + key) }
}
operator fun <K, V> Tree<K, V>.get(key: K): Tree<K, V>? =
when (this) {
is TreeNode -> nodes.firstOrNull { (k) -> k == key }?.second
else -> null
}
| 0 | Kotlin | 1 | 2 | a404fe41602e10d161a4b3e990aed92a0b9af95e | 1,985 | intellij-jump | Apache License 2.0 |
src/main/kotlin/ru/amai/study/hackerrank/practice/interviewPreparationKit/search/candies/MinimumPasses.kt | slobanov | 200,526,003 | false | null | package ru.amai.study.hackerrank.practice.interviewPreparationKit.search.candies
import java.math.BigDecimal
import java.math.BigDecimal.ONE
import java.math.BigDecimal.ZERO
import java.math.BigDecimal.valueOf
import java.math.RoundingMode.CEILING
import java.math.RoundingMode.FLOOR
import java.util.*
fun minimumPasses(machines: Long, workers: Long, price: Long, targetCnt: Long): Long {
var currentCandies = ZERO
var days = ZERO
val priceDecimal = price.toBigDecimal()
val targetDecimal = targetCnt.toBigDecimal()
var factoryResources = FactoryResources(
valueOf(workers),
valueOf(machines)
)
while (currentCandies < targetDecimal) {
val produced = factoryResources.production
currentCandies += produced
val (newResources, cost) = investPlan(
factoryResources,
currentCandies,
priceDecimal
)
val waitIfStore =
(targetDecimal - currentCandies).divide(produced, CEILING)
if (cost > ZERO) {
val waitIfInvest =
(targetDecimal - currentCandies + cost).divide((newResources.production), CEILING)
if ((waitIfStore > ZERO) && (waitIfInvest <= waitIfStore)) {
factoryResources = newResources
currentCandies -= cost
days++
} else {
days += (waitIfStore + ONE)
currentCandies = targetDecimal
}
} else {
val waitToInvest = (priceDecimal - currentCandies).divide(produced, CEILING)
if (waitIfStore <= waitToInvest) {
days += (waitIfStore + ONE)
currentCandies = targetDecimal
} else {
days += waitToInvest
currentCandies += produced * (waitToInvest - ONE)
}
}
}
return days.toLong()
}
private data class FactoryResources(
val workers: BigDecimal,
val machines: BigDecimal
)
private val FactoryResources.production: BigDecimal
get() = workers * machines
private data class InvestPlan(
val factoryResources: FactoryResources,
val cost: BigDecimal
)
private val TWO = valueOf(2)
private fun investPlan(factoryResources: FactoryResources, candies: BigDecimal, price: BigDecimal): InvestPlan {
val (currentWorkers, currentMachines) = factoryResources
val canBuy = candies.divide(price, FLOOR)
val diff = (currentMachines - currentWorkers).abs()
val toBuyForBalance = diff.min(canBuy)
val leftToBuy = canBuy - toBuyForBalance
var newMachines = currentMachines
var newWorkers = currentWorkers
if (currentMachines > currentWorkers) {
newWorkers += toBuyForBalance
} else if (currentWorkers > currentMachines) {
newMachines += toBuyForBalance
}
if (newMachines == newWorkers) {
newMachines += leftToBuy.divide(TWO, FLOOR)
newWorkers += leftToBuy.divide(TWO, CEILING)
}
val cost = ((newMachines - currentMachines) + (newWorkers - currentWorkers)) * price
return InvestPlan(
FactoryResources(newWorkers, newMachines),
cost
)
}
fun main() {
val scan = Scanner(System.`in`)
val (machines, workers, price, targetCnt) =
scan.nextLine().split(" ").map { it.trim().toLong() }
val result = minimumPasses(machines, workers, price, targetCnt)
println(result)
}
| 0 | Kotlin | 0 | 0 | 2cfdf851e1a635b811af82d599681b316b5bde7c | 3,428 | kotlin-hackerrank | MIT License |
java-kotlin/src/main/kotlin/com/example/dataset/CollectionOperations.kt | chubbyhippo | 464,697,650 | false | {"Kotlin": 20661, "Java": 1634} | package com.example.dataset
fun main() {
val courseList = courseList()
val devPredicate = { c: Course -> c.category == CourseCategory.DEVELOPMENT }
exploreFilter(courseList, devPredicate)
exploreMap(courseList, devPredicate)
val list = listOf(listOf(1, 2, 3), listOf(4, 5, 6))
println(list)
println(list.flatten())
println(exploreFlatMap(courseList, KAFKA))
exploreHashMap()
exploreCollectionsNullability()
}
fun exploreCollectionsNullability() {
val list: MutableList<String>? = null
list?.add("Hippo")
list?.forEach {
println("it = $it")
}
val listContainsNull = listOf("Hippo", null, "Kangaroo")
listContainsNull.forEach {
println("value length = ${it?.length}")
}
}
fun exploreHashMap() {
val nameAgeMutableMap = mutableMapOf("Hippo" to 33, "Kangaroo" to 5)
nameAgeMutableMap
.forEach { (k, v) ->
println("k = [${k}], v = [${v}]")
}
val value = nameAgeMutableMap["Hippo"]
println("value = $value")
val getOrElse = nameAgeMutableMap.getOrElse("Lion") { 3 }
println("getOrElse = $getOrElse")
val filteredMap = nameAgeMutableMap.filterKeys { it.length > 5 }
.map { it.key.uppercase() }
println("filteredMap = $filteredMap")
val maxAge = nameAgeMutableMap
.maxByOrNull { it.value }
println("maxAge = $maxAge")
}
fun exploreFlatMap(courseList: MutableList<Course>, kafka: String): List<String> {
return courseList.flatMap { course: Course ->
val courseName = course.name
course.topicsCovered.filter {
it == kafka
}.map {
courseName
}
}
}
fun exploreMap(courseList: MutableList<Course>, devPredicate: (Course) -> Boolean) {
courseList
.filter(devPredicate)
.map {
"""
${it.name} - ${it.category}
""".trimIndent()
}.forEach {
println(it)
}
}
fun exploreFilter(
courseList: MutableList<Course>,
predicate: (Course) -> Boolean
) {
courseList
// .filter { it.category == CourseCategory.DEVELOPMENT }
// .filter(predicate)
.filter { predicate.invoke(it) }
.forEach { println("developmentCourses : $it") }
}
| 0 | Kotlin | 0 | 0 | d4d6aedc22235eb84684c510759f0f6bac888e0f | 2,274 | kotlin-tinkering | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/SuperPalindromes.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 dev.shtanko.algorithms.extensions.isPalindrome
enum class SPNumType(val value: Int) {
EVEN(1),
ODD(2),
}
/**
* 906. Super Palindromes
* @see <a href="https://leetcode.com/problems/super-palindromes/">Source</a>
*/
object SuperPalindromes {
private const val MAGIC = 100_000
fun superPalindromesInRange(left: String, right: String): Int {
val l = left.toLong()
val r = right.toLong()
var ans = 0
countLen(l, r, SPNumType.ODD) {
ans++
}
countLen(l, r, SPNumType.EVEN) {
ans++
}
return ans
}
private fun countLen(l: Long, r: Long, numType: SPNumType, increase: () -> Unit) {
for (k in 1 until MAGIC) {
val sb = StringBuilder(k.toString())
for (i in sb.length - numType.value downTo 0) {
sb.append(sb[i])
}
var v = sb.toString().toLong()
v *= v
if (v > r) break
if (v >= l && v.isPalindrome()) increase()
}
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,695 | kotlab | Apache License 2.0 |
src/main/kotlin/day12/Day12.kt | Mee42 | 433,459,856 | false | {"Kotlin": 42703, "Java": 824} | package dev.mee42.day12
import dev.mee42.*
import dev.mee42.day9.println
typealias Path = List<String>
fun main() {
val input = input(day = 12, year = 2021).trim().lines()
val caves0 = mutableMapOf<String, MutableList<String>>()
input.map {
val (name, con) = it.split("-")
if(caves0[name] == null) {
caves0[name] = mutableListOf(con)
} else {
caves0[name]!!.add(con)
}
if(caves0[con] == null) {
caves0[con] = mutableListOf(name)
} else {
caves0[con]!!.add(name)
}
}
val caves: Map<String, List<String>> = caves0
fun paths(doneTwice: Boolean,
startAt: String = "start",
cavesCovered: Set<String> = emptySet(),
currentPath: List<String> = listOf("start")): Int =
caves[startAt]!!.sumOf { nextCave -> when {
nextCave == "end" -> 1
nextCave == "start" -> 0
nextCave[0].isLowerCase() && nextCave in cavesCovered && doneTwice -> 0
else -> paths(
doneTwice || (nextCave[0].isLowerCase() && nextCave in cavesCovered),
nextCave,
cavesCovered + setOf(nextCave),
currentPath + listOf(nextCave),
)
}
}
paths(true).println("Part 1")
paths(false).println("Part 2")
}
| 0 | Kotlin | 0 | 0 | db64748abc7ae6a92b4efa8ef864e9bb55a3b741 | 1,374 | aoc-2021 | MIT License |
src/main/kotlin/day4/main.kt | janneri | 572,969,955 | false | {"Kotlin": 99028} | package day4
import util.readTestInput
data class SectionPair(val first: IntRange, val second: IntRange)
// Input etc 2-4,6-8
private val inputRegex = Regex("""(\d+)-(\d+),(\d+)-(\d+)""")
fun parseInputToSectionPairs(line: String): SectionPair =
inputRegex.matchEntire(line)!!
.destructured
.let { (start, end, start2, end2) ->
SectionPair(IntRange(start.toInt(), end.toInt()), IntRange(start2.toInt(), end2.toInt()))
}
fun part1(inputLines: List<String>): Int {
return inputLines.map { parseInputToSectionPairs(it) }
.count { pair -> pair.first.all { pair.second.contains(it) } || pair.second.all { pair.first.contains(it) } }
}
fun part2(inputLines: List<String>): Int {
return inputLines.map { parseInputToSectionPairs(it) }
.count { pair -> pair.first.any { pair.second.contains(it) } || pair.second.any { pair.first.contains(it) } }
}
fun main() {
// Solution for https://adventofcode.com/2022/day/4
// Downloaded the input from https://adventofcode.com/2022/day/4/input
val inputLines = readTestInput("day4")
println(part1(inputLines))
println(part2(inputLines))
} | 0 | Kotlin | 0 | 0 | 1de6781b4d48852f4a6c44943cc25f9c864a4906 | 1,161 | advent-of-code-2022 | MIT License |
src/main/kotlin/net/danlew/wordle/algorithm/KnuthSolver.kt | dlew | 446,149,485 | false | {"Kotlin": 14254} | package net.danlew.wordle.algorithm
import net.danlew.wordle.*
/**
* Solver based on Knuth's Mastermind algorithm
*/
class KnuthSolver(
/**
* The first guess to make lacking any previous guesses.
*
* If null, it's calculated from scratch (warning: takes hours).
*/
private val firstGuess: String?
) : Solver {
override fun nextGuess(wordPool: List<String>, targets: List<String>, previousGuesses: List<GuessResult>): String {
if (previousGuesses.isEmpty() && firstGuess != null) {
return firstGuess
}
// Filter out targets which aren't possible anymore
var possibleTargets = targets
previousGuesses.forEach { previousGuess ->
possibleTargets = possibleTargets.filter { target -> previousGuess.couldMatch(target) }
}
// For each guess, calculate the score (minimum number of eliminated for each guess vs. each target)
// Then take the one with the highest score possible
val targetSize = possibleTargets.size
// If there's only one possibility left, nail it!
if (targetSize == 1) {
return possibleTargets[0]
}
val guessRankings = wordPool.map { guess ->
var score = Int.MAX_VALUE
val hitCounts = mutableMapOf<GuessResult, Int>().withDefault { 0 }
for (possibleTarget in possibleTargets) {
val guessResult = GuessResult(guess, evaluateGuess(guess, possibleTarget))
hitCounts[guessResult] = hitCounts.getValue(guessResult) + 1
score = minOf(score, targetSize - hitCounts.getValue(guessResult))
}
return@map GuessScore(guess, score)
}.sortedByDescending { it.score }
// Find the first word that's in possibleTargets that has the most eliminations (so we can bias
// towards nailing the correct answer). Otherwise, pick the first non-target word.
val maxScore = guessRankings.first().score
val guesses = guessRankings.takeWhile { it.score == maxScore }
return (guesses.find { it.guess in possibleTargets } ?: guesses.first()).guess
}
private data class GuessScore(val guess: String, val score: Int)
} | 0 | Kotlin | 1 | 12 | 73f46bf70178ab9aba6cdb6c2d7aadadf6ef7fa0 | 2,077 | wordle-solver | MIT License |
src/main/kotlin/g1901_2000/s1981_minimize_the_difference_between_target_and_chosen_elements/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1901_2000.s1981_minimize_the_difference_between_target_and_chosen_elements
// #Medium #Array #Dynamic_Programming #Matrix
// #2023_06_21_Time_588_ms_(100.00%)_Space_44.8_MB_(100.00%)
class Solution {
fun minimizeTheDifference(mat: Array<IntArray>, target: Int): Int {
val m = mat.size
val seen = Array(m) { BooleanArray(m * 70 + 1) }
dfs(0, mat, 0, seen)
var i = 0
while (true) {
var j = 0
var sign = 1
while (j < 2) {
val k = target - i * sign
if (k >= 0 && k <= m * 70 && seen[m - 1][k]) {
return i
}
j++
sign *= -1
}
i++
}
}
private fun dfs(i: Int, mat: Array<IntArray>, sum: Int, seen: Array<BooleanArray>) {
if (i == mat.size) {
return
}
for (j in mat[i].indices) {
if (!seen[i][sum + mat[i][j]]) {
seen[i][sum + mat[i][j]] = true
dfs(i + 1, mat, sum + mat[i][j], seen)
}
}
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,119 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/NumOfMinutes.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import java.util.LinkedList
import java.util.Queue
import kotlin.math.max
/**
* 1376. Time Needed to Inform All Employees
* @see <a href="https://leetcode.com/problems/time-needed-to-inform-all-employees/">Source</a>
*/
fun interface NumOfMinutes {
operator fun invoke(n: Int, headID: Int, manager: IntArray, informTime: IntArray): Int
}
/**
* Approach 1: Depth-First Search (DFS)
*/
class NumOfMinutesDFS : NumOfMinutes {
private var maxTime = Int.MIN_VALUE
override operator fun invoke(n: Int, headID: Int, manager: IntArray, informTime: IntArray): Int {
val adjList = ArrayList<ArrayList<Int>>(n)
for (i in 0 until n) {
adjList.add(ArrayList())
}
// Making an adjacent list, each index stores the Ids of subordinate employees.
// Making an adjacent list, each index stores the Ids of subordinate employees.
for (i in 0 until n) {
if (manager[i] != -1) {
adjList[manager[i]].add(i)
}
}
dfs(adjList, informTime, headID, 0)
return maxTime
}
private fun dfs(adjList: ArrayList<ArrayList<Int>>, informTime: IntArray, curr: Int, time: Int) {
// Maximum time for an employee to get the news.
maxTime = max(maxTime, time)
for (adjacent in adjList[curr]) {
// Visit the subordinate employee who gets the news after informTime[curr] unit time.
dfs(adjList, informTime, adjacent, time + informTime[curr])
}
}
}
/**
* Approach 2: Breadth-First Search (BFS)
*/
class NumOfMinutesBFS : NumOfMinutes {
private var maxTime = Int.MIN_VALUE
override operator fun invoke(n: Int, headID: Int, manager: IntArray, informTime: IntArray): Int {
val adjList = ArrayList<ArrayList<Int>>(n)
for (i in 0 until n) {
adjList.add(ArrayList())
}
// Making an adjacent list, each index stores the Ids of subordinate employees.
// Making an adjacent list, each index stores the Ids of subordinate employees.
for (i in 0 until n) {
if (manager[i] != -1) {
adjList[manager[i]].add(i)
}
}
val q: Queue<Pair<Int, Int>> = LinkedList()
q.add(Pair(headID, 0))
while (q.isNotEmpty()) {
val employeePair: Pair<Int, Int> = q.remove()
val parent: Int = employeePair.first
val time: Int = employeePair.second
// Maximum time for an employee to get the news.
maxTime = max(maxTime, time)
for (adjacent in adjList[parent]) {
q.add(Pair(adjacent, time + informTime[parent]))
}
}
return maxTime
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 3,382 | kotlab | Apache License 2.0 |
src/Day05.kt | mnajborowski | 573,619,699 | false | {"Kotlin": 7975} | fun main() {
val input = readInput("Day05")
val stackLabels = input[8]
fun prepareStacks(): List<ArrayDeque<Char>> =
stackLabels.last { it.isDigit() }.let { finalStackLabel ->
('1'..finalStackLabel).map { label ->
ArrayDeque(
input.take(8).map { floor ->
floor.getOrElse(stackLabels.indexOf(label)) { ' ' }
}.filter { it.isLetter() }
)
}
}
val instructions =
input.subList(10, input.size)
.map { instruction -> instruction.split("move ", " from ", " to ").takeLast(3).map { it.toInt() } }
fun part1(): String {
val stacks = prepareStacks()
instructions.forEach { instruction ->
repeat((0 until instruction[0]).count()) {
stacks[instruction[2] - 1].addFirst(stacks[instruction[1] - 1].removeFirst())
}
}
return stacks.map { it.first() }.joinToString("")
}
fun part2(): String {
val stacks = prepareStacks()
instructions.forEach { instruction ->
stacks[instruction[2] - 1].addAll(0, stacks[instruction[1] - 1].take(instruction[0]))
repeat((0 until instruction[0]).count()) { stacks[instruction[1] - 1].removeFirst() }
}
return stacks.map { it.firstOrNull() ?: "" }.joinToString("")
}
println(part1())
println(part2())
} | 0 | Kotlin | 0 | 0 | e54c13bc5229c6cb1504db7e3be29fc9b9c4d386 | 1,446 | advent-of-code-2022 | Apache License 2.0 |
src/Day02.kt | YunxiangHuang | 572,333,905 | false | {"Kotlin": 20157} | class shap(s: String) {
private val mark = {
when (s) {
"A", "X" -> {
"Rock"
}
"B", "Y" -> {
"Paper"
}
else -> {
"Scissors"
}
}
};
private val score = {
when (s) {
"A", "X" -> {
1
}
"B", "Y" -> {
2
}
else -> {
3
}
}
};
fun cal(other: shap): Int {
if (mark() == other.mark()) {
return 3 + score()
}
// Win cases
if ((mark() == "Rock" && other.mark() == "Scissors") ||
(mark() == "Scissors" && other.mark() == "Paper") ||
(mark() == "Paper" && other.mark() == "Rock")
) {
return 6 + score()
}
return score()
}
fun how2Lose(): shap {
return when (mark()) {
"Rock" -> {
shap("C")
}
"Scissors" -> {
shap("B")
}
else -> shap("A")
}
}
fun how2Draw(): shap {
return this
}
fun how2Win(): shap {
return when (mark()) {
"Rock" -> {
shap("B")
}
"Scissors" -> {
shap("A")
}
else -> {
shap("C")
}
}
}
}
fun partOne(lines: List<String>) {
var total = 0
for (l in lines) {
val line = l.split(" ")
val other = shap(line[0])
val me = shap(line[1])
total += me.cal(other)
}
println("Part I: $total")
}
fun partTwo(lines: List<String>) {
var total = 0
for (l in lines) {
var line = l.split(" ")
var other = shap(line[0])
var me = {
when(line[1]) {
"X" ->{ other.how2Lose()}
"Y" ->{other.how2Draw()}
else ->{other.how2Win()}
}
}
total += me().cal(other)
}
println("Part II: $total")
}
fun main() {
val input = readInput("Day02")
partOne(input)
partTwo(input)
}
| 0 | Kotlin | 0 | 0 | f62cc39dd4881f4fcf3d7493f23d4d65a7eb6d66 | 2,230 | AoC_2022 | Apache License 2.0 |
src/main/kotlin/g1501_1600/s1579_remove_max_number_of_edges_to_keep_graph_fully_traversable/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1501_1600.s1579_remove_max_number_of_edges_to_keep_graph_fully_traversable
// #Hard #Graph #Union_Find #2023_06_14_Time_942_ms_(32.52%)_Space_92.5_MB_(100.00%)
import java.util.Arrays
class Solution {
fun maxNumEdgesToRemove(n: Int, edges: Array<IntArray>): Int {
Arrays.sort(edges) { a: IntArray, b: IntArray -> b[0] - a[0] }
val alice = IntArray(n + 1)
val rankAlice = IntArray(n + 1)
val bob = IntArray(n + 1)
val rankBob = IntArray(n + 1)
for (i in 1..n) {
alice[i] = i
bob[i] = i
}
var countAlice = n
var countBob = n
var remove = 0
for (edge in edges) {
val type = edge[0]
val u = edge[1]
val v = edge[2]
if (type == 1) {
val a = union(u, v, alice, rankAlice)
if (a) {
countAlice--
} else {
remove++
}
} else if (type == 2) {
val b = union(u, v, bob, rankBob)
if (b) {
countBob--
} else {
remove++
}
} else {
val b = union(u, v, bob, rankBob)
val a = union(u, v, alice, rankAlice)
if (!a && !b) {
remove++
}
if (a) {
countAlice--
}
if (b) {
countBob--
}
}
}
return if (countAlice != 1 || countBob != 1) {
-1
} else remove
}
fun union(x: Int, y: Int, arr: IntArray, rank: IntArray): Boolean {
val p1 = find(arr[x], arr)
val p2 = find(arr[y], arr)
if (p1 != p2) {
if (rank[p1] > rank[p2]) {
arr[p2] = p1
} else if (rank[p1] < rank[p2]) {
arr[p1] = p2
} else {
arr[p1] = p2
rank[p2]++
}
return true
}
return false
}
fun find(x: Int, arr: IntArray): Int {
if (arr[x] == x) {
return x
}
val temp = find(arr[x], arr)
arr[x] = temp
return temp
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 2,329 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/com/anahoret/aoc2022/day22/CubeSolver.kt | mikhalchenko-alexander | 584,735,440 | false | null | package com.anahoret.aoc2022.day22
import com.anahoret.aoc2022.Vector3
import com.anahoret.aoc2022.Vector3Int
import com.anahoret.aoc2022.degToRad
import java.lang.RuntimeException
import kotlin.math.roundToInt
import kotlin.math.sqrt
class CubeSolver(private val input: String) {
fun solve(): List<Int> {
val (cube, path) = parseInputToCube(input)
val currentPos = Position3D(0, 0, 0, Vector3Int.RIGHT, CubeSide.BOTTOM)
path.actions.forEach {
currentPos.move(cube, it)
}
val finishTile3D = cube.tile3DAt(currentPos.x, currentPos.y, currentPos.z, currentPos.cubeSide)
val unfolded3dFacing = finishTile3D
.unfoldRotations
.reversed()
.fold(currentPos.direction3d) { acc, (axis, rotationDirection) ->
acc.rotateAround(axis, rotationDirection)
}
val facing = when (unfolded3dFacing) {
Vector3Int.LEFT -> Direction.LEFT
Vector3Int.RIGHT -> Direction.RIGHT
Vector3Int.BACKWARD -> Direction.UP
Vector3Int.FORWARD -> Direction.DOWN
else -> throw RuntimeException("Unsupported facing $unfolded3dFacing")
}.facing
val tile = finishTile3D.tile
return listOf(tile.row, tile.col, facing)
}
private fun parseInputToCube(str: String): Pair<Cube, Path> {
val (cubeStr, pathStr) = str.split("\n\n")
val cube = Cube.parseCube(cubeStr)
return cube to parsePath(pathStr)
}
}
private enum class Axis { X, Y, Z }
private data class Tile3D(val tile: Tile, var cubeSide: CubeSide, var pos: Vector3, var normal: Vector3) {
val unfoldRotations = mutableListOf<Pair<Axis, RotationDirection>>()
fun rotate(axis: Axis, direction: RotationDirection) {
when (direction) {
RotationDirection.CW -> rotateCW(axis)
RotationDirection.CCW -> rotateCCW(axis)
}
unfoldRotations.add(axis to direction.opposite())
}
private fun updateCubeSide() {
cubeSide = when (normal.round()) {
Vector3Int.LEFT -> CubeSide.LEFT
Vector3Int.RIGHT -> CubeSide.RIGHT
Vector3Int.UP -> CubeSide.TOP
Vector3Int.DOWN -> CubeSide.BOTTOM
Vector3Int.FORWARD -> CubeSide.FRONT
Vector3Int.BACKWARD -> CubeSide.BACK
else -> throw RuntimeException("Illegal normal $normal")
}
}
private fun rotateCCW(axis: Axis) {
pos = pos.rotateCCW(axis)
normal = normal.rotateCCW(axis)
updateCubeSide()
}
private fun rotateCW(axis: Axis) {
pos = pos.rotateCW(axis)
normal = normal.rotateCW(axis)
updateCubeSide()
}
fun move(dv: Vector3) {
pos += dv
}
fun move(dv: Vector3Int) {
pos += dv
}
}
private enum class CubeSide {
BOTTOM, TOP, LEFT, RIGHT, FRONT, BACK
}
private data class Position3D(
var x: Int,
var y: Int,
var z: Int,
var direction3d: Vector3Int,
var cubeSide: CubeSide
)
private class Cube(size: Int, tiles: List<Tile3D>) {
companion object {
fun parseCube(cubeStr: String): Cube {
val tiles = parseTiles(cubeStr)
val tilesList = tiles.flatten()
val startTile = tiles[0][0]
val cubeSize = sqrt(tiles.sumOf { it.size } / 6.0).toInt()
val cubeRange = 0 until cubeSize
val tileTo3d = mutableMapOf<Tile, Tile3D>()
fun outsideOfCube(tile3D: Tile3D): Boolean {
return tile3D.pos.x.roundToInt() !in cubeRange ||
tile3D.pos.y.roundToInt() !in cubeRange ||
tile3D.pos.z.roundToInt() !in cubeRange
}
for (tile in tilesList) {
tileTo3d[tile] =
Tile3D(tile, CubeSide.BOTTOM, Vector3(tile.x - startTile.x, tile.y - startTile.y, 0), Vector3.DOWN)
}
fun foldCube(
outFilter: (Vector3) -> Boolean,
oppositeVector: Vector3,
rotationMap: Map<Vector3Int, Pair<Axis, RotationDirection>>
) {
val out = tileTo3d.values.filter { outFilter(it.pos) }.takeIf { it.isNotEmpty() } ?: return
val closestToStart = out.minBy { it.tile.manhattanDistance(startTile) }
val outNormal = closestToStart.normal.round()
val outOriginVector = closestToStart.pos.round()
out.forEach { tile3D ->
tile3D.move(-outOriginVector)
val (axis, direction) = rotationMap.getValue(outNormal)
tile3D.rotate(axis, direction)
tile3D.move(outOriginVector)
tile3D.move(oppositeVector)
}
}
while (tileTo3d.values.any(::outsideOfCube)) {
foldCube(
{ it.x.roundToInt() < 0 }, Vector3.RIGHT, mapOf(
Vector3Int.FORWARD to RotationAxis.ZCW,
Vector3Int.BACKWARD to RotationAxis.ZCCW,
Vector3Int.UP to RotationAxis.YCCW,
Vector3Int.DOWN to RotationAxis.YCW
)
)
foldCube(
{ it.x.roundToInt() > cubeRange.last }, Vector3.LEFT, mapOf(
Vector3Int.FORWARD to RotationAxis.ZCCW,
Vector3Int.BACKWARD to RotationAxis.ZCW,
Vector3Int.UP to RotationAxis.YCW,
Vector3Int.DOWN to RotationAxis.YCCW
)
)
foldCube(
{ it.y.roundToInt() < 0 }, Vector3.FORWARD, mapOf(
Vector3Int.LEFT to RotationAxis.ZCW,
Vector3Int.RIGHT to RotationAxis.ZCCW,
Vector3Int.UP to RotationAxis.XCW,
Vector3Int.DOWN to RotationAxis.XCCW
)
)
foldCube(
{ it.y.roundToInt() > cubeRange.last }, Vector3.BACKWARD, mapOf(
Vector3Int.LEFT to RotationAxis.ZCCW,
Vector3Int.RIGHT to RotationAxis.ZCW,
Vector3Int.UP to RotationAxis.XCCW,
Vector3Int.DOWN to RotationAxis.XCW
)
)
foldCube(
{ it.z.roundToInt() < 0 }, Vector3.UP, mapOf(
Vector3Int.LEFT to RotationAxis.YCCW,
Vector3Int.RIGHT to RotationAxis.YCW,
Vector3Int.BACKWARD to RotationAxis.XCW,
Vector3Int.FORWARD to RotationAxis.XCCW
)
)
foldCube(
{ it.z.roundToInt() > cubeRange.last }, Vector3.DOWN, mapOf(
Vector3Int.LEFT to RotationAxis.YCW,
Vector3Int.RIGHT to RotationAxis.YCCW,
Vector3Int.BACKWARD to RotationAxis.XCCW,
Vector3Int.FORWARD to RotationAxis.XCW
)
)
}
return Cube(cubeSize, tileTo3d.values.toList())
}
}
val maxIndex = size - 1
private val tileLookup = tiles
.groupBy { it.cubeSide }
.mapValues { (_, tiles) -> tiles.associateBy { it.pos.round() } }
fun tileAt(x: Int, y: Int, z: Int, cubeSide: CubeSide): Tile {
return tile3DAt(x, y, z, cubeSide).tile
}
fun tile3DAt(x: Int, y: Int, z: Int, cubeSide: CubeSide): Tile3D {
return tileLookup.getValue(cubeSide).getValue(Vector3Int(x, y, z))
}
}
private fun Vector3.rotateCCW(axis: Axis): Vector3 {
val rotVec = when (axis) {
Axis.X -> Vector3.LEFT
Axis.Y -> Vector3.BACKWARD
Axis.Z -> Vector3.DOWN
}
return this.rotateAround(rotVec, 90.degToRad())
}
private fun Vector3.rotateCW(axis: Axis): Vector3 {
val rotVec = when (axis) {
Axis.X -> Vector3.RIGHT
Axis.Y -> Vector3.FORWARD
Axis.Z -> Vector3.UP
}
return this.rotateAround(rotVec, 90.degToRad())
}
private fun Vector3Int.rotateCCW(axis: Axis): Vector3Int {
return Vector3(x, y, z).rotateCCW(axis).round()
}
private fun Vector3Int.rotateCW(axis: Axis): Vector3Int {
return Vector3(x, y, z).rotateCW(axis).round()
}
private object RotationAxis {
val XCW = Axis.X to RotationDirection.CW
val XCCW = Axis.X to RotationDirection.CCW
val YCW = Axis.Y to RotationDirection.CW
val YCCW = Axis.Y to RotationDirection.CCW
val ZCW = Axis.Z to RotationDirection.CW
val ZCCW = Axis.Z to RotationDirection.CCW
}
private fun Position3D.move(cube: Cube, action: Action) {
fun moveRight() {
when {
x < cube.maxIndex && cube.tileAt(x + 1, y, z, cubeSide) is OpenTile -> x += 1
x == cube.maxIndex && cube.tileAt(x, y, z, CubeSide.RIGHT) is OpenTile -> {
direction3d = when (cubeSide) {
CubeSide.BOTTOM -> Vector3Int.UP
CubeSide.TOP -> Vector3Int.DOWN
CubeSide.FRONT -> Vector3Int.BACKWARD
CubeSide.BACK -> Vector3Int.FORWARD
else -> throw RuntimeException("Unsupported transfer: $cubeSide ${CubeSide.RIGHT}")
}
cubeSide = CubeSide.RIGHT
}
}
}
fun moveLeft() {
when {
x > 0 && cube.tileAt(x - 1, y, z, cubeSide) is OpenTile -> x -= 1
x == 0 && cube.tileAt(x, y, z, CubeSide.LEFT) is OpenTile -> {
direction3d = when (cubeSide) {
CubeSide.BOTTOM -> Vector3Int.UP
CubeSide.TOP -> Vector3Int.DOWN
CubeSide.FRONT -> Vector3Int.BACKWARD
CubeSide.BACK -> Vector3Int.FORWARD
else -> throw RuntimeException("Unsupported transfer: $cubeSide ${CubeSide.LEFT}")
}
cubeSide = CubeSide.LEFT
}
}
}
fun moveForward() {
when {
y < cube.maxIndex && cube.tileAt(x, y + 1, z, cubeSide) is OpenTile -> y += 1
y == cube.maxIndex && cube.tileAt(x, y, z, CubeSide.FRONT) is OpenTile -> {
direction3d = when (cubeSide) {
CubeSide.BOTTOM -> Vector3Int.UP
CubeSide.TOP -> Vector3Int.DOWN
CubeSide.LEFT -> Vector3Int.RIGHT
CubeSide.RIGHT -> Vector3Int.LEFT
else -> throw RuntimeException("Unsupported transfer: $cubeSide ${CubeSide.FRONT}")
}
cubeSide = CubeSide.FRONT
}
}
}
fun moveBackward() {
when {
y > 0 && cube.tileAt(x, y - 1, z, cubeSide) is OpenTile -> y -= 1
y == 0 && cube.tileAt(x, y, z, CubeSide.BACK) is OpenTile -> {
direction3d = when (cubeSide) {
CubeSide.BOTTOM -> Vector3Int.UP
CubeSide.TOP -> Vector3Int.DOWN
CubeSide.LEFT -> Vector3Int.RIGHT
CubeSide.RIGHT -> Vector3Int.LEFT
else -> throw RuntimeException("Unsupported transfer: $cubeSide ${CubeSide.BACK}")
}
cubeSide = CubeSide.BACK
}
}
}
fun moveUp() {
when {
z < cube.maxIndex && cube.tileAt(x, y, z + 1, cubeSide) is OpenTile -> z += 1
z == cube.maxIndex && cube.tileAt(x, y, z, CubeSide.TOP) is OpenTile -> {
direction3d = when (cubeSide) {
CubeSide.LEFT -> Vector3Int.RIGHT
CubeSide.RIGHT -> Vector3Int.LEFT
CubeSide.FRONT -> Vector3Int.BACKWARD
CubeSide.BACK -> Vector3Int.FORWARD
else -> throw RuntimeException("Unsupported transfer: $cubeSide ${CubeSide.TOP}")
}
cubeSide = CubeSide.TOP
}
}
}
fun moveDown() {
when {
z > 0 && cube.tileAt(x, y, z - 1, cubeSide) is OpenTile -> z -= 1
z == 0 && cube.tileAt(x, y, z, CubeSide.BOTTOM) is OpenTile -> {
direction3d = when (cubeSide) {
CubeSide.LEFT -> Vector3Int.RIGHT
CubeSide.RIGHT -> Vector3Int.LEFT
CubeSide.FRONT -> Vector3Int.BACKWARD
CubeSide.BACK -> Vector3Int.FORWARD
else -> throw RuntimeException("Unsupported transfer: $cubeSide ${CubeSide.BOTTOM}")
}
cubeSide = CubeSide.BOTTOM
}
}
}
fun move(steps: Int) {
repeat(steps) {
when (direction3d) {
Vector3Int.LEFT -> moveLeft()
Vector3Int.RIGHT -> moveRight()
Vector3Int.UP -> moveUp()
Vector3Int.DOWN -> moveDown()
Vector3Int.FORWARD -> moveForward()
Vector3Int.BACKWARD -> moveBackward()
}
}
}
when (action) {
is Movement -> move(action.steps)
is Rotation -> direction3d = rotation3DMap.getValue(cubeSide to action.direction)(direction3d)
}
}
private fun Vector3Int.rotateAround(axis: Axis, rotationDirection: RotationDirection): Vector3Int {
val vector = when (axis) {
Axis.X -> Vector3.RIGHT
Axis.Y -> Vector3.FORWARD
Axis.Z -> Vector3.UP
}
val theta = when (rotationDirection) {
RotationDirection.CW -> 90.0
RotationDirection.CCW -> -90.0
}
return rotateAround(vector, theta)
}
private val rotation3DMap = mapOf<Pair<CubeSide, Direction>, Vector3Int.() -> Vector3Int>(
(CubeSide.BOTTOM to Direction.RIGHT) to { rotateCW(Axis.Z) },
(CubeSide.BOTTOM to Direction.LEFT) to { rotateCCW(Axis.Z) },
(CubeSide.TOP to Direction.RIGHT) to { rotateCCW(Axis.Z) },
(CubeSide.TOP to Direction.LEFT) to { rotateCW(Axis.Z) },
(CubeSide.LEFT to Direction.RIGHT) to { rotateCW(Axis.X) },
(CubeSide.LEFT to Direction.LEFT) to { rotateCCW(Axis.X) },
(CubeSide.RIGHT to Direction.RIGHT) to { rotateCCW(Axis.X) },
(CubeSide.RIGHT to Direction.LEFT) to { rotateCW(Axis.X) },
(CubeSide.FRONT to Direction.RIGHT) to { rotateCCW(Axis.Y) },
(CubeSide.FRONT to Direction.LEFT) to { rotateCW(Axis.Y) },
(CubeSide.BACK to Direction.RIGHT) to { rotateCW(Axis.Y) },
(CubeSide.BACK to Direction.LEFT) to { rotateCCW(Axis.Y) },
)
private enum class RotationDirection {
CW, CCW;
fun opposite(): RotationDirection {
return when (this) {
CW -> CCW
CCW -> CW
}
}
}
| 0 | Kotlin | 0 | 0 | b8f30b055f8ca9360faf0baf854e4a3f31615081 | 14,871 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/nl/dirkgroot/adventofcode/year2020/Day09.kt | dirkgroot | 317,968,017 | false | {"Kotlin": 187862} | package nl.dirkgroot.adventofcode.year2020
import nl.dirkgroot.adventofcode.util.Input
import nl.dirkgroot.adventofcode.util.Puzzle
import kotlin.math.max
import kotlin.math.min
import kotlin.random.Random
class Day09(input: Input, private val preambleLenght: Int, private val part1Solution: Long) : Puzzle() {
private val numbers by lazy { input.lines().map { it.toLong() } }
override fun part1() =
numbers.drop(preambleLenght).withIndex()
.first { (index, number) ->
val preamble = numbers.drop(index).take(preambleLenght)
!preamble.any { n1 -> preamble.any { n2 -> n1 + n2 == number } }
}
.value
private class State(val sum: Long = 0, val min: Long = Long.MAX_VALUE, val max: Long = 0)
override fun part2() = numbers.indices.asSequence()
.map { index ->
numbers.asSequence().drop(index)
.runningFold(State()) { state, number ->
State(state.sum + number, min(state.min, number), max(state.max, number))
}
.first { it.sum >= part1Solution }
}
.first { state -> state.sum == part1Solution }
.let { state -> state.min + state.max }
/**
* Solution inspired by https://en.wikipedia.org/wiki/Bogosort.
*/
fun bogoPart2() = generateSequence { Random.nextInt(0, numbers.lastIndex - 1) }
.map { start -> start to Random.nextInt(start + 1, numbers.lastIndex + 1) }
.map { (start, end) -> numbers.subList(start, end + 1) }
.first { it.sum() == part1Solution }
.let { it.minOrNull()!! + it.maxOrNull()!! }
} | 1 | Kotlin | 1 | 1 | ffdffedc8659aa3deea3216d6a9a1fd4e02ec128 | 1,657 | adventofcode-kotlin | MIT License |
Main.kt | callej | 448,166,727 | false | {"Kotlin": 2610} | package search
import java.io.File
const val MENU = "=== Menu ===\n" +
"1. Find a person\n" +
"2. Print all people\n" +
"0. Exit"
fun findPerson(people: List<String> ,pIndex: Map<String, Set<Int>>) {
println("\nSelect a matching strategy: ALL, ANY, NONE")
val strategy = readLine()!!.uppercase()
println("\nEnter a name or email to search all matching people.")
val query = readLine()!!.lowercase()
when (strategy) {
"ALL" -> printResult(people, searchAll(people, pIndex, query))
"ANY" -> printResult(people, searchAny(people, pIndex, query))
"NONE" -> printResult(people, searchNone(people, pIndex, query))
else -> println("\nNo such strategy: $strategy")
}
}
fun searchAll(people: List<String>, pIndex: Map<String, Set<Int>>, query: String): Set<Int> {
var result = people.indices.toSet()
for (q in query.split(" ")) result = result.intersect((pIndex[q] ?: emptySet()).toSet())
return result
}
fun searchAny(people: List<String>, pIndex: Map<String, Set<Int>>, query: String): Set<Int> {
var result = emptySet<Int>()
for (q in query.split(" ")) result = result.union((pIndex[q] ?: emptySet()).toSet())
return result
}
fun searchNone(people: List<String>, pIndex: Map<String, Set<Int>>, query: String): Set<Int> {
return people.indices.toSet().subtract(searchAny(people, pIndex, query))
}
fun printResult(people: List<String>, result: Set<Int>) {
if (result.isNotEmpty()) {
println("\n${result.size} person${if (result.size > 1) "s" else ""} found:")
for (index in result) println(people[index])
} else {
println("\nNo matching people found.")
}
}
fun printAll(people: List<String>) {
println("\n=== List of people ===")
println(people.joinToString("\n"))
}
fun createIndex(people: List<String>): Map<String, Set<Int>> {
val peopleIndex = emptyMap<String, Set<Int>>().toMutableMap()
for (index in people.indices)
for (entry in people[index].lowercase().split(" "))
peopleIndex[entry] = peopleIndex[entry]?.plus(index) ?: setOf(index)
return peopleIndex
}
fun main(args: Array<String>) {
val filename = args[args.indexOf("--data") + 1]
val people = File(filename).readLines()
val peopleIndex = createIndex(people)
while (true) {
println("\n$MENU")
when (readLine()!!) {
"0" -> break
"1" -> findPerson(people, peopleIndex)
"2" -> printAll(people)
else -> println("\nIncorrect option! Try again.")
}
}
println("\nBye!")
}
| 0 | Kotlin | 0 | 0 | 81f9b14f48e3f8f796875ae84546689a0e550501 | 2,610 | Search-Engine | MIT License |
kotlin/src/main/kotlin/com/github/jntakpe/aoc2022/days/Day9.kt | jntakpe | 572,853,785 | false | {"Kotlin": 72329, "Rust": 15876} | package com.github.jntakpe.aoc2022.days
import com.github.jntakpe.aoc2022.shared.Day
import com.github.jntakpe.aoc2022.shared.readInputLines
import kotlin.math.abs
object Day9 : Day {
override val input = readInputLines(9)
.map { line -> line.split(" ").map { it.trim() } }
.map { (dir, steps) -> dir.first() to steps.toInt() }
override fun part1(): Int {
return buildSet {
val headPosition = Position()
val tailPosition = Position()
for ((dir, steps) in input) {
repeat(steps) {
headPosition.move(dir)
tailPosition.follow(headPosition)
add(tailPosition.copy())
}
}
}.size
}
override fun part2(): Int {
return buildSet {
val positions = buildMap { (0..9).forEach { put(it, Position()) } }
for ((dir, steps) in input) {
repeat(steps) {
positions.forEach { (k, v) ->
if (k == 0) v.move(dir) else v.follow(positions.getValue(k - 1))
if (k == 9) add(v.copy())
}
}
}
}.size
}
data class Position(var x: Int = 0, var y: Int = 0) {
fun move(direction: Char) {
when (direction) {
'L' -> this.x = x - 1
'R' -> this.x = x + 1
'D' -> this.y = y - 1
'U' -> this.y = y + 1
else -> error("Unknown direction")
}
}
fun follow(position: Position) {
if (!isAdjacent(position)) {
val relX = x - position.x
when {
relX > 0 -> move('L')
relX < 0 -> move('R')
}
val relY = y - position.y
when {
relY > 0 -> move('D')
relY < 0 -> move('U')
}
}
}
private fun isAdjacent(position: Position) = abs(x - position.x) <= 1 && abs(y - position.y) <= 1
}
} | 1 | Kotlin | 0 | 0 | 63f48d4790f17104311b3873f321368934060e06 | 2,151 | aoc2022 | MIT License |
src/main/kotlin/g1101_1200/s1178_number_of_valid_words_for_each_puzzle/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1101_1200.s1178_number_of_valid_words_for_each_puzzle
// #Hard #Array #String #Hash_Table #Bit_Manipulation #Trie
// #2023_05_25_Time_675_ms_(100.00%)_Space_121.2_MB_(100.00%)
class Solution {
fun findNumOfValidWords(words: Array<String>, puzzles: Array<String>): List<Int> {
val ans: MutableList<Int> = ArrayList()
val map = HashMap<Int, Int>()
for (word in words) {
val wordmask = createMask(word)
if (map.containsKey(wordmask)) {
val oldfreq = map.getValue(wordmask)
val newfreq = oldfreq + 1
map[wordmask] = newfreq
} else {
map[wordmask] = 1
}
}
for (puzzle in puzzles) {
val puzzlemask = createMask(puzzle)
val firstChar = puzzle[0]
val first = 1 shl firstChar.code - 'a'.code
var sub = puzzlemask
var count = 0
while (sub != 0) {
val firstCharPresent = sub and first == first
val wordvalid = map.containsKey(sub)
if (firstCharPresent && wordvalid) {
count += map.getValue(sub)
}
sub = sub - 1 and puzzlemask
}
ans.add(count)
}
return ans
}
private fun createMask(str: String): Int {
var mask = 0
for (i in 0 until str.length) {
val bit = str[i].code - 'a'.code
mask = mask or (1 shl bit)
}
return mask
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,561 | LeetCode-in-Kotlin | MIT License |
year2018/src/main/kotlin/net/olegg/aoc/year2018/day15/Day15.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2018.day15
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.get
import net.olegg.aoc.utils.set
import net.olegg.aoc.year2018.DayOf2018
/**
* See [Year 2018, Day 15](https://adventofcode.com/2018/day/15)
*/
object Day15 : DayOf2018(15) {
override fun first(): Any? {
val map = matrix
var characters = map
.flatMapIndexed { y, row ->
row.mapIndexedNotNull { x, c ->
if (c in listOf('E', 'G')) Character(Vector2D(x, y), c, 3, 200) else null
}
}
val walls = map
.map { row ->
row.map { if (it == '#') -1 else Int.MAX_VALUE }
}
(0..1_000_000_000).forEach { round ->
characters = characters
.filter { it.hit > 0 }
.sortedWith(compareBy({ it.pos.y }, { it.pos.x }))
.toMutableList()
for (character in characters) {
if (character.hit <= 0) {
continue
}
if (characters.none { it.hit > 0 && it.type != character.type }) {
return round * characters.filter { it.hit > 0 && it.type == character.type }.sumOf { it.hit }
}
val targets = characters.filter { it.hit > 0 && it.type != character.type }
val currMap = walls.map { it.toMutableList() }
characters
.filter { it.hit > 0 }
.forEach { other -> currMap[other.pos] = -1 }
currMap[character.pos] = Int.MAX_VALUE
val adjacent = targets
.flatMap { target ->
NEXT_4.map { target.pos + it.step }
}
.distinct()
.filter { cell -> currMap[cell] != -1 }
if (adjacent.isEmpty()) {
continue
}
val queue = ArrayDeque(listOf(character.pos to 0))
while (queue.isNotEmpty()) {
val (pos, step) = queue.removeFirst()
if (currMap[pos]!! > step) {
currMap[pos] = step
queue += NEXT_4
.map { pos + it.step }
.filter { currMap[it] != -1 }
.filter { currMap[it]!! > step + 1 }
.map { it to step + 1 }
}
}
val minDistance = adjacent.minOf { currMap[it] ?: Int.MAX_VALUE }
if (minDistance == Int.MAX_VALUE) {
continue
}
if (minDistance > 0) {
val nearest = adjacent
.filter { currMap[it] == minDistance }
.minWith(compareBy({ it.y }, { it.x }))
val moves = mutableListOf<Vector2D>()
val revQueue = ArrayDeque(listOf(nearest to minDistance))
while (revQueue.isNotEmpty()) {
val (pos, step) = revQueue.removeFirst()
if (step == 1) {
moves += pos
} else {
revQueue += NEXT_4
.map { pos + it.step }
.filter { currMap[it] != -1 }
.filter { currMap[it] == step - 1 }
.map { (it to step - 1) }
}
}
val move = moves.minWith(compareBy({ it.y }, { it.x }))
character.pos = move
}
val canHit = NEXT_4.map { character.pos + it.step }
val target = targets.filter { it.pos in canHit }
.minWithOrNull(compareBy({ it.hit }, { it.pos.y }, { it.pos.x }))
target?.let {
it.hit -= character.attack
}
}
}
return null
}
override fun second(): Any? {
val map = matrix
val walls = map
.map { row ->
row.map { if (it == '#') -1 else Int.MAX_VALUE }
}
return (3..200).first { elvenHit ->
var characters = map
.flatMapIndexed { y, row ->
row.mapIndexedNotNull { x, c ->
when (c) {
'E' -> Character(Vector2D(x, y), c, elvenHit, 200)
'G' -> Character(Vector2D(x, y), c, 3, 200)
else -> null
}
}
}
val elves = characters.count { it.type == 'E' }
(0..1_000_000_000).forEach { round ->
characters = characters
.filter { it.hit > 0 }
.sortedWith(compareBy({ it.pos.y }, { it.pos.x }))
.toMutableList()
if (characters.count { it.hit > 0 && it.type == 'E' } != elves) {
return@first false
}
for (character in characters) {
if (character.hit <= 0) {
if (character.type == 'E') {
return@first false
}
continue
}
if (characters.none { it.hit > 0 && it.type != character.type }) {
if (characters.count { it.hit > 0 && it.type == 'E' } == elves) {
return round * characters.filter { it.hit > 0 && it.type == character.type }.sumOf { it.hit }
}
}
val targets = characters.filter { it.hit > 0 && it.type != character.type }
val currMap = walls.map { it.toMutableList() }
characters
.filter { it.hit > 0 }
.forEach { other -> currMap[other.pos] = -1 }
currMap[character.pos] = Int.MAX_VALUE
val adjacent = targets
.flatMap { target ->
NEXT_4.map { target.pos + it.step }
}
.distinct()
.filter { currMap[it] != -1 }
if (adjacent.isEmpty()) {
continue
}
val queue = ArrayDeque(listOf(character.pos to 0))
while (queue.isNotEmpty()) {
val (pos, step) = queue.removeFirst()
if (currMap[pos]!! > step) {
currMap[pos] = step
queue += NEXT_4
.map { pos + it.step }
.filter { currMap[it] != -1 }
.filter { currMap[it]!! > step + 1 }
.map { (it to step + 1) }
}
}
val minDistance = adjacent.minOf { currMap[it] ?: Int.MAX_VALUE }
if (minDistance == Int.MAX_VALUE) {
continue
}
if (minDistance > 0) {
val nearest = adjacent
.filter { currMap[it] == minDistance }
.minWith(compareBy({ it.y }, { it.x }))
val moves = mutableListOf<Vector2D>()
val revQueue = ArrayDeque(listOf(nearest to minDistance))
while (revQueue.isNotEmpty()) {
val (pos, step) = revQueue.removeFirst()
if (step == 1) {
moves += pos
} else {
revQueue += NEXT_4
.map { pos + it.step }
.filter { currMap[it] != -1 }
.filter { currMap[it] == step - 1 }
.map { (it to step - 1) }
}
}
val move = moves.minWith(compareBy({ it.y }, { it.x }))
character.pos = move
}
val canHit = NEXT_4.map { character.pos + it.step }
val target = targets.filter { it.pos in canHit }
.minWithOrNull(compareBy({ it.hit }, { it.pos.y }, { it.pos.x }))
target?.let {
it.hit -= character.attack
}
}
}
return@first false
}
}
data class Character(
var pos: Vector2D,
val type: Char,
var attack: Int,
var hit: Int
)
}
fun main() = SomeDay.mainify(Day15)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 7,348 | adventofcode | MIT License |
src/test/kotlin/com/igorwojda/string/maxoccurringchar/Solution.kt | igorwojda | 159,511,104 | false | {"Kotlin": 254856} | package com.igorwojda.string.maxoccurringchar
// Kotlin idiomatic solution
private object Solution1 {
private fun maxOccurringChar(str: String): Char? {
if (str.isBlank()) return null
return str.toCharArray()
.groupBy { it }
.maxBy { it.value.size }
.key
}
}
// Kotlin idiomatic solution
private object Solution2 {
private fun maxOccurringChar(str: String): Char? {
if (str.isBlank()) return null
return str.toList()
.groupingBy { it }
.eachCount()
.maxBy { it.value }
.key
}
}
private object Solution3 {
private fun maxOccurringChar(str: String): Char? {
if (str.isBlank()) return null
val map = mutableMapOf<Char, Int>()
str.forEach {
map[it] = (map[it] ?: 0) + 1
}
return map.maxBy { it.value }.key
}
}
// Recursive naive approach
// Time complexity: O(n^2)
private object Solution4 {
private fun maxOccurringChar(str: String): Char? {
if (str.length == 1) {
return str.first()
}
str.forEachIndexed { index, c ->
str.substring(index + 1).forEach {
if (c == it) {
return it
}
}
}
return null
}
}
| 9 | Kotlin | 225 | 895 | b09b738846e9f30ad2e9716e4e1401e2724aeaec | 1,337 | kotlin-coding-challenges | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/KthSymbolInGrammar.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import kotlin.math.pow
/**
* 779. K-th Symbol in Grammar
* @see <a href="https://leetcode.com/problems/k-th-symbol-in-grammar">Source</a>
*/
fun interface KthSymbolInGrammar {
operator fun invoke(n: Int, k: Int): Int
}
/**
* Approach 1: Binary Tree Traversal
*/
class KthSymbolInGrammarDFS : KthSymbolInGrammar {
override fun invoke(n: Int, k: Int): Int {
return depthFirstSearch(n, k, 0)
}
private fun depthFirstSearch(n: Int, k: Int, rootVal: Int): Int {
if (n == 1) {
return rootVal
}
val totalNodes = 2.0.pow(n - 1.0)
// Target node will be present in the right half sub-tree of the current root node.
return if (k > totalNodes / 2) {
val nextRootVal = if (rootVal == 0) 1 else 0
depthFirstSearch(n - 1, k - totalNodes.toInt() / 2, nextRootVal)
} else {
val nextRootVal = if (rootVal == 0) 0 else 1
depthFirstSearch(n - 1, k, nextRootVal)
}
}
}
/**
* Approach 2: Normal Recursion
*/
class KthSymbolInGrammarRecursion : KthSymbolInGrammar {
override fun invoke(n: Int, k: Int): Int {
return recursion(n, k)
}
private fun recursion(n: Int, k: Int): Int {
// First row will only have one symbol '0'.
if (n == 1) {
return 0
}
val totalElements = 2.0.pow(n - 1)
val halfElements = totalElements / 2
// If the target is present in the right half, we switch to the respective left half symbol.
return if (k > halfElements) {
1 - recursion(n, k - halfElements.toInt())
} else {
recursion(n - 1, k)
}
// Otherwise, we switch to the previous row.
}
}
/**
* Approach 3: Recursion to Iteration
*/
class KthSymbolInGrammarIteration : KthSymbolInGrammar {
override fun invoke(n: Int, k: Int): Int {
if (n == 1) {
return 0
}
var k0 = k
// We assume the symbol at the target position is '1'.
var symbol = 1
for (currRow in n downTo 2) {
val totalElements = 2.0.pow(currRow - 1)
val halfElements = totalElements / 2
// If 'k' lies in the right half symbol, then we flip over to the respective left half symbol.
if (k0 > halfElements) {
// Flip the symbol.
symbol = 1 - symbol
// Change the position after flipping.
k0 -= halfElements.toInt()
}
}
// We reached the 1st row; if the symbol is not '0', we started with the wrong symbol.
return if (symbol != 0) {
// Thus, the start symbol was '0', not '1'.
0
} else {
// The start symbol was indeed what we started with, a '1'.
1
}
}
}
/**
* Approach 4: Math
*/
class KthSymbolInGrammarMath : KthSymbolInGrammar {
override fun invoke(n: Int, k: Int): Int {
val count = Integer.bitCount(k - 1)
return if (count % 2 == 0) 0 else 1
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 3,721 | kotlab | Apache License 2.0 |
app/src/main/kotlin/com/resurtm/aoc2023/day18/Solution.kt | resurtm | 726,078,755 | false | {"Kotlin": 119665} | package com.resurtm.aoc2023.day18
import kotlin.math.max
import kotlin.math.min
fun launchDay18(testCase: String) {
val moves = readMoves(testCase)
val part1 = solvePart1(moves)
println("Day 18, part 1: $part1")
// val part2 = solvePart2(moves)
// println("Day 18, part 2: $part2")
val part2good = solvePart2Good(moves)
println("Day 18, part 2: $part2good")
}
fun getNextPos(pos: Pos, move: Move): Pos = when (move.dir) {
Dir.U -> pos.copy(row = pos.row - move.len)
Dir.D -> pos.copy(row = pos.row + move.len)
Dir.L -> pos.copy(col = pos.col - move.len)
Dir.R -> pos.copy(col = pos.col + move.len)
}
fun getNextPosV2(pos: Pos, move: Move): Pos = when (move.dirV2) {
Dir.U -> pos.copy(row = pos.row - move.lenV2)
Dir.D -> pos.copy(row = pos.row + move.lenV2)
Dir.L -> pos.copy(col = pos.col - move.lenV2)
Dir.R -> pos.copy(col = pos.col + move.lenV2)
}
fun printGrid(g: Grid) {
println("=====")
g.grid.forEach { row ->
row.forEach { print(it) }
println()
}
}
fun readMoves(testCase: String): List<Move> {
val reader =
object {}.javaClass.getResourceAsStream(testCase)?.bufferedReader()
?: throw Exception("Invalid state, cannot read an input")
val moves = mutableListOf<Move>()
while (true) {
val rawLine = reader.readLine() ?: break
val rawParts = rawLine.trim().split(' ')
val dir = when (rawParts[0][0]) {
'U' -> Dir.U
'D' -> Dir.D
'L' -> Dir.L
'R' -> Dir.R
else -> throw Exception("Invalid state, an unknown direction")
}
val len = rawParts[1].toLong()
val color = rawParts[2].trimStart('(', '#').trimEnd(')')
val lenV2 = color.substring(0, 5).toLong(radix = 16)
val dirV2 = when (color.substring(5, 6)[0]) {
'0' -> Dir.R
'1' -> Dir.D
'2' -> Dir.L
'3' -> Dir.U
else -> throw Exception("Invalid state, an unknown direction")
}
moves.add(Move(dir, len, color, lenV2, dirV2))
}
return moves
}
data class Grid(val grid: GridData, val delta: Pos) {
fun set(row: Long, col: Long, ch: Char) {
grid[(row + delta.row).toInt()][(col + delta.col).toInt()] = ch
}
fun set(pos: Pos, ch: Char) {
set(pos.row, pos.col, ch)
}
fun get(row: Long, col: Long): Char {
return grid[(row + delta.row).toInt()][(col + delta.col).toInt()]
}
fun minPos(): Pos {
return Pos(-delta.row, -delta.col)
}
fun maxPos(): Pos {
return Pos(grid.size - delta.row, grid[0].size - delta.col)
}
}
typealias GridData = MutableList<MutableList<Char>>
data class MinMax(val min: Pos, val max: Pos)
data class Move(val dir: Dir, val len: Long, val color: String, val lenV2: Long, var dirV2: Dir)
data class Pos(val row: Long = 0L, val col: Long = 0L) {
override fun toString(): String = "row=$row/col=$col"
fun isInside(minMax: MinMax): Boolean {
return (this.row in minMax.min.row..minMax.max.row) &&
(this.col in minMax.min.col..minMax.max.col)
}
}
enum class Dir { U, D, L, R }
data class Rect(
val minMax: MinMax,
val isCw: Boolean = false,
val isCcw: Boolean = false,
val linesInMinMax: Long = 0L,
var checked: Boolean = false,
val lines: List<Line> = emptyList(),
) {
val area = ((minMax.max.row - minMax.min.row) + 1) * ((minMax.max.col - minMax.min.col) + 1)
fun isOtherInside(other: Rect): Boolean {
return (this.minMax.min.row <= other.minMax.min.row && this.minMax.min.col <= other.minMax.min.col)
&& (this.minMax.max.row >= other.minMax.max.row && this.minMax.max.col >= other.minMax.max.col)
}
}
fun findCommonArea(a: Rect, other: Rect, small: Boolean = false): Long {
val minMax = findCommonMinMax(a, other)
if (small)
return ((minMax.max.row - minMax.min.row) - 1) * ((minMax.max.col - minMax.min.col) - 1)
return ((minMax.max.row - minMax.min.row) + 1) * ((minMax.max.col - minMax.min.col) + 1)
}
/*fun findCommonArea(a: MinMax, other: MinMax): Long {
val minMax = findCommonMinMax(a, other)
return ((minMax.max.row - minMax.min.row) + 1) * ((minMax.max.col - minMax.min.col) + 1)
}*/
fun findCommonMinMax(a: Rect, other: Rect): MinMax {
val row0 = max(a.minMax.min.row, other.minMax.min.row)
val col0 = max(a.minMax.min.col, other.minMax.min.col)
val row1 = min(a.minMax.max.row, other.minMax.max.row)
val col1 = min(a.minMax.max.col, other.minMax.max.col)
return MinMax(Pos(row0, col0), Pos(row1, col1))
}
fun findCommonMinMax(a: MinMax, other: MinMax): MinMax {
val row0 = max(a.min.row, other.min.row)
val col0 = max(a.min.col, other.min.col)
val row1 = min(a.max.row, other.max.row)
val col1 = min(a.max.col, other.max.col)
return MinMax(Pos(row0, col0), Pos(row1, col1))
}
data class Line(val head: Pos, val tail: Pos) {
val start: Pos
val end: Pos
val length: Long
init {
val cmp = head.row < tail.row || head.col < tail.col
this.start = if (cmp) head else tail
this.end = if (cmp) tail else head
this.length = if (start.row == end.row) (end.col - start.col + 1) else (end.row - start.row + 1)
}
fun intersects(line: Line): Boolean {
val c1 = (this.start.row in line.start.row..line.end.row) &&
(line.start.col in this.start.col..this.end.col)
val c2 = (line.start.row in this.start.row..this.end.row) &&
(this.start.col in line.start.col..line.end.col)
return c1 || c2
}
override fun toString(): String = "start($start) & end($end) & len($length)"
}
| 0 | Kotlin | 0 | 0 | fb8da6c246b0e2ffadb046401502f945a82cfed9 | 5,762 | advent-of-code-2023 | MIT License |
src/Day03.kt | sebastian-heeschen | 572,932,813 | false | {"Kotlin": 17461} | fun main() {
fun priority(char: Char) = char.code - (if (char.isUpperCase()) ('A'.code - 27) else 'a'.code - 1)
fun part1(input: List<String>): Int = input
.flatMap {
it.chunked(it.length / 2).zipWithNext()
}
.map { (first, second) ->
first.first { second.contains(it) }
}
.sumOf(::priority)
fun part2(input: List<String>) = input
.chunked(3)
.map { Triple(it[0], it[1], it[2]) }
.map { (first, second, third) ->
first.first { second.contains(it) && third.contains(it) }
}
.sumOf(::priority)
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 4432581c8d9c27852ac217921896d19781f98947 | 899 | advent-of-code-2022 | Apache License 2.0 |
app/src/main/java/com/betulnecanli/kotlindatastructuresalgorithms/Complexity/TimeComplexity/TimeComplexity.kt | betulnecanli | 568,477,911 | false | {"Kotlin": 167849} | package com.betulnecanli.kotlindatastructuresalgorithms.Complexity.TimeComplexity
fun main(){
//For brevity, programmers use a notation known as Big O notation to represent
//various magnitudes of time complexity.
val list = mutableListOf<String>("a","b","c")
checkFirst(list)
printNames(list)
multiplicationBoard(10)
val numbers = listOf(1, 3, 56, 66, 68, 80, 99, 105, 450)
pseudoBinaryContains(66,numbers)
}
//constant time
/*The size of names does not affect the running time of this function. Whether names
has 10 items or 10 million items, this function only checks the first element of the
list*/
//The Big O notation for constant time is O(1).
//It’s one unit of time, regardless of the input. This time doesn’t need to be small,
//though. The algorithm can still be slow, but it’s equally slow all of the time.
fun checkFirst(names: List<String>){
if(names.firstOrNull() != null){
println(names.first())
}
else{
println("no names")
}
}
//linear time
/*This function prints all the names in a String list. As the input list increases in size,
the number of iterations is increased by the same amount.
Linear time complexity is usually the easiest to understand. As the amount of data
increases, the running time increases by the same amount. That’s why you have the
straight linear graph illustrated above.*/
//The Big O notation for linear time is O(n).
fun printNames(names : List<String>){
for(name in names){
println(name)
}
}
/*Note: What about a function that has two loops over all of the data and a calls
six different O(1) methods? Is it O(2n + 6) ?
Time complexity only gives a high-level shape of the performance. Loops that
happen a set number of times are not part of the calculation. You’ll need to
abstract everything and consider only the most important thing that affects
performance. All constants are dropped in the final Big O notation. In other
words, O(2n + 6) is surprisingly equal to O(n).
*/
//quadratic time
//More commonly referred to as n squared, this time complexity refers to an
//algorithm that takes time proportional to the square of the input size.
/*If the input is 10, it’ll print the full multiplication board of 10 × 10. That’s 100 print
statements. If you increase the input size by one, it’ll print the product of 11
numbers with 11 numbers, resulting in 121 print statements.
Unlike the previous function, which operates in linear time, the n squared algorithm
can quickly run out of control as the data size increases. Imagine printing the results
for multiplicationBoard(100_000)!*/
//The Big O notation for quadratic time is O(n^2).
fun multiplicationBoard(size : Int){
for(number in 1..size){
print(" | ")
for(otherNumber in 1..size){
print("$number x $otherNumber = ${number * otherNumber} |")
}
println()
}
}
//logarithmic time
//The algorithm first checks the middle value to see how it compares with the desired
//value. If the middle value is bigger than the desired value, the algorithm won’t
//bother looking at the values on the right half of the list; since the list is sorted,
//values to the right of the middle value can only get bigger
//Algorithms in this category are few but are extremely powerful in situations that
//allow for it.
// The Big O notation for logarithmic time complexity is O(log n).
fun pseudoBinaryContains(value : Int, numbers : List<Int> ) : Boolean{
if(numbers.isEmpty()) return false
val middleIndex = numbers.size / 2
if(value <= numbers[middleIndex]){
for(index in 0..middleIndex){
if(numbers[index] == value){
return true
}
}
} else{
for (index in middleIndex until numbers.size){
if(numbers[index] == value){
return true
}
}
}
return false
}
//quasilinear time
//The Big-O notation for quasilinear time complexity is O(n log n)
// which is a multiplication of linear and logarithmic time.
// So quasilinear fits between logarithmic and linear time.
//The quasilinear time complexity shares a similar curve with quadratic time. The key
//difference is that quasilinear complexity is more resilient to large data sets. | 2 | Kotlin | 2 | 40 | 70a4a311f0c57928a32d7b4d795f98db3bdbeb02 | 4,972 | Kotlin-Data-Structures-Algorithms | Apache License 2.0 |
src/y2015/Day20.kt | gaetjen | 572,857,330 | false | {"Kotlin": 325874, "Mermaid": 571} | package y2015
import kotlin.math.ceil
import kotlin.math.sqrt
object Day20 {
fun factors(n: Int): List<Int> {
return (1..ceil(sqrt(n.toDouble())).toInt()).mapNotNull {
if (n % it == 0) listOf(it, n / it) else null
}.flatten()
}
fun part1(input: Int): Int {
val target = input / 10
var x = 1
while (true) {
if (factors(x).sum() >= target) {
return x
}
x++
}
}
private fun factors50(n: Int): List<Int> {
return factors(n).filter { 50 * it >= n }
}
fun part2(input: Int): Int {
var x = 1
while (true) {
if (factors50(x).sum() * 11 >= input) {
return x
}
x++
}
}
}
fun main() {
val testInput = 140
println("------Tests------")
println(Day20.part1(testInput))
println(Day20.part2(testInput))
println("------Real------")
val input = 33100000
println(Day20.part1(input))
println(Day20.part2(input))
}
| 0 | Kotlin | 0 | 0 | d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a | 1,061 | advent-of-code | Apache License 2.0 |
platform/smRunner/src/com/intellij/execution/testframework/sm/runner/LongLineCutter.kt | JetBrains | 2,489,216 | false | null | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.execution.testframework.sm.runner
import com.intellij.execution.impl.ConsoleBuffer
import com.intellij.execution.testframework.sm.ServiceMessageUtil
import jetbrains.buildServer.messages.serviceMessages.ServiceMessage
private const val ELLIPSIS = "<...>"
private val FIELDS_NOT_TO_TOUCH = setOf("name", "duration", "type", "flowId", "nodeId", "parentNodeId")
private val EXPECTED_ACTUAL = arrayOf("expected", "actual")
/**
* If [text] is longer than [maxLength] cut it and insert [ELLIPSIS] in cut.
* If it is a [ServiceMessage], then find longest attribute and cut it leaving [margin] as prefix and postfix
* [EXPECTED_ACTUAL] attrs both are cut.
*
*/
fun cutLineIfTooLong(text: String, maxLength: Int = ConsoleBuffer.getCycleBufferSize(), margin: Int = 1000): String {
val minValueLengthToCut = (margin * 2) + ELLIPSIS.length
if (text.length <= maxLength || maxLength < minValueLengthToCut) {
return text
}
val message = ServiceMessageUtil.parse(text.trim(), false, false)
if (message == null) {
//Not a message, cut as regular text
return text.substring(0, maxLength - ELLIPSIS.length) + ELLIPSIS
}
val attributes = HashMap(message.attributes)
val attributesToCut = attributes
.filter { it.key !in FIELDS_NOT_TO_TOUCH }
.toList()
.sortedByDescending { it.second.length }
.map { it.first }
val shortener = Shortener(attributes, text.length, margin, minValueLengthToCut)
for (attr in attributesToCut) {
if (shortener.currentLength < maxLength) {
break
}
shortener.shortenAttribute(attr)
if (attr in EXPECTED_ACTUAL) {
EXPECTED_ACTUAL.forEach(shortener::shortenAttribute)
}
}
return ServiceMessage.asString(message.messageName, attributes)
}
private class Shortener(private val attributes: MutableMap<String, String>,
var currentLength: Int,
private val margin: Int,
private val minValueLengthToCut: Int) {
private val shortened = mutableSetOf<String>()
fun shortenAttribute(attribute: String) {
if (attribute in shortened) {
return
}
val value = attributes[attribute] ?: return
if (value.length <= minValueLengthToCut) { // Too short to cut
return
}
val lenBefore = value.length
val newValue = StringBuilder(value).replace(margin, value.length - margin, ELLIPSIS).toString()
currentLength -= (lenBefore - newValue.length)
attributes[attribute] = newValue
shortened.add(attribute)
}
}
| 251 | null | 5,079 | 16,158 | 831d1a4524048aebf64173c1f0b26e04b61c6880 | 2,677 | intellij-community | Apache License 2.0 |
codechef/snackdown2021/round1a/d.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package codechef.snackdown2021.round1a
import kotlin.math.abs
private fun solve(): Int {
readLn()
val a = readInts().sorted()
if (a.size == 2) return 0
var ans = minOf(makeEqual(a.drop(1)), makeEqual(a.dropLast(1))).coerceInInt()
var i = 1
var j = a.lastIndex - 1
val borders = a[0] + a.last()
while (i < j) {
ans = minOf(ans, abs(a[i] + a[j] - borders))
if (a[i] + a[j] < borders) i++ else j--
}
return ans
}
private fun makeEqual(a: List<Int>): Long {
val prefixSums = a.runningFold(0L, Long::plus)
fun sum(from: Int, to: Int) = prefixSums[to] - prefixSums[from]
return a.indices.minOf { a[it] * (2L * it - a.size) + sum(it, a.size) - sum(0, it) }
}
@Suppress("UNUSED_PARAMETER") // Kotlin 1.2
fun main(args: Array<String>) = repeat(readInt()) { println(solve()) }
private fun Long.coerceInInt() = if (this >= Int.MAX_VALUE) Int.MAX_VALUE else if (this <= Int.MIN_VALUE) Int.MIN_VALUE else toInt()
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 1,106 | competitions | The Unlicense |
src/Day02.kt | iam-afk | 572,941,009 | false | {"Kotlin": 33272} | fun main() {
fun part1(input: List<String>): Int = input.sumOf { (it[2] - it[0] - ('X' - 'A') + 4) % 3 * 3 + (it[2] - 'X' + 1) }
fun part2(input: List<String>): Int = input.sumOf {
(it[2] - 'X') * 3 + (it[0] - 'A' + (it[2] - 'X' - 1) + 3) % 3 + 1
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | b30c48f7941eedd4a820d8e1ee5f83598789667b | 547 | aockt | Apache License 2.0 |
src/adventOfCode/day8Problem.kt | cunrein | 159,861,371 | false | null | package adventOfCode
import java.util.*
val day8TestData = "2 3 0 3 10 11 12 1 1 0 1 99 2 1 1 2"
fun createTree(data: String): TreeNode<Int> {
val parts = data.split(" ")
val items = parts.map { it.toInt() }.toMutableList()
return createTree(items)
}
fun createTree(data: MutableList<Int>): TreeNode<Int> {
val retv = TreeNode<Int>(mutableListOf())
val nodes = data.removeAt(0)
val metaCnt = data.removeAt(0)
for (i in 0 until nodes){
retv.addChild(createTree(data))
}
val meta = mutableListOf<Int>()
for (i in 0 until metaCnt) {
meta.add(data.removeAt(0))
}
retv.metadata = meta
return retv
}
fun getKey(tree: TreeNode<Int>): Int {
return tree.metadata.sum() + tree.children.sumBy { getKey(it) }
}
fun nodeValue(tree: TreeNode<Int>?): Int {
return when(tree) {
null -> 0
else -> if (tree.children.size == 0) {
tree.metadata.sum()
} else {
tree.metadata.sumBy { nodeValue(tree.children.getOrNull(it - 1)) }
}
}
}
class TreeNode<T>(internal var metadata: List<T>) : Iterable<TreeNode<T>> {
override fun iterator(): Iterator<TreeNode<T>> {
TODO("not implemented")
}
private var parent: TreeNode<T>? = null
var children: MutableList<TreeNode<T>> = LinkedList()
var value = 0
init {
this.children
}
fun addChild(child: List<T>): TreeNode<T> {
val childNode = TreeNode(child)
childNode.parent = this
this.children.add(childNode)
return childNode
}
fun addChild(child: TreeNode<T>): TreeNode<T> {
child.parent = this
this.children.add(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 1 3 2 4 1 2 3 6 1 5 0 10 4 5 6 1 7 1 1 8 7 2 2 1 2 1 1 1 6 0 11 5 5 9 3 1 7 8 3 4 6 7 1 3 1 1 3 1 1 6 0 11 7 9 4 6 4 3 9 1 8 9 3 1 3 1 1 3 1 1 2 1 2 2 2 3 5 1 5 0 6 3 7 3 7 1 8 2 1 2 1 3 1 7 0 7 5 1 6 3 2 3 3 3 2 2 2 1 2 2 1 5 0 7 1 1 2 5 4 8 3 3 1 1 1 1 4 3 3 5 3 3 6 1 9 0 11 1 3 8 5 7 5 1 3 4 9 8 1 3 1 1 3 2 1 2 3 1 5 0 7 4 9 7 9 1 1 5 1 2 2 3 1 1 7 0 8 2 8 5 1 7 2 4 3 3 1 3 1 2 2 2 3 3 1 3 5 1 3 3 2 1 2 4 9 7 1 3 3 1 3 5 8 10 9" | 0 | Kotlin | 0 | 0 | 3488ccb200f993a84f1e9302eca3fe3977dbfcd9 | 33,122 | ProblemOfTheDay | Apache License 2.0 |
2021/src/main/kotlin/day15.kt | madisp | 434,510,913 | false | {"Kotlin": 388138} | import utils.Graph
import utils.IntGrid
import utils.Solution
import utils.Vec2i
fun main() {
Day15.run()
}
object Day15 : Solution<IntGrid>() {
override val name = "day15"
override val parser = IntGrid.singleDigits
override fun part1(input: IntGrid): Int {
return solve(input)
}
override fun part2(input: IntGrid): Number? {
val wide = IntGrid(input.width * 5, input.height * 5) { (x, y) ->
val dist = (x / input.width) + (y / input.height)
val orig = input[x % input.width][y % input.height]
val new = orig + dist
if (new > 9) new - 9 else new
}
return solve(wide)
}
private fun solve(input: IntGrid): Int {
val start = Vec2i(0, 0)
val end = Vec2i(input.width - 1, input.height - 1)
val graph = Graph<Vec2i, Int>(
edgeFn = { node -> node.adjacent.filter { it in input }.map { input[it] to it } },
weightFn = { it }
)
return graph.shortestPath(start, end)
}
}
| 0 | Kotlin | 0 | 1 | 3f106415eeded3abd0fb60bed64fb77b4ab87d76 | 960 | aoc_kotlin | MIT License |
src/main/kotlin/com/hackerrank/ConnectedCellsInAGrid.kt | iluu | 94,996,114 | false | {"Java": 89400, "Kotlin": 14594, "Scala": 1758, "Haskell": 776} | package com.hackerrank
import java.util.*
fun main(args: Array<String>) {
val scan = Scanner(System.`in`)
val n = scan.nextInt()
val m = scan.nextInt()
val arr = Array(n, { Array(m, { scan.nextInt() }) })
println(sizeOfMaxRegion(Board(arr, n, m)))
}
fun sizeOfMaxRegion(board: Board): Int {
var maxSize = 0
for (i in 0..board.n - 1) {
for (j in 0..board.m - 1) {
val node = Pair(i, j)
if (!board.wasVisited(node)) {
val size = regionSize(node, board)
if (size > maxSize) {
maxSize = size
}
}
}
}
return maxSize
}
fun regionSize(node: Pair<Int, Int>, board: Board): Int {
var region = if (board.isNode(node)) 1 else 0
board.markVisited(node)
board.neighbours(node)
.map { regionSize(it, board) }
.forEach { region += it }
return region
}
class Board(val arr: Array<Array<Int>>, val n: Int, val m: Int) {
private var visited = mutableSetOf<Pair<Int, Int>>()
fun markVisited(node: Pair<Int, Int>) {
visited.add(node)
}
fun neighbours(node: Pair<Int, Int>): List<Pair<Int, Int>> {
val neighbours = setOf(
Pair(node.first - 1, node.second - 1),
Pair(node.first - 1, node.second),
Pair(node.first - 1, node.second + 1),
Pair(node.first, node.second - 1),
Pair(node.first, node.second + 1),
Pair(node.first + 1, node.second - 1),
Pair(node.first + 1, node.second),
Pair(node.first + 1, node.second + 1))
return neighbours.filter { (first, second) -> valid(first, second) }
}
fun isNode(pair: Pair<Int, Int>): Boolean {
return arr[pair.first][pair.second] == 1 && !wasVisited(pair)
}
fun wasVisited(pair: Pair<Int, Int>): Boolean {
return visited.contains(pair)
}
private fun valid(row: Int, col: Int): Boolean {
return row in 0..n - 1
&& col in 0..m - 1
&& arr[row][col] == 1
&& !wasVisited(Pair(row, col))
}
} | 0 | Java | 3 | 5 | a89b0d332a3d4a257618e9ae6c7f898cb1695246 | 2,181 | algs-progfun | MIT License |
src/main/kotlin/days/Day19.kt | vovarova | 572,952,098 | false | {"Kotlin": 103799} | package days
import java.util.*
class Day19 : Day(19) {
data class Assets(val ore: Int = 0, val clay: Int = 0, val obsidian: Int = 0, val openGeode: Int = 0) {
fun isValid(): Boolean {
return ore >= 0 && clay >= 0 && obsidian >= 0 && openGeode >= 0
}
operator fun plus(other: Assets) =
Assets(ore + other.ore, clay + other.clay, obsidian + other.obsidian, openGeode + other.openGeode)
operator fun minus(other: Assets) =
Assets(ore - other.ore, clay - other.clay, obsidian - other.obsidian, openGeode - other.openGeode)
operator fun times(time: Int) = Assets(ore * time, clay * time, obsidian * time, openGeode * time)
}
data class RobotV2(val name: Name, val cost: Assets, val produce: Assets) {
enum class Name {
obsidianRobot, clayRobot, geodeRobot, oreRobot
}
fun buy(amount: Int, asset: Assets): Assets = asset - (cost * amount)
fun produce(robotAmount: Int, asset: Assets): Assets = asset + (produce * robotAmount)
}
class Blueprint(
val index: Int,
val oreRobot: RobotV2,
val clayRobot: RobotV2,
val obsidianRobot: RobotV2,
val geodeRobot: RobotV2
) {
val maxOreNeededToBuild = listOf(clayRobot.cost.ore, obsidianRobot.cost.ore, geodeRobot.cost.ore).max()
}
class Blueprints(input: List<String>) {
val blueprints: List<Blueprint>
init {
val blueprintRegexp =
"Blueprint (?<index>\\d+): Each ore robot costs (?<oreRobotOre>\\d+) ore. Each clay robot costs (?<clayRobotOre>\\d+) ore. Each obsidian robot costs (?<obsidianRobotOre>\\d+) ore and (?<obsidianRobotGlay>\\d+) clay. Each geode robot costs (?<geodeRobotOre>\\d+) ore and (?<geodeRobotObsidian>\\d+) obsidian.".toRegex()
blueprints = input.map {
blueprintRegexp.matchEntire(it)!!.groups.let {
Blueprint(
it["index"]!!.value.toInt(),
oreRobot = RobotV2(
RobotV2.Name.oreRobot,
Assets(ore = it["oreRobotOre"]!!.value.toInt()),
Assets(ore = 1)
),
clayRobot = RobotV2(
RobotV2.Name.clayRobot,
Assets(ore = it["clayRobotOre"]!!.value.toInt()),
Assets(clay = 1)
),
obsidianRobot = RobotV2(
RobotV2.Name.obsidianRobot,
Assets(
ore = it["obsidianRobotOre"]!!.value.toInt(),
clay = it["obsidianRobotGlay"]!!.value.toInt()
), Assets(obsidian = 1)
),
geodeRobot = RobotV2(
RobotV2.Name.geodeRobot,
Assets(
ore = it["geodeRobotOre"]!!.value.toInt(),
obsidian = it["geodeRobotObsidian"]!!.value.toInt()
), Assets(openGeode = 1)
)
)
}
}
}
}
data class BuyRobot(val robot: RobotV2, val minute: Int = 0)
class StrategyV2(
val robots: List<BuyRobot>,
val aggBuy: RobotAggregatedBuy,
val blueprint: Blueprint,
val maxMinutes: Int
) {
constructor(robot: BuyRobot, blueprint: Blueprint, maxMinutes: Int) : this(
listOf(robot), RobotAggregatedBuy(mapOf(robot.robot to 1), Assets(), robot.minute), blueprint, maxMinutes
)
val assets = asset()
fun shouldBuild(robot: RobotV2): Boolean {
if (robot.name == RobotV2.Name.oreRobot) {
if (blueprint.maxOreNeededToBuild <= aggBuy.countRobots().oreRobot) {
return false
}
} else if (robot.name == RobotV2.Name.clayRobot) {
if (blueprint.obsidianRobot.cost.clay <= aggBuy.countRobots().clayRobot) {
return false
}
} else if (robot.name == RobotV2.Name.obsidianRobot) {
if (blueprint.geodeRobot.cost.obsidian <= aggBuy.countRobots().obsidianRobot) {
return false
}
}
return true
}
fun buy(robot: RobotV2): StrategyV2? {
if (!shouldBuild(robot)) {
return null
}
val aggregatedBuy = aggBuy
var assets = aggregatedBuy.assets
for (additionalMinute in 1..maxMinutes - (aggregatedBuy.lastBuyMinute)) {
if (robot.buy(1, assets).isValid()) {
val buyRobot = BuyRobot(robot, aggregatedBuy.lastBuyMinute + additionalMinute)
return StrategyV2(robots + buyRobot, aggBuy.buy(buyRobot), blueprint, maxMinutes)
}
for (robotFromCount in aggregatedBuy.robotCount) {
assets = robotFromCount.key.produce(robotFromCount.value, assets)
}
}
return null
}
fun asset(minutes: Int = maxMinutes, aggBuyCur: RobotAggregatedBuy = aggBuy): Assets {
val aggregatedBuy = aggBuyCur
var assetsAggregated = aggregatedBuy.assets
if (aggregatedBuy.lastBuyMinute < minutes) {
for (robot in aggregatedBuy.robotCount) {
assetsAggregated =
robot.key.produce(robot.value * (minutes - aggregatedBuy.lastBuyMinute), assetsAggregated)
}
}
return assetsAggregated
}
}
class RobotAggregatedBuy(
val robotCount: Map<RobotV2, Int>,
val assets: Assets,
val lastBuyMinute: Int,
) {
data class RobotCount(
val oreRobot: Int,
val clayRobot: Int,
val obsidianRobot: Int,
val geodeRobot: Int
)
fun countRobots() = robotCount.map { it.key.name to it.value }.toMap().let {
RobotCount(
oreRobot = it.getOrDefault(RobotV2.Name.oreRobot, 0),
clayRobot = it.getOrDefault(RobotV2.Name.clayRobot, 0),
obsidianRobot = it.getOrDefault(RobotV2.Name.obsidianRobot, 0),
geodeRobot = it.getOrDefault(RobotV2.Name.geodeRobot, 0)
)
}
fun buy(robotBuy: BuyRobot): RobotAggregatedBuy {
var currentAsset = assets
for (robot in robotCount) {
currentAsset = robot.key.produce(robot.value * (robotBuy.minute - lastBuyMinute - 1), currentAsset)
}
currentAsset = robotBuy.robot.buy(1, currentAsset)
if (!currentAsset.isValid()) {
throw RuntimeException("Asset ${currentAsset} is not valid after ${robotBuy}")
}
for (robot in robotCount) {
currentAsset = robot.key.produce(robot.value, currentAsset)
}
return RobotAggregatedBuy(
robotCount + (Pair(robotBuy.robot, robotCount[robotBuy.robot]?.inc() ?: 1)),
currentAsset,
robotBuy.minute
)
}
}
fun bestStrategy(blueprint: Blueprint, minutes: Int): StrategyV2 {
println("Blueprint ${blueprint.index}")
val stack = LinkedList<StrategyV2>()
stack.add(StrategyV2(BuyRobot(blueprint.oreRobot), blueprint, minutes))
var result = stack.peek()
while (stack.isNotEmpty()) {
val poll = stack.pollLast()
if (poll.assets.openGeode > result.assets.openGeode) {
result = poll
}
listOf(
poll.buy(blueprint.oreRobot),
poll.buy(blueprint.geodeRobot),
poll.buy(blueprint.obsidianRobot),
poll.buy(blueprint.clayRobot),
).filterNotNull().forEach {
stack.addLast(it)
}
}
return result
}
override fun partOne(): Any {
var result = 0
val blueprints = Blueprints(inputList)
for (blueprint in blueprints.blueprints) {
val bestStrategy = bestStrategy(blueprint, minutes = 24)
println("Opened Geodes ${bestStrategy.assets.openGeode} with blueprint ${blueprint.index}")
result += bestStrategy.assets.openGeode * blueprint.index
}
return result
}
override fun partTwo(): Any {
val blueprints = Blueprints(inputList.take(3))
return blueprints.blueprints.map {
val bestStrategy = bestStrategy(it, minutes = 32)
println("Opened Geodes ${bestStrategy.assets.openGeode} with blueprint ${it.index}")
bestStrategy
}.map { it.assets.openGeode }.reduce { a, b -> a * b }
}
}
| 0 | Kotlin | 0 | 0 | e34e353c7733549146653341e4b1a5e9195fece6 | 9,077 | adventofcode_2022 | Creative Commons Zero v1.0 Universal |
kmath-stat/src/commonMain/kotlin/space/kscience/kmath/series/VarianceRatioTest.kt | SciProgCentre | 129,486,382 | false | {"Kotlin": 1974351, "ANTLR": 887} | /*
* Copyright 2018-2024 KMath contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package space.kscience.kmath.series
import space.kscience.kmath.distributions.NormalDistribution
import space.kscience.kmath.operations.Float64Field.pow
import space.kscience.kmath.operations.fold
import kotlin.math.absoluteValue
/**
* Container class for Variance Ratio Test result:
* ratio itself, corresponding Z-score, also it's p-value
*/
public data class VarianceRatioTestResult(
val varianceRatio: Double = 1.0,
val zScore: Double = 0.0,
val pValue: Double = 0.5,
)
/**
* Calculates the Z-statistic and the p-value for the Lo and MacKinlay's Variance Ratio test (1987)
* under Homoscedastic or Heteroscedstic assumptions
* with two-sided p-value test
* https://ssrn.com/abstract=346975
*
* @author https://github.com/mrFendel
*/
public fun SeriesAlgebra<Double, *, *, *>.varianceRatioTest(
series: Series<Double>,
shift: Int,
homoscedastic: Boolean = true,
): VarianceRatioTestResult {
require(shift > 1) { "Shift must be greater than one" }
require(shift < series.size) { "Shift must be smaller than sample size" }
val sum = { x: Double, y: Double -> x + y }
val mean = series.fold(0.0, sum) / series.size
val demeanedSquares = series.map { (it - mean).pow(2) }
val variance = demeanedSquares.fold(0.0, sum)
if (variance == 0.0) return VarianceRatioTestResult()
var seriesAgg = series
for (i in 1..<shift) {
seriesAgg = seriesAgg.zip(series.moveTo(i)) { v1, v2 -> v1 + v2 }
}
val demeanedSquaresAgg = seriesAgg.map { (it - shift * mean).pow(2) }
val varianceAgg = demeanedSquaresAgg.fold(0.0, sum)
val varianceRatio =
varianceAgg * (series.size.toDouble() - 1) / variance / (series.size.toDouble() - shift.toDouble() + 1) / (1 - shift.toDouble() / series.size.toDouble()) / shift.toDouble()
// calculating asymptotic variance
val phi = if (homoscedastic) { // under homoscedastic null hypothesis
2 * (2 * shift - 1.0) * (shift - 1.0) / (3 * shift * series.size)
} else { // under heteroscedastic null hypothesis
var accumulator = 0.0
for (j in 1..<shift) {
val temp = demeanedSquares
val delta = series.size * temp.zipWithShift(j) { v1, v2 -> v1 * v2 }.fold(0.0, sum) / variance.pow(2)
accumulator += delta * 4 * (shift - j).toDouble().pow(2) / shift.toDouble().pow(2)
}
accumulator
}
val zScore = (varianceRatio - 1) / phi.pow(0.5)
val pValue = 2 * (1 - NormalDistribution.zSNormalCDF(zScore.absoluteValue))
return VarianceRatioTestResult(varianceRatio, zScore, pValue)
}
| 91 | Kotlin | 52 | 600 | 83d9e1f0afb3024101a2f90a99b54f2a8b6e4212 | 2,777 | kmath | Apache License 2.0 |
src/main/kotlin/de/mbdevelopment/adventofcode/year2021/solvers/day18/Day18Puzzle.kt | Any1s | 433,954,562 | false | {"Kotlin": 96683} | package de.mbdevelopment.adventofcode.year2021.solvers.day18
import de.mbdevelopment.adventofcode.year2021.solvers.PuzzleSolver
import kotlin.math.ceil
import kotlin.math.floor
abstract class Day18Puzzle : PuzzleSolver {
final override fun solve(inputLines: Sequence<String>) = homework(inputLines).toString()
abstract fun homework(snailfishNumbers: Sequence<String>): Long
protected fun parse(snailfishNumber: ArrayDeque<Char>): SnailfishNumber {
return if (snailfishNumber.first() == '[') {
snailfishNumber.removeFirst()
snailfishNumber.removeLast()
val left = ArrayDeque<Char>()
var level = 0
while (true) {
val next = snailfishNumber.removeFirst()
if (next == '[') level += 1 else if (next == ']') level -= 1
if (next == ',' && level == 0) {
break
}
left.addLast(next)
}
SnailfishNumber.Pair(parse(left), parse(snailfishNumber))
} else {
SnailfishNumber.Regular(snailfishNumber.joinToString("").toLong())
}
}
protected operator fun SnailfishNumber.plus(other: SnailfishNumber): SnailfishNumber {
val sum = SnailfishNumber.Pair(this, other).also { println("after addition: $it") }
do {
val exploded = explode(sum).also { if (it) println("after explode: $sum") }
val split = if (exploded) false else split(sum).also { if (it) println("after split: $sum") }
} while (exploded || split)
return sum
}
private fun explode(number: SnailfishNumber): Boolean {
val pairSearchList = flattenForExplode(number)
var pairReferenceToExplode: SnailfishNumberReference? = null
for (reference in pairSearchList) {
if (reference.number is SnailfishNumber.Pair && reference.depth == 4 && pairReferenceToExplode == null) {
pairReferenceToExplode = reference
}
}
return if (pairReferenceToExplode != null) {
val pair = pairReferenceToExplode.number as SnailfishNumber.Pair
val regularSearchList = flattenForSplit(number)
val leftPos = regularSearchList.indexOfFirst { it.number == pair.left }
val regularNumberToLeft = regularSearchList.getOrNull(leftPos - 1)?.number as? SnailfishNumber.Regular
val regularNumberToRight = regularSearchList.getOrNull(leftPos + 2)?.number as? SnailfishNumber.Regular
regularNumberToLeft?.let { it.value += (pair.left as SnailfishNumber.Regular).value }
regularNumberToRight?.let { it.value += (pair.right as SnailfishNumber.Regular).value }
(pairReferenceToExplode.parent as? SnailfishNumber.Pair)?.let {
if (it.left == pair) it.left = SnailfishNumber.Regular(0L)
else it.right = SnailfishNumber.Regular(0L)
}
true
} else false
}
private fun split(number: SnailfishNumber): Boolean {
val numberToSplit = flattenForSplit(number)
.firstOrNull { it.number is SnailfishNumber.Regular && it.number.value >= 10 }
return if (numberToSplit != null) {
val oldValue = (numberToSplit.number as SnailfishNumber.Regular).value
numberToSplit.parent?.let {
val parent = (it as SnailfishNumber.Pair)
val newPair = SnailfishNumber.Pair(
SnailfishNumber.Regular(floor(oldValue / 2.0).toLong()),
SnailfishNumber.Regular(ceil(oldValue / 2.0).toLong())
)
if (parent.left == numberToSplit.number) parent.left = newPair
else parent.right = newPair
}
true
} else false
}
private fun flattenForExplode(
number: SnailfishNumber,
depth: Int = 0,
parent: SnailfishNumber? = null
): List<SnailfishNumberReference> {
return when (number) {
is SnailfishNumber.Regular -> listOf(SnailfishNumberReference(number, depth, parent))
is SnailfishNumber.Pair -> {
if (number.left is SnailfishNumber.Regular && number.right is SnailfishNumber.Regular) {
listOf(SnailfishNumberReference(number, depth, parent))
} else {
flattenForExplode(number.left, depth + 1, number) + flattenForExplode(
number.right,
depth + 1,
number
)
}
}
}
}
private fun flattenForSplit(
number: SnailfishNumber,
depth: Int = 0,
parent: SnailfishNumber? = null
): List<SnailfishNumberReference> {
return when (number) {
is SnailfishNumber.Regular -> listOf(SnailfishNumberReference(number, depth, parent))
is SnailfishNumber.Pair -> {
flattenForSplit(number.left, depth + 1, number) + flattenForSplit(number.right, depth + 1, number)
}
}
}
}
| 0 | Kotlin | 0 | 0 | 21d3a0e69d39a643ca1fe22771099144e580f30e | 5,139 | AdventOfCode2021 | Apache License 2.0 |
string-similarity/src/commonMain/kotlin/com/aallam/similarity/QGram.kt | aallam | 597,692,521 | false | null | package com.aallam.similarity
import com.aallam.similarity.internal.Profile
import com.aallam.similarity.internal.Shingle
import kotlin.math.abs
/**
* Q-gram distance, as defined by Ukkonen in [Approximate string-matching with q-grams and maximal matches](http://www.sciencedirect.com/science/article/pii/0304397592901434).
* The distance between two strings is defined as the L1 norm of the difference of their profiles (the number
* of occurrences of each n-gram).
*
* Q-gram distance is a lower bound on Levenshtein distance, but can be computed in O(m+n), where Levenshtein
* requires O(m.n).
*
* @param k length of k-shingles
*/
public class QGram(private val k: Int = 3) {
/**
* The distance between two strings is defined as the L1 norm of the
* difference of their profiles (the number of occurence of each k-shingle).
*
* @param first the first string to compare.
* @param second the second string to compare.
*/
public fun distance(first: String, second: String): Int {
if (first == second) return 0
val p1 = Shingle.profile(first, k)
val p2 = Shingle.profile(second, k)
return distance(p1, p2)
}
/**
* Compute QGram distance using precomputed profiles.
*/
private fun distance(first: Profile, second: Profile): Int {
var agg = 0
for (key in (first.keys + second.keys)) {
var v1 = 0
var v2 = 0
first[key]?.let { v1 = it }
second[key]?.let { v2 = it }
agg += abs(v1 - v2)
}
return agg
}
}
| 0 | Kotlin | 0 | 1 | 40cd4eb7543b776c283147e05d12bb840202b6f7 | 1,599 | string-similarity-kotlin | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.