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/year2022/day20/Solution.kt | TheSunshinator | 572,121,335 | false | {"Kotlin": 144661} | package year2022.day20
import io.kotest.matchers.shouldBe
import utils.cyclical
import utils.readInput
fun main() {
val testInput = readInput("20", "test_input").map(String::toLong)
val realInput = readInput("20", "input").map(String::toLong)
testInput.asSequence()
.withIndex()
.run { runMixing(toList()) }
.map { it.value }
.let(::computeResult)
.also(::println) shouldBe 3
realInput.asSequence()
.withIndex()
.run { runMixing(toList()) }
.map { it.value }
.let(::computeResult)
.let(::println)
testInput.asSequence()
.map { it * 811589153L }
.withIndex()
.run {
cyclical()
.take(testInput.size * 10)
.runMixing(toList())
}
.map { it.value }
.let(::computeResult)
.also(::println) shouldBe 1623178306L
realInput.asSequence()
.map { it * 811589153L }
.withIndex()
.run {
cyclical()
.take(realInput.size * 10)
.runMixing(toList())
}
.map { it.value }
.let(::computeResult)
.let(::println)
}
private fun Sequence<IndexedValue<Long>>.runMixing(initial: List<IndexedValue<Long>>): MutableList<IndexedValue<Long>> {
return fold(initial.toMutableList()) { accumulator, element ->
accumulator.apply {
val startIndex = indexOf(element)
val newIndex = startIndex + element.value
removeAt(startIndex)
val adjustedIndex = if (newIndex > 0) newIndex % size
else newIndex % size + size
add(adjustedIndex.toInt(), element)
}
}
}
private fun computeResult(input: List<Long>): Long {
return generateSequence(input.indexOf(0)) { it + 1000 }
.drop(1).take(3)
.map { it % input.size }
.sumOf(input::get)
}
| 0 | Kotlin | 0 | 0 | d050e86fa5591447f4dd38816877b475fba512d0 | 1,925 | Advent-of-Code | Apache License 2.0 |
src/Day01.kt | luiscobo | 574,302,765 | false | {"Kotlin": 19047} | fun main() {
fun part1(input: List<String>): Int {
var n = 0
var mayor = 0
var suma = 0
input.forEach {
if (it.trim().isEmpty()) {
n++
if (suma > mayor) {
mayor = suma
}
suma = 0
}
else {
suma += it.toInt()
}
}
n++
if (suma > mayor) {
mayor = suma
}
return mayor
}
fun part2(input: List<String>): Int {
val caloriasElfos = mutableListOf<Int>()
var suma = 0
input.forEach {
if (it.trim().isEmpty()) {
caloriasElfos.add(suma)
suma = 0
}
else {
suma += it.toInt()
}
}
caloriasElfos.add(suma)
caloriasElfos.sortDescending()
return caloriasElfos.take(3).sum()
}
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | c764e5abca0ea40bca0b434bdf1ee2ded6458087 | 1,050 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/leetcode/kotlin/array/easy/628. Maximum Product of Three Numbers.kt | sandeep549 | 262,513,267 | false | {"Kotlin": 530613} | package leetcode.kotlin.array.easy
private fun maximumProduct(nums: IntArray): Int {
var max = Int.MIN_VALUE
for (i in 0..nums.lastIndex - 2) {
for (j in i + 1 until nums.lastIndex) {
for (k in j + 1..nums.lastIndex) {
var p = nums[i] * nums[j] * nums[k]
max = max.coerceAtLeast(p)
}
}
}
return max
}
private fun maximumProduct2(nums: IntArray): Int {
nums.sort()
return (nums[0] * nums[1] * nums[nums.lastIndex]).coerceAtLeast(
nums[nums.lastIndex - 2] *
nums[nums.lastIndex - 1] * nums[nums.lastIndex]
)
}
private fun maximumProduct3(nums: IntArray): Int {
var min1 = Int.MAX_VALUE
var min2 = Int.MAX_VALUE
var max1 = Int.MIN_VALUE
var max2 = Int.MIN_VALUE
var max3 = Int.MIN_VALUE
for (n in nums) {
if (n <= min1) {
min2 = min1
min1 = n
} else if (n <= min2) {
min2 = n
}
if (n >= max1) {
max3 = max2
max2 = max1
max1 = n
} else if (n >= max2) {
max3 = max2
max2 = n
} else if (n >= max3) {
max3 = n
}
}
return (min1 * min2 * max1).coerceAtLeast(max1 * max2 * max3)
}
// private fun maximumProduct4(nums: IntArray): Int {
// var max3 = Int.MIN_VALUE
// var maxp2 = Int.MIN_VALUE
// var minn2 = Int.MAX_VALUE
// var max1 = Int.MIN_VALUE
// var min1 = Int.MAX_VALUE
// for (n in nums) {
// max3 = max3.coerceAtLeast(maxp2 * n).coerceAtLeast(minn2 * n)
// maxp2 = maxp2.coerceAtLeast(max1 * n)
// minn2 = minn2.coerceAtMost(min1 * n).coerceAtMost(max1 * n)
// max1 = max1.coerceAtLeast(n)
// min1 = min1.coerceAtMost(n)
// }
// return max3
// }
| 1 | Kotlin | 0 | 0 | cf357cdaaab2609de64a0e8ee9d9b5168c69ac12 | 1,828 | leetcode-kotlin | Apache License 2.0 |
src/Day02.kt | samorojy | 572,624,502 | false | {"Kotlin": 5094} | fun main() {
val inputs = readInput("Day02")
println("first=${calculateScore(inputs,true)}")
println("second=${calculateScore(inputs,false)}")
}
fun calculateScore(input: List<String>, withPlay: Boolean): Int {
val lose = mapOf(1 to 0, 2 to 1, 0 to 2)
val won = mapOf(0 to 1, 1 to 2, 2 to 0)
return input.sumOf { round ->
val (op, result) = round.split(" ").map { it[0].code }
val opCode = op - 'A'.code
val meCode = result - 'X'.code
val (resultScore, playScore) = if (withPlay) {
when {
opCode == meCode -> 3
won[opCode]!! == meCode -> 6
else -> 0
} to meCode + 1
} else {
3 * meCode to when (meCode) {
0 -> lose[opCode]!!
1 -> opCode
else -> won[opCode]!!
} + 1
}
resultScore + playScore
}
} | 0 | Kotlin | 0 | 0 | 7a38657c4ff7b42c5d49379014f88d054183bd2b | 926 | advent-of-code | Apache License 2.0 |
server/src/main/kotlin/com/heerkirov/hedge/server/library/compiler/grammar/definintion/SyntaxExpression.kt | HeerKirov | 298,201,781 | false | null | package com.heerkirov.hedge.server.library.compiler.grammar.definintion
//文法产生式的定义,作用是和syntax.txt中的定义对应。
/**
* 被定义的文法产生式。
*/
data class SyntaxExpression(val index: Int, val key: KeyNotation, val sequence: List<Notation>)
/**
* 文法产生式中的文法符号。
*/
interface Notation
/**
* 终结符。
*/
interface TerminalNotation : Notation
/**
* 用户定义的非终结符。
*/
class KeyNotation private constructor(val key: String) : Notation {
companion object {
private val cache = HashMap<String, KeyNotation>()
fun of(key: String): KeyNotation {
return cache.computeIfAbsent(key) { KeyNotation(it) }
}
}
override fun equals(other: Any?) = other === this || (other is KeyNotation && other.key == key)
override fun hashCode() = key.hashCode()
override fun toString() = key
}
/**
* 用户定义的终结符。
*/
class SyntaxNotation private constructor(val symbol: String) : TerminalNotation {
companion object {
private val cache = HashMap<String, SyntaxNotation>()
fun of(symbol: String): SyntaxNotation {
return cache.computeIfAbsent(symbol) { SyntaxNotation(it) }
}
}
override fun equals(other: Any?) = other === this || (other is SyntaxNotation && other.symbol == symbol)
override fun hashCode() = symbol.hashCode()
override fun toString() = symbol
}
/**
* 读取并生成原始的文法产生式定义。
* 原始文法定义没有序号,自动添加序号,从1开始。
*/
fun readSyntaxExpression(text: String): List<SyntaxExpression> {
val lines = text.split("\n")
.asSequence().filter { it.isNotBlank() }.map { it.split(Regex("\\s+")) }
.map {
if(it.size < 2 || it[1] != "->") throw RuntimeException("Expression [${it.joinToString(" ")}] is incorrect.")
it[0] to it.subList(2, it.size)
}.toList()
val nonTerminals = lines.asSequence().map { (left, _) -> left }.toSet()
return lines.mapIndexed { i, (left, right) ->
SyntaxExpression(i + 1, KeyNotation.of(left), right.map { if(it in nonTerminals) KeyNotation.of(it) else SyntaxNotation.of(it) })
}
}
| 0 | TypeScript | 0 | 1 | 8140cd693759a371dc5387c4a3c7ffcef6fb14b2 | 2,248 | Hedge-v2 | MIT License |
src/2021/Day10.kt | nagyjani | 572,361,168 | false | {"Kotlin": 369497} | package `2021`
import java.io.File
import java.math.BigInteger
import java.util.*
fun main() {
Day10().solve()
}
class Day10 {
val input = """
[({(<(())[]>[[{[]{<()<>>
[(()[<>])]({[<{<<[]>>(
{([(<{}[<>[]}>{[]{[(<()>
(((({<>}<{<{<>}{[]{[]{}
[[<[([]))<([[{}[[()]]]
[{[{({}]{}}([{[{{{}}([]
{<[[]]>}<{[{[{[]{()[[[]
[<(<(<(<{}))><([]([]()
<{([([[(<>()){}]>(<<{{
<{([{{}}[<[[[<>{}]]]>[]]
""".trimIndent()
class MyStack(s: String) {
var top = -1
val s = MutableList(s.length){-1}
var errorPoint = 0
init {
s.forEach {add(it)}
}
fun add(c: Char) {
if (errorPoint>0) {
return
}
val points = listOf(3, 57, 1197, 25137)
val openerIx = "([{<".indexOf(c)
val closeIx = ")]}>".indexOf(c)
if (openerIx>-1) {
s[++top] = openerIx
} else if (closeIx<0) {
println("ERROR ${closeIx} '${c}'")
} else if (top == -1 || s[top] != closeIx) {
errorPoint = points[closeIx]
} else {
--top
}
}
fun autoCompletePoints(): BigInteger {
if (errorPoint>0) {
return BigInteger.ZERO
}
val points = listOf(1, 2, 3, 4)
return s.slice(0..top).reversed().fold(BigInteger.ZERO){ p, it -> p.multiply(BigInteger.valueOf(5)).plus(
BigInteger.valueOf(points[it].toLong()))}
}
}
fun solve() {
val f = File("src/2021/inputs/day10.in")
val s = Scanner(f)
// val s = Scanner(input)
var sumErrorPoint = 0
val autoCompletePoints = mutableListOf<BigInteger>()
while (s.hasNextLine()) {
val l = s.nextLine().trim()
val m = MyStack(l)
sumErrorPoint += m.errorPoint
if (m.errorPoint == 0) {
autoCompletePoints.add(m.autoCompletePoints())
}
}
println("${sumErrorPoint} ${autoCompletePoints.sorted()[autoCompletePoints.size/2]} ${autoCompletePoints}")
}
} | 0 | Kotlin | 0 | 0 | f0c61c787e4f0b83b69ed0cde3117aed3ae918a5 | 2,131 | advent-of-code | Apache License 2.0 |
src/main/kotlin/com/eharrison/game/tdcreator/AStar.kt | toddharrison | 190,808,157 | false | null | package com.eharrison.game.tdcreator
import java.util.PriorityQueue
import java.util.ArrayList
typealias Neighbors<Node> = (Node) -> List<Node>
typealias Cost<Node> = (Node, Node) -> Double
typealias Exclude<Node> = (Node) -> Boolean
typealias Heuristic<Node> = (Node, Node) -> Double
fun <Node> aStar(
start: Node,
goal: Node,
neighbors: Neighbors<Node>,
cost: Cost<Node> = { _, _ -> 1.0 },
exclude: Exclude<Node> = { _ -> false },
heuristic: Heuristic<Node> = { _, _ -> 0.0 } // Dijkstra's algorithm, only for positive costs
): List<Node> {
val closedSet = mutableSetOf<Node>() // The set of nodes already evaluated.
val cameFrom = mutableMapOf<Node, Node>() // The map of navigated nodes.
val gScore = mutableMapOf<Node, Double>() // Cost from start along best known path.
gScore[start] = 0.0
// Estimated total cost from start to goal through y.
val fScore = mutableMapOf<Node, Double>()
fScore[start] = heuristic(start, goal)
// The set of tentative nodes to be evaluated, initially containing the start node
val openSet = PriorityQueue<Node> {o1, o2 ->
when {
fScore[o1] ?: Double.MAX_VALUE < fScore[o2] ?: Double.MAX_VALUE -> -1
fScore[o2] ?: Double.MAX_VALUE < fScore[o1] ?: Double.MAX_VALUE -> 1
else -> 0
}
}
openSet.add(start)
while (openSet.isNotEmpty()) {
val current = openSet.poll()!!
if (current == goal) {
return reconstructPath(cameFrom, goal)
}
closedSet.add(current)
for (neighbor in neighbors(current)) {
if (closedSet.contains(neighbor) || exclude(neighbor)) {
continue // Ignore the neighbor which is already evaluated or shouldn't be.
}
val tentativeGScore = gScore[current]!! + cost(current, neighbor) // Cost of this path.
if (!openSet.contains(neighbor)) {
openSet.add(neighbor) // Discovered a new node
}
else if (tentativeGScore >= gScore[neighbor]!!) {
continue // Found worse path, ignore.
}
// This path is the best until now. Record it!
cameFrom[neighbor] = current
gScore[neighbor] = tentativeGScore
val estimatedFScore = tentativeGScore + heuristic(neighbor, goal)
fScore[neighbor] = estimatedFScore
}
}
return emptyList()
}
private fun <Node> reconstructPath(
cameFrom: Map<Node, Node>,
current: Node?
): List<Node> {
var cur = current
val totalPath = ArrayList<Node>()
while (cur != null) {
val previous = cur
cur = cameFrom[cur]
if (cur != null) {
totalPath.add(previous)
}
}
totalPath.reverse()
return totalPath
}
| 1 | Kotlin | 0 | 1 | 269b3f2405b1ddbd99db55fe4ebde38f9fc9b411 | 2,826 | tdcreator | MIT License |
advent4/src/main/kotlin/Main.kt | thastreet | 574,294,123 | false | {"Kotlin": 29380} | import java.io.File
fun main(args: Array<String>) {
val lines = File("input.txt").readLines()
val pairs: List<Pair<IntRange, IntRange>> = parsePairs(lines)
println("part1Answer: ${part1(pairs)}")
println("part2Answer: ${part2(pairs)}")
}
fun parsePairs(lines: List<String>): List<Pair<IntRange, IntRange>> =
lines.map { line ->
val parts = line.split(",")
val range1Parts = parts[0].split("-")
val range2Parts = parts[1].split("-")
IntRange(
range1Parts[0].toInt(),
range1Parts[1].toInt()
) to IntRange(
range2Parts[0].toInt(),
range2Parts[1].toInt()
)
}
fun part1(pairs: List<Pair<IntRange, IntRange>>): Int =
pairs.count { (first, second) ->
first.contains(second, partially = false) || second.contains(first, partially = false)
}
fun part2(pairs: List<Pair<IntRange, IntRange>>): Int =
pairs.count { (first, second) ->
first.contains(second, partially = true) || second.contains(first, partially = true)
}
fun IntRange.contains(other: IntRange, partially: Boolean): Boolean =
if (partially)
any { other.contains(it) }
else
all { other.contains(it) } | 0 | Kotlin | 0 | 0 | e296de7db91dba0b44453601fa2b1696af9dbb15 | 1,235 | advent-of-code-2022 | Apache License 2.0 |
src/adventofcode/blueschu/y2017/day21/solution.kt | blueschu | 112,979,855 | false | null | package adventofcode.blueschu.y2017.day21
import java.io.File
import java.util.*
val initialImage: Array<BitSet> = arrayOf(
BitSet(3).apply { set(1) },
BitSet(3).apply { set(0) },
BitSet(3).apply { set(0, 3) }
)
val input: List<String> by lazy {
File("resources/y2017/day21.txt")
.bufferedReader()
.use { it.readLines() }
}
fun main(args: Array<String>) {
println("Part 1: ${renderImage(input, 5)}")
println("Part 2: ${renderImage(input, 18)}")
}
// Two-Dim Arrays of Booleans are less memory efficient than
// an array of BitSets but prove easier implement with the transformation
// logic required to match pixel chunks against the enhancement rules.
typealias BoolGrid = Array<Array<Boolean>>
// For ease of debugging
fun BoolGrid.render(lineSeparator: String = "/") =
joinToString(lineSeparator) { it.joinToString("") { if (it) "#" else "." } }
fun BoolGrid.transposed() = BoolGrid(size, { row ->
Array(size, { col -> this[col][row] })
})
class BitImage(_image: Array<BitSet> = initialImage) {
var image = _image
private set
val litPixels get() = image.sumBy(BitSet::cardinality)
// Rather esoteric, but functional
fun transform(rules: List<EnhancementRule>) {
val chunkDim = if (image.size % 2 == 0) 2 else 3
val newDim = image.size + (image.size / chunkDim)
val buffer = Array(newDim) { BitSet(newDim) }
// writeOffset*s increment with each iteration to account for the
// increase in the resolution of each chunk (2 => 3, 3 => 4).
for ((writeOffsetRow, row) in (0 until image.size step chunkDim).withIndex()) {
for ((writeOffsetCol, col) in (0 until image.size step chunkDim).withIndex()) {
val chunk = BoolGrid(chunkDim, { rowOffset ->
Array(chunkDim, { colOffset ->
image[row + rowOffset][col + colOffset]
})
})
val rule = rules.find { it matches chunk }
?: throw IllegalStateException("Chunk about [row=$row,col=$col] matches no rule")
val newChunk = rule.output
// write new chunk to the buffer
for (chunkRow in 0 until newChunk.size) {
for (chunkCol in 0 until newChunk.size) {
buffer[row + chunkRow + writeOffsetRow].set(
col + chunkCol + writeOffsetCol,
newChunk[chunkRow][chunkCol]
)
}
}
}
}
// assign buffer as bitimage
image = buffer
}
}
class EnhancementRule(val pattern: BoolGrid, val output: BoolGrid) {
infix fun matches(chunk: BoolGrid): Boolean {
fun check(grid: BoolGrid): Boolean {
// vertical flip
val mirror = grid.reversedArray()
return chunk contentDeepEquals grid
|| chunk contentDeepEquals mirror
|| chunk contentDeepEquals grid.map { it.reversedArray() }.toTypedArray()
|| chunk contentDeepEquals mirror.map { it.reversedArray() }.toTypedArray()
}
return check(pattern) || check(pattern.transposed())
}
// For ease of debugging
override fun toString(): String {
return pattern.render() + " => " + output.render()
}
}
fun parseEnhancementRule(token: String): EnhancementRule {
fun String.toBoolGrid(onToken: Char = '#'): BoolGrid = split('/')
.map { str -> Array(str.length) { pos -> str[pos] == onToken } }
.toTypedArray()
val (patten, output) = token.split(" => ")
return EnhancementRule(patten.toBoolGrid(), output.toBoolGrid())
}
fun renderImage(ruleDesc: List<String>, transformCount: Int): Int {
val rules = ruleDesc.map { parseEnhancementRule(it) }
val image = BitImage()
repeat(times = transformCount) {
image.transform(rules)
}
return image.litPixels
}
| 0 | Kotlin | 0 | 0 | 9f2031b91cce4fe290d86d557ebef5a6efe109ed | 4,025 | Advent-Of-Code | MIT License |
src/Day12.kt | IvanChadin | 576,061,081 | false | {"Kotlin": 26282} | import java.util.*
fun main() {
val inputName = "Day12_test"
val a = readInput(inputName).map { it.toCharArray() }
data class Pt(val x: Int, val y: Int)
fun part1(): Int {
val q: Queue<Pair<Pt, Int>> = LinkedList()
var end: Pt? = null
for (x in a.indices) {
for (y in a[x].indices) {
if (a[x][y] == 'S') {
q.offer(Pair(Pt(x, y), 0))
a[x][y] = 'a'
}
if (a[x][y] == 'E') {
end = Pt(x, y)
a[x][y] = 'z'
}
}
}
val dx = intArrayOf(0, 1, 0, -1)
val dy = intArrayOf(1, 0, -1, 0)
while (q.isNotEmpty()) {
val cur = q.peek().first
val steps = q.peek().second
q.poll()
if (cur == end) {
return steps
}
for (i in 0..3) {
val nx = cur.x + dx[i]
val ny = cur.y + dy[i]
if (nx in a.indices && ny in a[nx].indices
&& a[nx][ny] != '#' && a[nx][ny] - a[cur.x][cur.y] <= 1
) {
q.offer(Pair(Pt(nx, ny), steps + 1))
}
}
a[cur.x][cur.y] = '#'
}
return 0
}
fun part2(): Int {
val q: Queue<Pair<Pt, Int>> = LinkedList()
var end: Pt? = null
for (x in a.indices) {
for (y in a[x].indices) {
if (a[x][y] == 'S' || a[x][y] == 'a') {
q.offer(Pair(Pt(x, y), 0))
a[x][y] = 'a'
}
if (a[x][y] == 'E') {
end = Pt(x, y)
a[x][y] = 'z'
}
}
}
val dx = intArrayOf(0, 1, 0, -1)
val dy = intArrayOf(1, 0, -1, 0)
while (q.isNotEmpty()) {
val cur = q.peek().first
val steps = q.peek().second
q.poll()
if (cur == end) {
return steps
}
for (i in 0..3) {
val nx = cur.x + dx[i]
val ny = cur.y + dy[i]
if (nx in a.indices && ny in a[nx].indices
&& a[nx][ny] != '#' && a[nx][ny] - a[cur.x][cur.y] <= 1
) {
q.offer(Pair(Pt(nx, ny), steps + 1))
}
}
a[cur.x][cur.y] = '#'
}
return 0
}
var result = part2()
println(result)
} | 0 | Kotlin | 0 | 0 | 2241437e6c3a20de70306a0cb37b6fe2ed8f9e3a | 2,561 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/FindDuplicateSubtrees.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
/**
* 652. Find Duplicate Subtrees
* @see <a href="https://leetcode.com/problems/find-duplicate-subtrees/">Source</a>
*/
fun interface FindDuplicateSubtrees {
operator fun invoke(root: TreeNode): List<TreeNode>
}
class FindDuplicateSubtreesMap : FindDuplicateSubtrees {
override operator fun invoke(root: TreeNode): List<TreeNode> {
val map: MutableMap<String, MutableList<TreeNode>> = HashMap()
val dups: MutableList<TreeNode> = ArrayList()
serialize(root, map)
for (group in map.values) {
if (group.size > 1) {
dups.add(group[0])
}
}
return dups
}
private fun serialize(node: TreeNode?, map: MutableMap<String, MutableList<TreeNode>>): String {
if (node == null) return ""
val s = "(" + serialize(node.left, map) + node.value + serialize(node.right, map) + ")"
if (!map.containsKey(s)) map[s] = ArrayList()
map[s]?.add(node)
return s
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,635 | kotlab | Apache License 2.0 |
year2021/day05/part1/src/main/kotlin/com/curtislb/adventofcode/year2021/day05/part1/Year2021Day05Part1.kt | curtislb | 226,797,689 | false | {"Kotlin": 2146738} | /*
--- Day 5: Hydrothermal Venture ---
You come across a field of hydrothermal vents on the ocean floor! These vents constantly produce
large, opaque clouds, so it would be best to avoid them if possible.
They tend to form in lines; the submarine helpfully produces a list of nearby lines of vents (your
puzzle input) for you to review. For example:
```
0,9 -> 5,9
8,0 -> 0,8
9,4 -> 3,4
2,2 -> 2,1
7,0 -> 7,4
6,4 -> 2,0
0,9 -> 2,9
3,4 -> 1,4
0,0 -> 8,8
5,5 -> 8,2
```
Each line of vents is given as a line segment in the format `x1,y1 -> x2,y2` where `x1,y1` are the
coordinates of one end the line segment and `x2,y2` are the coordinates of the other end. These line
segments include the points at both ends. In other words:
- An entry like `1,1 -> 1,3` covers points `1,1`, `1,2`, and `1,3`.
- An entry like `9,7 -> 7,7` covers points `9,7`, `8,7`, and `7,7`.
For now, only consider horizontal and vertical lines: lines where either `x1 = x2` or `y1 = y2`.
So, the horizontal and vertical lines from the above list would produce the following diagram:
```
.......1..
..1....1..
..1....1..
.......1..
.112111211
..........
..........
..........
..........
222111....
```
In this diagram, the top left corner is `0,0` and the bottom right corner is `9,9`. Each position is
shown as the number of lines which cover that point or `.` if no line covers that point. The
top-left pair of 1s, for example, comes from `2,2 -> 2,1`; the very bottom row is formed by the
overlapping lines `0,9 -> 5,9` and `0,9 -> 2,9`.
To avoid the most dangerous areas, you need to determine the number of points where at least two
lines overlap. In the above example, this is anywhere in the diagram with a 2 or larger - a total of
5 points.
Consider only horizontal and vertical lines. At how many points do at least two lines overlap?
*/
package com.curtislb.adventofcode.year2021.day05.part1
import com.curtislb.adventofcode.year2021.day05.vents.VentField
import java.nio.file.Path
import java.nio.file.Paths
/**
* Returns the solution to the puzzle for 2021, day 5, part 1.
*
* @param inputPath The path to the input file for this puzzle.
*/
fun solve(inputPath: Path = Paths.get("..", "input", "input.txt")): Int {
val vents = VentField(inputPath.toFile().readLines()) { !it.isDiagonal }
return vents.overlapPoints().size
}
fun main() {
println(solve())
}
| 0 | Kotlin | 1 | 1 | 6b64c9eb181fab97bc518ac78e14cd586d64499e | 2,369 | AdventOfCode | MIT License |
src/main/kotlin/Day04.kt | dliszewski | 573,836,961 | false | {"Kotlin": 57757} | class Day04 {
fun part1(input: List<String>): Int {
return input
.map { it.toRanges() }
.count { (range1, range2) -> range1 includeRange range2 }
}
fun part2(input: List<String>): Int {
return input
.map { it.toRanges() }
.count { (range1, range2) -> range1 overlapRange range2 }
}
private fun String.toRanges(): Pair<IntRange, IntRange> {
val (range1, range2) = split(",")
return Pair(range1.toRange(), range2.toRange())
}
private infix fun IntRange.includeRange(other: IntRange): Boolean {
return (first <= other.first && last >= other.last)
|| (other.first <= first && other.last >= last)
}
private infix fun IntRange.overlapRange(other: IntRange): Boolean {
return (first <= other.last && other.first <= last)
|| (first <= other.last && other.first <= last)
}
private fun String.toRange(): IntRange {
val (from, to) = split("-")
return from.toInt()..to.toInt()
}
} | 0 | Kotlin | 0 | 0 | 76d5eea8ff0c96392f49f450660220c07a264671 | 1,066 | advent-of-code-2022 | Apache License 2.0 |
src/Day03/Day03.kt | suttonle24 | 573,260,518 | false | {"Kotlin": 26321} | package Day03
import readInput
//--- Day 3: Rucksack Reorganization ---
//One Elf has the important job of loading all of the rucksacks with supplies for the jungle journey. Unfortunately, that Elf didn't quite follow the packing instructions, and so a few items now need to be rearranged.
//
//Each rucksack has two large compartments. All items of a given type are meant to go into exactly one of the two compartments. The Elf that did the packing failed to follow this rule for exactly one item type per rucksack.
//
//The Elves have made a list of all of the items currently in each rucksack (your puzzle input), but they need your help finding the errors. Every item type is identified by a single lowercase or uppercase letter (that is, a and A refer to different types of items).
//
//The list of items for each rucksack is given as characters all on a single line. A given rucksack always has the same number of items in each of its two compartments, so the first half of the characters represent items in the first compartment, while the second half of the characters represent items in the second compartment.
//
//For example, suppose you have the following list of contents from six rucksacks:
//
//vJrwpWtwJgWrhcsFMMfFFhFp
//jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL
//PmmdzqPrVvPwwTWBwg
//wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn
//ttgJtRGJQctTZtZT
//CrZsJsPPZsGzwwsLwLmpwMDw
//
//The first rucksack contains the items vJrwpWtwJgWrhcsFMMfFFhFp, which means its first compartment contains the items vJrwpWtwJgWr, while the second compartment contains the items hcsFMMfFFhFp. The only item type that appears in both compartments is lowercase p.
//The second rucksack's compartments contain jqHRNqRjqzjGDLGL and rsFMfFZSrLrFZsSL. The only item type that appears in both compartments is uppercase L.
//The third rucksack's compartments contain PmmdzqPrV and vPwwTWBwg; the only common item type is uppercase P.
//The fourth rucksack's compartments only share item type v.
//The fifth rucksack's compartments only share item type t.
//The sixth rucksack's compartments only share item type s.
//To help prioritize item rearrangement, every item type can be converted to a priority:
//
//Lowercase item types a through z have priorities 1 through 26.
//Uppercase item types A through Z have priorities 27 through 52.
//In the above example, the priority of the item type that appears in both compartments of each rucksack is 16 (p), 38 (L), 42 (P), 22 (v), 20 (t), and 19 (s); the sum of these is 157.
//
//Find the item type that appears in both compartments of each rucksack. What is the sum of the priorities of those item types?
fun main() {
fun part1(input: List<String>): Int {
val lcPriorities = mapOf(
'a' to 1,
'b' to 2,
'c' to 3,
'd' to 4,
'e' to 5,
'f' to 6,
'g' to 7,
'h' to 8,
'i' to 9,
'j' to 10,
'k' to 11,
'l' to 12,
'm' to 13,
'n' to 14,
'o' to 15,
'p' to 16,
'q' to 17,
'r' to 18,
's' to 19,
't' to 20,
'u' to 21,
'v' to 22,
'w' to 23,
'x' to 24,
'y' to 25,
'z' to 26
);
val ucPriorities = mapOf(
'A' to 27,
'B' to 28,
'C' to 29,
'D' to 30,
'E' to 31,
'F' to 32,
'G' to 33,
'H' to 34,
'I' to 35,
'J' to 36,
'K' to 37,
'L' to 38,
'M' to 39,
'N' to 40,
'O' to 41,
'P' to 42,
'Q' to 43,
'R' to 44,
'S' to 45,
'T' to 46,
'U' to 47,
'V' to 48,
'W' to 49,
'X' to 50,
'Y' to 51,
'Z' to 52
);
var left = mutableListOf<String>();
var right = mutableListOf<String>();
var sumOfItems = 0;
val itr = input.listIterator();
itr.forEach {
left.add(it.substring(0, it.length / 2));
right.add(it.substring(it.length / 2));
}
val leftItr = left.listIterator();
for ((index, leftSide) in leftItr.withIndex()) {
var priorityValue = 0;
for (i in leftSide.indices) {
if(right[index].contains(leftSide[i])) {
val commonLetter = leftSide[i];
if(commonLetter.isUpperCase()) {
priorityValue = ucPriorities.getValue(commonLetter);
} else {
priorityValue = lcPriorities.getValue(commonLetter);
}
break;
}
}
sumOfItems += priorityValue;
}
println("sum of items in both compartments: $sumOfItems");
return input.size
}
fun part2(input: List<String>): Int {
val lcPriorities = mapOf(
'a' to 1,
'b' to 2,
'c' to 3,
'd' to 4,
'e' to 5,
'f' to 6,
'g' to 7,
'h' to 8,
'i' to 9,
'j' to 10,
'k' to 11,
'l' to 12,
'm' to 13,
'n' to 14,
'o' to 15,
'p' to 16,
'q' to 17,
'r' to 18,
's' to 19,
't' to 20,
'u' to 21,
'v' to 22,
'w' to 23,
'x' to 24,
'y' to 25,
'z' to 26
);
val ucPriorities = mapOf(
'A' to 27,
'B' to 28,
'C' to 29,
'D' to 30,
'E' to 31,
'F' to 32,
'G' to 33,
'H' to 34,
'I' to 35,
'J' to 36,
'K' to 37,
'L' to 38,
'M' to 39,
'N' to 40,
'O' to 41,
'P' to 42,
'Q' to 43,
'R' to 44,
'S' to 45,
'T' to 46,
'U' to 47,
'V' to 48,
'W' to 49,
'X' to 50,
'Y' to 51,
'Z' to 52
);
var sackGroups = mutableListOf<List<String>>();
var tempSackGroup = mutableListOf<String>();
var sumOfBadges = 0;
val itr = input.listIterator();
for ((index, sack) in itr.withIndex()) {
tempSackGroup.add(sack);
if ((index + 1) % 3 == 0) {
sackGroups.add(tempSackGroup);
tempSackGroup = mutableListOf<String>();
}
}
for ((index, sackGroup) in sackGroups.withIndex()) {
var inSecond = false;
var inThird = false;
var badgeLetter = '%';
var badgeValue = 0;
val firstSack = sackGroup.get(0);
val secondSack = sackGroup.get(1);
val thirdSack = sackGroup.get(2);
for(i in firstSack.indices) {
badgeLetter = firstSack[i];
if(badgeLetter.isUpperCase()) {
badgeValue = ucPriorities.getValue(badgeLetter);
} else {
badgeValue = lcPriorities.getValue(badgeLetter);
}
if(secondSack.contains(badgeLetter)) {
inSecond = true;
}
if(thirdSack.contains(badgeLetter)) {
inThird = true;
}
if(inSecond && inThird) {
sumOfBadges += badgeValue;
break;
} else {
inSecond = false;
inThird = false;
}
}
}
println("Sum of badge groups: $sumOfBadges");
return input.size
}
val input = readInput("Day03/Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 039903c7019413d13368a224fd402625023d6f54 | 8,085 | AoC-2022-Kotlin | Apache License 2.0 |
src/main/kotlin/g0901_1000/s0953_verifying_an_alien_dictionary/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g0901_1000.s0953_verifying_an_alien_dictionary
// #Easy #Array #String #Hash_Table #Programming_Skills_I_Day_9_String
// #2023_05_02_Time_137_ms_(100.00%)_Space_35.5_MB_(93.75%)
class Solution {
fun isAlienSorted(words: Array<String>, order: String): Boolean {
val map = IntArray(26)
for (i in order.indices) {
map[order[i].code - 'a'.code] = i
}
for (i in 0 until words.size - 1) {
if (!isSmaller(words[i], words[i + 1], map)) {
return false
}
}
return true
}
private fun isSmaller(str1: String, str2: String, map: IntArray): Boolean {
val len1 = str1.length
val len2 = str2.length
val minLength = len1.coerceAtMost(len2)
for (i in 0 until minLength) {
if (map[str1[i].code - 'a'.code] > map[str2[i].code - 'a'.code]) {
return false
} else if (map[str1[i].code - 'a'.code] < map[str2[i].code - 'a'.code]) {
return true
}
}
return len1 <= len2
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,091 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/de/mbdevelopment/adventofcode/year2021/solvers/day17/Day17Puzzle2.kt | Any1s | 433,954,562 | false | {"Kotlin": 96683} | package de.mbdevelopment.adventofcode.year2021.solvers.day17
import de.mbdevelopment.adventofcode.year2021.solvers.PuzzleSolver
import kotlin.math.max
class Day17Puzzle2 : PuzzleSolver {
override fun solve(inputLines: Sequence<String>) =
bruteForceNumberOfSuccessfullInitialVelocities(inputLines.first()).toString()
private fun bruteForceNumberOfSuccessfullInitialVelocities(targetArea: String): Int {
val targetAreaCoordinates = targetArea.removePrefix("target area: ").split(", ")
val xTarget = targetAreaCoordinates[0].removePrefix("x=").toTargetRange()
val yTarget = targetAreaCoordinates[1].removePrefix("y=").toTargetRange()
val successfulInitialVelocities = mutableSetOf<Point>()
for (startVelocityX in -1000..1000) {
for (startVelocityY in -1000..1000) {
var xPosition = 0
var yPosition = 0
for (step in 0..1000) {
xPosition += max(0, startVelocityX - step)
yPosition += startVelocityY - step
if (xPosition in xTarget && yPosition in yTarget) {
successfulInitialVelocities += Point(startVelocityX, startVelocityY)
break // One hit is enough for this combination
}
if (xPosition > xTarget.last || yPosition < yTarget.first)
break // beyond target, cannot hit it anymore
}
}
}
return successfulInitialVelocities.size
}
private fun String.toTargetRange() = split("..").map { it.toInt() }.let { it[0]..it[1] }
}
data class Point(val x: Int, val y: Int)
| 0 | Kotlin | 0 | 0 | 21d3a0e69d39a643ca1fe22771099144e580f30e | 1,708 | AdventOfCode2021 | Apache License 2.0 |
Day_10/Solution_Part2.kts | 0800LTT | 317,590,451 | false | null | import java.io.File
import java.math.BigInteger
val INPUT_FILE_NAME = "test.txt"
// This was my initial implementation, though I knew it wouldn't work for the
// puzzle input. There are too many overlapping cases and we need to memoize the results.
// It works fine for the two small inputs.
/*
fun countCombinations(adapters: Set<Int>): BigInteger {
val lastAdapterValue = adapters.maxOrNull()!!
var combinations = 0.toBigInteger()
fun backtrack(currentAdapterValue: Int) {
if (currentAdapterValue == lastAdapterValue) combinations++
for (i in 1..3) {
val nextAdapterValue = currentAdapterValue + i
if (nextAdapterValue in adapters) {
backtrack(nextAdapterValue)
}
}
}
backtrack(0)
return combinations
}*/
fun countCombinations(adapters: IntArray): BigInteger {
val lastAdapterValue = adapters.maxOrNull()!!
val dp = mutableMapOf<Int, BigInteger>()
dp.put(0, 1.toBigInteger())
for (i in 0..adapters.size-1) {
val adapter = adapters[i]
for (diff in 1..3) {
dp[adapter] = dp.getOrDefault(adapter, 0.toBigInteger()) + dp.getOrDefault(adapter - diff, 0.toBigInteger())
}
}
return dp.getOrDefault(lastAdapterValue, -1.toBigInteger())
}
fun main() {
val sortedAdapters = File(INPUT_FILE_NAME).readLines().map { it.toInt() }.sorted().toMutableList()
sortedAdapters.add(sortedAdapters.maxOrNull()!! + 3)
val combinations = countCombinations(sortedAdapters.toIntArray())
println(combinations)
}
main()
| 0 | Kotlin | 0 | 0 | 191c8c307676fb0e7352f7a5444689fc79cc5b54 | 1,515 | advent-of-code-2020 | The Unlicense |
lib/src/main/kotlin/de/linkel/aoc/utils/rangeset/IntRangeSet.kt | norganos | 726,350,504 | false | {"Kotlin": 162220} | package de.linkel.aoc.utils.rangeset
import de.linkel.aoc.utils.iterables.intersect
import de.linkel.aoc.utils.iterables.intersects
class IntRangeSetFactory: RangeFactory<Int, IntRange, Int> {
companion object {
val INSTANCE = IntRangeSetFactory()
}
override fun build(start: Int, endInclusive: Int) = IntRange(start, endInclusive)
override fun incr(a: Int) = a +1
override fun add(a: Int, b: Int) = a + b
override fun subtract(a: Int, b: Int) = a - b
override fun count(range: IntRange) = range.last - range.first + 1
override fun sumCounts(counts: Iterable<Int>) = counts.sum()
override fun without(a: IntRange, b: IntRange): Collection<IntRange> {
return if (a.first >= b.first && a.last <= b.last) emptyList() // a completely inside b -> nothing left
else if (a.first < b.first && a.last > b.last) listOf(IntRange(a.first, b.first - 1), IntRange(b.last + 1, a.last)) // b completely inside a -> b cuts a in 2 parts
else if (a.first < b.first && a.last > b.first) listOf(IntRange(a.first, b.first - 1)) // b cuts a upper end
else if (a.last > b.last && a.first < b.last) listOf(IntRange(b.last + 1, a.last)) // b cuts a lower end
else listOf(a) // no intersection -> a stays the same
}
override fun intersects(a: IntRange, b: IntRange): Boolean {
return a.intersects(b)
}
override fun intersect(a: IntRange, b: IntRange): IntRange {
return a.intersect(b)
}
override val maxValue = Int.MAX_VALUE
override val minValue = Int.MIN_VALUE
}
class IntRangeSet(
ranges: Iterable<IntRange>
): AbstractNumberRangeSet<IntRangeSet, Int, IntRange, Int>(
ranges,
IntRangeSetFactory.INSTANCE
) {
override fun copy(ranges: Iterable<IntRange>) = IntRangeSet(ranges)
}
fun IntRange.toRangeSet(): IntRangeSet {
return IntRangeSet(listOf(this))
}
| 0 | Kotlin | 0 | 0 | 3a1ea4b967d2d0774944c2ed4d96111259c26d01 | 1,892 | aoc-utils | Apache License 2.0 |
src/Day03.kt | ElenaRgC | 572,898,962 | false | null | fun buscarCaracter(elemento: String): Char {
var i = 0
var j = 0
var caracterRepetido = ' '
while (i < elemento.length / 2) {
j = elemento.length / 2
while (j < elemento.length) {
if (elemento[i] == elemento[j]) {
caracterRepetido = elemento[i]
return elemento[i]
}
j++
}
i++
}
return caracterRepetido
}
fun comprobarValor(caracter: Char): Int {
var caracteres: String = "abcdefghijklmnopqrstuvwxyzABCDEFGHYJKLMNOPQRSTUVWXYZ"
var valor = 0
var i = 0
while (i < caracteres.length) {
if (caracteres[i] == caracter) {
valor = i + 1
}
i++
}
return valor
}
fun main() {
fun part1(input: List<String>): Int {
var caracterRepetido = ' '
var valorTotal = 0
for (elemento in input) {
caracterRepetido = buscarCaracter(elemento)
valorTotal += comprobarValor(caracterRepetido)
}
return valorTotal
}
fun part2(input: List<String>): Int {
var stringBadges = ""
var fila = 2
var caracter = 0
while (fila < input.size) {
for (caracterA in input[fila]) {
for (caracterB in input[fila - 1]) {
for (caracterC in input[fila - 2]) {
if (caracterA == caracterB && caracterB == caracterC) {
if ((fila+1) / 3 == stringBadges.length +1) {
stringBadges += caracterA
}
}
}
}
}
fila += 3
}
//println(stringBadges.length)
var valorTotal = 0
var i = 0
while (i < stringBadges.length) {
valorTotal += comprobarValor(stringBadges[i])
i++
}
return valorTotal
}
// 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 | b7505e891429970c377f7b45bfa8b5157f85c457 | 2,244 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/staricka/adventofcode2022/Day15.kt | mathstar | 569,952,400 | false | {"Kotlin": 77567} | package com.staricka.adventofcode2022
import com.staricka.adventofcode2022.Day15.Sensor.Companion.toSensor
import kotlin.math.abs
class Day15(
private val part1Row: Int = 2000000,
private val part2Limit: Int = 4000000
) : Day {
override val id = 15
enum class Tile {
AIR, SENSOR, BEACON
}
data class Sensor(
val x: Int,
val y: Int,
val beaconX: Int,
val beaconY: Int
) {
val distanceToBeacon = abs(x - beaconX) + abs(y - beaconY)
fun ringPastExclusion(limit: Int): Set<Pair<Int, Int>> {
val ring = HashSet<Pair<Int, Int>>()
for(ringX in (x - distanceToBeacon - 1)..(x + distanceToBeacon + 1)) {
if (ringX < 0 || ringX > limit) continue
val yDist = (distanceToBeacon + 1) - abs(x - ringX)
if (y + yDist in 0..limit) {
ring.add(Pair(ringX, y + yDist))
}
if (y - yDist in 0..limit) {
ring.add(Pair(ringX, y - yDist))
}
}
return ring
}
companion object {
private val REGEX = Regex("""Sensor at x=(-?[0-9]+), y=(-?[0-9]+): closest beacon is at x=(-?[0-9]+), y=(-?[0-9]+)""")
fun String.toSensor() : Sensor {
val match = REGEX.matchEntire(this)
return Sensor(
match!!.groups[1]!!.value.toInt(),
match.groups[2]!!.value.toInt(),
match.groups[3]!!.value.toInt(),
match.groups[4]!!.value.toInt()
)
}
}
}
class Grid {
val map = HashMap<Int, HashMap<Int, Tile>>()
private val sensors = ArrayList<Sensor>()
fun get(x: Int, y: Int): Tile = map[x]?.get(y) ?: Tile.AIR
fun put(x: Int, y: Int, tile: Tile) {
map.computeIfAbsent(x) {HashMap()}[y] = tile
}
fun manhattanDistance(x1: Int, y1: Int, x2: Int, y2: Int): Int = abs(x1 - x2) + abs(y1 - y2)
fun putSensor(sensor: Sensor) {
put(sensor.x, sensor.y, Tile.SENSOR)
put(sensor.beaconX, sensor.beaconY, Tile.BEACON)
sensors.add(sensor)
}
fun excludedTilesInCol(y: Int): Set<Pair<Int, Int>> {
val excluded = HashSet<Pair<Int, Int>>()
for (sensor in sensors) {
val x = sensor.x
var dist = 0
while (manhattanDistance(x + dist, y, sensor.x, sensor.y) <= sensor.distanceToBeacon) {
if (get(x + dist, y) != Tile.BEACON) {
excluded.add(Pair(x + dist, y))
}
if (get(x - dist, y) != Tile.BEACON) {
excluded.add(Pair(x - dist, y))
}
dist++
}
}
return excluded
}
private fun notExcluded(x: Int, y: Int): Boolean {
for (sensor in sensors) {
if (manhattanDistance(sensor.x, sensor.y, x, y) <= sensor.distanceToBeacon) {
return false
}
}
return true
}
fun findDistress(limit: Int): Pair<Int, Int> {
// check ring of points just past sensor range for each sensor
// start with sensor with lowest range for optimization
sensors.sortedBy { it.distanceToBeacon }
.forEach {
val ring = it.ringPastExclusion(limit)
ring.filter { point -> notExcluded(point.first, point.second) }
.forEach{ point -> return point }
}
throw Exception("Not found")
}
}
override fun part1(input: String): Any {
val grid = Grid()
input.lines().map { it.toSensor() }.forEach { grid.putSensor(it) }
return grid.excludedTilesInCol(part1Row).count()
}
override fun part2(input: String): Any {
val grid = Grid()
input.lines().map { it.toSensor() }.forEach { grid.putSensor(it) }
val distress = grid.findDistress(part2Limit)
return distress.first.toLong() * 4000000L + distress.second.toLong()
}
} | 0 | Kotlin | 0 | 0 | 2fd07f21348a708109d06ea97ae8104eb8ee6a02 | 3,698 | adventOfCode2022 | MIT License |
src/y2022/day04.kt | sapuglha | 573,238,440 | false | {"Kotlin": 33695} | package y2022
import extensions.contains
import readFileAsLines
fun main() {
fun getElves(line: String): Pair<IntRange, IntRange> {
val (first, second) = line.split(",")
val (firstBegin, firstEnd) = first.split("-").map(String::toInt)
val (secondBegin, secondEnd) = second.split("-").map(String::toInt)
return (firstBegin..firstEnd) to (secondBegin..secondEnd)
}
fun part1(input: List<String>): Int = input
.map { getElves(it) }
.map { (elf1, elf2) -> elf1.contains(elf2) || elf2.contains(elf1) }
.count { it }
fun part2(input: List<String>): Int = input
.map { getElves(it) }
.map { (elf1, elf2) -> (elf1.contains(elf2) || elf2.contains(elf1) || elf1.intersect(elf2).isNotEmpty()) }
.count { it }
"y2022/data/day04".readFileAsLines().let { input ->
println("part1: ${part1(input)}")
println("part2: ${part2(input)}")
}
}
| 0 | Kotlin | 0 | 0 | 82a96ccc8dcf38ae4974e6726e27ddcc164e4b54 | 948 | adventOfCode2022 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/CountPalindromicSubsequence.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
/**
* 1930. Unique Length-3 Palindromic Subsequences
* @see <a href="https://leetcode.com/problems/unique-length-3-palindromic-subsequences">Source</a>
*/
fun interface CountPalindromicSubsequence {
operator fun invoke(s: String): Int
}
sealed interface CountPalindromicStrategy {
/**
* Approach 1: Count Letters In-Between
*/
data object CountLetters : CountPalindromicSubsequence, CountPalindromicStrategy {
override fun invoke(s: String): Int {
val letters: MutableSet<Char> = HashSet()
for (c in s.toCharArray()) {
letters.add(c)
}
var ans = 0
for (letter in letters) {
var i = -1
var j = 0
for (k in s.indices) {
if (s[k] == letter) {
if (i == -1) {
i = k
}
j = k
}
}
val between: MutableSet<Char> = HashSet()
for (k in i + 1 until j) {
between.add(s[k])
}
ans += between.size
}
return ans
}
}
/**
* Approach 2: Pre-Compute First and Last Indices
*/
data object PreComputeFirstAndLastIndices : CountPalindromicSubsequence, CountPalindromicStrategy {
override fun invoke(s: String): Int {
val first = IntArray(ALPHABET_LETTERS_COUNT) { -1 }
val last = IntArray(ALPHABET_LETTERS_COUNT)
for (i in s.indices) {
val curr: Int = s[i] - 'a'
if (first[curr] == -1) {
first[curr] = i
}
last[curr] = i
}
var ans = 0
for (i in 0..<ALPHABET_LETTERS_COUNT) {
if (first[i] == -1) {
continue
}
val between: MutableSet<Char> = HashSet()
for (j in first[i] + 1 until last[i]) {
between.add(s[j])
}
ans += between.size
}
return ans
}
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,916 | kotlab | Apache License 2.0 |
src/commonMain/kotlin/faraday/base/Distance.kt | Amagi82 | 289,812,027 | false | null | package faraday.base
import faraday.Prefixes
import faraday.Units
import faraday.derived.Energy
import faraday.derived.Force
import faraday.derived.kinematic.Velocity
import faraday.derived.mechanical.Area
import faraday.derived.mechanical.FuelEfficiency
import faraday.derived.mechanical.Stiffness
import faraday.derived.mechanical.Volume
import kotlin.jvm.JvmInline
import kotlin.math.PI
/**
* Length is a measure of distance. In the International System of Quantities, length is a
* quantity with dimension distance. In most systems of measurement a base unit for length
* is chosen, from which all other units are derived. In the International System of Units
* (SI) system the base unit for length is the meter.
*
* Length is commonly understood to mean the most extended dimension of a fixed object.
* However, this is not always the case and may depend on the position the object is in.
*
* Various terms for the length of a fixed object are used, and these include height, which
* is vertical length or vertical extent, and width, breadth or depth. Height is used when
* there is a base from which vertical measurements can be taken. Width or breadth usually
* refer to a shorter dimension when length is the longest one. Depth is used for the third
* dimension of a three dimensional object.
*
* [Wiki](https://en.wikipedia.org/wiki/Length)
*/
@JvmInline
value class Distance(val meters: Double) : Units<Distance> {
val angstroms get() = meters / ANGSTROM
val millimeters get() = meters / Prefixes.MILLI
val centimeters get() = meters / Prefixes.CENTI
val kilometers get() = meters / Prefixes.KILO
val astronomicalUnits get() = meters / ASTRONOMICAL_UNIT
val lightYears get() = meters / LIGHT_YEAR
val parsecs get() = meters / PARSEC
val inches get() = meters / INCH
val feet get() = meters / FOOT
val yards get() = meters / YARD
val miles get() = meters / MILE
val nauticalMiles get() = meters / NAUTICAL_MILE
override fun plus(other: Distance) = Distance(meters = meters + other.meters)
override fun minus(other: Distance) = Distance(meters = meters - other.meters)
override fun times(factor: Number) = Distance(meters = meters * factor.toDouble())
override fun div(factor: Number) = Distance(meters = meters / factor.toDouble())
override fun compareTo(other: Distance): Int = meters.compareTo(other.meters)
operator fun times(distance: Distance) = Area(squareMeters = meters * distance.meters)
operator fun times(area: Area): Volume = area * this
operator fun times(force: Force): Energy = force * this
operator fun times(stiffness: Stiffness): Force = stiffness * this
operator fun div(time: Time) = Velocity(metersPerSecond = meters / time.seconds)
operator fun div(velocity: Velocity) = Time(seconds = meters / velocity.metersPerSecond)
operator fun div(volume: Volume) = FuelEfficiency(metersPerCubicMeter = meters / volume.cubicMeters)
companion object {
const val LIGHT_SECOND = 299_792_458.0
const val LIGHT_YEAR = LIGHT_SECOND * Time.JULIAN_YEAR
const val ASTRONOMICAL_UNIT = 149_597_870_700.0
const val PARSEC = (648_000.0 / PI) * ASTRONOMICAL_UNIT
const val ANGSTROM = 1e-10
const val INCH = 0.0254
const val FOOT = INCH * 12
const val YARD = FOOT * 3
const val MILE = YARD * 1760
const val NAUTICAL_MILE = 1852.0
}
}
typealias Length = Distance
typealias Width = Distance
typealias Height = Distance
typealias Depth = Distance
val Number.angstroms get() = Distance(meters = toDouble() * Distance.ANGSTROM)
val Number.millimeters get() = Distance(meters = toDouble() * Prefixes.MILLI)
val Number.centimeters get() = Distance(meters = toDouble() * Prefixes.CENTI)
val Number.meters get() = Distance(meters = toDouble())
val Number.kilometers get() = Distance(meters = toDouble() * Prefixes.KILO)
val Number.lightYears get() = Distance(meters = toDouble() * Distance.LIGHT_YEAR)
val Number.parsecs get() = Distance(meters = toDouble() * Distance.PARSEC)
val Number.inches get() = Distance(meters = toDouble() * Distance.INCH)
val Number.feet get() = Distance(meters = toDouble() * Distance.FOOT)
val Number.yards get() = Distance(meters = toDouble() * Distance.YARD)
val Number.miles get() = Distance(meters = toDouble() * Distance.MILE)
val Number.nauticalMiles get() = Distance(meters = toDouble() * Distance.NAUTICAL_MILE)
| 0 | Kotlin | 0 | 0 | b0f08fc06e51344736ef0953a42061044de47f80 | 4,457 | Faraday | Apache License 2.0 |
Retos/Reto #2 - EL PARTIDO DE TENIS [Media]/kotlin/IsmaelMatiz.kts | mouredev | 581,049,695 | false | {"Python": 3866914, "JavaScript": 1514237, "Java": 1272062, "C#": 770734, "Kotlin": 533094, "TypeScript": 457043, "Rust": 356917, "PHP": 281430, "Go": 243918, "Jupyter Notebook": 221090, "Swift": 216751, "C": 210761, "C++": 164758, "Dart": 159755, "Ruby": 70259, "Perl": 52923, "VBScript": 49663, "HTML": 45912, "Raku": 44139, "Scala": 30892, "Shell": 27625, "R": 19771, "Lua": 16625, "COBOL": 15467, "PowerShell": 14611, "Common Lisp": 12715, "F#": 12710, "Pascal": 12673, "Haskell": 11051, "Assembly": 10368, "Elixir": 9033, "Visual Basic .NET": 7350, "Groovy": 7331, "PLpgSQL": 6742, "Clojure": 6227, "TSQL": 5744, "Zig": 5594, "Objective-C": 5413, "Apex": 4662, "ActionScript": 3778, "Batchfile": 3608, "OCaml": 3407, "Ada": 3349, "ABAP": 2631, "Erlang": 2460, "BASIC": 2340, "D": 2243, "Awk": 2203, "CoffeeScript": 2199, "Vim Script": 2158, "Brainfuck": 1550, "Prolog": 1342, "Crystal": 783, "Fortran": 778, "Solidity": 560, "Standard ML": 525, "Scheme": 457, "Vala": 454, "Limbo": 356, "xBase": 346, "Jasmin": 285, "Eiffel": 256, "GDScript": 252, "Witcher Script": 228, "Julia": 224, "MATLAB": 193, "Forth": 177, "Mercury": 175, "Befunge": 173, "Ballerina": 160, "Smalltalk": 130, "Modula-2": 129, "Rebol": 127, "NewLisp": 124, "Haxe": 112, "HolyC": 110, "GLSL": 106, "CWeb": 105, "AL": 102, "Fantom": 97, "Alloy": 93, "Cool": 93, "AppleScript": 85, "Ceylon": 81, "Idris": 80, "Dylan": 70, "Agda": 69, "Pony": 69, "Pawn": 65, "Elm": 61, "Red": 61, "Grace": 59, "Mathematica": 58, "Lasso": 57, "Genie": 42, "LOLCODE": 40, "Nim": 38, "V": 38, "Chapel": 34, "Ioke": 32, "Racket": 28, "LiveScript": 25, "Self": 24, "Hy": 22, "Arc": 21, "Nit": 21, "Boo": 19, "Tcl": 17, "Turing": 17} | /*
* Escribe un programa que muestre cómo transcurre un juego de tenis y quién lo ha ganado.
* El programa recibirá una secuencia formada por "P1" (Player 1) o "P2" (Player 2), según quien
* gane cada punto del juego.
*
* - Las puntuaciones de un juego son "Love" (cero), 15, 30, 40, "Deuce" (empate), ventaja.
* - Ante la secuencia [P1, P1, P2, P2, P1, P2, P1, P1], el programa mostraría lo siguiente:
* 15 - Love
* 30 - Love
* 30 - 15
* 30 - 30
* 40 - 30
* Deuce
* Ventaja P1
* Ha ganado el P1
* - Si quieres, puedes controlar errores en la entrada de datos.
* - Consulta las reglas del juego si tienes dudas sobre el sistema de puntos.
*/
fun SetScore(match: Array<String>){
//Score for each player
var p1 = 0
var p2 = 0
//Posible scores
val SCORES = arrayOf("Love","15","30","40")
//Check the input
match.forEach { if((it.capitalize().equals("P1") || it.capitalize().equals("P2")) == false) {println("Ingresa un valor valido(P1,P2)"); return;}}
if (match.size > 8) {println("Ingresa hasta 8 rondas"); return;}
for(round in match){
//Plus the points per round
if (round.capitalize().equals("P1")) p1 ++ else p2++
//if points are less than 3 print the scores otherwise print the words
if (p1 <= 3 && p2 <= 3){
println(SCORES[p1]+" - "+SCORES[p2])
}else{
if(p1 == p2) println("Deuce")
else if(p1 > p2) println("Ventaja P1")
else if (p1 < p2) println("Ventaja P2")
}
}
//finally print which payer won
println(if (p1 > p2) "Ha ganado el P1" else if (p1 == p2) "Empate" else "Ha ganado el P2")
}
var game = arrayOf("P1", "P1", "P1","P1", "P2","P2","P2","P2")
SetScore(game)
| 4 | Python | 2,929 | 4,661 | adcec568ef7944fae3dcbb40c79dbfb8ef1f633c | 1,768 | retos-programacion-2023 | Apache License 2.0 |
src/day1/Day01.kt | kacperhreniak | 572,835,614 | false | {"Kotlin": 85244} | import java.util.PriorityQueue
import kotlin.math.max
private const val MAX_SIZE = 3
private fun part1(input: List<String>): Int {
var max = Int.MIN_VALUE
var temp = 0
input.forEach {
if (it.isEmpty() && temp > 0) {
max = max(max, temp)
temp = 0
} else {
temp += it.toInt()
}
}
return max
}
private fun part2(input: List<String>): Int {
fun PriorityQueue<Int>.addNewItem(value: Int) {
if (isNotEmpty() && size == MAX_SIZE && peek() < value) poll()
if (value != 0) add(value)
}
val queue = PriorityQueue<Int>(MAX_SIZE, compareByDescending { it })
var temp = 0
input.forEach {
if (it.isEmpty() && temp > 0) {
queue.addNewItem(value = temp)
temp = 0
} else {
temp += it.toInt()
}
}
queue.addNewItem(value = temp)
var result = 0
for (index in 0 until MAX_SIZE) {
result += queue.poll()
}
return result
}
fun main() {
val input = readInput("day1/input")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 1 | 0 | 03368ffeffa7690677c3099ec84f1c512e2f96eb | 1,124 | aoc-2022 | Apache License 2.0 |
src/test/kotlin/be/brammeerten/y2023/Day10Pt2Test.kt | BramMeerten | 572,879,653 | false | {"Kotlin": 170522} | package be.brammeerten.y2023
import be.brammeerten.C
import be.brammeerten.readFile
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
class Day10Pt2Test {
@Test
fun `part 1`() {
// val map = PipeMap(readFile("2023/day10/exampleInput3.txt"))
// val map = PipeMap(readFile("2023/day10/exampleInput4.txt"))
// val map = PipeMap(readFile("2023/day10/exampleInput5.txt"))
val map = PipeMap(readFile("2023/day10/input.txt"))
val distances = listOfNotNull(
map.getPolygonNonStack(map.start + C.DOWN),
map.getPolygonNonStack(map.start + C.UP),
map.getPolygonNonStack(map.start + C.RIGHT),
map.getPolygonNonStack(map.start + C.LEFT),
)
// if (distances.size != 2) throw RuntimeException("Not expected")
val polygon = distances[1]
val newPoly = toPolygon(polygon)
val bounding = getBounding(polygon)
var inside = 0
for (row in bounding.first.y .. bounding.second.y) {
for (col in bounding.first.x .. bounding.second.x) {
var x = col
var y = row
if (polygon.contains(C(col, row))) continue
var count = 0
while (x <= bounding.second.x && y <= bounding.second.y) {
val partOfPoly = polygon.contains(C(x, y))
if (map.isStartWall(C(x, y)) && partOfPoly) {
count++
}
x++
y++
}
if (count % 2 == 1)
inside++
}
// println("$row: $count")
}
// assertThat(inside).isEqualTo(4);
// assertThat(inside).isEqualTo(8);
// assertThat(inside).isEqualTo(10);
assertThat(inside).isEqualTo(285); // 217 = too low, 298 = too high
}
private fun toPolygon(polygon: List<C>): MutableList<C> {
val newPoly = mutableListOf<C>()
for (i in polygon.indices) {
if (i + 1 == polygon.size) {
newPoly.add(polygon[i])
break;
}
val prev = if (i == 0) polygon.last() else polygon[i - 1]
val next = polygon[i + 1]
val cur = polygon[i]
if (prev.x == cur.x && next.x == cur.x) continue
if (prev.y == cur.y && next.y == cur.y) continue
newPoly.add(cur)
}
return newPoly
}
private fun getBounding(polygon: List<C>): Pair<C, C> {
var min = C(Int.MAX_VALUE, Int.MAX_VALUE)
var max = C(Int.MIN_VALUE, Int.MIN_VALUE)
for (p in polygon) {
min = C(Math.min(p.x, min.x), Math.min(p.y, min.y))
max = C(Math.max(p.x, max.x), Math.max(p.y, max.y))
}
return min to max
}
class PipeMap(val rows: List<String>) {
val UP_DOWN = '|'
val LEFT_RIGHT = '-'
val UP_RIGHT = 'L'
val UP_LEFT = 'J'
val LEFT_DOWN = '7'
val RIGHT_DOWN = 'F'
val start: C;
val w: Int = rows[0].length;
val h: Int = rows.size
init {
var s: C? = null;
for (y in 0 until h) {
for (x in 0 until w) {
if (rows[y][x] == 'S') {
s = C(x, y);
break;
}
}
}
if (s != null) start = s else throw RuntimeException("No start")
}
fun getSurrounding(): List<C> {
val surrounding = mutableListOf<C>()
val down = get(start + C.DOWN)
if (down == UP_DOWN || down == UP_LEFT || down == UP_RIGHT)
surrounding.add(start + C.DOWN)
val left = get(start + C.LEFT)
if (left == RIGHT_DOWN || left == UP_RIGHT || left == LEFT_RIGHT)
surrounding.add(start + C.LEFT)
val right = get(start + C.RIGHT)
if (right == LEFT_RIGHT || right == LEFT_DOWN || right == UP_LEFT)
surrounding.add(start + C.RIGHT)
val up = get(start + C.UP)
if (up == UP_DOWN || up == RIGHT_DOWN || up == LEFT_DOWN)
surrounding.add(start + C.UP)
return surrounding
}
fun isStartWall(c: C): Boolean {
val value = get(c)!!
// return value == '|'/* || value == 'L' || value == 'F'*/
// return value == '|' || value == 'L' || value == 'J'
return value != '7' && value != 'L'
}
fun isEndWall(c: C): Boolean {
val value = get(c)!!
// return value == '|' || value == 'J' || value == '7'
return value == '|' || value == 'L' || value == 'J'
}
fun get(c: C): Char? {
if (c.y < rows.size && c.x < rows[0].length && c.y >= 0 && c.x >= 0)
return rows[c.y][c.x]
else return null
}
fun getDistanceMap(cur: C, next: C, curVal: Int = 0, map: MutableMap<C, Int> = mutableMapOf()): Map<C, Int>? {
val nextVal = get(next)
if (nextVal == 'S') return map
map[next] = curVal + 1
if (nextVal == UP_DOWN && cur != next + C.DOWN)
return getDistanceMap(next, next + C.DOWN, curVal + 1, map)
else if (nextVal == UP_DOWN)
return getDistanceMap(next, next + C.UP, curVal + 1, map)
if (nextVal == LEFT_RIGHT && cur != next + C.LEFT)
return getDistanceMap(next, next + C.LEFT, curVal + 1, map)
else if (nextVal == LEFT_RIGHT)
return getDistanceMap(next, next + C.RIGHT, curVal + 1, map)
if (nextVal == UP_RIGHT && cur != next + C.UP)
return getDistanceMap(next, next + C.UP, curVal + 1, map)
else if (nextVal == UP_RIGHT)
return getDistanceMap(next, next + C.RIGHT, curVal + 1, map)
if (nextVal == UP_LEFT && cur != next + C.UP)
return getDistanceMap(next, next + C.UP, curVal + 1, map)
else if (nextVal == UP_LEFT)
return getDistanceMap(next, next + C.LEFT, curVal + 1, map)
if (nextVal == LEFT_DOWN && cur != next + C.LEFT)
return getDistanceMap(next, next + C.LEFT, curVal + 1, map)
else if (nextVal == LEFT_DOWN)
return getDistanceMap(next, next + C.DOWN, curVal + 1, map)
if (nextVal == RIGHT_DOWN && cur != next + C.RIGHT)
return getDistanceMap(next, next + C.RIGHT, curVal + 1, map)
else if (nextVal == RIGHT_DOWN)
return getDistanceMap(next, next + C.DOWN, curVal + 1, map)
return null
}
fun getPolygonNonStack(nnnn: C): List<C>? {
var cur = start
var next = nnnn
val map = mutableListOf<C>()
while (true) {
val nextVal = get(next)
map.add(next)
if (nextVal == 'S') return map
if (nextVal == UP_DOWN && cur != next + C.DOWN) {
cur = next; next += C.DOWN; continue;
} else if (nextVal == UP_DOWN) {
cur = next; next += C.UP; continue;
}
if (nextVal == LEFT_RIGHT && cur != next + C.LEFT) {
cur = next; next += C.LEFT; continue;
} else if (nextVal == LEFT_RIGHT) {
cur = next; next += C.RIGHT; continue;
}
if (nextVal == UP_RIGHT && cur != next + C.UP) {
cur = next; next += C.UP; continue;
} else if (nextVal == UP_RIGHT) {
cur = next; next += C.RIGHT; continue;
}
if (nextVal == UP_LEFT && cur != next + C.UP) {
cur = next; next += C.UP; continue;
} else if (nextVal == UP_LEFT) {
cur = next; next += C.LEFT; continue;
}
if (nextVal == LEFT_DOWN && cur != next + C.LEFT) {
cur = next; next += C.LEFT; continue;
} else if (nextVal == LEFT_DOWN) {
cur = next; next += C.DOWN; continue;
}
if (nextVal == RIGHT_DOWN && cur != next + C.RIGHT) {
cur = next; next += C.RIGHT; continue;
} else if (nextVal == RIGHT_DOWN) {
cur = next; next += C.DOWN; continue;
}
return null
}
}
}
} | 0 | Kotlin | 0 | 0 | 1defe58b8cbaaca17e41b87979c3107c3cb76de0 | 8,696 | Advent-of-Code | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/SortArrayByParity2.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2020 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import dev.shtanko.algorithms.extensions.swap
/**
* Given an array A of non-negative integers, half of the integers in A are odd, and half of the integers are even.
* Sort the array so that whenever A[i] is odd, i is odd; and whenever A[i] is even, i is even.
*/
fun interface AbstractSortByParity {
operator fun invoke(array: IntArray): IntArray
}
class SortByParityTwoPass : AbstractSortByParity {
override operator fun invoke(array: IntArray): IntArray {
val arraySize = array.size
val resultArray = IntArray(arraySize)
var evenIndex = 0
var oddIndex = 1
for (element in array) {
if (element % 2 == 0) {
resultArray[evenIndex] = element
evenIndex += 2
}
}
for (element in array) {
if (element % 2 == 1) {
resultArray[oddIndex] = element
oddIndex += 2
}
}
return resultArray
}
}
class SortByParityHeads : AbstractSortByParity {
override operator fun invoke(array: IntArray): IntArray {
var oddIndex = 1
var evenIndex = 0
while (evenIndex < array.size) {
if (array[evenIndex] % 2 == 1) {
while (array[oddIndex] % 2 == 1) {
oddIndex += 2
}
array.swap(evenIndex, oddIndex)
}
evenIndex += 2
}
return array
}
}
class SortByParityStraightForward : AbstractSortByParity {
override operator fun invoke(array: IntArray): IntArray {
val n = array.size
var evenIndex = 0
var oddIndex = 1
while (evenIndex < n && oddIndex < n) {
if (array[evenIndex] % 2 != 0) {
array.swap(evenIndex, oddIndex)
oddIndex += 2
} else {
evenIndex += 2
}
}
return array
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,587 | kotlab | Apache License 2.0 |
scripts/Day3.kts | matthewm101 | 573,325,687 | false | {"Kotlin": 63435} | import java.io.File
data class Sack(val first: Set<Int>, val second: Set<Int>) {
fun match() = first.intersect(second)
fun all() = first.union(second)
}
data class Group(val first: Sack, val second: Sack, val third: Sack) {
fun badge() = first.all().intersect(second.all()).intersect(third.all())
}
fun adjustValue(c: Char) = if (c >= 'A' && c <= 'Z') c.code - 65 + 27 else c.code - 97 + 1
val sacks = File("../inputs/3.txt").readLines().map { line ->
val chars = line.map { adjustValue(it) }
Sack(chars.subList(0, chars.size / 2).toSet(), chars.subList(chars.size / 2, chars.size).toSet())
}
val matchSum = sacks.map { sack ->
val set = sack.match()
assert(set.size == 1)
set.first()
}.sum()
println("The sum of the priorities of the items that appear in both compartments in each sack is $matchSum.")
val groups = (0).until(sacks.size / 3).map { Group(sacks[it*3], sacks[it*3+1], sacks[it*3+2]) }
val badgeSum = groups.map { group ->
val set = group.badge()
assert(set.size == 1)
set.first()
}.sum()
println("The sum of the priorities of the items that appear in all sacks in each group is $badgeSum.") | 0 | Kotlin | 0 | 0 | bbd3cf6868936a9ee03c6783d8b2d02a08fbce85 | 1,191 | adventofcode2022 | MIT License |
src/Day06.kt | josemarcilio | 572,290,152 | false | {"Kotlin": 5535} | fun main() {
fun solve(input: String, window: Int): Int {
return input.indices.windowed(window, step = 1) { values ->
if (values.map{ input[it] }.toSet().size == window) {
return@windowed values.last() + 1
}
-1
}.first { it > 0 }
}
fun part1(input: String) = solve(input, 4)
fun part2(input: String) = solve(input, 14)
// test if implementation meets criteria from the description, like:
val testInput = readInputText("Day06_test")
check(part1(testInput) == 11)
check(part2(testInput) == 26)
val input = readInputText("Day06")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | d628345afeb014adce189fddac53a1fcd98479fb | 690 | advent-of-code-2022 | Apache License 2.0 |
src/main/aoc2021/Day3.kt | nibarius | 154,152,607 | false | {"Kotlin": 963896} | package aoc2021
class Day3(val input: List<String>) {
private fun getOneCounts(numbers: List<String>): List<Int> {
val len = numbers.first().length
val oneCounts = Array(len) { 0 }
numbers.forEach { number ->
number.forEachIndexed { index, c ->
if (c == '1') {
oneCounts[index] += 1
}
}
}
return oneCounts.toList()
}
fun solvePart1(): Int {
val oneCounts = getOneCounts(input)
val numbers = input.size
val most = oneCounts.joinToString("") {
if (it > numbers / 2) "1" else "0"
}.toInt(2)
// Inverting the binary representation of most gives fewest
// xor:ing with only ones flips all bits.
val mask = "1".repeat(input.first().length).toInt(2)
val fewest = most xor mask
return most * fewest
}
/**
* Get the oxygen/co2 rating. Returns the oxygen generation
* rating when numberToKeep is 1 and the co2 scrubbing rating
* when numberToKeep is 0.
*/
private fun getRating(numberToKeep: Int): Int {
val keep = numberToKeep.toString().first()
val discard = (1 - numberToKeep).toString().first()
var remainingNumbers = input
var offset = 0
while (remainingNumbers.size > 1) {
val ones = getOneCounts(remainingNumbers)
// If ones are most common at the current offset, keep the 'keep' digits.
// For oxygen keep is '1' which means keeping 1 when 1 is most common (or keeping the most common value)
// For co2 keep is '0' which means keeping 0 when 1 is most common (or keeping the least common value)
val toKeep = if (ones[offset] >= remainingNumbers.size - ones[offset]) keep else discard
remainingNumbers = remainingNumbers.filter { it[offset] == toKeep }
offset++
}
return remainingNumbers.first().toInt(2)
}
fun solvePart2(): Int {
return getRating(0) * getRating(1)
}
} | 0 | Kotlin | 0 | 6 | f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22 | 2,078 | aoc | MIT License |
src/Day04.kt | romainbsl | 572,718,344 | false | {"Kotlin": 17019} | fun main() {
fun String.toRange(): Set<Int> {
val (start, end) = split("-").map(String::toInt)
return IntRange(start, end).toSet()
}
fun List<String>.toAssignments(): List<Pair<Set<Int>, Set<Int>>> = map {
val (left, right) = it.split(",")
left.toRange() to right.toRange()
}
fun part1(input: List<String>): Int {
return input.toAssignments()
.count { assignments ->
val (first, second) = assignments
first.all { it in second } || second.all { it in first }
}
}
fun part2(input: List<String>): Int {
return input.toAssignments()
.count { assignments ->
val (first, second) = assignments
first.any { it in second } || second.any { it in first }
}
}
val testInput = readInput("Day04")
// Part 1
println(part1(testInput))
// Part 2
println(part2(testInput))
} | 0 | Kotlin | 0 | 0 | b72036968769fc67c222a66b97a11abfd610f6ce | 974 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/Day16.kt | andrewrlee | 434,584,657 | false | {"Kotlin": 29493, "Clojure": 14117, "Shell": 398} | import Day16.Type.EQUAL_TO
import Day16.Type.G_THAN
import Day16.Type.LITERAL
import Day16.Type.L_THAN
import Day16.Type.MAX
import Day16.Type.MIN
import Day16.Type.PRODUCT
import Day16.Type.SUM
import java.io.File
import java.math.BigInteger
import java.nio.charset.Charset.defaultCharset
object Day16 {
enum class Type(val code: Int) {
SUM(0),
PRODUCT(1),
MIN(2),
MAX(3),
LITERAL(4),
G_THAN(5),
L_THAN(6),
EQUAL_TO(7);
companion object {
fun fromCode(code: Int) = values().first { it.code == code }
}
}
private fun String.toBinary() = BigInteger(this, 16).toString(2).let {
String.format("%4s", it).replace(" ", "0").toCharArray().toList()
}
sealed class Packet(
open val version: Int,
open val type: Type,
) {
abstract fun getTotalVersion(): Int
abstract fun evaluate(): Long
}
data class Literal(
override val version: Int,
val literal: Long
) : Packet(version, LITERAL) {
override fun getTotalVersion() = version
override fun evaluate(): Long = literal
}
data class Operator(
override val version: Int,
override val type: Type,
val payload: List<Packet>
) : Packet(version, type) {
override fun getTotalVersion() = version + (payload.sumOf { it.getTotalVersion() })
override fun evaluate() = when (type) {
SUM -> payload.sumOf { it.evaluate() }
PRODUCT -> payload.fold(1L) { acc, i -> acc * i.evaluate() }
MIN -> payload.minOf { it.evaluate() }
MAX -> payload.maxOf { it.evaluate() }
G_THAN -> if (payload[0].evaluate() > payload[1].evaluate()) 1 else 0
L_THAN -> if (payload[0].evaluate() < payload[1].evaluate()) 1 else 0
EQUAL_TO -> if (payload[0].evaluate() == payload[1].evaluate()) 1 else 0
else -> throw RuntimeException("unexpected type")
}
}
data class BinaryString(var input: List<Char>) {
fun isNotEmpty() = input.isNotEmpty() && input.size > 3
fun readString(length: Int): String {
val chars = mutableListOf<Char>()
var index = 0
var realCount = 0
do {
when (val c = input[index]) {
'%' -> {}
else -> {
chars.add(c)
realCount++
}
}
index++
} while (realCount != length)
input = input.subList(index, input.size)
return chars.joinToString("")
}
fun readSection(length: Int): BinaryString {
val chars = mutableListOf<Char>()
var index = 0
var realCount = 0
do {
val c = input[index]
when (c) {
'%' -> {}
else -> {
realCount++
}
}
chars.add(c)
index++
} while (realCount != length)
input = input.subList(index, input.size)
return BinaryString(chars)
}
fun readInt(length: Int): Int {
val string = readString(length)
return Integer.parseInt(string, 2)
}
}
private fun readPackets(input: BinaryString): MutableList<Packet> {
val packets = mutableListOf<Packet>()
while (input.isNotEmpty()) {
packets.add(input.readPacket())
}
return packets
}
private fun BinaryString.readPacket(): Packet {
val version = this.readInt(3)
return when (val type = Type.fromCode(this.readInt(3))) {
LITERAL -> readLiteral(version, this)
else -> readOperator(version, type, this)
}
}
private fun readOperator(version: Int, type: Type, input: BinaryString): Packet {
val packets = when (input.readString(1)) {
"0" -> {
val size = input.readInt(15)
readPackets(input.readSection(size))
}
"1" -> {
val numberOfPackets = input.readInt(11)
(0 until numberOfPackets).map { input.readPacket() }
}
else -> throw RuntimeException("unexpected val")
}
return Operator(version, type, packets)
}
private fun readLiteral(version: Int, input: BinaryString): Packet {
val parts = mutableListOf<Char>()
var finish: Boolean
do {
val (a, b, c, d, e) = input.readString(5).toList()
parts.addAll(listOf(b, c, d, e))
finish = a == '0'
} while (!finish)
val value = BigInteger(parts.joinToString(""), 2).longValueExact()
return Literal(version, value)
}
val input = {
File("day16/input-real.txt")
.readText(defaultCharset())
.map { it.toString().toBinary() }
.flatMap { it + '%' }
.let { BinaryString(it) }
}
object Part1 {
fun run() = println(input().readPacket().getTotalVersion())
}
object Part2 {
fun run() = println(input().readPacket().evaluate())
}
}
fun main() {
Day16.Part1.run()
Day16.Part2.run()
} | 0 | Kotlin | 0 | 0 | aace0fccf9bb739d57f781b0b79f2f3a5d9d038e | 5,394 | adventOfCode2021 | MIT License |
src/main/kotlin/se/saidaspen/aoc/aoc2015/Day06.kt | saidaspen | 354,930,478 | false | {"Kotlin": 301372, "CSS": 530} | package se.saidaspen.aoc.aoc2015
import se.saidaspen.aoc.util.Day
import se.saidaspen.aoc.util.P
import se.saidaspen.aoc.util.ints
import se.saidaspen.aoc.util.rectangle
fun main() = Day06.run()
object Day06 : Day(2015, 6) {
override fun part1(): Any {
val map = mutableMapOf<P<Int, Int>, Boolean>()
input.lines()
.map { it.substring(0, 7) to ints(it) }
.forEach {
val (x1, y1, x2, y2) = it.second
val rect = rectangle(P(x1, y1), P(x2, y2))
for (p in rect) {
when (it.first) {
"turn on" -> map[p] = true
"turn of" -> map[p] = false
"toggle " -> map[p] = map.getOrDefault(p, false).not()
else -> throw RuntimeException("Unsupported action '" + it.first + "'")
}
}
}
return map.count { it.value }
}
override fun part2(): Any {
val map = mutableMapOf<P<Int, Int>, Int>()
input.lines()
.map { it.substring(0, 7) to ints(it) }
.forEach {
val (x1, y1, x2, y2) = it.second
val rect = rectangle(P(x1, y1), P(x2, y2))
for (p in rect) {
when (it.first) {
"turn on" -> map[p] = map.getOrDefault(p, 0) + 1
"turn of" -> map[p] = map.getOrDefault(p, 0) - 1
"toggle " -> map[p] = map.getOrDefault(p, 0) + 2
else -> throw RuntimeException("Unsupported action '" + it.first + "'")
}
if (map[p]!! < 0 ) map[p] = 0
}
}
return map.values.sum()
}
}
| 0 | Kotlin | 0 | 1 | be120257fbce5eda9b51d3d7b63b121824c6e877 | 1,792 | adventofkotlin | MIT License |
src/org/mjurisic/aoc2020/day7/Day7.kt | mjurisic | 318,555,615 | false | null | package org.mjurisic.aoc2020.day7
import java.io.File
import java.util.function.Consumer
class Day7 {
companion object {
@JvmStatic
fun main(args: Array<String>) = try {
val nodes = HashMap<String, Node>()
val vertices = ArrayList<Vertex>()
File(ClassLoader.getSystemResource("resources/input7.txt").file).forEachLine {
val bagColor = it.substring(0, it.indexOf("bags") - 1)
val bagContent = it.substring(it.indexOf("contain") + 8, it.length - 1)
val edges = ArrayList<Vertex>()
if (bagContent != "no other bags") {
bagContent.split(",").forEach(Consumer {
val bag = it.trim()
val strength = bag.substring(0, bag.indexOf(" "))
val color = bag.substring(bag.indexOf(" ") + 1, bag.lastIndexOf(" "))
val vertex = Vertex(bagColor, color, strength.toInt())
edges.add(vertex)
vertices.add(vertex)
})
}
nodes.put(bagColor, Node(bagColor, edges))
}
// part 1
// println(nodes.filter { isContained(it.value, vertices, nodes, "shiny gold") }.size)
val sourceNode = nodes["shiny gold"]
println(countBags(sourceNode!!, nodes, vertices))
} catch (e: Exception) {
e.printStackTrace()
}
// part 1
private fun isContained(
bag: Node,
vertices: java.util.ArrayList<Vertex>,
nodes: HashMap<String, Node>,
color: String
): Boolean {
if (bag.color == color) {
return false
}
if (contains(bag, vertices, nodes, color)) {
return true
}
return false
}
private fun contains(
bag: Node,
vertices: java.util.ArrayList<Vertex>,
nodes: HashMap<String, Node>,
color: String
): Boolean {
if (bag.color == color) {
return false
}
if (vertices.any { it.source == bag.color && it.destination == color }) {
return true
}
if (vertices.filter { it.source == bag.color }.map { nodes[it.destination] }.any {
contains(
it!!,
vertices,
nodes,
color
)
}) {
return true
}
return false
}
// part 2
private fun countBags(
sourceNode: Node,
nodes: java.util.HashMap<String, Node>,
vertices: java.util.ArrayList<Vertex>
): Int {
var count = 0
sourceNode.vertices.forEach {
count += it.strength
val childNode = nodes[it.destination]!!
count += it.strength * countBags(childNode, nodes, vertices)
}
return count
}
}
}
class Node(var color: String, var vertices: List<Vertex>) {
override fun toString(): String {
return "Node(color='$color', vertices=$vertices)"
}
}
class Vertex(var source: String, var destination: String, var strength: Int) {
override fun toString(): String {
return "Vertex(source='$source', destination='$destination', strength=$strength)"
}
}
| 0 | Kotlin | 0 | 0 | 9fabcd6f1daa35198aaf91084de3b5240e31b968 | 3,582 | advent-of-code-2020 | Apache License 2.0 |
N-smooth_numbers/Kotlin/src/NSmooth.kt | ncoe | 108,064,933 | false | {"D": 425100, "Java": 399306, "Visual Basic .NET": 343987, "C++": 328611, "C#": 289790, "C": 216950, "Kotlin": 162468, "Modula-2": 148295, "Groovy": 146721, "Lua": 139015, "Ruby": 84703, "LLVM": 58530, "Python": 46744, "Scala": 43213, "F#": 21133, "Perl": 13407, "JavaScript": 6729, "CSS": 453, "HTML": 409} | import java.math.BigInteger
var primes = mutableListOf<BigInteger>()
var smallPrimes = mutableListOf<Int>()
// cache all primes up to 521
fun init() {
val two = BigInteger.valueOf(2)
val three = BigInteger.valueOf(3)
val p521 = BigInteger.valueOf(521)
val p29 = BigInteger.valueOf(29)
primes.add(two)
smallPrimes.add(2)
var i = three
while (i <= p521) {
if (i.isProbablePrime(1)) {
primes.add(i)
if (i <= p29) {
smallPrimes.add(i.toInt())
}
}
i += two
}
}
fun min(bs: List<BigInteger>): BigInteger {
require(bs.isNotEmpty()) { "slice must have at lease one element" }
val it = bs.iterator()
var res = it.next()
while (it.hasNext()) {
val t = it.next()
if (t < res) {
res = t
}
}
return res
}
fun nSmooth(n: Int, size: Int): List<BigInteger> {
require(n in 2..521) { "n must be between 2 and 521" }
require(size >= 1) { "size must be at least 1" }
val bn = BigInteger.valueOf(n.toLong())
var ok = false
for (prime in primes) {
if (bn == prime) {
ok = true
break
}
}
require(ok) { "n must be a prime number" }
val ns = Array<BigInteger>(size) { BigInteger.ZERO }
ns[0] = BigInteger.ONE
val next = mutableListOf<BigInteger>()
for (i in 0 until primes.size) {
if (primes[i] > bn) {
break
}
next.add(primes[i])
}
val indices = Array(next.size) { 0 }
for (m in 1 until size) {
ns[m] = min(next)
for (i in indices.indices) {
if (ns[m] == next[i]) {
indices[i]++
next[i] = primes[i] * ns[indices[i]]
}
}
}
return ns.toList()
}
fun main() {
init()
for (i in smallPrimes) {
println("The first 25 $i-smooth numbers are:")
println(nSmooth(i, 25))
println()
}
for (i in smallPrimes.drop(1)) {
println("The 3,000th to 3,202 $i-smooth numbers are:")
println(nSmooth(i, 3_002).drop(2_999))
println()
}
for (i in listOf(503, 509, 521)) {
println("The 30,000th to 30,019 $i-smooth numbers are:")
println(nSmooth(i, 30_019).drop(29_999))
println()
}
}
| 0 | D | 0 | 4 | c2a9f154a5ae77eea2b34bbe5e0cc2248333e421 | 2,333 | rosetta | MIT License |
src/nativeMain/kotlin/com.qiaoyuang.algorithm/special/Questions25.kt | qiaoyuang | 100,944,213 | false | {"Kotlin": 338134} | package com.qiaoyuang.algorithm.special
import com.qiaoyuang.algorithm.round1.SingleDirectionNode
import com.qiaoyuang.algorithm.round1.printlnLinkedList
fun test25() {
printlnResult(
head1 = SingleDirectionNode(element = 1, next = SingleDirectionNode(element = 2, next = SingleDirectionNode(element = 3))),
head2 = SingleDirectionNode(element = 5, next = SingleDirectionNode(element = 3, next = SingleDirectionNode(element = 1))),
)
printlnResult(
head1 = SingleDirectionNode(element = 9, next = SingleDirectionNode(element = 8, next = SingleDirectionNode(element = 4))),
head2 = SingleDirectionNode(element = 1, next = SingleDirectionNode(element = 8)),
)
}
/**
* Questions 25: The addition of two linked lists
*/
private operator fun SingleDirectionNode<Int>.plus(target: SingleDirectionNode<Int>): SingleDirectionNode<Int> {
var head1: SingleDirectionNode<Int>? = reverse()
var head2: SingleDirectionNode<Int>? = target.reverse()
var pointer: SingleDirectionNode<Int>? = null
var extra = 0
val range = 0..9
while (head1 != null || head2 != null || extra != 0) {
if (head1 != null)
require(head1.element in range) { "The parameters are illegal" }
if (head2 != null)
require(head2.element in range) { "The parameters are illegal" }
var sum = (head1?.element ?: 0) + (head2?.element ?: 0) + extra
if (sum > 9) {
extra = sum / 10
sum %= 10
} else {
extra = 0
}
val temp = SingleDirectionNode(sum)
temp.next = pointer
pointer = temp
head1 = head1?.next
head2 = head2?.next
}
return pointer!!
}
private fun printlnResult(head1: SingleDirectionNode<Int>, head2: SingleDirectionNode<Int>) {
print("The linked list: ")
printlnLinkedList(head1)
print("add the linked list: ")
printlnLinkedList(head2)
print("The result is: ")
printlnLinkedList(head1 + head2)
} | 0 | Kotlin | 3 | 6 | 66d94b4a8fa307020d515d4d5d54a77c0bab6c4f | 2,012 | Algorithm | Apache License 2.0 |
src/main/kotlin/kotml/knn/KNN.kt | tommypacker | 127,594,710 | false | null | package kotml.knn
import kotml.utils.DataRow
import kotml.utils.MathHelper
class KNN (val data: Array<DataRow>, val labels: Array<String>, val k: Int = 1, val weighted: Boolean = false){
/**
* Test our model by making predictions and comparing them to the actual labels
*/
fun test(testData: Array<DataRow>, testLabels: Array<String>): Double {
val predictions = getPredictions(testData)
val accuracy = MathHelper.getAccuracy(testLabels, predictions)
return accuracy
}
/**
* Gets an Array of label predictions for given test data
*/
fun getPredictions(testData: Array<DataRow>): Array<String> {
val res = mutableListOf<String>()
for (testRow in testData) {
res.add(predict(testRow))
}
return res.toTypedArray()
}
/**
* Predicts the label of a DataRow using the K-Nearest Neighbor algorithm.
* It sorts all the distances and then returns the label with the most neighbors.
*/
fun predict(inputRow: DataRow): String {
// Calculate distances
val distances = mutableListOf<Pair<Double, String>>()
for (i in 0..data.size - 1) {
val dataRow = data[i]
val label = labels[i]
val distance = euclideanDistance(inputRow, dataRow)
distances.add(Pair(distance, label))
}
// Sort distances
distances.sortBy { it.first }
// Aggregate neighbor value/counts
val neighborCounts = hashMapOf<String, Double>()
if (!weighted) {
val neighbors = distances.slice(0..k-1)
for (neighbor in neighbors) {
val neighborLabel = neighbor.second
neighborCounts.put(neighborLabel, neighborCounts.getOrDefault(neighborLabel, 0.0) + 1.0)
}
} else {
for (distancePair in distances) {
val neighborDistance = 1 / distancePair.first
val neighborLabel = distancePair.second
neighborCounts.put(neighborLabel, neighborCounts.getOrDefault(neighborLabel, 0.0) + neighborDistance)
}
}
// Find most common or highest weighted neighbor label
val ranks = neighborCounts.toList().sortedBy { (_, value) -> value }.reversed()
return ranks[0].first
}
/**
* Calculates the Euclidean distance between two DataRows
*/
fun euclideanDistance(A: DataRow, B: DataRow): Double {
var distance = 0.0
for (key in A.keys) {
val aVal = A.get(key) as Double
val bVal = B.get(key) as Double
distance += Math.pow((aVal - bVal), 2.0)
}
return distance
}
} | 4 | Kotlin | 2 | 13 | c4b69e7f15de3d8b63f8e3251ebae2ccc23bb8d0 | 2,728 | kotml | MIT License |
src/day8/day8.kt | TimCastelijns | 113,205,922 | false | null | package day8
import java.io.File
fun main(args: Array<String>) {
val lines = File("src/day8/input").readLines()
p1(lines)
p2(lines)
}
fun p1(lines: List<String>) {
val values = mutableMapOf<String, Int>()
for (line in lines) {
values.put(line.split(" ")[0], 0)
}
for (line in lines) {
val parts = line.split(" ")
val subject = parts[0]
val operator = parts[1]
val n = parts[2].toInt()
val condition = parts.subList(4, parts.size)
if (checkCondition(condition, values)) {
val currentValue = values[subject]!!
if (operator == "inc") {
values[subject] = currentValue + n
} else if (operator == "dec") {
values[subject] = currentValue - n
}
}
}
println(values.values.max())
}
fun p2(lines: List<String>) {
val values = mutableMapOf<String, Int>()
var max = 0;
for (line in lines) {
values.put(line.split(" ")[0], 0)
}
for (line in lines) {
val parts = line.split(" ")
val subject = parts[0]
val operator = parts[1]
val n = parts[2].toInt()
val condition = parts.subList(4, parts.size)
if (checkCondition(condition, values)) {
val currentValue = values[subject]!!
if (operator == "inc") {
values[subject] = currentValue + n
} else if (operator == "dec") {
values[subject] = currentValue - n
}
if (values[subject]!! > max) {
max = values[subject]!!
}
}
}
println(max)
}
fun checkCondition(condition: List<String>, values: Map<String, Int>): Boolean {
val a = values[condition[0]]!!.toInt()
val b = condition[2].toInt()
return when (condition[1]) {
"==" -> a == b
"!=" -> a != b
">" -> a > b
"<" -> a < b
">=" -> a >= b
"<=" -> a <= b
else -> false
}
} | 0 | Kotlin | 0 | 0 | 656f2a424b323175cd14d309bc25430ac7f7250f | 2,027 | aoc2017 | MIT License |
src/main/kotlin/g1801_1900/s1898_maximum_number_of_removable_characters/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1801_1900.s1898_maximum_number_of_removable_characters
// #Medium #Array #String #Binary_Search #Binary_Search_II_Day_6
// #2023_06_22_Time_636_ms_(100.00%)_Space_54.4_MB_(33.33%)
class Solution {
fun maximumRemovals(s: String, p: String, removable: IntArray): Int {
if (s.isEmpty()) {
return 0
}
// binary search for the k which need to be removed
val convertedS = s.toCharArray()
var left = 0
var right = removable.size - 1
while (left <= right) {
val middle = (left + right) / 2
// remove letters from 0 to mid by changing it into some other non letters
for (i in 0..middle) {
convertedS[removable[i]] = '?'
}
// if it is still subsequence change left boundary
// else replace all removed ones and change right boundary
if (isSubsequence(convertedS, p)) {
left = middle + 1
} else {
for (i in 0..middle) {
convertedS[removable[i]] = s[removable[i]]
}
right = middle - 1
}
}
return left
}
// simple check for subsequence
private fun isSubsequence(convertedS: CharArray, p: String): Boolean {
var p1 = 0
var p2 = 0
while (p1 < convertedS.size && p2 < p.length) {
if (convertedS[p1] != '?' && convertedS[p1] == p[p2]) {
p2 += 1
}
p1 += 1
}
return p2 == p.length
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,582 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/common/Utils.kt | hughjdavey | 225,440,374 | false | null | package common
import java.util.Stack
fun <T> stackOf(vararg input: T): Stack<T> {
val stack = Stack<T>()
input.toList().reversed().forEach { stack.push(it) }
return stack
}
// credit LukArToDo - https://code.sololearn.com/c24EP02YuQx3/#kt
fun <T> permutations(ts: List<T>): List<List<T>> {
if (ts.size == 1) {
return listOf(ts)
}
val perms = mutableListOf<List<T>>()
val sub = ts[0]
for (perm in permutations(ts.drop(1))) {
for (i in 0..perm.size) {
val newPerm = perm.toMutableList()
newPerm.add(i, sub)
perms.add(newPerm)
}
}
return perms
}
class CircularList<T>(vararg val elements: T) {
private val size: Int
private var head = -1
init {
if (elements.isEmpty()) {
throw IllegalArgumentException("Array size must be greater than 0")
}
this.size = elements.size
}
fun next(): T {
if (++head == size) {
head = 0
}
return elements[head]
}
fun prev(): T {
if (--head < 0) {
head = size - 1
}
return elements[head]
}
}
// taken from https://youtrack.jetbrains.com/issue/KT-7657
fun <R, T> Sequence<T>.scan(seed: R, transform: (a: R, b: T) -> R): Sequence<R> = object : Sequence<R> {
override fun iterator(): Iterator<R> = object : Iterator<R> {
val it = this@scan.iterator()
var last: R = seed
var first = true
override fun next(): R {
if (first) first = false else last = transform(last, it.next())
return last
}
override fun hasNext(): Boolean = it.hasNext()
}
}
| 0 | Kotlin | 0 | 1 | 84db818b023668c2bf701cebe7c07f30bc08def0 | 1,695 | aoc-2019 | Creative Commons Zero v1.0 Universal |
src/main/kotlin/com/jacobhyphenated/day10/Day10.kt | jacobhyphenated | 572,119,677 | false | {"Kotlin": 157591} | package com.jacobhyphenated.day10
import com.jacobhyphenated.Day
import java.io.File
import java.math.BigDecimal
import kotlin.math.absoluteValue
// Monitoring Station
class Day10: Day<List<Asteroid>> {
override fun getInput(): List<Asteroid> {
return mapAsteroids(
this.javaClass.classLoader.getResource("day10/input.txt")!!
.readText()
.lines()
)
}
/**
* Find the asteroid with the line of sight to the most other asteroids.
*
* Do this by grouping based on the slope of the line between each asteroid.
* the best location is the asteroid that can see the most other asteroids.
* Return the number of asteroids that location can see.
*/
override fun part1(input: List<Asteroid>): Number {
return determineBestPosition(input).second.size
}
/**
* From the best location for the asteroid base, shoot down the other asteroids.
* The firing mechanism starts pointed straight up, then rotates clockwise.
* In each position it will shoot down the first asteroid in line of sight, then rotate.
* If there are still asteroids around, it will rotate again, with the same firing sequence.
*
* For the 200th asteroid shot down, return the x coordinate multiplied by 100 plus the y coordinate
*/
override fun part2(input: List<Asteroid>): Number {
val (bestPosition, others) = determineBestPosition(input)
val sortedOrder = others.keys.sorted()
var removeCount = 0
while (others.values.any { it.size > 0 }) {
// each firing direction is the slope of the line of sight. Sorted in order
for (slope in sortedOrder) {
val otherAsteroids = others[slope] ?: mutableListOf()
if (otherAsteroids.isNotEmpty()) {
val closest = otherAsteroids.minBy { it.distance(bestPosition) }
otherAsteroids.remove(closest)
removeCount++
if (removeCount == 200) {
return closest.x * 100 + closest.y
}
}
}
}
return 0
}
fun mapAsteroids(input: List<String>): List<Asteroid> {
return input.foldIndexed(mutableListOf()) { y, acc, line ->
line.toCharArray().forEachIndexed { x, value ->
if (value == '#') {
acc.add(Asteroid(x,y))
}
}
acc
}
}
/**
* Determine the best location for the asteroid monitoring station. Used for parts 1 and 2
*
* Returns a tuple
* - the first value is the location of the best asteroid.
* - the second value is a map with the slope of the line of sight from the asteroid's location
* to a list of all asteroids along that line of sight.
*/
private fun determineBestPosition(input: List<Asteroid>): Pair<Asteroid, Map<Slope, MutableList<Asteroid>>> {
var bestLocation = Pair(Asteroid(0,0), mapOf<Slope, MutableList<Asteroid>>())
for (asteroid in input) {
val slopes = mutableMapOf<Slope, MutableList<Asteroid>>()
for (target in input) {
if (target == asteroid) {
continue
}
val (x1, y1) = asteroid
val (x2, y2) = target
val dx = (x2 - x1).toBigDecimal()
val slope = if (dx == BigDecimal.ZERO) {
// protect against division by 0
BigDecimal.valueOf(Long.MAX_VALUE)
}
else {
(y2 - y1).toBigDecimal().setScale(3) / dx
}
val up = if (y2 != y1) { y2 < y1 } else { x2 < x1 }
slopes.getOrPut(Slope(slope, up)) { mutableListOf() }.add(target)
}
if (slopes.size > bestLocation.second.size) {
bestLocation = Pair(asteroid, slopes)
}
}
return bestLocation
}
}
// Custom asteroid type with a helper function to calculate the manhattan distance between 2 asteroids
data class Asteroid(val x: Int, val y: Int ){
fun distance(other: Asteroid): Int {
return (other.x - this.x).absoluteValue + (other.y - this.y).absoluteValue
}
}
// Custom slope class that adds natural ordering
private data class Slope(val slope: BigDecimal, val up: Boolean): Comparable<Slope> {
// slopes are sorted according to how the asteroid station fires at incoming asteroids
// starting at the top and going clockwise
override fun compareTo(other: Slope): Int {
val unitCircle = this.getUnitCircle()
val quadrantCompare = unitCircle.compareTo(other.getUnitCircle())
if (quadrantCompare != 0) {
return quadrantCompare
}
return slope.compareTo(other.slope)
}
private fun getUnitCircle(): UnitCircle {
val infinity = BigDecimal(Long.MAX_VALUE)
return when {
slope == infinity && up -> UnitCircle.UP
slope < BigDecimal.ZERO && up -> UnitCircle.QUADRANT1
slope.compareTo(BigDecimal.ZERO) == 0 && !up -> UnitCircle.RIGHT
slope > BigDecimal.ZERO && !up -> UnitCircle.QUADRANT4
slope == infinity && !up -> UnitCircle.DOWN
slope < BigDecimal.ZERO && !up -> UnitCircle.QUADRANT3
slope.compareTo(BigDecimal.ZERO) == 0 && up -> UnitCircle.LEFT
slope > BigDecimal.ZERO && up -> UnitCircle.QUADRANT2
else -> throw NotImplementedError("slope: $slope, up: $up")
}
}
}
private enum class UnitCircle {
UP,
QUADRANT1,
RIGHT,
QUADRANT4,
DOWN,
QUADRANT3,
LEFT,
QUADRANT2
} | 0 | Kotlin | 0 | 0 | 1a0b9cb6e9a11750c5b3b5a9e6b3d63649bf78e4 | 5,810 | advent2019 | The Unlicense |
src/Utils.kt | Tandrial | 47,354,790 | false | null | import java.io.File
import java.util.regex.Pattern
import kotlin.math.abs
import kotlin.system.measureTimeMillis
/**
* Returns the alphabetically sorted String
*
* @return The string sorted alphabetically
*/
fun String.sort(): String = this.toCharArray().sorted().joinToString()
/**
* Parses the File contents into a 2D Int
*
* @param delim The delimiter by which the [Int]s are sperated in each line
* @return The file contents parsed to a 2D Int structure
*/
fun File.to2DIntArr(delim: Pattern = "\\s+".toPattern()): List<List<Int>> {
return this.readLines().map { it.toIntList(delim) }
}
/**
* Splits the string into a [List] of [Int].
*
* @param delim The delimiter by which the [Int]s in the string are sperated
* @return [List] of [Int]s
*/
fun String.toIntList(delim: Pattern = "\\s+".toPattern()): List<Int> = this.split(delim).map { it.toInt() }
/**
* Splits the [String] into a [List] or words, where a word is matched bs \w+
*
* @return [List] of matched words
*/
fun String.getWords(): List<String> = Regex("\\w+").findAll(this).toList().map { it.value }
/**
* Splits the [String] into a [List] or numbers, where a word is matched bs -?\d+
*
* @return [List] of matched numbers
*/
fun String.getNumbers(): List<Int> = Regex("-?\\d+").findAll(this).toList().map { it.value.toInt() }
/**
* Converts the [Int]s in the [Iterable] into their hex-Representation and joints them together
*
* @return a [String] of hexValuess
*/
fun Iterable<Int>.toHexString(): String = joinToString(separator = "") { it.toString(16).padStart(2, '0') }
/**
* Combination of [take] and [remove]
*
* @param take How many elements to remove from the [MutableList]
*
* @return a [List] of the taken elements
*/
fun <T : Any> MutableList<T>.removeTake(take: Int): List<T> {
val removed = this.take(take)
repeat(take) { this.removeAt(0) }
return removed
}
fun timeIt(block: () -> Unit) {
println("${measureTimeMillis(block)}ms")
}
/**
* Calculates the difference between the [max] and [min] Value of the elemnts of the List, transfomred by [block]
*
* @param block What to do calculate the difference of
*
* @return difference
*/
fun <T : Any> List<T>.diffBy(block: (T) -> Long): Long {
val values = map(block)
return abs((values.max() ?: 0L) - (values.min() ?: 0L))
}
| 0 | Kotlin | 1 | 1 | 9294b2cbbb13944d586449f6a20d49f03391991e | 2,312 | Advent_of_Code | MIT License |
src/Day25.kt | EdoFanuel | 575,561,680 | false | {"Kotlin": 80963} | class Day25 {
fun decode(input: String): Long {
var result = 0L
for (c in input) {
result *= 5
result += when(c) {
'2' -> 2
'1' -> 1
'0' -> 0
'-' -> -1
'=' -> -2
else -> throw IllegalArgumentException()
}
}
return result
}
fun encode(input: Long): String {
val sb = StringBuilder()
var n = input
var carry = 0
while (n > 0) {
n += carry
carry = 0
when (n % 5) {
0L -> sb.append(0)
1L -> sb.append(1)
2L -> sb.append(2)
3L -> {
sb.append('=')
carry = 1
}
4L -> {
sb.append('-')
carry = 1
}
}
n /= 5
}
return sb.toString().reversed()
}
}
fun main() {
val day = Day25()
fun part1(input: List<String>): String {
return day.encode(input.sumOf { day.decode(it) })
}
fun part2(input: List<String>): String {
return "There is no part 2"
}
val test = readInput("Day25_test")
println("=== Part 1 (test) ===")
println(part1(test))
println("=== Part 2 (test) ===")
println(part2(test))
val input = readInput("Day25")
println("=== Part 1 (puzzle) ===")
println(part1(input))
println("=== Part 2 (puzzle) ===")
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 46a776181e5c9ade0b5e88aa3c918f29b1659b4c | 1,582 | Advent-Of-Code-2022 | Apache License 2.0 |
kotlin/graphs/flows/MinCostFlowSimple.kt | polydisc | 281,633,906 | true | {"Java": 540473, "Kotlin": 515759, "C++": 265630, "CMake": 571} | package graphs.flows
import java.util.Arrays
object MinCostFlowSimple {
fun minCostFlow(cap: Array<IntArray>, cost: Array<IntArray>, s: Int, t: Int): IntArray {
val n = cap.size
val d = IntArray(n)
val p = IntArray(n)
var flow = 0
var flowCost = 0
while (true) {
Arrays.fill(d, Integer.MAX_VALUE)
d[s] = 0
for (i in 0 until n - 1) for (j in 0 until n) for (k in 0 until n) if (cap[j][k] > 0 && d[j] < Integer.MAX_VALUE && d[k] > d[j] + cost[j][k]) {
d[k] = d[j] + cost[j][k]
p[k] = j
}
if (d[t] == Integer.MAX_VALUE) return intArrayOf(flowCost, flow)
flowCost += d[t]
var v = t
while (v != s) {
--cap[p[v]][v]
++cap[v][p[v]]
v = p[v]
}
++flow
}
}
fun addEdge(cap: Array<IntArray>, cost: Array<IntArray>, u: Int, v: Int, edgeCapacity: Int, edgeCost: Int) {
cap[u][v] = edgeCapacity
cost[u][v] = edgeCost
cost[v][u] = -edgeCost
}
// Usage example
fun main(args: Array<String?>?) {
val n = 3
val capacity = Array(n) { IntArray(n) }
val cost = Array(n) { IntArray(n) }
addEdge(capacity, cost, 0, 1, 3, 1)
addEdge(capacity, cost, 0, 2, 2, 1)
addEdge(capacity, cost, 1, 2, 2, 1)
val costFlow = minCostFlow(capacity, cost, 0, 2)
System.out.println(6 == costFlow[0])
System.out.println(4 == costFlow[1])
}
}
| 1 | Java | 0 | 0 | 4566f3145be72827d72cb93abca8bfd93f1c58df | 1,584 | codelibrary | The Unlicense |
src/main/kotlin/dev/shtanko/algorithms/leetcode/SetMismatch.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2024 <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.abs
/**
* 645. Set Mismatch
* @see <a href="https://leetcode.com/problems/set-mismatch">Source</a>
*/
fun interface SetMismatch {
operator fun invoke(nums: IntArray): IntArray
}
class SetMismatchBruteForce : SetMismatch {
override fun invoke(nums: IntArray): IntArray {
var dup = -1
var missing = -1
for (i in 1..nums.size) {
var count = 0
for (element in nums) {
if (element == i) {
count++
}
}
if (count == 2) {
dup = i
} else if (count == 0) {
missing = i
}
}
return intArrayOf(dup, missing)
}
}
class SetMismatchSet : SetMismatch {
override fun invoke(nums: IntArray): IntArray {
val n: Int = nums.size
val actualSum = n * (n + 1) / 2
var arraySum = 0
var uniqueSum = 0
val s: MutableSet<Int> = HashSet()
for (a in nums) {
arraySum += a
}
for (a in nums) {
s.add(a)
}
for (a in s) {
uniqueSum += a
}
val missing = actualSum - uniqueSum
val duplicate = arraySum - uniqueSum
return intArrayOf(duplicate, missing)
}
}
class SetMismatchMap : SetMismatch {
override fun invoke(nums: IntArray): IntArray {
val res = IntArray(2) // duplicate, missing
// For each number we found, set nums[number-1] to its negative value (<0)
for (element in nums) {
val idx = abs(element) - 1 // since index starts from 0, and the set starts from 1
if (nums[idx] > 0) {
nums[idx] = -nums[idx]
} else {
res[0] = idx + 1 // have already been found
}
}
// At this point, only nums[missingNumber-1] > 0
for (i in nums.indices) {
if (nums[i] < 0) {
nums[i] = -nums[i] // restore the original values
} else {
res[1] = i + 1 // since index starts from 0, and the set starts from 1
}
}
return res
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,835 | kotlab | Apache License 2.0 |
Kotlin/5 kyu Maximum subarray sum.kt | MechaArms | 508,384,440 | false | {"Kotlin": 22917, "Python": 18312} | /*
The maximum sum subarray problem consists in finding the maximum sum of a contiguous subsequence in an array or list of integers:
maxSequence(listOf(-2, 1, -3, 4, -1, 2, 1, -5, 4));
// should be 6: listOf(4, -1, 2, 1)
Easy case is when the list is made up of only positive numbers and the maximum sum is the sum of the whole array. If the list is made up of only negative numbers, return 0 instead.
Empty list is considered to have zero greatest sum. Note that the empty list or array is also a valid sublist/subarray.
*/
import kotlin.math.max
fun maxSequence(arr: List<Int>): Int {
return arr.fold(Pair(0, 0)) { (current, max), x ->
val nextCurrent = max(0, current + x)
val nextMax = max(nextCurrent, max)
Pair(nextCurrent, nextMax)
}.second
}
| 0 | Kotlin | 0 | 1 | b23611677c5e2fe0f7e813ad2cfa21026b8ac6d3 | 788 | My-CodeWars-Solutions | MIT License |
LeetCode/Kotlin/src/main/kotlin/org/redquark/tutorials/leetcode/MergeKSortedLists.kt | ani03sha | 297,402,125 | false | null | package org.redquark.tutorials.leetcode
class MergeKSortedLists {
internal fun mergeKLists(lists: Array<ListNode?>): ListNode? {
// Base condition
return if (lists.isEmpty()) {
null
} else mergeKLists(lists, 0, lists.size - 1)
}
private fun mergeKLists(lists: Array<ListNode?>, start: Int, end: Int): ListNode? {
if (start == end) {
return lists[start]
}
// Mid of list of lists
val mid = start + (end - start) / 2
// Recursive call for left sublist
val left = mergeKLists(lists, start, mid)
// Recursive call for right sublist
val right = mergeKLists(lists, mid + 1, end)
// Merge the left and right sublist
return merge(left, right)
}
private fun merge(left: ListNode?, right: ListNode?): ListNode? {
// Create a dummy node
var leftNode = left
var rightNode = right
val head = ListNode(-1)
// Temp node
var temp: ListNode? = head
// Loop until any of the list becomes null
while (leftNode != null && rightNode != null) {
// Choose the value from the left and right which is smaller
if (leftNode.`val` < rightNode.`val`) {
temp!!.next = leftNode
leftNode = leftNode.next
} else {
temp!!.next = rightNode
rightNode = rightNode.next
}
temp = temp.next
}
// Take all nodes from left list if remaining
while (leftNode != null) {
temp!!.next = leftNode
leftNode = leftNode.next
temp = temp.next
}
// Take all nodes from right list if remaining
while (rightNode != null) {
temp!!.next = rightNode
rightNode = rightNode.next
temp = temp.next
}
return head.next
}
internal class ListNode(val `val`: Int) {
var next: ListNode? = null
}
}
fun main() {
val m = MergeKSortedLists()
val head1 = MergeKSortedLists.ListNode(1)
head1.next = MergeKSortedLists.ListNode(4)
head1.next!!.next = MergeKSortedLists.ListNode(5)
val head2 = MergeKSortedLists.ListNode(1)
head2.next = MergeKSortedLists.ListNode(3)
head2.next!!.next = MergeKSortedLists.ListNode(4)
val head3 = MergeKSortedLists.ListNode(2)
head3.next = MergeKSortedLists.ListNode(6)
var result = m.mergeKLists(arrayOf(head1, head2, head3))
while (result != null) {
print(result.`val`.toString() + " ")
result = result.next
}
} | 2 | Java | 40 | 64 | 67b6ebaf56ec1878289f22a0324c28b077bcd59c | 2,631 | RedQuarkTutorials | MIT License |
src/Day18.kt | spaikmos | 573,196,976 | false | {"Kotlin": 83036} | fun main() {
fun parseInput(input: List<String>): MutableList<List<Int>> {
val lava = mutableListOf<List<Int>>()
for (i in input) {
val a = i.split(',').map{ it -> it.toInt()}
lava.add(a)
}
return lava
}
fun part1(input: MutableList<List<Int>>): Int {
var exposedFaces = 0
val points = mutableSetOf<List<Int>>()
fun checkPoint(x: Int, y: Int, z: Int) {
if (points.contains(mutableListOf(x, y, z)) == true) {
// Rock is detected, remove two faces from total
exposedFaces -= 2
}
}
for (i in input) {
val (x, y, z) = i
// Each new block initially adds 6 faces. When a block is next to another block, two
// faces are touching and need to be removed.
exposedFaces += 6
checkPoint(x+1, y, z)
checkPoint(x-1, y, z)
checkPoint(x, y+1, z)
checkPoint(x, y-1, z)
checkPoint(x, y, z+1)
checkPoint(x, y, z-1)
points.add(i)
}
return exposedFaces
}
fun part2(input: MutableList<List<Int>>): Int {
val points = input.toList()
val empty = mutableSetOf<List<Int>>()
// Start at (0,0,0) and do a BFS to find all faces accessible from outside the lava
val q = ArrayDeque<List<Int>>()
var numEmptyFaces = 0
// Helper function that checks each new point and adds to the q as needed
fun checkPoint(x:Int, y:Int, z:Int) {
val MIN = -1
val MAX = 20
if ((x in MIN..MAX) && (y in MIN..MAX) && (z in MIN..MAX)) {
val newPoint = listOf(x,y,z)
when (newPoint) {
in points -> numEmptyFaces++
!in empty -> {q.add(newPoint); empty.add(newPoint)}
}
}
}
q.add(listOf(0,0,0))
while (q.size > 0) {
val (x,y,z) = q.removeFirst()
checkPoint(x+1, y, z)
checkPoint(x-1, y, z)
checkPoint(x, y+1, z)
checkPoint(x, y-1, z)
checkPoint(x, y, z+1)
checkPoint(x, y, z-1)
}
return numEmptyFaces
}
val input = readInput("../input/Day18")
val points = parseInput(input)
println(part1(points)) // 3390
println(part2(points)) // 2058
}
| 0 | Kotlin | 0 | 0 | 6fee01bbab667f004c86024164c2acbb11566460 | 2,448 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/22.kts | reitzig | 318,492,753 | false | null | @file:Include("shared.kt")
import java.io.File
// NB: Would like this to be an inline class, but alas, not possible in kscript (yet)
data class Card(val value: Int)
data class Hand(val cards: List<Card>) {
fun isEmpty(): Boolean = cards.isEmpty()
val score: Int
get() = cards.reversed().mapIndexed { i, card -> (i + 1) * card.value }.sum()
}
data class GameResult(val winningPlayer: Int, val score: Int)
enum class WinCondition {
ByScore {
override fun determineWinner(hand1: Hand, hand2: Hand): GameResult =
if (hand1.isEmpty()) {
GameResult(1, hand2.score)
} else {
GameResult(0, hand1.score)
}
},
InfiniteLoop {
override fun determineWinner(hand1: Hand, hand2: Hand): GameResult =
GameResult(0, hand1.score)
};
abstract fun determineWinner(hand1: Hand, hand2: Hand): GameResult
fun determineWinner(hand1: List<Card>, hand2: List<Card>): GameResult =
determineWinner(Hand(hand1), Hand(hand2))
}
fun play(hand1: Hand, hand2: Hand, recursive: Boolean = true): GameResult {
val seenConfigurations = mutableSetOf<String>()
val players = listOf(
hand1.cards.toMutableList(),
hand2.cards.toMutableList()
)
while (players.none { it.isEmpty() }) {
val configuration = players.joinToString("#") { it.joinToString(",") }
if (seenConfigurations.contains(configuration)) {
return WinCondition.InfiniteLoop.determineWinner(players[0], players[1])
} else {
seenConfigurations.add(configuration)
}
val cards = players.map { it.removeFirst() }
val winner = players.zip(cards).let { played ->
if (recursive && played.all { (hand, card) -> card.value <= hand.size }) {
played.map { (hand, card) ->
Hand(hand.toList().take(card.value))
}.let { play(it[0], it[1]).winningPlayer }
} else {
cards.indexOfMaxByOrNull { it.value } ?: throw IllegalStateException("No cards drawn?!")
}
}
players[winner].addAll(if (winner == 0) cards else cards.reversed())
}
return WinCondition.ByScore.determineWinner(players[0], players[1])
}
// Input:
val (player1, player2) = File(args[0]).readLines()
.split("")
.map { playerInput ->
playerInput.drop(1).map { Card(it.toInt()) }
}
.map { Hand(it) }
// Part 1:
play(player1, player2, recursive = false)
.also { println(it) }
// Part 2:
play(player1, player2)
.also { println(it) }
| 0 | Kotlin | 0 | 0 | f17184fe55dfe06ac8897c2ecfe329a1efbf6a09 | 2,619 | advent-of-code-2020 | The Unlicense |
Java_part/Assigment9/src/Q1.kt | enihsyou | 58,862,788 | false | {"Java": 77446, "Python": 65409, "Kotlin": 35032, "C++": 6214, "C": 3796, "CMake": 818} | import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.RepeatedTest
import java.util.*
import java.util.Collections.swap
import kotlin.test.assertEquals
/**
* 1)分治算法求n个数的数组中找出第二个最大元素
*/
fun main(args: Array<String>) {
Scanner(System.`in`).use { s ->
println("输入数组数字,以非数字结束")
val list = ArrayList<Long>()
while (s.hasNextLong())
list.add(s.nextLong())
println(list.findKthLargest(2))
}
}
fun <T : Comparable<T>> MutableList<T>.findKthLargest(k: Int): T {
val n = this.size
if (k > n || k < 0) throw IllegalArgumentException("没有这种操作")
return quickSelect(this, 0, n - 1, k - 1)
}
fun <T : Comparable<T>> quickSelect(list: MutableList<T>, _left: Int, _right: Int, k: Int): T {
var left = _left
var right = _right
while (left <= right) {
if (left == right)
return list[left]
var pivotIndex = (left + right) / 2
pivotIndex = partition(list, left, right, pivotIndex)
when {
k == pivotIndex -> return list[k]
k < pivotIndex -> right = pivotIndex - 1
k > pivotIndex -> left = pivotIndex + 1
}
}
throw RuntimeException(String.format("%d %d", left, right))
}
fun <T : Comparable<T>> partition(list: MutableList<T>, left: Int, right: Int, pivotIndex: Int): Int {
val pivot = list[pivotIndex]
swap(list, pivotIndex, right)
var index = left
for (i in left until right) {
if (list[i] > pivot) { // 下降序排列
swap(list, index, i)
index++
}
}
swap(list, right, index)
return index
}
class Q1KtTest {
@DisplayName("╯°□°)╯")
@RepeatedTest(5)
fun findKthLargest() {
val random = Random()
val list = LongArray(1000000, {
random.nextLong()
})
assertEquals(
list.sortedArrayDescending()[1], list.toMutableList().findKthLargest(2))
}
}
| 0 | Java | 0 | 0 | 09a109bb26e0d8d165a4d1bbe18ec7b4e538b364 | 1,889 | Sorting-algorithm | MIT License |
src/main/kotlin/aoc2022/Utils.kt | davidsheldon | 565,946,579 | false | {"Kotlin": 161960} | package aoc2022
import java.io.File
import java.math.BigInteger
import java.security.MessageDigest
/**
* Reads lines from the given input txt file.
*/
fun readInput(name: String) = File("src", "$name.txt").readLines()
/**
* Converts string to aoc2022.md5 hash.
*/
fun String.md5(): String = BigInteger(1, MessageDigest.getInstance("MD5").digest(toByteArray())).toString(16)
fun <T> Sequence<T>.splitBy(predicate: (T) -> Boolean): Sequence<List<T>> {
val seq = this;
if (!seq.iterator().hasNext())
return emptySequence()
return sequence {
val current = mutableListOf<T>()
seq.forEach { element ->
val split = predicate(element)
if (split && current.isNotEmpty()) {
yield(current)
current.clear()
}
else {
current.add(element)
}
}
if (current.isNotEmpty()) yield(current)
}
}
fun blocksByBlankLines(lineSeq: Iterable<String>): Sequence<IndexedValue<String>> = sequence {
var blockId = 0
lineSeq.forEach { line ->
if (line.isBlank()) {
blockId++
} else {
yield(IndexedValue(blockId, line))
}
}
}
fun blocksOfLines(lineSeq: Iterable<String>): Collection<List<String>> =
blocksByBlankLines(lineSeq)
.groupBy({ it.index }, { it.value })
.values
fun <R> parseMatchOrThrow(line: String, pattern: Regex, onMatch: (MatchResult) -> R): R {
val match = pattern.matchEntire(line)
if (match != null) {
return onMatch(match)
}
throw IllegalArgumentException(line)
}
fun listOfNumbers(list: String): List<Int> = list.trim().split(',').map { it.trim().toInt() }
fun Iterable<String>.parsedBy(pattern: Regex): Sequence<MatchResult> = parsedBy(pattern) { it }
fun <R> String.parsedBy(pattern: Regex, onMatch: (MatchResult) -> R): R =
onMatch(pattern.matchEntire(this) ?: throw IllegalArgumentException(this))
fun <R> Iterable<String>.parsedBy(pattern: Regex, onMatch: (MatchResult) -> R): Sequence<R> =
asSequence().map { line ->
line.parsedBy(pattern, onMatch)
}
fun <A> applyN(dir: A, count: Int, func: (A) -> A): A =
(1..count).fold(dir) { acc, i -> func(acc) }
fun <T: Comparable<T>> Iterable<T>.topN(n: Int) = this.fold(ArrayList<T>()) { acc, item ->
if (acc.size < n || item > acc.last()) {
acc.add(item)
acc.sortDescending()
if (acc.size > n) acc.removeAt(n)
}
acc
}
fun <T> Sequence<T>.takeWhilePlusOne(predicate: (T) -> Boolean): Sequence<T> {
var lastSeen: T? = null
return takeWhile {
val shouldTake = predicate(it)
if (!shouldTake) lastSeen = it
shouldTake
} + sequence {
if (lastSeen != null) yield(lastSeen!!)
}
}
fun Sequence<Int>.product() = reduce(Int::times)
fun List<Int>.product() = reduce(Int::times)
fun <T> Sequence<Set<T>>.intersectAll() = reduce(Set<T>::intersect)
fun <T> Sequence<Set<T>>.unionAll() = reduce(Set<T>::union)
fun <T> Sequence<T>.repeatForever() = generateSequence(this) { it }.flatten()
| 0 | Kotlin | 0 | 0 | 5abc9e479bed21ae58c093c8efbe4d343eee7714 | 3,110 | aoc-2022-kotlin | Apache License 2.0 |
src/Day01.kt | JCampbell8 | 572,669,444 | false | {"Kotlin": 10115} | fun main() {
fun getCalorieList(input: List<String>):List<Int> {
val sums:MutableList<Int> = mutableListOf()
var sum = 0
input.forEach {
if (it == "") {
sums.add(sum)
sum = 0
} else {
sum += it.toInt()
}
}
if(sum > 0) {
sums.add(sum)
}
return sums
}
fun part1(input: List<String>): Int {
return getCalorieList(input).maxOrNull() ?: 0
}
fun part2(input: List<String>): Int {
return getCalorieList(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 | 1 | 0bac6b866e769d0ac6906456aefc58d4dd9688ad | 917 | advent-of-code-2022 | Apache License 2.0 |
day05/kotlin/RJPlog/day2105_1_2.kts | razziel89 | 438,180,535 | true | {"Rust": 368326, "Python": 219109, "Go": 200337, "Kotlin": 80185, "Groovy": 67858, "JavaScript": 45619, "TypeScript": 43504, "CSS": 35030, "Shell": 18611, "C": 5260, "Ruby": 2359, "Dockerfile": 2285, "HTML": 227, "C++": 153} | import java.io.File
// tag::lines[]
fun lines(solution: Int = 0): Int {
var ground = mutableMapOf<Pair<Int, Int>, Int>()
var result: Int = 0
File("day2105_puzzle_input.txt").forEachLine {
var instruction = it.split(" -> ")
var pos1 = instruction[0].split(",")
var pos2 = instruction[1].split(",")
var x1: Int = pos1[0].toInt()
var y1: Int = pos1[1].toInt()
var x2: Int = pos2[0].toInt()
var y2: Int = pos2[1].toInt()
if (x1 == x2) {
for (i in minOf(y1, y2)..maxOf(y1, y2)) {
if (ground.contains(Pair(x1, i))) {
ground.put(Pair(x1, i), ground.getValue(Pair(x1, i)) + 1)
} else {
ground.put(Pair(x1, i), 1)
}
}
} else if (y1 == y2) {
for (i in minOf(x1, x2)..maxOf(x1, x2)) {
if (ground.contains(Pair(i, y1))) {
ground.put(Pair(i, y1), ground.getValue(Pair(i, y1)) + 1)
} else {
ground.put(Pair(i, y1), 1)
}
}
} else {
// tag::lines2[]
if (solution > 0) {
for (j in 0..(maxOf(x1, x2)-minOf(x1, x2))) {
if (x2 > x1 && y2 > y1 ) {
if (ground.contains(Pair(j + minOf(x1, x2), j + minOf(y1, y2)))) {
ground.put(
Pair(j + minOf(x1, x2) , j + minOf(y1, y2)),
ground.getValue(Pair(j + minOf(x1, x2), j + minOf(y1, y2))) + 1
)
} else {
ground.put(Pair(j + minOf(x1, x2), j + minOf(y1, y2)), 1)
}
} else if (x2 < x1 && y2 > y1) {
if (ground.contains(Pair( maxOf(x1, x2) - j, minOf(y1,y2)+j))) {
ground.put(
Pair(maxOf(x1, x2) - j, minOf(y1, y2)+j),
ground.getValue(Pair(maxOf(x1, x2) - j, minOf(y1, y2) + j)) + 1
)
} else {
ground.put(Pair(maxOf(x1, x2) - j, minOf(y1, y2) +j), 1)
}
} else if (x2 > x1 && y2 < y1) {
if (ground.contains(Pair(j + minOf(x1, x2), maxOf(y1, y2) - j))) {
ground.put(
Pair(j + minOf(x1, x2) , maxOf(y1, y2) - j),
ground.getValue(Pair(j + minOf(x1, x2), maxOf(y1, y2)-j)) + 1
)
} else {
ground.put(Pair(j + minOf(x1, x2), maxOf(y1, y2)-j), 1)
}
} else if (x2 < x1 && y2 < y1) {
if (ground.contains(Pair(maxOf(x1, x2) - j, maxOf(y1, y2) - j))) {
ground.put(
Pair(maxOf(x1, x2) - j , maxOf(y1, y2) - j),
ground.getValue(Pair(maxOf(x1, x2) - j, maxOf(y1, y2)-j)) + 1
)
} else {
ground.put(Pair(maxOf(x1, x2) - j, maxOf(y1, y2)-j), 1)
}
}
}
}
}
// end::lines2[]
}
for ((key, value) in ground) {
if (value > 1) {
result += 1
}
}
return result
}
// end::lines[]
//fun main(args: Array<String>) {
var solution1: Int
var solution2: Int
// tag::part_1[]
solution1 = lines()
// end::part_1[]
// tag::part_2[]
solution2 = lines(2)
// end::part_2[]
// tag::output[]
// print solution for part 1
println("***********************************")
println("--- Day 5: Hydrothermal Venture ---")
println("***********************************")
println("Solution for part1")
println(" At $solution1 points at least two lines overlap ")
println()
// print solution for part 2
println("*********************************")
println("Solution for part2")
println(" At $solution2 points at least two lines overlap")
println()
// end::output[]
//} | 1 | Rust | 0 | 0 | 91a801b3c812cc3d37d6088a2544227cf158d114 | 3,221 | aoc-2021 | MIT License |
src/day25/a/day25a.kt | pghj | 577,868,985 | false | {"Kotlin": 94937} | package day25.a
import readInputLines
import shouldBe
fun main() {
val l = read()
val v = printSnafu(l.sumOf { parseSnafu(it) })
shouldBe("2=10---0===-1--01-20", v)
}
fun valueOfSnafuChar(c: Char): Long = "=-012".indexOf(c) - 2L
fun snafuDigitToChar(d: Int): Char = "=-012"[d+2]
fun parseSnafu(s: String): Long {
var acc = 0L
var p = 1L
for (i in s.indices.reversed()) {
acc += p * valueOfSnafuChar(s[i])
p *= 5
}
return acc
}
fun printSnafu(v: Long): String {
if (v == 0L) return "0"
val sb = StringBuilder()
var x = v
while (x != 0L) {
var r = x % 5L
x /= 5L
if (r > 2) {
r -= 5L
x++
}
sb.append(snafuDigitToChar(r.toInt()))
}
return sb.reversed().toString()
}
fun read(): List<String> {
return readInputLines(25).filter { it.isNotBlank() }
}
| 0 | Kotlin | 0 | 0 | 4b6911ee7dfc7c731610a0514d664143525b0954 | 892 | advent-of-code-2022 | Apache License 2.0 |
year2021/day16/part2/src/main/kotlin/com/curtislb/adventofcode/year2021/day16/part2/Year2021Day16Part2.kt | curtislb | 226,797,689 | false | {"Kotlin": 2146738} | /*
--- Part Two ---
Now that you have the structure of your transmission decoded, you can calculate the value of the
expression it represents.
Literal values (type ID 4) represent a single number as described above. The remaining type IDs are
more interesting:
- Packets with type ID 0 are `sum` packets - their value is the sum of the values of their
sub-packets. If they only have a single sub-packet, their value is the value of the sub-packet.
- Packets with type ID 1 are `product` packets - their value is the result of multiplying together
the values of their sub-packets. If they only have a single sub-packet, their value is the value
of the sub-packet.
- Packets with type ID 2 are `minimum` packets - their value is the minimum of the values of their
sub-packets.
- Packets with type ID 3 are `maximum` packets - their value is the maximum of the values of their
sub-packets.
- Packets with type ID 5 are `greater than` packets - their value is 1 if the value of the first
sub-packet is greater than the value of the second sub-packet; otherwise, their value is 0. These
packets always have exactly two sub-packets.
- Packets with type ID 6 are `less than` packets - their value is 1 if the value of the first
sub-packet is less than the value of the second sub-packet; otherwise, their value is 0. These
packets always have exactly two sub-packets.
- Packets with type ID 7 are `equal to` packets - their value is 1 if the value of the first
sub-packet is equal to the value of the second sub-packet; otherwise, their value is 0. These
packets always have exactly two sub-packets.
Using these rules, you can now work out the value of the outermost packet in your BITS transmission.
For example:
- `C200B40A82` finds the sum of 1 and 2, resulting in the value 3.
- `04005AC33890` finds the product of 6 and 9, resulting in the value 54.
- `880086C3E88112` finds the minimum of 7, 8, and 9, resulting in the value 7.
- `CE00C43D881120` finds the maximum of 7, 8, and 9, resulting in the value 9.
- `D8005AC2A8F0` produces 1, because 5 is less than 15.
- `F600BC2D8F` produces 0, because 5 is not greater than 15.
- `9C005AC2F8F0` produces 0, because 5 is not equal to 15.
- `9C0141080250320F1802104A08` produces 1, because 1 + 3 = 2 * 2.
What do you get if you evaluate the expression represented by your hexadecimal-encoded BITS
transmission?
*/
package com.curtislb.adventofcode.year2021.day16.part2
import com.curtislb.adventofcode.year2021.day16.bits.BitsReader
import java.nio.file.Path
import java.nio.file.Paths
/**
* Returns the solution to the puzzle for 2021, day 16, part 2.
*
* @param inputPath The path to the input file for this puzzle.
*/
fun solve(inputPath: Path = Paths.get("..", "input", "input.txt")): Long {
val bitsReader = BitsReader(inputPath.toFile().readText().trim())
return bitsReader.evaluatePacket()
}
fun main() {
println(solve())
}
| 0 | Kotlin | 1 | 1 | 6b64c9eb181fab97bc518ac78e14cd586d64499e | 2,923 | AdventOfCode | MIT License |
src/main/kotlin/g0401_0500/s0410_split_array_largest_sum/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g0401_0500.s0410_split_array_largest_sum
// #Hard #Array #Dynamic_Programming #Greedy #Binary_Search
// #2022_12_03_Time_165_ms_(100.00%)_Space_33.9_MB_(100.00%)
class Solution {
fun splitArray(nums: IntArray, m: Int): Int {
var maxVal = 0
var minVal = nums[0]
for (num in nums) {
maxVal += num
minVal = Math.max(minVal, num)
}
while (minVal < maxVal) {
val midVal = minVal + (maxVal - minVal) / 2
// if we can split, try to reduce the midVal so decrease maxVal
if (canSplit(midVal, nums, m)) {
maxVal = midVal
} else {
// if we can't split, then try to increase midVal by increasing minVal
minVal = midVal + 1
}
}
return minVal
}
private fun canSplit(maxSubArrSum: Int, nums: IntArray, m: Int): Boolean {
var currSum = 0
var currSplits = 1
for (num in nums) {
currSum += num
if (currSum > maxSubArrSum) {
currSum = num
currSplits++
// if maxSubArrSum was TOO high that we can split the array into more that 'm' parts
// then its not ideal
if (currSplits > m) {
return false
}
}
}
return true
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,404 | LeetCode-in-Kotlin | MIT License |
src/Day09.kt | zt64 | 572,594,597 | false | null | import kotlin.math.absoluteValue
private object Day9 : Day(9) {
private val visitedPoints = hashSetOf<Point>()
private val motions = input.lines().map {
val (direction, steps) = it.split(" ")
Direction[direction] to steps.toInt()
}
override fun part1(): Int {
var head = Point(0, 0)
var tail = Point(0, 0)
visitedPoints += head
motions.forEach { (direction, steps) ->
for (index in 0..steps) {
val (x, y) = when (direction) {
Direction.UP -> 0 to 1
Direction.DOWN -> 0 to -1
Direction.LEFT -> -1 to 0
Direction.RIGHT -> 1 to 0
}
head = head.move(x, y)
val touching = (head.x - tail.x).absoluteValue < 2 && (head.y - tail.y).absoluteValue < 2
if (touching) {
break
}
tail = tail.move(x, y)
visitedPoints += tail
}
}
println(visitedPoints)
return visitedPoints.distinct().size
}
override fun part2(): Int = TODO("Not yet implemented")
private enum class Direction(private val letter: String) {
UP("U"),
DOWN("D"),
LEFT("L"),
RIGHT("R");
companion object {
operator fun get(letter: String) = values().first { it.letter == letter }
}
}
private data class Point(val x: Int, val y: Int) {
fun move(x: Int, y: Int) = Point(this.x + x, this.y + y)
}
}
private fun main() = Day9.main() | 0 | Kotlin | 0 | 0 | 4e4e7ed23d665b33eb10be59670b38d6a5af485d | 1,624 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/me/peckb/aoc/_2021/calendar/day13/Day13.kt | peckb1 | 433,943,215 | false | {"Kotlin": 956135} | package me.peckb.aoc._2021.calendar.day13
import me.peckb.aoc.generators.InputGenerator.InputGeneratorFactory
import javax.inject.Inject
import kotlin.Int.Companion.MIN_VALUE
import kotlin.math.max
class Day13 @Inject constructor(private val generatorFactory: InputGeneratorFactory) {
companion object {
const val ACTIVE = true
const val INACTIVE = false
const val FOLD_PREFIX = "fold along "
}
fun oneFoldCount(fileName: String) = generatorFactory.forFile(fileName).read { input ->
val (dotLines, foldInstructions) = parseInput(input)
val paper = fillPaper(generatePaperData(dotLines))
val (updatedX, updatedY) = foldPaper(paper, foldInstructions.take(1))
(0 until updatedY).sumOf { y ->
(0 until updatedX).count { x ->
paper[y][x] == ACTIVE
}
}
}
fun everyFoldCode(fileName: String) = generatorFactory.forFile(fileName).read { input ->
val (dotLines, foldInstructions) = parseInput(input)
val paper = fillPaper(generatePaperData(dotLines))
val (updatedX, updatedY) = foldPaper(paper, foldInstructions)
val codes = Array(updatedY + 1) { Array(updatedX + 1) { ' ' } }
(0 until updatedY).forEach { y ->
(0 until updatedX).forEach { x ->
codes[y][x] = if (paper[y][x]) '#' else ' '
}
}
codes.joinToString("\n") { it.joinToString("") }
}
private fun fillPaper(paper: Paper) =
Array(paper.y + 1) { Array(paper.x + 1) { INACTIVE } }.apply {
paper.dots.forEach { (x, y) -> this[y][x] = ACTIVE }
}
private fun parseInput(input: Sequence<String>): Pair<List<String>, List<String>> {
val dotLines = mutableListOf<String>()
val foldInstructions = mutableListOf<String>()
input.forEach {
if (it.startsWith(FOLD_PREFIX)) {
foldInstructions.add(it.split(FOLD_PREFIX).last())
} else if (it.isNotEmpty()) {
dotLines.add(it)
}
}
return dotLines to foldInstructions
}
private fun foldPaper(paper: Array<Array<Boolean>>, foldInstructions: List<String>): Pair<Int, Int> {
var maxX = paper[0].size
var maxY = paper.size
fun fold(sourceX: Int, sourceY: Int, destinationX: Int, destinationY: Int) {
if (paper[sourceY][sourceX] == ACTIVE) paper[destinationY][destinationX] = ACTIVE
}
foldInstructions.forEach {
val (direction, foldIndexString) = it.split("=")
val foldIndex = foldIndexString.toInt()
if (direction == "y") {
((foldIndex + 1) until maxY).forEach { y ->
repeat(maxX) { x->
fold(x, y, x, 2 * foldIndex - y)
}
}
maxY = foldIndex
} else {
((foldIndex + 1) until maxX).forEach { x ->
repeat(maxY) { y ->
fold(x, y, 2 * foldIndex - x, y)
}
}
maxX = foldIndex
}
}
return maxX to maxY
}
private fun generatePaperData(dotLines: List<String>): Paper {
var maxX = MIN_VALUE
var maxY = MIN_VALUE
val dots = dotLines.map { line ->
line.split(",").map{ it.toInt() }.let { (x, y) ->
maxX = max(maxX, x)
maxY = max(maxY, y)
Dot(x, y)
}
}
return Paper(dots, maxX, maxY)
}
data class Dot(val x: Int, val y: Int)
data class Paper(val dots: List<Dot>, val x: Int, val y: Int)
}
| 0 | Kotlin | 1 | 3 | 2625719b657eb22c83af95abfb25eb275dbfee6a | 3,303 | advent-of-code | MIT License |
src/nativeMain/kotlin/com.qiaoyuang.algorithm/round1/Questions44.kt | qiaoyuang | 100,944,213 | false | {"Kotlin": 338134} | package com.qiaoyuang.algorithm.round1
import kotlin.math.pow
fun test44() {
printlnResult(0)
printlnResult(1)
printlnResult(5)
printlnResult(10)
printlnResult(13)
printlnResult(15)
printlnResult(19)
printlnResult(190)
printlnResult(191)
printlnResult(1000)
}
/**
* Questions 44: A number sequence is: 0123456789101112131415..., find the number of index n
*/
private fun findNIndexNum(n: Int): Int {
var minuend = n
var amount = 0
var sum = amount
var bit = 1
while (true) {
val newAmount = if (amount == 0) 9 else amount * 10
val subtrahend = newAmount * bit
if (minuend - subtrahend > 0) {
minuend -= subtrahend
amount = newAmount
sum += amount
bit++
} else
break
}
val rem = minuend % bit
val number = minuend / bit
return if (rem == 0) (sum + number) % 10 else (sum + number + 1) / 10f.pow(bit - rem).toInt() % 10
}
private fun printlnResult(n: Int) =
println("The ${n}th number is ${findNIndexNum(n)}")
| 0 | Kotlin | 3 | 6 | 66d94b4a8fa307020d515d4d5d54a77c0bab6c4f | 1,086 | Algorithm | Apache License 2.0 |
src/main/kotlin/g1901_2000/s1948_delete_duplicate_folders_in_system/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1901_2000.s1948_delete_duplicate_folders_in_system
// #Hard #Array #String #Hash_Table #Trie #Hash_Function
// #2023_06_20_Time_1420_ms_(100.00%)_Space_80.6_MB_(100.00%)
class Solution {
private var duplicates: MutableMap<String, ArrayList<Folder>>? = null
private var foldersWithRemovedNames: MutableList<List<String>>? = null
fun deleteDuplicateFolder(paths: List<List<String>>): List<List<String>> {
duplicates = HashMap()
val rootFolder = Folder("", null)
for (path in paths) {
var folder = rootFolder
for (foldername in path) {
folder = folder.addSubFolder(foldername)
}
}
rootFolder.calculateHash()
for ((_, foldersWithSameHash) in duplicates as HashMap<String, ArrayList<Folder>>) {
if (foldersWithSameHash.size > 1) {
for (folder in foldersWithSameHash) {
folder.parent?.subFolders?.remove(folder.name)
}
}
}
foldersWithRemovedNames = ArrayList()
for ((_, folder) in rootFolder.subFolders) {
val path: List<String> = ArrayList()
folder.addPaths(path)
}
return foldersWithRemovedNames as ArrayList<List<String>>
}
private inner class Folder(val name: String, val parent: Folder?) {
val subFolders: MutableMap<String, Folder>
private var folderHash = ""
init {
subFolders = HashMap()
}
fun addSubFolder(foldername: String): Folder {
return subFolders.computeIfAbsent(foldername) { f: String -> Folder(f, this) }
}
fun calculateHash() {
val subFolderNames: MutableList<String> = ArrayList(subFolders.keys)
subFolderNames.sort()
val builder = StringBuilder()
for (foldername in subFolderNames) {
val folder = subFolders[foldername]
folder!!.calculateHash()
builder.append('#')
builder.append(foldername)
if (folder.folderHash.isNotEmpty()) {
builder.append('(')
builder.append(folder.folderHash)
builder.append(')')
}
}
folderHash = builder.toString()
if (folderHash.isNotEmpty()) {
val duplicateFolders = duplicates!!.computeIfAbsent(folderHash) { _: String? -> ArrayList() }
duplicateFolders.add(this)
}
}
fun addPaths(parentPath: List<String>) {
val currentPath: MutableList<String> = ArrayList(parentPath)
currentPath.add(name)
foldersWithRemovedNames!!.add(currentPath)
for ((_, folder) in subFolders) {
folder.addPaths(currentPath)
}
}
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 2,895 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/ArrayStringsAreEqual.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
/**
* 1662. Check If Two String Arrays are Equivalent
* @see <a href="https://leetcode.com/problems/check-if-two-string-arrays-are-equivalent">Source</a>
*/
fun interface ArrayStringsAreEqual {
operator fun invoke(word1: Array<String>, word2: Array<String>): Boolean
}
class ArrayStringsAreEqualCompare : ArrayStringsAreEqual {
override fun invoke(word1: Array<String>, word2: Array<String>): Boolean {
// Creates a new string by combining all the strings in word1.
val word1Combined = StringBuilder()
for (s in word1) {
word1Combined.append(s)
}
// Creates a new string by combining all the strings in word2.
val word2Combined = StringBuilder()
for (s in word2) {
word2Combined.append(s)
}
// Returns true if both string are the same.
return word1Combined.compareTo(word2Combined) == 0
}
}
class ArrayStringsAreEqualTwoPointers : ArrayStringsAreEqual {
override fun invoke(word1: Array<String>, word2: Array<String>): Boolean {
var word1Pointer = 0
var word2Pointer = 0
var string1Pointer = 0
var string2Pointer = 0
while (word1Pointer < word1.size && word2Pointer < word2.size) {
if (word1[word1Pointer][string1Pointer++] !=
word2[word2Pointer][string2Pointer++]
) {
return false
}
if (string1Pointer == word1[word1Pointer].length) {
word1Pointer++
string1Pointer = 0
}
if (string2Pointer == word2[word2Pointer].length) {
word2Pointer++
string2Pointer = 0
}
}
return word1Pointer == word1.size && word2Pointer == word2.size
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,443 | kotlab | Apache License 2.0 |
src/main/kotlin/4. Median of Two Sorted Arrays.kts | ShreckYe | 206,086,675 | false | null | import kotlin.math.max
import kotlin.math.min
class Solution {
fun findMedianSortedArrays(nums1: IntArray, nums2: IntArray): Double {
val totalSize = nums1.size + nums2.size
val totalMid = totalSize / 2
val odd = totalSize % 2 == 1
val longerNums: IntArray
val shorterNums: IntArray
if (nums1.size >= nums2.size) {
longerNums = nums1
shorterNums = nums2
} else {
longerNums = nums2
shorterNums = nums1
}
var left = totalMid - shorterNums.size
var right = totalMid
// longer nums partition index
var midLpi: Int
var spi: Int
while (true) {
midLpi = (left + right) / 2
// shorter nums partition index
spi = totalMid - midLpi
if (longerNums.getOrNull(midLpi - 1)?.let { l ->
shorterNums.getOrNull(spi)?.let { r -> l > r }
} == true)
right = midLpi - 1
else if (shorterNums.getOrNull(spi - 1)?.let { l ->
longerNums.getOrNull(midLpi)?.let { r -> l > r }
} == true)
left = midLpi + 1
else
break
}
// 2 max/min values can't be retrieved at the same time
return if (odd)
min(longerNums.getOrElse(midLpi) { Int.MAX_VALUE }, shorterNums.getOrElse(spi) { Int.MAX_VALUE }).toDouble()
else
(max(longerNums.getOrElse(midLpi - 1) { Int.MIN_VALUE }, shorterNums.getOrElse(spi - 1) { Int.MIN_VALUE })
.toDouble() +
min(longerNums.getOrElse(midLpi) { Int.MAX_VALUE }, shorterNums.getOrElse(spi) { Int.MAX_VALUE })
.toDouble()) / 2
}
/*fun maxOrNull(vararg nums: Int?) =
nums.filterNotNull().max()
fun minOrNull(vararg nums: Int?) =
nums.filterNotNull().min()*/
} | 0 | Kotlin | 0 | 0 | 20e8b77049fde293b5b1b3576175eb5703c81ce2 | 1,951 | leetcode-solutions-kotlin | MIT License |
src/day23/a/day23a.kt | pghj | 577,868,985 | false | {"Kotlin": 94937} | package day23.a
import readInputLines
import shouldBe
import util.IntVector
import vec
fun main() {
val map = read()
map.simulate(10)
val answer = map.width() * map.height() - map.elves.size
shouldBe(3812, answer)
}
class Ground(
val elves: HashMap<IntVector, Elf>
) {
fun print() {
val b = bbox()
for (y in b[0][1] .. b[1][1]) {
for (x in b[0][0] .. b[1][0]) {
print(if (elves.contains(vec(x, y))) '#' else '.')
}
println()
}
println()
}
fun bbox(): Array<IntVector> {
val x1 = elves.values.minOf { it.pos[0] }
val y1 = elves.values.minOf { it.pos[1] }
val x2 = elves.values.maxOf { it.pos[0] }
val y2 = elves.values.maxOf { it.pos[1] }
return arrayOf(vec(x1,y1), vec(x2,y2))
}
fun width(): Int {
return bbox().let { it[1][0] - it[0][0] + 1 }
}
fun height(): Int {
return bbox().let { it[1][1] - it[0][1] + 1 }
}
private fun hasNeighbour(e: Elf): Boolean {
val pos = e.pos
var d = vec(1,0)
for (j in 0..3) {
if (elves.containsKey(pos+d)) return true
d = d.rotate(0,1)
}
d = vec(1,1)
for (j in 0..3) {
if (elves.containsKey(pos+d)) return true
d = d.rotate(0,1)
}
return false
}
private fun isDirectionFree(p: IntVector, d: IntVector): Boolean {
val l = d.rotate(0,1)
val r = d.rotate(1,0)
var f = d + l
for (k in 0..2) {
if (elves.containsKey(p + f)) return false
f += r
}
return true
}
fun simulate(maxRounds: Int): Int? {
val listOfAllElves = elves.values.toList()
val loop = listOf(vec(0,-1), vec(0,1), vec(-1,0), vec(1,0))
var loopIdx = 0
val dst = HashMap<IntVector, Elf>()
for (i in 1..maxRounds) {
// decide where to go
var wouldMove = false
for (e in listOfAllElves) {
e.goto = null
if (!hasNeighbour(e)) continue
wouldMove = true
for (j in 0..3) {
val d = loop[(loopIdx + j) % 4]
if (isDirectionFree(e.pos, d)) {
e.goto = e.pos + d
break
}
}
}
if (!wouldMove) return i-1
// detect collisions
dst.clear()
for (e in listOfAllElves) {
val g = e.goto
if (g != null) {
val e2 = dst[e.goto]
if (e2 != null) {
e2.goto = null
e.goto = null
} else {
dst[g] = e
}
}
}
// apply movements
for (e in listOfAllElves) {
val g = e.goto
if (g != null) {
elves.remove(e.pos)
elves[g] = e
e.pos = g
e.goto = null
}
}
loopIdx = (loopIdx+1)%4
}
return null
}
}
class Elf(
var pos : IntVector,
var goto : IntVector? = null,
)
typealias Input = Ground
fun read(): Input {
val map = HashMap<IntVector, Elf>()
readInputLines(23)
.filter { it.isNotBlank() }
.forEachIndexed { i, s ->
for (j in s.indices) {
val p = vec(j + 1, i + 1)
if (s[j] == '#') map[p] = Elf(p)
}
}
return Ground(map)
}
| 0 | Kotlin | 0 | 0 | 4b6911ee7dfc7c731610a0514d664143525b0954 | 3,717 | advent-of-code-2022 | Apache License 2.0 |
src/nativeMain/kotlin/com.qiaoyuang.algorithm/special/Questions15.kt | qiaoyuang | 100,944,213 | false | {"Kotlin": 338134} | package com.qiaoyuang.algorithm.special
fun test15() {
printlnResult("abc", "cbadabacg")
}
/**
* Questions 15: Find all anagrams of s1 in s2, return the indexes
*/
private fun findAnagrams(s1: String, s2: String): List<Int> {
require(s2.length >= s1.length) { "The input is illegal" }
val s1CharMap = HashMap<Char, Int>(s1.length)
s1.forEach {
s1CharMap[it] = if (s1CharMap.contains(it)) s1CharMap[it]!! + 1 else 1
}
val results = ArrayList<Int>()
val copyMap = HashMap<Char, Int>(s1.length)
for (i in 0 .. s2.length - s1.length) {
s1CharMap.forEach { (key, value) ->
copyMap[key] = value
}
for (j in i ..< i + s1.length) {
val c = s2[j]
if (copyMap.contains(c)) {
copyMap[c] = copyMap[c]!! - 1
if (copyMap[c] == 0)
copyMap.remove(c)
} else
continue
}
if (copyMap.isEmpty())
results.add(i)
}
return results
}
private fun printlnResult(s1: String, s2: String) =
println("The indexes are ${findAnagrams(s1, s2)} of all anagrams of s1 in s2") | 0 | Kotlin | 3 | 6 | 66d94b4a8fa307020d515d4d5d54a77c0bab6c4f | 1,168 | Algorithm | Apache License 2.0 |
proyecto-1/codigo/VerificadorTSP.kt | lmisea | 640,071,913 | false | null | /**
* Verificador de soluciones para el problema del vendedor viajero
* Recibe como argumentos el archivo de instancia y el archivo de solucion
* Imprime si la solucion es correcta o no y muestra algunos errores si los hay
*/
import java.io.BufferedReader
import java.io.File
import java.io.FileReader
/**
* Funcion: distancia2D(p1: Pair<Int, Int>, p2: Pair<Int, Int>)
* Entradas: p1 y p2, dos pares de enteros que representan las coordenadas de dos puntos
* Salidas: La distancia euclidiana entre los dos puntos
* Descripcion: Calcula la distancia euclidiana entre dos puntos en el plano
*/
fun distancia2D(p1: Pair<Double, Double>, p2: Pair<Double, Double>): Double {
val x = p1.first - p2.first
val y = p1.second - p2.second
return Math.sqrt((x * x + y * y).toDouble())
}
/**
* Funcion: distanciaRuta(ciudades: Array<Pair<Int, Int>>)
* Entradas: ciudades, un arreglo de pares de enteros que representan las coordenadas de las ciudades
* Salidas: La distancia total de la ruta que recorre todas las ciudades en el orden dado
* Descripcion: Calcula la distancia total de la ruta que recorre todas las ciudades en el orden dado
*/
fun distanciaRuta(ciudades: Array<Pair<Double, Double>>): Int {
var acc: Double = 0.0
for (i in 0 until ciudades.size - 1) {
acc += distancia2D(ciudades[i], ciudades[i + 1])
}
return acc.toInt()
}
/**
* Funcion: checkSolution(ciudadesInstancia: Array<Pair<Int, Int>>, ciudadesSolucion: Array<Pair<Int, Int>>)
* Entradas: ciudadesInstancia, un arreglo de pares de enteros que representan las coordenadas de las ciudades de la instancia
* ciudadesSolucion, un arreglo de pares de enteros que representan las coordenadas de las ciudades de la solucion
* Salidas: true si la solucion es correcta, false en otro caso
* Descripcion: Verifica que la solucion dada sea correcta
*/
fun checkSolution(indicesInstancia: Array<Int>, indicesSolucion: Array<Int>): Boolean {
// Verificar que la solucion tenga todas las ciudades de la instancia
for (i in 0 until indicesInstancia.size) {
if (!indicesInstancia.contains(indicesSolucion[i])) {
println("La solución no contiene la ciudad ${indicesSolucion[i] + 1}.")
return false
}
}
// Verificar que la solucion no tenga ciudades repetidas
for (i in 0 until indicesSolucion.size) {
for (j in i + 1 until indicesSolucion.size) {
if (indicesSolucion[i] == indicesSolucion[j]) {
println("La solución tiene la ciudad ${indicesSolucion[i] + 1} repetida.")
return false
}
}
}
return true
}
/**
* Funcion: ciudadesFaltantes(ciudadesInstancia: Array<Pair<Int, Int>>, ciudadesSolucion: Array<Pair<Int, Int>>)
* Entradas: indicesInstancia, un arreglo de pares de enteros que representan las coordenadas de las ciudades de la instancia
* indicesSolucion, un arreglo de pares de enteros que representan las coordenadas de las ciudades de la solucion
* Salidas: Imprime (en caso de que sea necesario) las ciudades que faltan en la solucion
*/
fun ciudadesFaltantes(indicesInstancia: Array<Int>, indicesSolucion: Array<Int>){
for (i in 0 until indicesSolucion.size){
if (!indicesInstancia.contains(indicesSolucion[i])){
println("La ciudad ${indicesSolucion[i]+1} no se encuentra en la instancia")
}
}
}
fun main(args: Array<String>) {
// args[0] es el archivo de instancia
// args[1] es el archivo de solucion
val archivoInstancia = File(args[0])
val archivoSolucion = File(args[1])
// Leer las ciudades de la instancia
val lectorInstancia = BufferedReader(FileReader(archivoInstancia, Charsets.UTF_8))
lectorInstancia.readLine() // Ignorar primera linea. Es el nombre del archivo
lectorInstancia.readLine() // Ignorar segunda linea. Es el comentario
val numeroCiudadesInstancia = lectorInstancia.readLine().split(":")[1].trim().toInt()
lectorInstancia.readLine() // Ignorar linea. Es el comentario
val indicesInstancia = Array<Int>(numeroCiudadesInstancia, { 0 })
for (i in 0 until numeroCiudadesInstancia) {
val indice = lectorInstancia.readLine().trim().toInt()
indicesInstancia[i] = indice - 1
}
lectorInstancia.close()
// Leer las ciudades de la solucion
val lectorSolucion = BufferedReader(FileReader(archivoSolucion, Charsets.UTF_8))
lectorSolucion.readLine() // Ignorar primera linea. Es el nombre del archivo
lectorSolucion.readLine() // Ignorar segunda linea. Es el comentario
val numeroCiudadesSolucion = lectorSolucion.readLine().split(":")[1].trim().toInt()
lectorSolucion.readLine() // Ignorar linea. Es el comentario
val indicesSolucion = Array<Int>(numeroCiudadesSolucion, { 0 })
for (i in 0 until numeroCiudadesSolucion) {
val indice = lectorSolucion.readLine().trim().toInt()
indicesSolucion[i] = indice-1
}
lectorSolucion.close()
// Verificar que la solucion sea correcta
if (!checkSolution(indicesInstancia, indicesSolucion)) {
// Si la solucion no es correcta, terminar el programa
println("Solución incorrecta!!")
ciudadesFaltantes(indicesInstancia, indicesSolucion)
return
}
println("Es una solución correcta!!")
println("Se visitaron todas las ciudades de la instancia, solo una vez cada una.")
} | 0 | Kotlin | 1 | 0 | 948a9e52d0760a82a163d01c4361e07a021444cb | 5,397 | lab-algos-2 | MIT License |
advent-of-code-2020/src/main/kotlin/eu/janvdb/aoc2020/day08/Computer.kt | janvdbergh | 318,992,922 | false | {"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335} | package eu.janvdb.aoc2020.day08
import eu.janvdb.aocutil.kotlin.readLines
import java.util.function.BiConsumer
import java.util.function.Consumer
class ComputerState {
var programCounter = 0
var accumulator = 0L
}
enum class EndCondition {
NORMAL_END, INFINITE_LOOP
}
class ExitState(val endState: ComputerState, val endCondition: EndCondition)
enum class InstructionType(var action: BiConsumer<ComputerState, Long>) {
ACC({ state, operand -> state.accumulator += operand }),
JMP({ state, operand -> state.programCounter += operand.toInt() - 1 }),
NOP({ _, _ -> })
}
class Instruction(val instructionType: InstructionType, val operand: Long): Consumer<ComputerState> {
override fun accept(state: ComputerState) {
instructionType.action.accept(state, operand)
}
}
class Program(val instructions: List<Instruction>) {
val size: Int
get() = instructions.size
operator fun get(index: Int): Instruction {
return instructions[index]
}
fun updateInstruction(index: Int, instruction: Instruction): Program {
val newInstructions = instructions.toMutableList()
newInstructions[index] = instruction
return Program(newInstructions)
}
}
class Computer(private val program: Program) {
fun run(): ExitState {
val instructionsRun = mutableListOf<Int>()
val computerState = ComputerState()
while (true) {
instructionsRun.add(computerState.programCounter)
program[computerState.programCounter].accept(computerState)
computerState.programCounter++
if (computerState.programCounter >= program.size) {
return ExitState(computerState, EndCondition.NORMAL_END)
}
if(instructionsRun.contains(computerState.programCounter)) {
return ExitState(computerState, EndCondition.INFINITE_LOOP)
}
}
}
}
var INSTRUCTION_REGEX = Regex("([A-Z]+) ([+-][0-9]+)")
fun readProgram(fileName: String): Program {
val instructions = readLines(2020, fileName)
.map(String::uppercase)
.map(INSTRUCTION_REGEX::matchEntire)
.map(::checkNotNull)
.map { Instruction(InstructionType.valueOf(it.groupValues[1]), it.groupValues[2].toLong()) }
return Program(instructions)
} | 0 | Java | 0 | 0 | 78ce266dbc41d1821342edca484768167f261752 | 2,108 | advent-of-code | Apache License 2.0 |
src/main/kotlin/fr/pturpin/coursera/dynprog/PrimitiveCalculator.kt | TurpIF | 159,055,822 | false | null | package fr.pturpin.coursera.dynprog
class PrimitiveCalculator(private val number: Int) {
private val availableOperations = listOf(
MultByOperation(2),
MultByOperation(3),
AddToOperation(1)
)
private val cache = mutableMapOf<Int, OperationStates>()
fun getMinimumOperationsToCompute(): OperationStates {
cache.clear()
cache[1] = NoOpStates(1)
for (currentNumber in 1..number) {
val currentOperation = cache[currentNumber]!!
availableOperations.forEach {
val appliedNumber = it.apply(currentNumber)
cache.compute(appliedNumber) { _, oldState ->
val newState = LinkedOperationStates(
appliedNumber,
currentOperation
)
if (oldState == null || newState.size() < oldState.size()) {
newState
} else {
oldState
}
}
if (appliedNumber == number) {
return cache[number]!!
}
}
}
return cache[number]!!
}
private interface Operation {
fun apply(number: Int): Int
}
private class MultByOperation(private val factor: Int) :
Operation {
override fun apply(number: Int): Int {
return number * factor
}
}
private class AddToOperation(private val term: Int) :
Operation {
override fun apply(number: Int): Int {
return number + term
}
}
interface OperationStates {
fun size(): Int
fun getStates(): Iterable<Int>
}
private class LinkedOperationStates(
private val currentState: Int,
private val nextState: OperationStates
)
: OperationStates {
private val size = nextState.size() + 1
override fun size() = size
override fun getStates(): Iterable<Int> {
return listOf(currentState) + nextState.getStates()
}
}
private class NoOpStates(private val initialValue: Int):
OperationStates {
override fun size() = 0
override fun getStates() = listOf(initialValue)
}
}
fun main(args: Array<String>) {
val number = readLine()!!.toInt()
val primitiveCalculator = PrimitiveCalculator(number)
val minimumOperationsToCompute = primitiveCalculator.getMinimumOperationsToCompute()
println(minimumOperationsToCompute.size())
print(minimumOperationsToCompute.getStates().reversed().joinToString(" "))
}
| 0 | Kotlin | 0 | 0 | 86860f8214f9d4ced7e052e008b91a5232830ea0 | 2,662 | coursera-algo-toolbox | MIT License |
src/Day01.kt | uzorov | 576,933,382 | false | {"Kotlin": 6068} | import java.io.File
import java.util.*
fun main() {
fun parseInput(input: String): List<List<Int>> = input.split("\n\n").map { elf:String ->
elf.split("\n").map { it.toInt() }
}
fun List<List<Int>>.topNElves(n: Int): Int {
val best: TreeSet<Int> = sortedSetOf<Int>()
for (calories:Int in map { it.sum()}) {
best.add(calories)
if (best.size > n) {
best.remove(best.first())
}
}
return best.sum()
}
fun part1(input: String): Int {
val data: List<List<Int>> = parseInput(input)
return data.topNElves(3)
}
fun part2(input: List<String>): Int {
return input.size
}
// test if implementation meets criteria from the description, like:
//val testInput = readInput("Day01_test")
//check(part1(testInput) == 1)
val input = File("src/input.txt").readText()
part1(input).println()
//part2(input).println()
}
| 0 | Kotlin | 0 | 0 | be4ec026f6114f2fa7ae7ebd9b55af9215de8e7b | 977 | aoc-2022-in-kotlin | Apache License 2.0 |
dcp_kotlin/src/main/kotlin/dcp/day280/day280.kt | sraaphorst | 182,330,159 | false | {"C++": 577416, "Kotlin": 231559, "Python": 132573, "Scala": 50468, "Java": 34742, "CMake": 2332, "C": 315} | package dcp.day280
// day280.kt
// By <NAME>, 2020.
typealias Vertex = Int
typealias AdjacencyList = Set<Vertex>
typealias AdjacencyGraph = Map<Vertex, AdjacencyList>
/**
* Perform a DFS to search for cycles. If we find, in our DFS, a vertex that is a neighbour of the top vertex of the
* stack that is not its parent that is already in the stack, we have found a cycle.
*/
fun AdjacencyGraph.containsCycles(): Boolean {
if (isEmpty())
return false
val vertices = this.keys + this.values.flatten()
fun AdjacencyGraph.isSimpleGraph(): Boolean {
// No loops.
val noLoops = vertices.none{ v -> v in (this[v] ?: emptySet()) }
require(noLoops){"Graph contains loops."}
// Undirected.
val undirected = vertices.none{ v -> vertices.any { u -> v in (this[u] ?: emptySet()) && u !in (this[v] ?: emptySet()) }}
require(undirected){"Graph is directed."}
return true
}
require(this.isSimpleGraph())
// Unfortunately, use mutability so that we don't lose the visited information and then perform unnecessary work.
val unvisited: MutableSet<Vertex> = vertices.toMutableSet()
fun aux(vertexStack: List<Vertex> = emptyList()): Boolean {
// If we have visited all the vertices, we are done.
if (unvisited.isEmpty())
return false
// If there is a top vertex, grab it. Otherwise, get the first unvisited vertex.
val v = if (vertexStack.isEmpty()) unvisited.first() else vertexStack.first()
unvisited -= v
// Get the neighbours of the vertex.
val nbrs = (get(v) ?: emptySet())
// If any of the nbrs are in the list and not the parent of v, we have a cycle.
if (nbrs.any { it in vertexStack.drop(2) }) {
return true
}
// Extend the list by every unvisited vertex. We check unvisited in the lambda instead of intersecting before
// to account for vertices that will be visited by intermediary extensions.
return nbrs.any{ u -> u in unvisited && aux(listOf(u) + vertexStack) }
}
return aux()
}
| 0 | C++ | 1 | 0 | 5981e97106376186241f0fad81ee0e3a9b0270b5 | 2,132 | daily-coding-problem | MIT License |
src/main/java/aoc/xxi/Day5.kt | XuaTheGrate | 434,629,962 | false | {"Kotlin": 19136} | package aoc.xxi
class Day5: DayXXI() {
override val dayNum = 5
data class Vector2(val x1: Int, val x2: Int, val y1: Int, val y2: Int)
private val geysers = data.map {
val (start, end) = it.split(" -> ")
val (x1, y1) = start.split(",").map(String::toInt)
val (x2, y2) = end.split(",").map(String::toInt)
Vector2(x1, x2, y1, y2)
}
override fun solutionPart1(): Number {
val counter = mutableMapOf<Pair<Int, Int>, Int>()
for (point in geysers) {
if (point.y1 == point.y2) {
for (x in point.x1 rangeTo point.x2) {
counter[x to point.y1] = counter[x to point.y1]?.inc() ?: 1
}
} else if (point.x1 == point.x2) {
for (y in point.y1 rangeTo point.y2) {
counter[point.x1 to y] = counter[point.x1 to y]?.inc() ?: 1
}
}
}
val overlap = counter.values.filter { it > 1 }
return overlap.size
}
infix fun Int.rangeTo(other: Int): IntProgression {
if (this > other) return this downTo other
return this .. other
}
override fun solutionPart2(): Number {
val counter = mutableMapOf<Pair<Int, Int>, Int>()
for (point in geysers) {
if (point.y1 == point.y2) {
for (x in point.x1 rangeTo point.x2) {
counter[x to point.y1] = counter[x to point.y1]?.inc() ?: 1
}
} else if (point.x1 == point.x2) {
for (y in point.y1 rangeTo point.y2) {
counter[point.x1 to y] = counter[point.x1 to y]?.inc() ?: 1
}
} else {
for ((x, y) in (point.x1 rangeTo point.x2).zip(point.y1 rangeTo point.y2)) {
counter[x to y] = counter[x to y]?.inc() ?: 1
}
}
}
val overlap = counter.values.filter { it > 1 }
return overlap.size
}
} | 0 | Kotlin | 0 | 1 | 7caeac6fe5c51b853eb59526306401ba516bcea8 | 2,013 | Advent-of-Code | The Unlicense |
Myjava/projects/src/com/learn/day05/19. 黑马商店.kt | turbohiro | 158,934,823 | false | {"Java": 96641, "Kotlin": 46735, "HTML": 27149, "Shell": 16087, "Batchfile": 6794} | package com.learn.day05
/**函数式编程的训练
*
*/
data class Product(val name:String, val price:Double)
data class Order(val products:List<Product>,val isDelivered:Boolean)
data class Customer(val name:String,val city:String,val orders:List<Order>)
data class Shop(val name:String,val customers:List<Customer>)
//模拟产品数据
val dianFanBao = Product("电饭煲",400.0)
val weiBoLu = Product("电波卢",200.0)
val dianKaoXiang = Product("电烤箱",300.0)
//模拟订单数据
val order1 = Order(listOf(dianFanBao, weiBoLu),true)
val order2 = Order(listOf(dianFanBao, dianKaoXiang),true)
val order3 = Order(listOf(weiBoLu, dianKaoXiang),false)
//模拟顾客数据
val customer1 = Customer("chen","hubei",listOf(order1, order2))
val customer2 = Customer("wen","wuhan",listOf(order1, order3))
val customer3 = Customer("kai","shanghai",listOf(order3, order2))
//模拟商店数据
val shop1 = Shop("黑马商店",listOf(customer1,customer2,customer3))
fun main(args:Array<String>) {
println("----黑马商店,用户来自哪些城市----")
val list_city = shop1.customers.map{
it.city //map将原来集合的数据组成一个新的集合
}.distinct()
println(list_city)
println("----黑马商店,chen买过哪些商品")
var chen = shop1.customers.find{
it.name=="chen"
}?.orders?.flatMap {
it.products
}?.distinct()
println(chen)
println("---黑马商店,用户买过的所有商品")
val products = shop1.customers.flatMap{
it.orders
}?.flatMap{
it.products
}.distinct()
println(products)
println("---黑马商店,chen买东西花了多少钱")
val chen_money = shop1.customers.find{
it.name=="chen"
}?.orders?.filter{
it.isDelivered
}?.flatMap {
it.products
}?.sumByDouble {
it.price
}
println(chen_money)
println("黑马商店,所有订单里已发货的价格最贵的商品")
val max_price = shop1.customers.flatMap {
it.orders
}.filter{
it.isDelivered
}.flatMap {
it.products
}.distinct()?.maxBy {
it.price
}?.name
println(max_price)
} | 0 | Java | 0 | 0 | 55268b5c1c5e202641fd1acfce4e842d8567f9e0 | 2,216 | kotlin_learning | MIT License |
30-days-leetcoding-challenge/April 27/src/Solution.kt | alexey-agafonov | 240,769,182 | false | null | import kotlin.math.max
import kotlin.math.min
class Solution {
fun maximalSquare(matrix: Array<CharArray>): Int {
if (matrix.isEmpty()) {
return 0
}
var result = 0
val dp = Array(matrix.size) { IntArray(matrix[0].size) }
for (i in matrix.indices) {
dp[i][0] = matrix[i][0] - '0'
result = max(result, dp[i][0])
}
for (j in matrix[0].indices) {
dp[0][j] = matrix[0][j] - '0'
result = max(result, dp[0][j])
}
for (i in 1 until matrix.size) {
for (j in 1 until matrix[0].size) {
if (matrix[i][j] == '1') {
var min = min(dp[i - 1][j], dp[i][j - 1])
min = min(min, dp[i - 1][j - 1])
dp[i][j] = min + 1
result = max(result, min + 1)
} else {
dp[i][j] = 0
}
}
}
return result * result
}
}
fun main() {
val solution = Solution()
println(solution.maximalSquare(arrayOf(charArrayOf('1', '0', '1', '0', '0'),
charArrayOf('1', '0', '1', '1', '1'),
charArrayOf('1', '1', '1', '1', '1'),
charArrayOf('1', '0', '0', '1', '0'))))
} | 0 | Kotlin | 0 | 0 | d43d9c911c6fd89343e392fd6f93b7e9d02a6c9e | 1,395 | leetcode | MIT License |
src/Day05.kt | colund | 573,040,201 | false | {"Kotlin": 10244} | fun main() {
println("Day5 part 1: " + day5(::part1))
println("Day5 part 2: " + day5(::part2))
}
private fun day5(
doInstruction: (
count: Int,
stacks: MutableList<MyStack>,
fromIndex: Int,
toIndex: Int
) -> Unit
): String {
val stacks = mutableListOf<MyStack>()
var parsingStack = true
val moveRegex = "move (\\d+) from (\\d+) to (\\d+)".toRegex()
val input = readInput("Day05")
input.forEach {
if (it.startsWith(" 1")) {
parsingStack = false
} else if (parsingStack) {
it.chunked(4).forEachIndexed { index, string ->
val stack = stacks.elementAtOrNull(index) ?: MyStack().also { stacks.add(it) }
val char = string.elementAt(1)
if (char != ' ') {
stack.insertLast(char)
}
}
} else {
val groupValues: List<String> = moveRegex.matchEntire(it)?.groupValues ?: return@forEach
val count = groupValues[1].toInt()
val fromIndex = groupValues[2].toInt() - 1
val toIndex = groupValues[3].toInt() - 1
doInstruction(count, stacks, fromIndex, toIndex)
}
}
return stacks.map { it.pop() }.joinToString("")
}
private fun part1(
count: Int,
stacks: MutableList<MyStack>,
fromIndex: Int,
toIndex: Int
) {
repeat(count) {
val popped = stacks[fromIndex].pop()
stacks[toIndex].push(popped)
}
}
private fun part2(
count: Int,
stacks: MutableList<MyStack>,
fromIndex: Int,
toIndex: Int
) {
val popped = stacks[fromIndex].popCount(count)
stacks[toIndex].pushGroup(popped)
} | 0 | Kotlin | 0 | 0 | 49dcd2fccad0e54ee7b1a9cb99df2acdec146759 | 1,713 | aoc-kotlin-2022 | Apache License 2.0 |
Line_circle_intersection/Kotlin/src/LineCircleIntersection.kt | ncoe | 108,064,933 | false | {"D": 425100, "Java": 399306, "Visual Basic .NET": 343987, "C++": 328611, "C#": 289790, "C": 216950, "Kotlin": 162468, "Modula-2": 148295, "Groovy": 146721, "Lua": 139015, "Ruby": 84703, "LLVM": 58530, "Python": 46744, "Scala": 43213, "F#": 21133, "Perl": 13407, "JavaScript": 6729, "CSS": 453, "HTML": 409} | import kotlin.math.absoluteValue
import kotlin.math.sqrt
const val eps = 1e-14
class Point(val x: Double, val y: Double) {
override fun toString(): String {
var xv = x
if (xv == 0.0) {
xv = 0.0
}
var yv = y
if (yv == 0.0) {
yv = 0.0
}
return "($xv, $yv)"
}
}
fun sq(x: Double): Double {
return x * x
}
fun intersects(p1: Point, p2: Point, cp: Point, r: Double, segment: Boolean): MutableList<Point> {
val res = mutableListOf<Point>()
val x0 = cp.x
val y0 = cp.y
val x1 = p1.x
val y1 = p1.y
val x2 = p2.x
val y2 = p2.y
val A = y2 - y1
val B = x1 - x2
val C = x2 * y1 - x1 * y2
val a = sq(A) + sq(B)
val b: Double
val c: Double
var bnz = true
if (B.absoluteValue >= eps) {
b = 2 * (A * C + A * B * y0 - sq(B) * x0)
c = sq(C) + 2 * B * C * y0 - sq(B) * (sq(r) - sq(x0) - sq(y0))
} else {
b = 2 * (B * C + A * B * x0 - sq(A) * y0)
c = sq(C) + 2 * A * C * x0 - sq(A) * (sq(r) - sq(x0) - sq(y0))
bnz = false
}
var d = sq(b) - 4 * a * c // discriminant
if (d < 0) {
return res
}
// checks whether a point is within a segment
fun within(x: Double, y: Double): Boolean {
val d1 = sqrt(sq(x2 - x1) + sq(y2 - y1)) // distance between end-points
val d2 = sqrt(sq(x - x1) + sq(y - y1)) // distance from point to one end
val d3 = sqrt(sq(x2 - x) + sq(y2 - y)) // distance from point to other end
val delta = d1 - d2 - d3
return delta.absoluteValue < eps // true if delta is less than a small tolerance
}
var x = 0.0
fun fx(): Double {
return -(A * x + C) / B
}
var y = 0.0
fun fy(): Double {
return -(B * y + C) / A
}
fun rxy() {
if (!segment || within(x, y)) {
res.add(Point(x, y))
}
}
if (d == 0.0) {
// line is tangent to circle, so just one intersect at most
if (bnz) {
x = -b / (2 * a)
y = fx()
rxy()
} else {
y = -b / (2 * a)
x = fy()
rxy()
}
} else {
// two intersects at most
d = sqrt(d)
if (bnz) {
x = (-b + d) / (2 * a)
y = fx()
rxy()
x = (-b - d) / (2 * a)
y = fx()
rxy()
} else {
y = (-b + d) / (2 * a)
x = fy()
rxy()
y = (-b - d) / (2 * a)
x = fy()
rxy()
}
}
return res
}
fun main() {
println("The intersection points (if any) between:")
var cp = Point(3.0, -5.0)
var r = 3.0
println(" A circle, center $cp with radius $r, and:")
var p1 = Point(-10.0, 11.0)
var p2 = Point(10.0, -9.0)
println(" a line containing the points $p1 and $p2 is/are:")
println(" ${intersects(p1, p2, cp, r, false)}")
p2 = Point(-10.0, 12.0)
println(" a segment starting at $p1 and ending at $p2 is/are:")
println(" ${intersects(p1, p2, cp, r, true)}")
p1 = Point(3.0, -2.0)
p2 = Point(7.0, -2.0)
println(" a horizontal line containing the points $p1 and $p2 is/are:")
println(" ${intersects(p1, p2, cp, r, false)}")
cp = Point(0.0, 0.0)
r = 4.0
println(" A circle, center $cp with radius $r, and:")
p1 = Point(0.0, -3.0)
p2 = Point(0.0, 6.0)
println(" a vertical line containing the points $p1 and $p2 is/are:")
println(" ${intersects(p1, p2, cp, r, false)}")
println(" a vertical segment containing the points $p1 and $p2 is/are:")
println(" ${intersects(p1, p2, cp, r, true)}")
cp = Point(4.0, 2.0)
r = 5.0
println(" A circle, center $cp with radius $r, and:")
p1 = Point(6.0, 3.0)
p2 = Point(10.0, 7.0)
println(" a line containing the points $p1 and $p2 is/are:")
println(" ${intersects(p1, p2, cp, r, false)}")
p1 = Point(7.0, 4.0)
p2 = Point(11.0, 8.0)
println(" a segment starting at $p1 and ending at $p2 is/are:")
println(" ${intersects(p1, p2, cp, r, true)}")
}
| 0 | D | 0 | 4 | c2a9f154a5ae77eea2b34bbe5e0cc2248333e421 | 4,215 | rosetta | MIT License |
advanced-algorithms/kotlin/src/h1PrecPmtnRFMax.kt | nothingelsematters | 135,926,684 | false | {"Jupyter Notebook": 7400788, "Java": 512017, "C++": 378834, "Haskell": 261217, "Kotlin": 251383, "CSS": 45551, "Vue": 37772, "Rust": 34636, "HTML": 22859, "Yacc": 14912, "PLpgSQL": 10573, "JavaScript": 9741, "Makefile": 8222, "TeX": 7166, "FreeMarker": 6855, "Python": 6708, "OCaml": 5977, "Nix": 5059, "ANTLR": 4802, "Logos": 3516, "Perl": 2330, "Mustache": 1527, "Shell": 1105, "MATLAB": 763, "M": 406, "Batchfile": 399} | import java.io.File
import java.util.Scanner
private fun <T> MutableList<T>.addAll(vararg ts: T) = addAll(ts)
data class Job(
val time: Long,
var release: Long,
val index: Int,
val f: (Long) -> Long,
val times: MutableList<Long> = mutableListOf(),
)
private data class Block(val start: Long, var time: Long = 0, val jobs: MutableList<Job> = mutableListOf()) {
val end: Long
get() = start + time
fun add(job: Job) {
jobs += job
time += job.time
}
}
private fun topologicalSort(jobs: List<Job>, edges: List<List<Int>>, reverseEdges: List<List<Int>>): List<Job> {
fun depthFirstSearch(
edges: List<List<Int>>,
jobs: List<Job>,
currentVertex: Int,
result: MutableList<Job>,
used: MutableSet<Int>,
) {
if (currentVertex in used) return
used += currentVertex
edges[currentVertex]
.asSequence()
.filter { it !in used }
.forEach { depthFirstSearch(edges, jobs, it, result, used) }
result += jobs[currentVertex]
}
val result = mutableListOf<Job>()
val used = mutableSetOf<Int>()
jobs.indices
.asSequence()
.filter { it !in used && reverseEdges[it].isEmpty() }
.forEach { depthFirstSearch(edges, jobs, it, result, used) }
return result
}
private fun createBlocks(jobs: List<Job>): List<Block> = buildList {
jobs.forEach { job ->
val block = if (lastOrNull()?.let { it.end >= job.release } == true) {
last()
} else {
Block(job.release).also { add(it) }
}
block.add(job)
}
}
private fun decompose(edges: List<List<Int>>, block: Block): Long {
val end = block.end
val used = mutableSetOf<Int>()
val minimumJobIndex = block.jobs
.indices
.reversed()
.asSequence()
.map { it to block.jobs[it] }
.filter { (_, job) -> edges[job.index].none { it in used }.also { used += job.index } }
.minBy { (_, job) -> job.f(end) }
.first
val deleted = block.jobs[minimumJobIndex]
block.jobs.removeAt(minimumJobIndex)
val newBlocks = createBlocks(block.jobs)
return if (newBlocks.isEmpty()) {
deleted.times.addAll(block.start, block.end)
deleted.f(end)
} else {
if (block.start < newBlocks.first().start) {
deleted.times.addAll(block.start, newBlocks.first().start)
}
newBlocks.asSequence()
.windowed(2)
.map { (left, right) -> left.end to right.start }
.filter { (start, end) -> start < end }
.forEach { deleted.times.addAll(it.toList()) }
if (block.end > newBlocks.last().end) {
deleted.times.addAll(newBlocks.last().end, block.end)
}
maxOf(deleted.f(end), newBlocks.maxOf { decompose(edges, it) })
}
}
fun schedule1PrecPmtnRFMax(jobs: List<Job>, edges: List<List<Int>>, reverseEdges: List<List<Int>>): Long {
val topologicalSorted = topologicalSort(jobs, edges, reverseEdges)
topologicalSorted.asReversed().forEach { job ->
edges[job.index]
.asSequence()
.map { jobs[it] }
.forEach { it.release = maxOf(it.release, job.release + job.time) }
}
return createBlocks(topologicalSorted.sortedBy { it.release }).maxOf { decompose(edges, it) }
}
fun main() {
val scanner = Scanner(File("p1precpmtnrifmax.in").bufferedReader())
val n = scanner.nextInt()
val times = List(n) { scanner.nextLong() }
val releases = List(n) { scanner.nextLong() }
val m = scanner.nextInt()
val edges = List(n) { mutableListOf<Int>() }
val reverseEdges = List(n) { mutableListOf<Int>() }
repeat(m) {
val (from, to) = List(2) { scanner.nextInt() - 1 }
edges[from] += to
reverseEdges[to] += from
}
val jobs = List(n) {
val (a, b, c) = List(3) { scanner.nextLong() }
Job(times[it], releases[it], it, { time -> a * time * time + b * time + c })
}
val fMax = schedule1PrecPmtnRFMax(jobs, edges, reverseEdges)
File("p1precpmtnrifmax.out").printWriter().use { output ->
output.println(fMax)
jobs.forEach { job ->
output.write("${job.times.size / 2} ")
job.times.forEach { output.print("$it ") }
output.println()
}
}
}
| 0 | Jupyter Notebook | 3 | 5 | d442a3d25b579b96c6abda13ed3f7e60d1747b53 | 4,408 | university | Do What The F*ck You Want To Public License |
src/Day01.kt | BrianEstrada | 572,700,177 | false | {"Kotlin": 22757} | fun main() {
fun getElves(input: List<String>): IntArray {
val elfs = IntArray(input.count { it.isEmpty() } + 1) { 0 }
var elfIndex = 0
for (value in input) {
if (value.isEmpty()) {
elfIndex++
} else {
elfs[elfIndex] += value.toInt()
}
}
return elfs
}
fun part1(input: List<String>): Int {
return getElves(input).max()
}
fun part2(input: List<String>): Int {
return getElves(input).sortedArrayDescending().take(3).sum()
}
println("Part 1: " + part1(readInput("Day01_test")))
println("Part 1: " + part1(readInput("Day01")))
println("Part 2: " + part2(readInput("Day01_test")))
println("Part 2: " + part2(readInput("Day01")))
}
| 1 | Kotlin | 0 | 1 | 032a4693aff514c9b30e979e63560dc48917411d | 797 | aoc-kotlin-2022 | Apache License 2.0 |
kotlin/src/katas/kotlin/leetcode/swap_nodes_in_pairs/SwapNodesInPairs.kt | dkandalov | 2,517,870 | false | {"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221} | package katas.kotlin.leetcode.swap_nodes_in_pairs
import katas.kotlin.leetcode.ListNode
import katas.kotlin.leetcode.listNodes
import datsok.shouldEqual
import org.junit.Test
/**
* https://leetcode.com/problems/swap-nodes-in-pairs
*/
class SwapNodesInPairsTests {
@Test fun `swap every two adjacent nodes`() {
listNodes(1, 2).swapPairs() shouldEqual listNodes(2, 1)
listNodes(1, 2, 3, 4).swapPairs() shouldEqual listNodes(2, 1, 4, 3)
listNodes(1, 2, 3, 4, 5, 6).swapPairs() shouldEqual listNodes(2, 1, 4, 3, 6, 5)
listNodes(1, 2, 3, 4, 5, 6, 7, 8).swapPairs() shouldEqual listNodes(2, 1, 4, 3, 6, 5, 8, 7)
listNodes(1).swapPairs() shouldEqual listNodes(1)
listNodes(1, 2, 3).swapPairs() shouldEqual listNodes(2, 1, 3)
listNodes(1, 2, 3, 4, 5).swapPairs() shouldEqual listNodes(2, 1, 4, 3, 5)
}
}
private fun ListNode.swapPairs(): ListNode {
var first: ListNode? = this
var second = first?.next
var third = second?.next
var fourth = third?.next
val head = second ?: return first!!
second.next = first
first?.next = fourth ?: third
do {
first = third
second = first?.next
third = second?.next
fourth = third?.next
second?.next = first
first?.next = fourth ?: third
} while (third != null)
return head
}
| 7 | Roff | 3 | 5 | 0f169804fae2984b1a78fc25da2d7157a8c7a7be | 1,364 | katas | The Unlicense |
PeakInArray.kt | prashantsinghpaliwal | 537,191,958 | false | {"Kotlin": 9473} | // Question Link - https://leetcode.com/problems/find-peak-element/
fun main() {
val arr = arrayOf(2, 3, 4, 7, 8, 6, 5, 1)
println(findPeak(arr))
}
fun findPeak(
arr: Array<Int>
): Int {
var start = 0
var end = arr.size -1
while (start < end) {
val mid = start + (end - start) / 2
if (arr[mid] > arr[mid+1]) {
// we are in decreasing part, so the answer should lie at mid itself or on the left side.
// this is why end != mid - 1
end = mid
} else if (arr[mid] < arr[mid+1]) {
// we are in increasing part, so the answer should lie at mid itself or on the right side.
// Also, we know mid + 1 is greater than mid element and we are finding
// greater elements only, so we are ignoring mid element
start = mid + 1
}
}
// In the end, start & end will point to largest element
// because of 2 checks.
// look closely, since start and end are trying to find max element only
// hence when both start and end will point to same element,
// that's the maximum element.
// so we can now return anything, start or end. After running above checks, now
// they are pointing to same max elements.
return arr[start]
}
| 0 | Kotlin | 0 | 0 | e66599817508beb4e90de43305939d200a9e3964 | 1,287 | DsAlgo | Apache License 2.0 |
src/day19.kt | eldarbogdanov | 577,148,841 | false | {"Kotlin": 181188} | import kotlin.math.max
fun main() {
data class State(
val oreRobots: Int, val clayRobots: Int, val obsidianRobots: Int, val geodeRobots: Int,
val clay: Int, val obsidian: Int, val geode: Int
) {
fun next(): State {
return State(
oreRobots, clayRobots, obsidianRobots, geodeRobots,
clay + clayRobots, obsidian + obsidianRobots, geode + geodeRobots
)
}
}
fun solve(time: Int, oreOreCost: Int, clayOreCost: Int, obsidianOreCost: Int, obsidianClayCost: Int, geodeOreCost: Int, geodeObsidianCost: Int): Int {
val best = Array(time + 1) { mutableMapOf<State, Int>() }
best[0][State(1, 0, 0, 0, 0, 0, 0)] = 0
var ret = 0
fun put(t: Int, state: State, value: Int) {
if (!best[t + 1].contains(state) || best[t + 1].getValue(state) < value) {
best[t + 1][state] = value
}
}
for(t in 0 until time) {
for(entry in best[t]) {
val state = entry.key
ret = max(ret, state.next().geode)
if (t == time - 1) continue;
// don't build anything
put(t, state.next(), entry.value + state.oreRobots);
// build ore robot
if (entry.value >= oreOreCost) {
val newState = state.next().copy(oreRobots = state.oreRobots + 1)
val newOre = entry.value - oreOreCost + state.oreRobots
put(t, newState, newOre)
}
// build clay robot
if (entry.value >= clayOreCost) {
val newState = state.next().copy(clayRobots = state.clayRobots + 1)
val newOre = entry.value - clayOreCost + state.oreRobots
put(t, newState, newOre)
}
// build obsidian robot
if (entry.value >= obsidianOreCost && state.clay >= obsidianClayCost) {
val newState = state.next().copy(obsidianRobots = state.obsidianRobots + 1, clay = state.clay - obsidianClayCost + state.clayRobots)
val newOre = entry.value - obsidianOreCost + state.oreRobots
put(t, newState, newOre)
}
// build geode robot
if (entry.value >= geodeOreCost && state.obsidian >= geodeObsidianCost) {
val newState = state.next().copy(geodeRobots = state.geodeRobots + 1, obsidian = state.obsidian - geodeObsidianCost + state.obsidianRobots)
val newOre = entry.value - geodeOreCost + state.oreRobots
put(t, newState, newOre)
}
}
}
return ret
}
// val test = """Blueprint 1: Each ore robot costs 4 ore. Each clay robot costs 2 ore. Each obsidian robot costs 3 ore and 14 clay. Each geode robot costs 2 ore and 7 obsidian.
//Blueprint 2: Each ore robot costs 2 ore. Each clay robot costs 3 ore. Each obsidian robot costs 3 ore and 8 clay. Each geode robot costs 3 ore and 12 obsidian."""
val test = """Blueprint 1: Each ore robot costs 4 ore. Each clay robot costs 4 ore. Each obsidian robot costs 2 ore and 16 clay. Each geode robot costs 4 ore and 16 obsidian.
Blueprint 2: Each ore robot costs 4 ore. Each clay robot costs 4 ore. Each obsidian robot costs 3 ore and 14 clay. Each geode robot costs 4 ore and 8 obsidian.
Blueprint 3: Each ore robot costs 3 ore. Each clay robot costs 4 ore. Each obsidian robot costs 3 ore and 18 clay. Each geode robot costs 4 ore and 16 obsidian."""
val regex = Regex("Blueprint ([0-9]+): Each ore robot costs ([0-9]+) ore. Each clay robot costs ([0-9]+) ore. Each obsidian robot costs ([0-9]+) ore and ([0-9]+) clay. Each geode robot costs ([0-9]+) ore and ([0-9]+) obsidian.")
var ans = 0;
for(s in test.split("\n")) {
val list = regex.find(s)!!.groupValues
println("Test " + list[1])
val geodes = solve(
32,
Integer.parseInt(list[2]),
Integer.parseInt(list[3]),
Integer.parseInt(list[4]),
Integer.parseInt(list[5]),
Integer.parseInt(list[6]),
Integer.parseInt(list[7]),
)
println(geodes)
ans += Integer.parseInt(list[1]) * geodes
}
println(ans)
}
| 0 | Kotlin | 0 | 0 | bdac3ab6cea722465882a7ddede89e497ec0a80c | 4,390 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/com/colinodell/advent2021/Day14.kt | colinodell | 433,864,377 | true | {"Kotlin": 111114} | package com.colinodell.advent2021
class Day14(input: List<String>) {
private val template = input[0]
private val insertionRules = input.drop(2).map { line ->
line.split(" -> ").let { it[0] to it[0][0] + it[1] + it[0][1] }
}.toMap()
fun solvePart1() = polymerizeAndCalculateAnswer(10)
fun solvePart2() = polymerizeAndCalculateAnswer(40)
fun polymerizeAndCalculateAnswer(rounds: Int): Long {
var polymers = template.windowed(2).groupingBy { it }.eachCount().mapValues { it.value.toLong() }
repeat (rounds) {
val foo = mutableMapOf<String, Long>()
polymers.mapKeys { insertionRules[it.key] ?: it.key }.forEach {
it.key.windowed(2).forEach { pair ->
foo[pair] = (foo[pair] ?: 0L) + it.value
}
}
polymers = foo
}
val frequencies = mutableMapOf<Char, Long>()
polymers.forEach {
it.key.forEach { letter ->
frequencies[letter] = (frequencies[letter] ?: 0L) + it.value
}
}
return (frequencies.maxOf { it.value + 1 }!! / 2) - (frequencies.minOf { it.value + 1 }!! / 2)
}
} | 0 | Kotlin | 0 | 1 | a1e04207c53adfcc194c85894765195bf147be7a | 1,201 | advent-2021 | Apache License 2.0 |
scripts/Day18.kts | matthewm101 | 573,325,687 | false | {"Kotlin": 63435} | import java.io.File
data class Cube(val x: Int, val y: Int, val z: Int) {
operator fun plus(c: Cube) = Cube(x+c.x,y+c.y,z+c.z)
fun neighbors() = listOf(Cube(1,0,0),Cube(-1,0,0),Cube(0,1,0),Cube(0,-1,0),Cube(0,0,1),Cube(0,0,-1)).map { this + it }
}
val droplet = File("../inputs/18.txt").readLines().map { val splits = it.split(","); Cube(splits[0].toInt(),splits[1].toInt(),splits[2].toInt()) }.toSet()
val surfaceArea = droplet.sumOf { cube -> cube.neighbors().count { it !in droplet } }
println("The surface area of the droplet (including pockets) is $surfaceArea.")
val xMin = droplet.minOf { it.x }
val xMax = droplet.maxOf { it.x }
val yMin = droplet.minOf { it.y }
val yMax = droplet.maxOf { it.y }
val zMin = droplet.minOf { it.z }
val zMax = droplet.maxOf { it.z }
val air = (xMin..xMax).flatMap { x -> (yMin..yMax).flatMap { y -> (zMin..zMax).map { z -> Cube(x,y,z) } } }.filter { it !in droplet }.toMutableSet()
var frontier = setOf(Cube(xMin,yMin,zMin))
while (frontier.isNotEmpty()) {
frontier = frontier.flatMap { it.neighbors() }.filter { it in air }.toSet()
air.removeAll(frontier)
}
val filledDroplet = droplet + air
val fixedSurfaceArea = filledDroplet.sumOf { cube -> cube.neighbors().count { it !in filledDroplet } }
println("The surface area of the droplet (without pockets) is $fixedSurfaceArea.") | 0 | Kotlin | 0 | 0 | bbd3cf6868936a9ee03c6783d8b2d02a08fbce85 | 1,366 | adventofcode2022 | MIT License |
src/main/kotlin/day2.kt | sviams | 726,160,356 | false | {"Kotlin": 9233} | object day2 {
data class DrawSet(val red: Int, val green: Int, val blue: Int)
data class Game(val id: Int, val sets: List<DrawSet>) {
val power: Int by lazy { sets.maxOf { it.red } * sets.maxOf { it.blue } * sets.maxOf { it.green } }
fun withinLimit(r: Int, b: Int, g: Int): Boolean = sets.all { set ->
set.red <= r && set.blue <= b && set.green <= g
}
}
fun parseInput(input: List<String>): List<Game> = input.fold(emptyList()) { games, line ->
val (gameId) = Regex("""Game (\d+):""").find(line)!!.destructured
val drawSets = line.split(": ")[1].split(';').fold(emptyList<DrawSet>()) { drawSets, setString ->
val red = Regex("""(\d+) red""").find(setString)?.groupValues?.last()?.toInt() ?: 0
val blue = Regex("""(\d+) blue""").find(setString)?.groupValues?.last()?.toInt() ?: 0
val green = Regex("""(\d+) green""").find(setString)?.groupValues?.last()?.toInt() ?: 0
drawSets + DrawSet(red, green, blue)
}
games + Game(gameId.toInt(), drawSets)
}
fun pt1(input: List<String>): Int = parseInput(input).filter { it.withinLimit(12, 14, 13) }.sumOf { it.id }
fun pt2(input: List<String>): Int = parseInput(input).sumOf { it.power }
} | 0 | Kotlin | 0 | 0 | 4914a54b21e8aac77ce7bbea3abc88ac04037d50 | 1,278 | aoc23 | Apache License 2.0 |
app/src/main/kotlin/advent_of_code/year_2021/AdventOfCode2021.kt | mavomo | 574,441,138 | false | {"Kotlin": 56468} | package advent_of_code.year_2021
class AdventOfCode2021 {
fun countingDepthMeasurementIncreases(report: List<Int>): Int {
var increaseCounter = 0
for (depth in report.withIndex()) {
val depthValue = depth.value
val nextIdx = depth.index + 1
if (nextIdx < report.size && depthValue < report[nextIdx]) {
increaseCounter++
}
}
return increaseCounter
}
fun countingIncresalOfMeasurements(measurementsBySlidingWindow: Map<Char, List<Int>>): Int {
val sumByWindow: Map<Char, Int> = measurementsBySlidingWindow.entries.associate { it.key to it.value.sum() }
var numberOfIncrease = 0
var previousValue = sumByWindow.entries.iterator().next()
sumByWindow.entries.filterNot { it.key == previousValue.key }
.forEach {
if (it.value > previousValue.value) {
numberOfIncrease++
}
previousValue = it
}
return numberOfIncrease
}
fun makeListOfThreeSlidingWindowData(measures: List<Int>, chunk: Int): MutableList<Int> {
val listWithSum = mutableListOf<Int>()
val maxSum = measures.subList(0, chunk).sum()
listWithSum.add(maxSum)
var i = chunk
var windowSum = maxSum
while (i < measures.size) {
windowSum += measures[i] - measures[i - chunk]
listWithSum.add(windowSum)
i++
}
return listWithSum
}
fun getSubmarinPosition(instructions: List<String>): Pair<Int, Int> {
var horizontal = 0
var depth = 0
instructions.forEach {
val instruction = it.split(" ")
val command = instruction[0]
val distance = instruction[1].toInt()
when (command) {
"forward" -> horizontal += distance
"down" -> depth += distance
"up" -> depth -= distance
}
}
return Pair(depth, horizontal)
}
}
| 0 | Kotlin | 0 | 0 | b7fec100ea3ac63f48046852617f7f65e9136112 | 2,066 | advent-of-code | MIT License |
src/Day17-delete.kt | p357k4 | 573,068,508 | false | {"Kotlin": 59696} | package ndrsh.puzzles.adventofcode2022
import java.io.File
// positions are represented as ints, a position with coords x,y (where y increases as rocks fall) is represented as k = y*cols + x
typealias Rocks = List<Int>
val rows = 20_000
val cols = 7
val bottom = rows*cols
val line = File("src/Day17_test.txt").readLines().first()
val rockVecs = listOf(listOf(0, 1, 2, 3),
listOf(1, 1 - cols, 1 - 2*cols, 2 - cols, -cols),
listOf(0, 1, 2, 2 - cols, 2 - 2*cols),
listOf(0, -cols, -2*cols, -3*cols),
listOf(0, 1, -cols, -cols + 1))
fun main(args: Array<String>) {
val ans1 = State(2022L).simulate()
val ans2 = State(1000000000000L).simulate() // runs in 1ms
println(ans1)
println(ans2)
}
fun State.firstCycleEnd() = step == line.length
fun State.thirdCycleEnd() = step == line.length*3
/*
* after the first run through the input, the state repeats each input cycle.
* but after the first run, instead of waiting 1 cycle before forwarding, we wait 2 because line.length could be odd.
*/
tailrec fun State.simulate(): Long {
if (rockCount == target) return rows - row + heightToAdd
if (firstCycleEnd()) save = Save(rockCount, row)
return if (thirdCycleEnd() && target != 2022L) forward().simulate()
else updateRocks().simulate()
}
fun State.forward(): State {
val rockDiff = rockCount - save.rockCount
val factor = (target - save.rockCount)/rockDiff
return copy(heightToAdd = (save.row - row)*(factor - 1),
rockCount = save.rockCount + factor*rockDiff,
step = step + 1)
}
fun State.rightDir() = line[(step/2)%line.length] == '>'
fun State.jetPushTime() = step and 1 == 1
fun State.updateRocks() = apply {
rocks = if (jetPushTime()) if (rightDir()) rocks.right() else rocks.left()
else if (rocks.canFall()) rocks.fall()
else {
rocks.forEach { taken[it] = true }
row = minOf(row, rocks.min()/cols)
rockVecs[(++rockCount%5).toInt()].map { it + getSpawningPoint(row*cols) }
}
step++
}
data class Save(val rockCount: Long = 0L, val row: Int = 0)
data class State(val target: Long,
var rocks: Rocks = rockVecs.first().map { it + getSpawningPoint(bottom) },
val taken: BooleanArray = BooleanArray((rows + 1)*cols),
var rockCount: Long = 0,
var row: Int = rows,
var step: Int = 1,
var heightToAdd: Long = 0L,
var save: Save = Save()) {
fun Rocks.left() = if (any { it%cols == 0 || taken[it - 1] }) this else map { it - 1 }
fun Rocks.right() = if (any { it%cols == cols - 1 || taken[it + 1] }) this else map { it + 1 }
fun Rocks.canFall() = none { it + cols > rows*cols || taken[it + cols] }
fun Rocks.fall() = map { it + cols }
}
fun getSpawningPoint(initial: Int) = (initial/cols - 4)*cols + 2 | 0 | Kotlin | 0 | 0 | b9047b77d37de53be4243478749e9ee3af5b0fac | 2,856 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/com/kishor/kotlin/algo/problems/arrayandstrings/PairSum.kt | kishorsutar | 276,212,164 | false | null | package com.kishor.kotlin.algo.problems.arrayandstrings
fun main(args: Array<String>) {
println(numberOfWays(arrayOf(1, 2, 3, 4, 3), 6))
println(numberOfWays(arrayOf(1, 5, 3, 3, 3), 6))
println(numberOfWaysUsingHashSet(arrayOf(1, 2, 3, 4, 3), 6))
println(numberOfWaysUsingHashSet(arrayOf(1, 5, 3, 3, 3), 6))
}
fun numberOfWays(arr: Array<Int>, k: Int): Int {
arr.sort()
var count = 0
for (ele in arr) {
if (isPresentIn(k - ele, arr)) count++
}
return count
}
fun isPresentIn(diff: Int, arr: Array<Int>): Boolean {
var left = 0
var right = arr.size - 1
while (left < right) {
val mid = (left + right) / 2
if (arr[mid] == diff) return true
else if (diff < mid) {
right = mid - 1
} else {
left = mid + 1
}
}
return false
}
fun numberOfWaysUsingHashSet(arr: Array<Int>, k: Int): Int {
val dataSet = mutableMapOf<Int, Int>()
for (ele in arr) {
dataSet[ele] = dataSet.getOrDefault(ele, 0) + 1
}
var count = 0
for (ele in arr) {
if (dataSet.contains(ele)) {
count += dataSet[ele]!!
}
}
return (count / 2) - 1
} | 0 | Kotlin | 0 | 0 | 6672d7738b035202ece6f148fde05867f6d4d94c | 1,210 | DS_Algo_Kotlin | MIT License |
src/Day01.kt | eps90 | 574,098,235 | false | {"Kotlin": 9738} | fun main() {
fun caloriesPerElf(input: List<String>): List<Int> {
return input
.fold(mutableListOf()) { acc, s ->
if (s.isEmpty()) {
acc.add(0)
acc
} else {
val lastElem = acc.lastOrNull() ?: 0
val newAcc = acc.dropLast(1).toMutableList()
newAcc.add(lastElem + s.toInt())
newAcc
}
}
}
fun part1(input: List<String>): Int {
return caloriesPerElf(input).max()
}
fun part2(input: List<String>): Int {
return caloriesPerElf(input).sortedDescending().take(3).sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | bbf58c512fddc0ef1112c3bee5e5c6d43f5aabc0 | 949 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/io/jadon/election/model.kt | phase | 277,456,271 | false | null | package io.jadon.election
import java.util.*
import kotlin.math.abs
import kotlin.math.floor
import kotlin.math.pow
/**
* Categories of issues
*/
enum class Category {
ECONOMIC, // Equalities <-> Markets
DIPLOMATIC, // Nation <-> World
CIVIL, // Liberty <-> Authority
SOCIETAL // Tradition <-> Progress
}
/**
* Represents a political issue a voter or party can take a stance on.
* Examples include Public Health Care, Climate Change, Abortion
*/
data class Issue(val category: Category, val id: Int, val name: String = "Issue #$id")
/**
* Represents a stance on an issue.
*/
enum class Policy(val value: Double) {
STRONGLY_DISAPPROVE(-1.5),
DISAPPROVE(-1.0),
INDIFFERENT(0.0),
APPROVE(1.0),
STRONGLY_APPROVE(1.5),
;
fun approves(): Boolean = value > 0
fun disapproves(): Boolean = value < 0
fun above(amount: Int): Policy =
Policy.values()[(this.ordinal + amount).coerceIn(0, Policy.values().size - 1)]
fun below(amount: Int): Policy = above(-amount)
override fun toString(): String =
when (this) {
STRONGLY_APPROVE -> "Strongly Approves"
APPROVE -> "Approves"
INDIFFERENT -> "Indifferent"
DISAPPROVE -> "Disapproves"
STRONGLY_DISAPPROVE -> "Strongly Disapproves"
}
}
// given a map of stances on issues, calculate what the category policy values are and find the closest ideology
fun Map<Issue, Policy>.ideology(): Ideology {
val issueCount = this.keys.size
val min = Policy.STRONGLY_DISAPPROVE.value * issueCount / Category.values().size
val max = Policy.STRONGLY_APPROVE.value * issueCount / Category.values().size
val categoryValues = mutableMapOf<Category, Double>()
this.forEach { (issue, policy) ->
categoryValues.compute(issue.category) { _, old -> (old ?: 0.0) + policy.value }
}
val scaledCategoryValues = categoryValues.map { (category, value) ->
category to floor((((value - min ) / (max - min)).coerceIn(0.0, 1.0) * 100))
}.toMap()
var currentIdeology: Ideology? = null
var currentDistance = Double.POSITIVE_INFINITY
for (ideology in Ideology.values()) {
val distance = scaledCategoryValues.map { (category, value) ->
abs(ideology.values.getOrDefault(category, 50.0) - value).pow(2.0)
}.sum()
if (distance < currentDistance) {
currentDistance = distance
currentIdeology = ideology
}
}
return currentIdeology!!
}
/**
* Represents a Political Party that can takes stances on issues
*/
data class Party(
val id: Int,
val name: String,
val issueStances: MutableMap<Issue, Policy> = mutableMapOf()
) {
fun getStance(issue: Issue): Policy =
this.issueStances.getOrDefault(issue, Policy.INDIFFERENT)
override fun hashCode(): Int = id
override fun equals(other: Any?): Boolean {
if (other !is Party) return false;
return other.id == this.id
}
override fun toString(): String = "$name Party (${this.issueStances.ideology()})"
fun report(): String =
"${toString()}\n" + issueStances.toList()
.joinToString("\n") { " " + it.second.toString() + " of " + it.first.name }
}
/**
* Represents a human voter that can take stances on issues
*/
data class Voter(
val id: Int,
val name: String?,
val issueStances: MutableMap<Issue, Policy>,
val memory: Queue<ElectionResults> = LinkedList()
) {
companion object {
const val RESULT_MEMORY = 5
}
fun getStance(issue: Issue): Policy =
this.issueStances.getOrDefault(issue, Policy.INDIFFERENT)
/**
* Gets the party that most closely aligns with this voter's stances on issues
*/
fun findClosestParty(parties: List<Party>): Party =
findClosestParties(parties).first()
fun findClosestParties(parties: List<Party>): List<Party> {
val partyDistance = mutableMapOf<Party, Double>()
for (issueStance in issueStances) {
val (issue, personalPolicy) = issueStance
for (party in parties) {
val policyDifference = abs(personalPolicy.value - party.getStance(issue).value)
partyDistance.compute(party) { _, old -> (old ?: 0.0) + policyDifference }
}
}
val partiesSortedByDistance = partyDistance.toList().sortedBy { it.second }
// filter out parties that disagree on 75% of the voter's stances
val preferableParties = partiesSortedByDistance.filter { it.second < (issueStances.size * 1.25) }
// if the above filter results in the voter not aligning with any parties, use the first 3 closest parties
// (this should rarely happen)
val closestParties = if (preferableParties.isNotEmpty() && preferableParties.size <= 3) {
preferableParties
} else {
partiesSortedByDistance.take(3)
}
return closestParties.map { it.first }
}
fun vote(parties: List<Party>): Vote {
val closestParties = findClosestParties(parties)
if (memory.isEmpty()) {
return Vote(this, closestParties.toMutableList())
}
val vote = Chance.chance(listOf(
// 25% chance they'll change their vote based on past results
25.0 to {
// past support of a party will influence a voter's current vote
// if the party a voter most aligns with isn't that popular, they will want to change their vote to a party
// they think has a better chance at winning
var pastSupport = mutableMapOf<Party, Double>()
memory.forEach {
it.supportPercentage.forEach { (party, support) ->
// add up all the support
pastSupport.compute(party) { _, old ->
(old ?: 0.0) + support
}
}
}
pastSupport = pastSupport.normalize().toMutableMap()
val newSupport = closestParties.map { it to pastSupport[it] }
.filter { it.second != null }
.sortedBy { it.second }
.reversed()
.map { it.first }
/* debug stats for voter vote change
val pastWinners = memory.map { it.winner }.joinToString(", ") { it.toString() }
if (!toString().contains("Voter")) {
println(toString() + " memory: " + pastWinners + " \n past support: " + pastSupport + " \n party alignment: " + closestParties)
println(" new vote: $newSupport")
} */
newSupport
}
), closestParties)
return Vote(this, vote.toMutableList())
}
fun remember(results: ElectionResults) {
if (memory.size >= RESULT_MEMORY) {
// remove the oldest election from memory
memory.poll()
}
// 80% chance they remember this election
Chance.chance(listOf(
80.0 to { memory.offer(results) }
))
}
override fun toString(): String = name ?: "Voter #$id"
fun report(): String =
"${toString()} \n" + issueStances.toList()
.joinToString("\n") { " " + it.second.toString() + " of " + it.first.name }
}
data class ElectionModel(val issues: List<Issue>, val parties: List<Party>, val voters: List<Voter>)
| 0 | Kotlin | 0 | 7 | 3002e4a2082a35fb9735f4bd5574ca51b9dff1a5 | 7,548 | electoral-systems | The Unlicense |
src/main/kotlin/day02/RockPaperScissors.kt | iamwent | 572,947,468 | false | {"Kotlin": 18217} | package day02
import readInput
class RockPaperScissors(
private val name: String
) {
private fun readRockPaperScissors(): List<Pair<Char, Char>> {
return readInput(name).map { line ->
return@map (line.first()) to (line.last())
}
}
fun part1(): Int {
return readRockPaperScissors()
.map { round ->
(round.first - 'A' + 1) to (round.second - 'X' + 1)
}
.fold(0) { score, round ->
val outcome = when (round.second - round.first) {
0 -> 3
1 -> 6
-2 -> 6
else -> 0
}
val shape = round.second
return@fold score + shape + outcome
}
}
fun part2(): Int {
val strategy = listOf(3, 1, 2, 3, 1)
return readRockPaperScissors()
.map { round ->
val shape = round.first - 'A' + 1
return@map when (round.second) {
'X' -> 0 + strategy[shape - 1]
'Y' -> 3 + shape
else -> 6 + strategy[shape + 1]
}
}
.sum()
}
}
| 0 | Kotlin | 0 | 0 | 77ce9ea5b227b29bc6424d9a3bc486d7e08f7f58 | 1,228 | advent-of-code-kotlin | Apache License 2.0 |
src/main/kotlin/days/Day5.kt | andilau | 433,504,283 | false | {"Kotlin": 137815} | package days
import kotlin.math.absoluteValue
@AdventOfCodePuzzle(
name = "Hydrothermal Venture",
url = "https://adventofcode.com/2021/day/5",
date = Date(day = 5, year = 2021)
)
class Day5(input: List<String>) : Puzzle {
private val lines = input.map { Line.from(it) }.toSet()
override fun partOne() =
lines.commonPoints { vertical() || horizontal() }
override fun partTwo() =
lines.commonPoints { vertical() || horizontal() || diagonal() }
private fun Set<Line>.commonPoints(filter: Line.() -> Boolean) =
this.filter { it.filter() }
.flatMap { it.points() }
.groupBy { it }
.filterValues { it.size >= 2 }
.count()
data class Line(val from: Point, val to: Point) {
fun vertical() = from.x == to.x
fun horizontal() = from.y == to.y
fun diagonal() = (from.x - to.x).absoluteValue == (from.y - to.y).absoluteValue
fun points(): Set<Point> =
when {
vertical() -> rangeVertical().map { Point(from.x, it) }.toSet()
horizontal() -> rangeHorizontal().map { Point(it, from.y) }.toSet()
diagonal() -> rangeHorizontal().toList()
.zip(rangeVertical().toList())
.map { (x, y) -> Point(x, y) }
.toSet()
else -> error("Line is not vertical, horizontal or diagonal: $this")
}
private fun rangeHorizontal() = if (from.x < to.x) from.x..to.x else from.x downTo to.x
private fun rangeVertical() = if (from.y < to.y) from.y..to.y else from.y downTo to.y
companion object {
private val linePattern = Regex("""(\d+),(\d+)\s+->\s+(\d+),(\d+)""")
fun from(line: String): Line {
val find = linePattern.find(line) ?: throw IllegalArgumentException("")
val (x1, y1, x2, y2) = find.groupValues.drop(1).map(String::toInt)
return Line(Point(x1, y1), Point(x2, y2))
}
}
}
} | 0 | Kotlin | 0 | 0 | b3f06a73e7d9d207ee3051879b83e92b049a0304 | 2,057 | advent-of-code-2021 | Creative Commons Zero v1.0 Universal |
src/main/kotlin/algorithm/core.kt | Tiofx | 175,697,373 | false | null | package algorithm
open class Program(operators: List<IOperator>) : List<IOperator> by operators, Relations {
inline fun S(i: Int) = get(i)
override val operators: List<IOperator> get() = this
fun I(operator: Int) = this[operator].R.filter { it !in this.take(operator).flatMap(IOperator::C) }.toSet()
fun O(operator: Int) = this[operator].C.filter { it !in this.drop(operator + 1).flatMap(IOperator::C) }.toSet()
val I get() = (0..lastIndex).flatMap { I(it) }.toCollection(LinkedHashSet(size))
val O get() = (0..lastIndex).flatMap { O(it) }.toCollection(LinkedHashSet(size))
}
class GroupOperator(
val from: Program,
val range: IntRange,
val type: Type
) : Relations {
override val operators: List<IOperator> = from.subList(range.first, range.endInclusive + 1)
enum class Type {
PARALLEL,
SEQUENTIAL
}
override fun toString() = "G\ncore.C = {$C}\ncore.R = {$R}"
}
class Operator(val expression: String) : IOperator {
companion object {
private val separators = listOf("+", "*", "-", "/", "(", ")", ",", ";", "[", "]").toTypedArray()
}
override val C = expression
.split("=")
.first()
.trim()
.let { linkedSetOf(it) }
override val R = expression
.split("=")[1]
.split(*separators)
.map(String::trim)
.filter(String::isNotBlank)
.filter { it.toFloatOrNull() == null }
.toCollection(LinkedHashSet())
inline operator fun component1() = C
inline operator fun component2() = R
override fun toString() = "C = {$C}\nR = {$R}"
}
typealias Matrix = List<List<Boolean>>
| 0 | Kotlin | 0 | 0 | 32c1cc3e95940e377ed9a99293eccc871ce13864 | 1,709 | CPF | The Unlicense |
year2017/src/main/kotlin/net/olegg/aoc/year2017/day16/Day16.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2017.day16
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.year2017.DayOf2017
/**
* See [Year 2017, Day 16](https://adventofcode.com/2017/day/16)
*/
object Day16 : DayOf2017(16) {
override fun first(): Any? {
return data
.split(",")
.fold(StringBuilder("abcdefghijklmnop")) { acc, op ->
when (op[0]) {
's' -> {
val shift = op.substring(1).toInt()
val toEnd = acc.substring(0, acc.length - shift)
acc.delete(0, acc.length - shift)
acc.append(toEnd)
}
'x' -> {
val replace = op.substring(1).split("/").map { it.toInt() }
val a = acc[replace[0]]
val b = acc[replace[1]]
acc[replace[0]] = b
acc[replace[1]] = a
}
'p' -> {
val replace = op.substring(1).split("/").map { it[0] }
val a = acc.indexOf(replace[0])
val b = acc.indexOf(replace[1])
acc[a] = replace[1]
acc[b] = replace[0]
}
}
acc
}
.toString()
}
override fun second(): Any? {
val dance = data.split(",")
var curr = "abcdefghijklmnop" to 0
val seen = mutableMapOf(curr)
repeat(1000000000) { _ ->
val next = dance.fold(StringBuilder(curr.first)) { acc, op ->
when (op[0]) {
's' -> {
val shift = op.substring(1).toInt()
val toEnd = acc.substring(0, acc.length - shift)
acc.delete(0, acc.length - shift)
acc.append(toEnd)
}
'x' -> {
val replace = op.substring(1).split("/").map { it.toInt() }
val a = acc[replace[0]]
val b = acc[replace[1]]
acc[replace[0]] = b
acc[replace[1]] = a
}
'p' -> {
val replace = op.substring(1).split("/").map { it[0] }
val a = acc.indexOf(replace[0])
val b = acc.indexOf(replace[1])
acc[a] = replace[1]
acc[b] = replace[0]
}
}
acc
}.toString() to curr.second + 1
if (next.first in seen.keys) {
val prev = seen[next.first] ?: 0
val period = next.second - prev
return seen.entries
.first { it.value >= prev && it.value % period == 1_000_000_000 % period }
.key
} else {
seen += next
curr = next
}
}
return curr.first
}
}
fun main() = SomeDay.mainify(Day16)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 2,534 | adventofcode | MIT License |
src/main/java/com/barneyb/aoc/aoc2022/day10/CathodeRayTube.kt | barneyb | 553,291,150 | false | {"Kotlin": 184395, "Java": 104225, "HTML": 6307, "JavaScript": 5601, "Shell": 3219, "CSS": 1020} | package com.barneyb.aoc.aoc2022.day10
import com.barneyb.aoc.util.Solver
import com.barneyb.aoc.util.toInt
import com.barneyb.aoc.util.toSlice
fun main() {
Solver.execute(
::parse,
::signalStrengths,
::render, // RBPARAGF
)
}
internal data class State(
val cycle: Int = 0,
val x: Int = 1
) {
fun tick() =
copy(cycle = cycle + 1)
fun add(n: Int) =
copy(x = x + n)
val strength
get() = cycle * x
}
internal fun parse(input: String) =
input.toSlice()
.trim()
.lines()
.map { it ->
if (it[0] == 'a') { // addx <N>
it.drop(5).toInt()
} else { // noop
null
}
}
internal fun states(lines: List<Int?>) =
sequence {
var s = State()
lines.forEach {
s = s.tick()
yield(s)
if (it != null) { // addx <N>
s = s.tick()
yield(s)
s = s.add(it)
} // noop
}
}
internal fun signalStrengths(lines: List<Int?>) =
states(lines).fold(0) { sig, s ->
if (s.cycle % 40 == 20) sig + s.strength else sig
}
internal fun render(lines: List<Int?>) =
buildString {
states(lines).forEach {
val pixel = (it.cycle - 1) % 40
if (pixel == 0) {
append('\n')
}
val sprite = it.x - 1..it.x + 1
val on = pixel in sprite
append(if (on) '#' else '.')
}
}
| 0 | Kotlin | 0 | 0 | 8b5956164ff0be79a27f68ef09a9e7171cc91995 | 1,557 | aoc-2022 | MIT License |
src/main/kotlin/algorithms/ManhattanTouristProblem.kt | jimandreas | 377,843,697 | false | null | @file:Suppress("SameParameterValue", "UnnecessaryVariable", "UNUSED_VARIABLE", "ControlFlowWithEmptyBody", "unused")
package algorithms
import kotlin.math.max
/**
* Code Challenge: Find the length of a longest path in the Manhattan Tourist Problem.
*
* See also:
* stepik: @link: https://stepik.org/lesson/240301/step/10?unit=212647
* rosalind: @link: http://rosalind.info/problems/ba5b/
* book (5.6): https://www.bioinformaticsalgorithms.org/bioinformatics-chapter-5
*/
class ManhattanTouristProblem {
data class Manhattan(val row: Int, val col: Int, val downList: List<Int>, val rightList: List<Int>)
/**
* iterate to find the longest (weighted) path in the Manhattan matrix of down and right
* edges.
* @return weight of longest path
*/
fun findLongestPathInManhatten(m: Manhattan): Int {
val nRows: Int = m.row
val mCols: Int = m.col
val d = m.downList
val r = m.rightList
val s : MutableList<Int> = arrayListOf()
for (i in 0 until (nRows+1) * (mCols+1)) {
s.add(0)
}
// fill out first column of weights from down list
for (i in 1..nRows) {
s[i*(mCols+1)] = s[(i-1)*(mCols+1)] + d[(i-1)*(mCols+1)]
}
// fill out first row of weights from right list
for (j in 1..mCols) {
s[j] = s[j-1] + r[j-1]
}
/*
* now walk the interior matrix and fill out the
* summ of the path winners (maximizing the weights)
*/
for (i in 1..nRows) {
for (j in 1..mCols) {
val down = s[(i-1)*(mCols+1) + j] + d[(i-1)*(mCols+1) + j]
val right = s[i*(mCols+1) + j-1] + r[i*(mCols+0) + j-1]
s[i*(mCols+1) + j] = max(down, right)
}
}
val bottomRightCell = s[(nRows+1)*(mCols+1)-1]
return bottomRightCell
}
/**
* scan a well formed string of
* row col
* col cols of depth row-1
* "hyphen"
* col-1 cols of depth row
* @link: http://rosalind.info/problems/ba5b/
*
* No error checking performed.
*/
fun readManhattanMatrices(connList: String): Manhattan? {
val ep = EulerianPathArrayBased()
val list: MutableList<EulerConnectionData> = mutableListOf()
val reader = connList.reader()
val lines = reader.readLines()
val rowcol = lines[0].split(" ")
val row = rowcol[0].toInt()
val col = rowcol[1].toInt()
val downMatrix : MutableList<Int> = mutableListOf()
var offset = 1
for (i in 0 until row) {
val rowLine = lines[i+offset].split(" ")
for (j in 0..col) {
downMatrix.add(rowLine[j].toInt())
}
}
// error check. Should be a hyphen here.
offset += row
if (lines[offset] != "-") {
return null
}
// read down matrix. row rows and col-1 cols
offset++
val rightMatrix : MutableList<Int> = mutableListOf()
for (i in 0..row) {
val downLine = lines[i+offset].split(" ")
for (j in 0 until col) {
rightMatrix.add(downLine[j].toInt())
}
}
val theMatrix = Manhattan(row, col, downMatrix, rightMatrix)
return theMatrix
}
} | 0 | Kotlin | 0 | 0 | fa92b10ceca125dbe47e8961fa50242d33b2bb34 | 3,369 | stepikBioinformaticsCourse | Apache License 2.0 |
src/main/kotlin/com/github/davio/aoc/y2021/Day3.kt | Davio | 317,510,947 | false | {"Kotlin": 405939} | package com.github.davio.aoc.y2021
import com.github.davio.aoc.general.Day
import com.github.davio.aoc.general.getInputAsList
import java.util.function.BiPredicate
import kotlin.math.pow
fun main() {
Day3.getResultPart1()
Day3.getResultPart2()
}
object Day3 : Day() {
/*
--- Day 3: Binary Diagnostic ---
The submarine has been making some odd creaking noises, so you ask it to produce a diagnostic report just in case.
The diagnostic report (your puzzle input) consists of a list of binary numbers which, when decoded properly, can tell you many useful things about the conditions of the submarine. The first parameter to check is the power consumption.
You need to use the binary numbers in the diagnostic report to generate two new binary numbers (called the gamma rate and the epsilon rate). The power consumption can then be found by multiplying the gamma rate by the epsilon rate.
Each bit in the gamma rate can be determined by finding the most common bit in the corresponding position of all numbers in the diagnostic report. For example, given the following diagnostic report:
00100
11110
10110
10111
10101
01111
00111
11100
10000
11001
00010
01010
Considering only the first bit of each number, there are five 0 bits and seven 1 bits. Since the most common bit is 1, the first bit of the gamma rate is 1.
The most common second bit of the numbers in the diagnostic report is 0, so the second bit of the gamma rate is 0.
The most common value of the third, fourth, and fifth bits are 1, 1, and 0, respectively, and so the final three bits of the gamma rate are 110.
So, the gamma rate is the binary number 10110, or 22 in decimal.
The epsilon rate is calculated in a similar way; rather than use the most common bit, the least common bit from each position is used. So, the epsilon rate is 01001, or 9 in decimal. Multiplying the gamma rate (22) by the epsilon rate (9) produces the power consumption, 198.
Use the binary numbers in your diagnostic report to calculate the gamma rate and epsilon rate, then multiply them together. What is the power consumption of the submarine? (Be sure to represent your answer in decimal, not binary.)
*/
fun getResultPart1() {
val input = getInputAsList()
val lineLength = input[0].length
val numberOfOnes = IntArray(lineLength)
input.forEach {
it.forEachIndexed { index, c ->
if (c == '1') {
numberOfOnes[index]++
}
}
}
val halfSize = input.size / 2
val gamma = numberOfOnes.map {
if (it >= halfSize) '1' else '0'
}.toCharArray().concatToString().toInt(2)
val epsilon = gamma.inv() and 2.0.pow(lineLength).toInt() - 1
println("Gamma $gamma Epsilon $epsilon")
println("${gamma * epsilon}")
}
/*
--- Part Two ---
Next, you should verify the life support rating, which can be determined by multiplying the oxygen generator rating by the CO2 scrubber rating.
Both the oxygen generator rating and the CO2 scrubber rating are values that can be found in your diagnostic report - finding them is the tricky part. Both values are located using a similar process that involves filtering out values until only one remains. Before searching for either rating value, start with the full list of binary numbers from your diagnostic report and consider just the first bit of those numbers. Then:
Keep only numbers selected by the bit criteria for the type of rating value for which you are searching. Discard numbers which do not match the bit criteria.
If you only have one number left, stop; this is the rating value for which you are searching.
Otherwise, repeat the process, considering the next bit to the right.
The bit criteria depends on which type of rating value you want to find:
To find oxygen generator rating, determine the most common value (0 or 1) in the current bit position, and keep only numbers with that bit in that position. If 0 and 1 are equally common, keep values with a 1 in the position being considered.
To find CO2 scrubber rating, determine the least common value (0 or 1) in the current bit position, and keep only numbers with that bit in that position. If 0 and 1 are equally common, keep values with a 0 in the position being considered.
For example, to determine the oxygen generator rating value using the same example diagnostic report from above:
Start with all 12 numbers and consider only the first bit of each number. There are more 1 bits (7) than 0 bits (5), so keep only the 7 numbers with a 1 in the first position: 11110, 10110, 10111, 10101, 11100, 10000, and 11001.
Then, consider the second bit of the 7 remaining numbers: there are more 0 bits (4) than 1 bits (3), so keep only the 4 numbers with a 0 in the second position: 10110, 10111, 10101, and 10000.
In the third position, three of the four numbers have a 1, so keep those three: 10110, 10111, and 10101.
In the fourth position, two of the three numbers have a 1, so keep those two: 10110 and 10111.
In the fifth position, there are an equal number of 0 bits and 1 bits (one each). So, to find the oxygen generator rating, keep the number with a 1 in that position: 10111.
As there is only one number left, stop; the oxygen generator rating is 10111, or 23 in decimal.
Then, to determine the CO2 scrubber rating value from the same example above:
Start again with all 12 numbers and consider only the first bit of each number. There are fewer 0 bits (5) than 1 bits (7), so keep only the 5 numbers with a 0 in the first position: 00100, 01111, 00111, 00010, and 01010.
Then, consider the second bit of the 5 remaining numbers: there are fewer 1 bits (2) than 0 bits (3), so keep only the 2 numbers with a 1 in the second position: 01111 and 01010.
In the third position, there are an equal number of 0 bits and 1 bits (one each). So, to find the CO2 scrubber rating, keep the number with a 0 in that position: 01010.
As there is only one number left, stop; the CO2 scrubber rating is 01010, or 10 in decimal.
Finally, to find the life support rating, multiply the oxygen generator rating (23) by the CO2 scrubber rating (10) to get 230.
Use the binary numbers in your diagnostic report to calculate the oxygen generator rating and CO2 scrubber rating, then multiply them together. What is the life support rating of the submarine? (Be sure to represent your answer in decimal, not binary.)
*/
fun getResultPart2() {
val input = getInputAsList()
var bitIndex = 0
var oxygenCandidates = input
var co2Candidates = input
val getNextCandidates = { candidates: List<String>, comparison: BiPredicate<Int, Int> ->
val partitions = candidates.partition { line -> line[bitIndex] == '0' }
val zerosPartition = partitions.first
val onesPartition = partitions.second
if (comparison.test(zerosPartition.size, onesPartition.size)) zerosPartition else onesPartition
}
while (oxygenCandidates.size > 1 || co2Candidates.size > 1) {
if (oxygenCandidates.size > 1) {
oxygenCandidates = getNextCandidates(oxygenCandidates) { left, right -> left > right }
}
if (co2Candidates.size > 1) {
co2Candidates = getNextCandidates(co2Candidates) { left, right -> left <= right }
}
bitIndex++
}
val oxygenRating = oxygenCandidates[0].toInt(2)
val co2Rating = co2Candidates[0].toInt(2)
println("Oxygen rating $oxygenRating, CO2 rating $co2Rating")
println("${oxygenRating * co2Rating}")
}
}
| 1 | Kotlin | 0 | 0 | 4fafd2b0a88f2f54aa478570301ed55f9649d8f3 | 7,751 | advent-of-code | MIT License |
src/questions/RomanToInteger.kt | realpacific | 234,499,820 | false | null | package questions
import _utils.UseCommentAsDocumentation
import java.util.*
import kotlin.collections.LinkedHashMap
import kotlin.test.assertEquals
/**
* Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
* I = 1, V=5, X = 10, L = 50, C = 100, D = 500, M = 1000
*
* For example, 2 is written as II in Roman numeral, just two one's added together.
* 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.
*
* Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII.
* Instead, the number four is written as IV.
* Because the one is before the five we subtract it making four.
* The same principle applies to the number nine, which is written as IX.
* There are six instances where subtraction is used:
*
* * I can be placed before V (5) and X (10) to make 4 and 9.
* * X can be placed before L (50) and C (100) to make 40 and 90.
* * C can be placed before D (500) and M (1000) to make 400 and 900.
*
* Given a roman numeral, convert it to an integer.
*/
@UseCommentAsDocumentation
private fun romanToInt(s: String): Int {
val charMap = mapOf('I' to 1, 'V' to 5, 'X' to 10, 'L' to 50, 'C' to 100, 'D' to 500, 'M' to 1000)
return parse(s, 0, charMap, 0)
}
fun parse(s: String, index: Int, map: Map<Char, Int>, total: Int): Int {
val first = s.getOrNull(index) ?: return total
val second = s.getOrNull(index + 1) ?: return total + map[first]!!
var newTotal = total
// Subtraction case
return if (
(first == 'I' && (second == 'V' || second == 'X')) ||
(first == 'X' && (second == 'L' || second == 'C')) ||
(first == 'C' && (second == 'D' || second == 'M'))
) {
newTotal += (map[second]!! - map[first]!!)
// +2 as we tried to pair two roman char together so skip the pairs
parse(s, index + 2, map, newTotal)
} else {
// Didn't get paired so use this character individually
parse(s, index + 1, map, total + map[first]!!)
}
}
fun main() {
assertEquals(1994, romanToInt("MCMXCIV"))
assertEquals(3, romanToInt("III"))
assertEquals(4, romanToInt("IV"))
assertEquals(9, romanToInt("IX"))
} | 4 | Kotlin | 5 | 93 | 22eef528ef1bea9b9831178b64ff2f5b1f61a51f | 2,263 | algorithms | MIT License |
year2021/day02/part1/src/main/kotlin/com/curtislb/adventofcode/year2021/day02/part1/Year2021Day02Part1.kt | curtislb | 226,797,689 | false | {"Kotlin": 2146738} | /*
--- Day 2: Dive! ---
Now, you need to figure out how to pilot this thing.
It seems like the submarine can take a series of commands like `forward 1`, `down 2`, or `up 3`:
- `forward X` increases the horizontal position by X units.
- `down X` increases the depth by X units.
- `up X` decreases the depth by X units.
Note that since you're on a submarine, `down` and `up` affect your depth, and so they have the
opposite result of what you might expect.
The submarine seems to already have a planned course (your puzzle input). You should probably figure
out where it's going. For example:
```
forward 5
down 5
forward 8
up 3
down 8
forward 2
```
Your horizontal position and depth both start at 0. The steps above would then modify them as
follows:
- `forward 5` adds 5 to your horizontal position, a total of 5.
- `down 5` adds 5 to your depth, resulting in a value of 5.
- `forward 8` adds 8 to your horizontal position, a total of 13.
- `up 3` decreases your depth by 3, resulting in a value of 2.
- `down 8` adds 8 to your depth, resulting in a value of 10.
- `forward 2` adds 2 to your horizontal position, a total of 15.
After following these instructions, you would have a horizontal position of 15 and a depth of 10.
(Multiplying these together produces 150.)
Calculate the horizontal position and depth you would have after following the planned course. What
do you get if you multiply your final horizontal position by your final depth?
*/
package com.curtislb.adventofcode.year2021.day02.part1
import com.curtislb.adventofcode.year2021.day02.submarine.SimpleSubmarine
import java.nio.file.Path
import java.nio.file.Paths
/**
* Returns the solution to the puzzle for 2021, day 2, part 1.
*
* @param inputPath The path to the input file for this puzzle.
* @param initialPosition The horizontal position of the submarine before running any commands.
* @param initialDepth The depth of the submarine before running any commands.
*/
fun solve(
inputPath: Path = Paths.get("..", "input", "input.txt"),
initialPosition: Int = 0,
initialDepth: Int = 0
): Int {
val submarine = SimpleSubmarine(initialPosition, initialDepth)
inputPath.toFile().forEachLine { submarine.runCommand(it) }
return submarine.horizontalPosition * submarine.depth
}
fun main() {
println(solve())
}
| 0 | Kotlin | 1 | 1 | 6b64c9eb181fab97bc518ac78e14cd586d64499e | 2,394 | AdventOfCode | MIT License |
src/Day04.kt | AleksanderBrzozowski | 574,061,559 | false | null | fun main() {
fun IntRange.fullyOverlaps(other: IntRange) = this.first >= other.first && this.last <= other.last
fun IntRange.partiallyOverlaps(other: IntRange) = this.any { other.contains(it) }
fun String.toRange(): Pair<IntRange, IntRange> {
val (firstRange, secondRange) = split(",")
.map {
val (start, end) = it.split("-")
IntRange(start = start.toInt(), endInclusive = end.toInt())
}
return firstRange to secondRange
}
val testResult = readInput("Day04")
.count {
val (first, second) = it.toRange()
first.fullyOverlaps(second) || second.fullyOverlaps(first)
}
println(testResult)
val result = readInput("Day04")
.count {
val (first, second) = it.toRange()
first.partiallyOverlaps(second) || second.partiallyOverlaps(first)
}
println(result)
}
| 0 | Kotlin | 0 | 0 | 161c36e3bccdcbee6291c8d8bacf860cd9a96bee | 935 | kotlin-advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/g0901_1000/s0990_satisfiability_of_equality_equations/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g0901_1000.s0990_satisfiability_of_equality_equations
// #Medium #Array #String #Graph #Union_Find
// #2023_05_11_Time_163_ms_(100.00%)_Space_37.6_MB_(100.00%)
class Solution {
private lateinit var par: IntArray
fun equationsPossible(equations: Array<String>): Boolean {
var counter = 0
val map: HashMap<Char, Int> = HashMap()
for (str in equations) {
var ch = str[0]
if (!map.containsKey(ch)) {
map[ch] = counter
counter++
}
ch = str[3]
if (!map.containsKey(ch)) {
map[ch] = counter
counter++
}
}
par = IntArray(counter)
for (i in par.indices) {
par[i] = i
}
for (str in equations) {
val oper = str.substring(1, 3)
if (oper == "==") {
val px = find(map[str[0]])
val py = find(map[str[3]])
if (px != py) {
par[px] = py
}
}
}
for (str in equations) {
val oper = str.substring(1, 3)
if (oper == "!=") {
val px = find(map[str[0]])
val py = find(map[str[3]])
if (px == py) {
return false
}
}
}
return true
}
private fun find(x: Int?): Int {
if (par[x!!] == x) {
return x
}
par[x] = find(par[x])
return par[x]
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,568 | LeetCode-in-Kotlin | MIT License |
2022/src/main/kotlin/Day09.kt | dlew | 498,498,097 | false | {"Kotlin": 331659, "TypeScript": 60083, "JavaScript": 262} | import kotlin.math.abs
import kotlin.math.sign
object Day09 {
fun part1(input: String) = simulateRope(input, 2)
fun part2(input: String) = simulateRope(input, 10)
private fun simulateRope(input: String, size: Int): Int {
val rope = MutableList(size) { Point(0, 0) }
val tailsVisited = mutableSetOf(rope.last())
input.splitNewlines()
.forEach { line ->
val (direction, number) = line.splitWhitespace()
repeat(number.toInt()) {
rope[0] = rope[0].move(direction)
rope.indices.drop(1).forEach { rope[it] = rope[it].follow(rope[it - 1]) }
tailsVisited.add(rope.last())
}
}
return tailsVisited.size
}
private fun Point.move(direction: String): Point {
return when (direction) {
"L" -> Point(x - 1, y)
"R" -> Point(x + 1, y)
"U" -> Point(x, y - 1)
"D" -> Point(x, y + 1)
else -> throw IllegalArgumentException("Unknown direction: $direction")
}
}
private fun Point.follow(heads: Point): Point {
if (abs(this.x - heads.x) < 2 && abs(this.y - heads.y) < 2) {
return this
}
return Point(
this.x + (heads.x - this.x).sign,
this.y + (heads.y - this.y).sign
)
}
private data class Point(val x: Int, val y: Int)
} | 0 | Kotlin | 0 | 0 | 6972f6e3addae03ec1090b64fa1dcecac3bc275c | 1,282 | advent-of-code | MIT License |
app/src/main/java/com/lukaslechner/coroutineusecasesonandroid/playground/challenges/MathChallenge.kt | ahuamana | 627,986,788 | false | null | package com.lukaslechner.coroutineusecasesonandroid.playground.challenges
// Challenge
// Have the function MathChallenge(str) take the str parameter, which will be a simple mathematical formula with three numbers, a single operator (+, -, *, or /) and an equal sign (=) and return the digit that completes the equation. In one of the numbers in the equation, there will be an x character, and your program should determine what digit is missing. For example, if str is "3x + 12 = 46" then your program should output 4. The x character can appear in any of the three numbers and all three numbers will be greater than or equal to 0 and less than or equal to 1000000.
// Examples
// Input: "4 - 2 = x"
// Output: 2
// Input: "1x0 * 12 = 1200"
// Output: 0
// Input: "3x + 12 = 46"
// Output: 4
//Constrainst
//1. The x character can appear in any of the three numbers -> has x in it
//2. all three numbers will be greater than or equal to 0 and less than or equal to 1000000.
//Identify the missing number
private fun MathChallenge(str: String): String {
//validate constraints 1 -> has x in it
if (!str.contains("x")) return "not possible"
//validate constraints 2 -> all three numbers will be greater than or equal to 0 and less than or equal to 1000000.
val numbersSplit = str.split(" ")
//remove operators and equal sign
val numbersOnlyValid = numbersSplit.filter { it != "+" && it != "-" && it != "*" && it != "/" && it != "=" }
//convert to int
val numbersOnlyIntegers = numbersOnlyValid.map {
//if it contains x, replace it with 1
if (it.contains("x")) 1 else it.toInt()
}
//check if all numbers are between 0 and 1000000
numbersOnlyIntegers.forEach {
if (it < 0 || it > 1000000) return "not possible"
}
for(digit in 0..9){
val newStr = str.replace("x", digit.toString())
val numbers = newStr.split(" ")
val numbersOnly = numbers.filter { it != "+" && it != "-" && it != "*" && it != "/" && it != "=" }
val numbersOnlyInt = numbersOnly.map {
//if it contains x, replace it with 1
if (it.contains("x")) 1 else it.toInt()
}
val firstNumber = numbersOnlyInt[0]
val secondNumber = numbersOnlyInt[1]
val thirdNumber = numbersOnlyInt[2]
val operator = numbers[1]
//check if the equation is correct
if (operator == "+") {
if (firstNumber + secondNumber == thirdNumber) return digit.toString()
}
if (operator == "-") {
if (firstNumber - secondNumber == thirdNumber) return digit.toString()
}
if (operator == "*") {
if (firstNumber * secondNumber == thirdNumber) return digit.toString()
}
if (operator == "/") {
if (firstNumber / secondNumber == thirdNumber) return digit.toString()
}
}
//if no digit is found
return "not possible"
}
fun main () {
println(MathChallenge("4 - 2 = x"))
println(MathChallenge("1x0 * 12 = 1200"))
println(MathChallenge("3x + 12 = 46"))
} | 0 | Kotlin | 0 | 0 | 931ce884b8c70355e38e007141aab58687ed1909 | 3,086 | KotlinCorutinesExpert | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.