path stringlengths 5 169 | owner stringlengths 2 34 | repo_id int64 1.49M 755M | is_fork bool 2
classes | languages_distribution stringlengths 16 1.68k ⌀ | content stringlengths 446 72k | issues float64 0 1.84k | main_language stringclasses 37
values | forks int64 0 5.77k | stars int64 0 46.8k | commit_sha stringlengths 40 40 | size int64 446 72.6k | name stringlengths 2 64 | license stringclasses 15
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/main/kotlin/com/adventofcode/year2021/day9/part1/App.kt | demidko | 433,889,383 | false | {"Kotlin": 7692, "Dockerfile": 264} | package com.adventofcode.year2021.day9.part1
import com.adventofcode.year2021.day
class RiskMap(private val rows: List<String>) {
val horizontalLength = rows.first().length
val verticalLength = rows.size
/**
* @param x horizontal
* @param y vertical
*/
operator fun get(x: Int, y: Int): Point? {
if (x in 0 until horizontalLength && y in 0 until verticalLength) {
return Point(this, x, y, rows[y][x].toString().toShort());
}
return null
}
}
class Point(private val map: RiskMap, private val x: Int, private val y: Int, private val number: Short) {
fun isLow(): Boolean {
val neighbors = listOfNotNull(
map[x, y - 1],
map[x, y + 1],
map[x - 1, y],
map[x + 1, y]
)
return neighbors.all {
it.number > number
}
}
fun calculateRisk(): Int {
return number + 1
}
}
fun calculateRisk(map: RiskMap): Int {
var totalRisk = 0
for (x in 0 until map.horizontalLength) {
for (y in 0 until map.verticalLength) {
val p = map[x, y]
if (p != null && p.isLow()) {
totalRisk += p.calculateRisk()
}
}
}
return totalRisk
}
fun main() {
val map = RiskMap(day(9))
println(calculateRisk(map))
} | 0 | Kotlin | 0 | 0 | 2f42bede3ed0c4b17cb2575f6b61a1917a465bda | 1,220 | adventofcode | MIT License |
src/array/leetcode18.kt | Alex-Linrk | 180,918,573 | false | null | package leecode
/**
* 给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,
* 使得 a + b + c + d 的值与 target 相等?找出所有满足条件且不重复的四元组。
注意:
答案中不可以包含重复的四元组。
示例:
给定数组 nums = [1, 0, -1, 0, -2, 2],和 target = 0。
满足要求的四元组集合为:
[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]
*/
class leetcode18 {
fun fourSum(nums: IntArray, target: Int): List<List<Int>> {
val result = mutableListOf<List<Int>>()
if (nums.size < 4) return result
nums.sort()
for (i in 0..nums.size - 4) {
if (i > 0 && nums[i] == nums[i - 1]) continue
for (j in i + 1..nums.size - 3) {
if (j > i + 1 && nums[j] == nums[j - 1]) continue
var low = j + 1
var height = nums.size - 1
while (low < height) {
val sum = nums[i] + nums[j] + nums[low] + nums[height]
when {
sum == target -> {
val find = listOf(nums[i], nums[j], nums[low], nums[height])
result.add(find)
while (low < height && nums[low] == nums[low + 1]) low++
low++
while (height > low && nums[height - 1] == nums[height]) height--
height--
}
sum > target -> {
height--
}
sum < target -> {
low++
}
}
}
}
}
return result
}
}
/**
* [-1,0,-5,-2,-2,-4,0,1,-2]
-9
*/
fun main() {
val nums = intArrayOf(-1, 0, -5, -2, -2, -4, 0, 1, -2)
val target = -9
val result = leetcode18().fourSum(nums = nums, target = target)
println(result)
} | 0 | Kotlin | 0 | 0 | 59f4ab02819b7782a6af19bc73307b93fdc5bf37 | 2,074 | LeetCode | Apache License 2.0 |
src/Day14.kt | cagriyildirimR | 572,811,424 | false | {"Kotlin": 34697} | fun day14Part1() {
val input = readInput("Day14")
var ymin = 0
var ymax = 0
var xmin = 500
var xmax = 0
fun calculateMinMax() {
input.forEach { y ->
y.split("->").forEach { x ->
val p = x.split(",").map { it.trim().toInt() }
if (ymin > p.last()) ymin = p.last()
if (ymax < p.last()) ymax = p.last()
if (xmin > p.first()) xmin = p.first()
if (xmax < p.first()) xmax = p.first()
}
}
}
calculateMinMax()
val cave: MutableList<MutableList<Char>> = MutableList(ymax - ymin + 1) {
MutableList(xmax - xmin + 1) { '.' }
}
// render(cave)
fun caveSet(x: Int, y: Int, t: Char = '#') {
cave[y - ymin][x - xmin] = t
}
fun caveSetN(x: Int, y: Int, t: Char = '#') {
cave[y][x] = t
}
fun initialize() {
input.forEach { y ->
val list = y.split("->")
for (i in 0 until list.lastIndex) {
val A = list[i].split(",").map { it.trim().toInt() }
val B = list[i + 1].split(",").map { it.trim().toInt() }
val x1min = if (A.first() > B.first()) B.first() else A.first()
val x1max = if (A.first() > B.first()) A.first() else B.first()
val y1min = if (A.last() > B.last()) B.last() else A.last()
val y1max = if (A.last() > B.last()) A.last() else B.last()
if (x1min == x1max) {
for (v in y1min..y1max) {
caveSet(x1min, v)
}
} else {
for (v in x1min..x1max) {
caveSet(v, y1min)
}
}
}
}
}
initialize()
// render(cave)
val s = Pair(500 - xmin, ymin) // source
caveSet(500, 0, 'o')
var c = s
var sands = 0
fun createNewSand(){
caveSet(500, 0, 'o')
c = s
sands++
}
fun canFallDown(o: Pair<Int, Int>): Boolean {
return cave[c.second+1][c.first] == '.'
}
fun goDown(o: Pair<Int, Int>) {
caveSetN(o.first, o.second, '.')
c = Pair(o.first, o.second+1)
caveSetN(c.first, c.second, 'o')
}
fun canFallLeft(o: Pair<Int, Int>): Boolean {
return cave[c.second+1][c.first-1] == '.'
}
fun goLeft(o: Pair<Int, Int>) {
caveSetN(o.first, o.second, '.')
c = Pair(o.first-1, o.second+1)
caveSetN(c.first, c.second, 'o')
}
fun canFallRight(o: Pair<Int, Int>): Boolean {
return cave[c.second+1][c.first+1] == '.'
}
fun goRight(o: Pair<Int, Int>) {
caveSetN(o.first, o.second, '.')
c = Pair(o.first+1, o.second+1)
caveSetN(c.first, c.second, 'o')
}
createNewSand()
while (true) {
try {
when {
canFallDown(c) -> goDown(c)
canFallLeft(c) -> goLeft(c)
canFallRight(c) -> goRight(c)
else -> createNewSand()
}
} catch (e: IndexOutOfBoundsException){
sands--
break
}
}
// render(cave)
println(sands)
}
fun render(cave: MutableList<MutableList<Char>>) {
cave.forEach { it.joinToString(separator = "").print() }
}
fun day14Part2() {
val input = readInput("Day14")
var ymin = 0
var ymax = 0
var xmin = 500
var xmax = 0
fun calculateMinMax() {
input.forEach { y ->
y.split("->").forEach { x ->
val p = x.split(",").map { it.trim().toInt() }
if (ymin > p.last()) ymin = p.last()
if (ymax < p.last()) ymax = p.last()
if (xmin > p.first()) xmin = p.first()
if (xmax < p.first()) xmax = p.first()
}
}
}
calculateMinMax()
val cave: MutableList<MutableList<Char>> = MutableList(ymax - ymin + 3) {
MutableList(xmax * 2) { '.' }
}
cave[cave.lastIndex] = MutableList(xmax + xmax){ '#' }
// render(cave)
fun caveSetN(x: Int, y: Int, t: Char = '#') {
cave[y][x] = t
}
fun caveSet(x: Int, y: Int, t: Char = '#') {
// cave[y - ymin][x - xmin] = t
caveSetN(x, y ,t)
}
fun initialize() {
input.forEach { y ->
val list = y.split("->")
for (i in 0 until list.lastIndex) {
val A = list[i].split(",").map { it.trim().toInt() }
val B = list[i + 1].split(",").map { it.trim().toInt() }
val x1min = if (A.first() > B.first()) B.first() else A.first()
val x1max = if (A.first() > B.first()) A.first() else B.first()
val y1min = if (A.last() > B.last()) B.last() else A.last()
val y1max = if (A.last() > B.last()) A.last() else B.last()
if (x1min == x1max) {
for (v in y1min..y1max) {
caveSet(x1min, v)
}
} else {
for (v in x1min..x1max) {
caveSet(v, y1min)
}
}
}
}
}
initialize()
// render(cave)
val s = Pair(500, 0) // source
// caveSet(500, 0, 'o')
var c = s
var sands = 0
fun createNewSand(){
caveSet(s.first, s.second, 'o')
c = s
sands++
}
fun canFallDown(o: Pair<Int, Int>): Boolean {
return cave[c.second+1][c.first] == '.'
}
fun goDown(o: Pair<Int, Int>) {
caveSetN(o.first, o.second, '.')
c = Pair(o.first, o.second+1)
caveSetN(c.first, c.second, 'o')
}
fun canFallLeft(o: Pair<Int, Int>): Boolean {
return cave[c.second+1][c.first-1] == '.'
}
fun goLeft(o: Pair<Int, Int>) {
caveSetN(o.first, o.second, '.')
c = Pair(o.first-1, o.second+1)
caveSetN(c.first, c.second, 'o')
}
fun canFallRight(o: Pair<Int, Int>): Boolean {
return cave[c.second+1][c.first+1] == '.'
}
fun goRight(o: Pair<Int, Int>) {
caveSetN(o.first, o.second, '.')
c = Pair(o.first+1, o.second+1)
caveSetN(c.first, c.second, 'o')
}
createNewSand()
while (true) {
try {
when {
canFallDown(c) -> goDown(c)
canFallLeft(c) -> goLeft(c)
canFallRight(c) -> goRight(c)
else -> {
if (cave[s.second][s.first] == 'o') break else createNewSand()
}
}
} catch (e: IndexOutOfBoundsException){
sands--
break
}
}
// render(cave)
println(sands)
}
| 0 | Kotlin | 0 | 0 | 343efa0fb8ee76b7b2530269bd986e6171d8bb68 | 6,795 | AoC | Apache License 2.0 |
src/main/kotlin/year2021/day-16.kt | ppichler94 | 653,105,004 | false | {"Kotlin": 182859} | package year2021
import lib.aoc.Day
import lib.aoc.Part
import lib.aoc.TestCase
fun main() {
Day(16, 2021, PartA16(), PartB16()).run()
}
open class PartA16 : Part() {
sealed class Packet(val version: Int, val length: Int, val value: () -> Long)
sealed class OperatorPacket(version: Int, length: Int, val subPackets: List<Packet>, value: () -> Long) :
Packet(version, length, value)
class LiteralPacket(version: Int, length: Int, v: Long) : Packet(version, length, { v })
class SumPacket(version: Int, length: Int, subPackets: List<Packet>) :
OperatorPacket(version, length, subPackets, { subPackets.sumOf { it.value() } })
class ProductPacket(version: Int, length: Int, subPackets: List<Packet>) :
OperatorPacket(version, length, subPackets, { subPackets.fold(1) { acc, p -> acc * p.value() } })
class MinPacket(version: Int, length: Int, subPackets: List<Packet>) :
OperatorPacket(version, length, subPackets, { subPackets.minOf { it.value() } })
class MaxPacket(version: Int, length: Int, subPackets: List<Packet>) :
OperatorPacket(version, length, subPackets, { subPackets.maxOf { it.value() } })
class GreaterThanPacket(version: Int, length: Int, subPackets: List<Packet>) :
OperatorPacket(version, length, subPackets, { if (subPackets[0].value() > subPackets[1].value()) 1 else 0 })
class LessThanPacket(version: Int, length: Int, subPackets: List<Packet>) :
OperatorPacket(version, length, subPackets, { if (subPackets[0].value() < subPackets[1].value()) 1 else 0 })
class EqualToPacket(version: Int, length: Int, subPackets: List<Packet>) :
OperatorPacket(version, length, subPackets, { if (subPackets[0].value() == subPackets[1].value()) 1 else 0 })
private fun Packet(text: String): Packet {
val version = text.take(3).toInt(2)
val type = text.slice(3..<6).toInt(2)
val content = text.drop(6)
return if (type == 4) {
val (length, value) = parseLiteralPacket(content)
LiteralPacket(version, length + 6, value)
} else {
val (length, subpackets) = parseSubpackets(content)
Packet(version, length + 6, subpackets, type)
}
}
private fun Packet(version: Int, length: Int, subPackets: List<Packet>, type: Int): Packet = when (type) {
0 -> SumPacket(version, length, subPackets)
1 -> ProductPacket(version, length, subPackets)
2 -> MinPacket(version, length, subPackets)
3 -> MaxPacket(version, length, subPackets)
5 -> GreaterThanPacket(version, length, subPackets)
6 -> LessThanPacket(version, length, subPackets)
7 -> EqualToPacket(version, length, subPackets)
else -> throw IllegalArgumentException("Unknown Packet type $type")
}
private fun parseLiteralPacket(text: String): Pair<Int, Long> {
var value = ""
var length = 0
var current = text
while (true) {
val block = current.take(5)
value += block.drop(1)
length += 5
if (block[0] == '0') {
return length to value.toLong(2)
}
current = current.drop(5)
}
}
private fun parseSubpackets(text: String): Pair<Int, List<Packet>> {
var length = 1
val lengthType = text[0]
var currentLength = 0
val subPackets = mutableListOf<Packet>()
var content: String
val subpacketLength: Int
if (lengthType == '0') {
subpacketLength = text.slice(1..<16).toInt(2)
length += 15
content = text.drop(16)
} else {
subpacketLength = text.slice(1..<12).toInt(2)
length += 11
content = text.drop(12)
}
while (currentLength < subpacketLength) {
val subpacket = Packet(content)
subPackets.add(subpacket)
length += subpacket.length
content = content.drop(subpacket.length)
currentLength += if (lengthType == '1') 1 else subpacket.length
}
return length to subPackets
}
protected lateinit var packet: Packet
override fun parse(text: String) {
val binaryText = text.map(::hexDigitToBinary).joinToString("")
packet = Packet(binaryText)
}
private fun hexDigitToBinary(digit: Char): String {
return "%4s".format(digit.digitToInt(16).toString(2)).replace(' ', '0')
}
override fun compute(): String {
return versionSum(packet).toString()
}
private fun versionSum(packet: Packet): Int = when (packet) {
is OperatorPacket -> packet.version + packet.subPackets.sumOf { versionSum(it) }
else -> packet.version
}
override val exampleAnswer: String
get() = "16"
override val customExampleData: String?
get() = "8A004A801A8002F478"
override val testCases = sequence {
yield(TestCase("Operator Packet with 2 subpackets", "620080001611562C8802118E34", "12"))
yield(TestCase("Operator Packet with length type 1", "C0015000016115A2E0802F182340", "23"))
yield(TestCase("Multiple nested packets", "A0016C880162017C3686B18A3D4780", "31"))
}
}
class PartB16 : PartA16() {
override fun compute(): String {
return packet.value().toString()
}
override val exampleAnswer: String
get() = "15"
override val testCases = sequence {
yield(TestCase("Sum of 1 and 2", "C200B40A82", "3"))
yield(TestCase("Product of 6 and 9", "04005AC33890", "54"))
yield(TestCase("Min of 7, 8 and 9", "880086C3E88112", "7"))
yield(TestCase("Max of 7, 8, and 9", "CE00C43D881120", "9"))
yield(TestCase("5 less than 15", "D8005AC2A8F0", "1"))
yield(TestCase("5 greater than 15", "F600BC2D8F", "0"))
yield(TestCase("5 equal to 15", "9C005AC2F8F0", "0"))
yield(TestCase("1 + 3 = 2 * 2", "9C0141080250320F1802104A08", "1"))
}
}
| 0 | Kotlin | 0 | 0 | 49dc6eb7aa2a68c45c716587427353567d7ea313 | 6,183 | Advent-Of-Code-Kotlin | MIT License |
2022/main/day_19/Main.kt | Bluesy1 | 572,214,020 | false | {"Rust": 280861, "Kotlin": 94178, "Shell": 996} | package day_19_2022
import java.io.File
class Blueprint(val input: String) {
val blueprintNumber: Int
val oreRobotCost: Int
val clayRobotCost: Int
val obsidianRobotCost: Pair<Int, Int>
val geodeRobotCost: Pair<Int, Int>
var value = 0
init {
val ints = input.split(" ").map { it.removeSuffix(":") }.mapNotNull(String::toIntOrNull)
blueprintNumber = ints[0]
oreRobotCost = ints[1]
clayRobotCost = ints[2]
obsidianRobotCost = Pair(ints[3], ints[4])
geodeRobotCost = Pair(ints[5], ints[6])
}
}
data class Nonet(val one: Int, val two: Int, val three: Int, val four: Int, val five: Int, val six: Int, val seven: Int, val eight: Int, val nine: Int)
fun solve(
oreRobotCost: Int,
clayRobotCost: Int,
obsidianRobotCostFirst: Int,
obsidianRobotCostSecond: Int,
geodeRobotCostFirst: Int,
geodeRobotCostSecond: Int,
allottedTime: Int
): Int {
var best = 0
val queue = ArrayDeque(listOf(Nonet(0, 0, 0, 0, 1, 0, 0, 0, allottedTime)))
val seen = mutableSetOf<Nonet>()
while (queue.isNotEmpty()) {
var state = queue.removeFirst()
var (ore, clay, obsidian, geodes, r1, r2, r3, r4, time) = state
best = maxOf(best, geodes)
if (time==0)
continue
val core = maxOf(oreRobotCost, clayRobotCost, obsidianRobotCostFirst, geodeRobotCostFirst)
if (r1>=core)
r1 = core
if (r2>=obsidianRobotCostSecond)
r2 = obsidianRobotCostSecond
if (r3>=geodeRobotCostSecond)
r3 = geodeRobotCostSecond
if (ore >= time*core-r1*(time-1))
ore = time*core-r1*(time-1)
if (clay>=time*obsidianRobotCostSecond-r2*(time-1))
clay = time*obsidianRobotCostSecond - r2*(time-1)
if (obsidian>=time*geodeRobotCostSecond-r3*(time-1))
obsidian = time*geodeRobotCostSecond-r3*(time-1)
state = Nonet(ore,clay,obsidian,geodes,r1,r2,r3,r4,time)
if (state in seen)
continue
seen.add(state)
queue.add(Nonet(ore+r1,clay+r2,obsidian+r3,geodes+r4,r1,r2,r3,r4,time-1))
if (ore>=oreRobotCost) // buy ore
queue.add(
Nonet(ore-oreRobotCost+r1, clay+r2, obsidian+r3, geodes+r4, r1+1,r2,r3,r4,time-1)
)
if (ore>=clayRobotCost)
queue.add(
Nonet(ore-clayRobotCost+r1, clay+r2, obsidian+r3, geodes+r4, r1,r2+1,r3,r4,time-1)
)
if (ore>=obsidianRobotCostFirst && clay>=obsidianRobotCostSecond)
queue.add(
Nonet(ore-obsidianRobotCostFirst+r1, clay-obsidianRobotCostSecond+r2, obsidian+r3, geodes+r4, r1,r2,r3+1,r4,time-1)
)
if (ore>=geodeRobotCostFirst && obsidian>=geodeRobotCostSecond)
queue.add(
Nonet(ore-geodeRobotCostFirst+r1, clay+r2, obsidian-geodeRobotCostSecond+r3, geodes+r4, r1,r2,r3,r4+1,time-1)
)
}
return best
}
fun part1(input: List<String>) {
var score = 0
for (line in input) {
val blueprint = Blueprint(line)
val subScore = solve(
blueprint.oreRobotCost,
blueprint.clayRobotCost,
blueprint.obsidianRobotCost.first,
blueprint.obsidianRobotCost.second,
blueprint.geodeRobotCost.first,
blueprint.geodeRobotCost.second,
24
)
score += subScore * blueprint.blueprintNumber
}
print("The sum of the quality levels is $score")
}
fun part2(input: List<String>) {
var score = 1
for (line in input.subList(0,3)) {
val blueprint = Blueprint(line)
val subScore = solve(
blueprint.oreRobotCost,
blueprint.clayRobotCost,
blueprint.obsidianRobotCost.first,
blueprint.obsidianRobotCost.second,
blueprint.geodeRobotCost.first,
blueprint.geodeRobotCost.second,
32
)
score *= subScore
}
print("The product of the max geodes for blueprints 1 to 3 is $score")
}
fun main(){
val inputFile = File("2022/inputs/Day_19.txt")
print("\n----- Part 1 -----\n")
part1(inputFile.readLines())
print("\n----- Part 2 -----\n")
part2(inputFile.readLines())
} | 0 | Rust | 0 | 0 | 537497bdb2fc0c75f7281186abe52985b600cbfb | 4,296 | AdventofCode | MIT License |
model/src/test/kotlin/ScopeTest.kt | codeakki | 354,880,826 | true | {"Kotlin": 2934213, "JavaScript": 337630, "HTML": 34185, "CSS": 24865, "Python": 21694, "FreeMarker": 13132, "Shell": 7793, "Dockerfile": 7023, "Scala": 6656, "Ruby": 3515, "ANTLR": 1877, "Go": 1071, "Rust": 280} | /*
* Copyright (C) 2017-2020 HERE Europe B.V.
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
* License-Filename: LICENSE
*/
package org.ossreviewtoolkit.model
import io.kotest.core.spec.style.WordSpec
import io.kotest.matchers.should
import io.kotest.matchers.shouldBe
import org.ossreviewtoolkit.utils.test.containExactly
class ScopeTest : WordSpec({
"getDependencyTreeDepth()" should {
"return 0 if it does not contain any package" {
val scope = Scope(name = "test", dependencies = sortedSetOf())
scope.getDependencyTreeDepth() shouldBe 0
}
"return 1 if it contains only direct dependencies" {
val scope = Scope(
name = "test",
dependencies = sortedSetOf(
PackageReference(id = Identifier("a")),
PackageReference(id = Identifier("b"))
)
)
scope.getDependencyTreeDepth() shouldBe 1
}
"return 2 if it contains a tree of height 2" {
val scope = Scope(
name = "test",
dependencies = sortedSetOf(
pkg("a") {
pkg("a1")
}
)
)
scope.getDependencyTreeDepth() shouldBe 2
}
"return 3 if it contains a tree of height 3" {
val scope = Scope(
name = "test",
dependencies = sortedSetOf(
pkg("a") {
pkg("a1") {
pkg("a11")
pkg("a12")
}
},
pkg("b")
)
)
scope.getDependencyTreeDepth() shouldBe 3
}
}
"getShortestPaths()" should {
"find the shortest path to each dependency" {
val scope = Scope(
name = "test",
dependencies = sortedSetOf(
pkg("A"),
pkg("B") {
pkg("A")
},
pkg("C") {
pkg("B") {
pkg("A") {
pkg("H")
pkg("I") {
pkg("H")
}
}
}
pkg("D") {
pkg("E")
}
},
pkg("F") {
pkg("E") {
pkg("I")
}
},
pkg("G") {
pkg("E")
}
)
)
scope.getShortestPaths() should containExactly(
Identifier("A") to emptyList(),
Identifier("B") to emptyList(),
Identifier("C") to emptyList(),
Identifier("D") to listOf(Identifier("C")),
Identifier("E") to listOf(Identifier("F")),
Identifier("F") to emptyList(),
Identifier("G") to emptyList(),
Identifier("H") to listOf(Identifier("C"), Identifier("B"), Identifier("A")),
Identifier("I") to listOf(Identifier("F"), Identifier("E"))
)
}
}
})
private class PackageReferenceBuilder(id: String) {
private val id = Identifier(id)
private val dependencies = sortedSetOf<PackageReference>()
fun pkg(id: String, block: PackageReferenceBuilder.() -> Unit = {}) {
dependencies += PackageReferenceBuilder(id).apply { block() }.build()
}
fun build(): PackageReference = PackageReference(id = id, dependencies = dependencies)
}
private fun pkg(id: String, block: PackageReferenceBuilder.() -> Unit = {}): PackageReference =
PackageReferenceBuilder(id).apply { block() }.build()
| 17 | null | 2 | 2 | edbb46cb1dab1529d5ffb81cba18d365b98ef23e | 4,577 | ort | Apache License 2.0 |
src/Day06.kt | befrvnk | 574,229,637 | false | {"Kotlin": 15788} | fun String.isMarker(): Boolean {
return all { char -> this.count(char) == 1 }
}
fun String.count(char: Char): Int {
return count { it == char }
}
fun main() {
fun part1(input: List<String>): Int {
val firstLine = input.first()
(0..firstLine.length - 4).forEach { index ->
val potentialMarker = firstLine.substring(index, index + 4)
if (potentialMarker.isMarker()) return index + 4
}
throw Exception("Marker was not found")
}
fun part2(input: List<String>): Int {
val firstLine = input.first()
(0..firstLine.length - 14).forEach { index ->
val potentialMarker = firstLine.substring(index, index + 14)
if (potentialMarker.isMarker()) return index + 14
}
throw Exception("Marker was not found")
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day06_test")
check(part1(testInput) == 7)
// check(part2(testInput) == "MCD")
val input = readInput("Day06")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 68e5dd5656c052d8c8a2ea9e03c62f4cd2438dd7 | 1,112 | aoc-2022-kotlin | Apache License 2.0 |
day10/src/main/kotlin/App.kt | ascheja | 317,918,055 | false | null | package net.sinceat.aoc2020.day10
fun main() {
println(differences(parseFile("testinput.txt")))
println(differences(parseFile("input.txt")))
println(with(Cached()) { parseFile("testinput.txt").combinations() })
println(
with(Cached()) {
val result = parseFile("input.txt").combinations()
result
}
)
}
fun parseFile(fileName: String): List<Int> {
return ClassLoader.getSystemResourceAsStream(fileName)!!.bufferedReader().useLines { lines ->
lines.filter(String::isNotBlank).map(String::toInt).sorted().toList()
}
}
fun differences(input: List<Int>): Int {
var oneDiffs = 0
var threeDiffs = 1
var lastJoltage = 0
for (adapterJoltage in input) {
when (adapterJoltage - lastJoltage) {
1 -> oneDiffs++
3 -> threeDiffs++
}
lastJoltage = adapterJoltage
}
return oneDiffs * threeDiffs
}
class Cached {
private val cache = mutableMapOf<Pair<List<Int>, Int>, Long>()
fun List<Int>.combinations(last: Int = 0): Long {
return cache.computeIfAbsent(Pair(this, last)) {
if (isEmpty()) {
return@computeIfAbsent 0
}
val head = first()
val diff = head - last
if (diff > 3) {
return@computeIfAbsent 0
}
val tail = subList(1, size)
if (tail.isEmpty()) {
return@computeIfAbsent 1
}
return@computeIfAbsent tail.combinations(last) + tail.combinations(head)
}
}
}
| 0 | Kotlin | 0 | 0 | f115063875d4d79da32cbdd44ff688f9b418d25e | 1,593 | aoc2020 | MIT License |
src/main/kotlin/letterboxed/Puzzle.kt | gmarmstrong | 531,249,433 | false | {"Kotlin": 22711} | package letterboxed
const val EDGES_PER_PUZZLE = 4
const val LETTERS_PER_EDGE = 3
/**
* Represents a Letter Boxed puzzle configuration.
*/
data class Puzzle(val edges: Set<Set<Char>>) {
val letters: Set<Char>
get() = edges.flatten().toSet()
/**
* Constructs a puzzle from a set of 4 edges (sets of 3 uppercase ASCII characters).
*/
init {
require(edges.size == EDGES_PER_PUZZLE) { "Puzzle must have exactly 4 unique edges" }
require(edges.all { it.size == LETTERS_PER_EDGE }) { "Each edge must be exactly 3 unique characters" }
require(
edges.all { edge -> edge.all { it in 'A'..'Z' } }
) { "Each edge must contain only uppercase ASCII letters" }
require(
edges.flatten().toSet().size == EDGES_PER_PUZZLE * LETTERS_PER_EDGE
) { "Puzzle must consist of exactly 12 unique characters" }
}
/**
* Constructs a puzzle from a string of comma-separated of edges. Letters are converted to uppercase.
*
* @throws IllegalArgumentException if the string is not a valid puzzle.
*/
constructor(input: String) : this(parseEdges(input.uppercase()))
// Define Puzzle equality by equality of edges.
override fun equals(other: Any?): Boolean = other is Puzzle && other.edges == edges
// Define Puzzle hashCode by hashCode of edges.
override fun hashCode(): Int = edges.hashCode()
// Define Puzzle toString by concatenating edges.
override fun toString(): String = edges.joinToString(separator = ",") { edge -> edge.joinToString(separator = "") }
companion object {
/**
* Parses a string of comma-separated edges into a set of sets of characters.
*
* For example, "ABC,DEF,GHI,JKL" becomes
* { {'A', 'B', 'C'}, {'D', 'E', 'F'}, {'G', 'H', 'I'}, {'J', 'K', 'L'} }.
*/
private fun parseEdges(input: String): Set<Set<Char>> = input
.split(",")
.map { it.toSet() }
.toSet()
}
}
| 2 | Kotlin | 0 | 0 | a0545396ebe135ebd602f1d874bf8c4dd9b037d5 | 2,028 | letter-boxed | MIT License |
src/commonMain/kotlin/io/github/alexandrepiveteau/graphs/algorithms/BreadthFirstTraversal.kt | alexandrepiveteau | 630,931,403 | false | {"Kotlin": 132267} | @file:JvmName("Traversals")
@file:JvmMultifileClass
package io.github.alexandrepiveteau.graphs.algorithms
import io.github.alexandrepiveteau.graphs.*
import io.github.alexandrepiveteau.graphs.internal.collections.IntDequeue
import kotlin.contracts.contract
import kotlin.jvm.JvmMultifileClass
import kotlin.jvm.JvmName
/**
* Traverses the graph in breadth-first order, starting from the given [from] vertex, and performs
* the given [action] on each vertex.
*
* ## Asymptotic complexity
* - **Time complexity**: O(|N| + |E|), where |N| is the number of vertices in this graph and |E| is
* the number of edges in this graph.
* - **Space complexity**: O(|N|), where n is the number of vertices in this graph.
*
* @param from the vertex from which to start the search.
* @param action the action to execute on each vertex.
*/
public inline fun <G> G.forEachVertexBreadthFirst(
from: Vertex,
action: (Vertex) -> Unit,
) where G : Successors {
contract { callsInPlace(action) }
val queue = IntDequeue().apply { addLast(index(from)) }
val visited = BooleanArray(size).apply { this[index(from)] = true }
while (queue.size > 0) {
val next = queue.removeFirst()
action(vertex(next))
forEachSuccessor(vertex(next)) {
if (!visited[index(it)]) {
queue.addLast(index(it))
visited[index(it)] = true
}
}
}
}
/**
* Returns a [VertexArray] with the shortest path going from the [from] vertex to the [to] vertex,
* using breadth-first search.
*
* ## Asymptotic complexity
* - **Time complexity**: O(|N| + |E|), where |N| is the number of vertices in this graph and |E| is
* the number of edges in this graph.
* - **Space complexity**: O(|N|), where |N| is the number of vertices in this graph.
*
* @param from the starting vertex.
* @param to the ending vertex.
* @return the [VertexArray] with the shortest path going from the [from] vertex to the [to] vertex,
* or `null` if there is no path between the two vertices.
*/
public fun <G> G.shortestPathBreadthFirst(
from: Vertex,
to: Vertex,
): VertexArray? where G : Successors {
if (from !in this) throw NoSuchVertexException()
if (to !in this) throw NoSuchVertexException()
val parents = VertexMap(size) { Vertex.Invalid }
forEachVertexBreadthFirst(from) { u ->
forEachSuccessor(u) { v ->
if (parents[v] == Vertex.Invalid) parents[v] = u
if (v == to) return computePath(parents, from, to)
}
}
return null
}
| 9 | Kotlin | 0 | 6 | a4fd159f094aed5b6b8920d0ceaa6a9c5fc7679f | 2,481 | kotlin-graphs | MIT License |
src/main/kotlin/com/lucaszeta/adventofcode2020/day18/sumOverMultiplication.kt | LucasZeta | 317,600,635 | false | null | package com.lucaszeta.adventofcode2020.day18
fun evaluateAdvancedMathExpression(expression: String): Long {
var line = "($expression)"
val operatorPrecedence = listOf(
SUM_IN_PARENTHESIS to sum,
SUM to sum,
MULTIPLE_MULTIPLICATION to multiplication,
MULTIPLICATION_IN_PARENTHESIS to multiplication,
MULTIPLICATION to multiplication
)
var didAnyOperation: Boolean
do {
didAnyOperation = false
for (precedence in operatorPrecedence) {
val (pattern, operation) = precedence
if (pattern.containsMatchIn(line)) {
line = pattern.replace(line, operation)
didAnyOperation = true
break
}
}
} while (didAnyOperation)
return line.toLong()
}
private val SUM_IN_PARENTHESIS = "\\((\\d+) \\+ (\\d+)\\)".toRegex()
private val SUM = "(\\d+) \\+ (\\d+)".toRegex()
private val MULTIPLE_MULTIPLICATION = "\\((\\d+) \\* (\\d+)( [^()]+)\\)".toRegex()
private val MULTIPLICATION_IN_PARENTHESIS = "\\((\\d+) \\* (\\d+)\\)".toRegex()
private val MULTIPLICATION = "(\\d+) \\* (\\d+)".toRegex()
private val sum: (MatchResult) -> CharSequence = {
doOperationAndReturnString(it, Long::plus)
}
private val multiplication: (MatchResult) -> CharSequence = {
doOperationAndReturnString(it, Long::times)
}
private val doOperationAndReturnString: (
MatchResult,
(Long, Long) -> Long
) -> CharSequence = { matchResult, operation ->
val (_, operand1, operand2) = matchResult.groupValues
val restOfExpression = if (matchResult.groupValues.size == 4) {
matchResult.groupValues.last()
} else ""
val result = operation(operand1.toLong(), operand2.toLong())
if (restOfExpression.isNotEmpty()) {
"($result$restOfExpression)"
} else {
"$result"
}
}
| 0 | Kotlin | 0 | 1 | 9c19513814da34e623f2bec63024af8324388025 | 1,863 | advent-of-code-2020 | MIT License |
src/Day01.kt | Oktosha | 573,139,677 | false | {"Kotlin": 110908} | import kotlin.math.max
import java.util.PriorityQueue
fun main() {
fun part1(input: List<String>): Int {
var answer = 0
var current = 0
for (line in input) {
if (line.trim() == "") {
answer = max(current, answer)
current = 0
} else {
current += line.toInt()
}
}
answer = max(current, answer)
return answer
}
fun part2(input: List<String>): Int {
val highestValues = PriorityQueue<Int>()
var current = 0
for (line in input) {
if (line.trim() == "") {
highestValues.add(current)
if (highestValues.size > 3) {
highestValues.remove()
}
current = 0
} else {
current += line.toInt()
}
}
highestValues.add(current)
if (highestValues.size > 3) {
highestValues.remove()
}
return highestValues.fold(0) { x, y -> x + y }
}
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | e53eea61440f7de4f2284eb811d355f2f4a25f8c | 1,164 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/Day09.kt | SimonMarquis | 724,825,757 | false | {"Kotlin": 30983} | class Day09(input: List<String>) {
private val histories = input.asSequence()
.map { it.split(" ").map(String::toLong) }
.map { it.differences() }
private fun List<Long>.differences(): List<List<Long>> = buildList {
add(this@differences)
while (last().any { it != 0L }) add(last().windowed(size = 2) { (l, r) -> r - l })
}
fun part1(): Long = histories
.sumOf { it.reversed().fold(0L) { acc, values -> acc + values.last() } }
fun part2(): Long = histories
.sumOf { it.reversed().fold(0L) { acc, values -> values.first() - acc } }
}
| 0 | Kotlin | 0 | 1 | 043fbdb271603c84b7e5eddcd0e8f323c6ebdf1e | 605 | advent-of-code-2023 | MIT License |
sort/bogo_sort/kotlin/bogo_sort.kt | ZoranPandovski | 93,438,176 | false | {"Jupyter Notebook": 21909905, "C++": 1692994, "Python": 1158220, "Java": 806066, "C": 560110, "JavaScript": 305918, "Go": 145277, "C#": 117882, "PHP": 85458, "Kotlin": 72238, "Rust": 53852, "Ruby": 43243, "MATLAB": 34672, "Swift": 31023, "Processing": 22089, "HTML": 18961, "Haskell": 14298, "Dart": 11842, "CSS": 10509, "Scala": 10277, "Haxe": 9750, "PureScript": 9122, "M": 9006, "Perl": 8685, "Prolog": 8165, "Shell": 7901, "Erlang": 7483, "Assembly": 7284, "R": 6832, "Lua": 6392, "LOLCODE": 6379, "VBScript": 6283, "Clojure": 5598, "Elixir": 5495, "OCaml": 3989, "Crystal": 3902, "Common Lisp": 3839, "Julia": 3567, "F#": 3376, "TypeScript": 3268, "Nim": 3201, "Brainfuck": 2466, "Visual Basic .NET": 2033, "ABAP": 1735, "Pascal": 1554, "Groovy": 976, "COBOL": 887, "Mathematica": 799, "Racket": 755, "PowerShell": 708, "Ada": 490, "CMake": 393, "Classic ASP": 339, "QMake": 199, "Makefile": 111} | /*
Bogo Sort
Bogo Sort is the most inefficient way of sorting an algorithm.
The way Bogo Sort works is like throwing a deck of cards in the air
and picking them back up and checking to see if it's organized.
Array of ints [ 3, 1, 2 ]
Step 1.
Starts at the start of the array and will grab a random index from the array to switch with.
randomIndex = RANDOM NUMBER
Step 2.
Once random index is obtained, it will then switch the current index value with the random index value
Example: randomIndex = 2, currentIndex = 0
[ 3, 1, 2 ] ---> [ 2, 1, 3 ]
Step 3.
Check if array is sorted.
[ 2, 1, 3 ] <---- Is not sorted so go onto the next index and repeat steps 1 & 2. Stop when sorted
- You could be done in the next step or the next million steps :')
*/
package com.exam.kotlin.codingproject
import kotlin.random.Random
class BogoSort {
companion object{
private val randomValues = List(10) { Random.nextInt(0, 100) }
private fun isSorted(arr: IntArray): Boolean {
for (i in 0 until arr.size - 1) {
if (arr[i] > arr[i + 1]) {
return false
}
}
return true
}
fun bogoSort(numbersToSort: IntArray) : IntArray {
while (!isSorted(numbersToSort)) {
for (i in numbersToSort.indices) {
val randomIndex = randomValues[numbersToSort.size]
val holder = numbersToSort[i]
numbersToSort[i] = numbersToSort[randomIndex]
numbersToSort[randomIndex] = holder
}
}
return numbersToSort
}
}
}
| 62 | Jupyter Notebook | 1,994 | 1,298 | 62a1a543b8f3e2ca1280bf50fc8a95896ef69d63 | 1,665 | al-go-rithms | Creative Commons Zero v1.0 Universal |
src/Day01.kt | romainbsl | 572,718,344 | false | {"Kotlin": 17019} | fun main() {
fun part1(input: String): Elf {
return input.split("\n\n")
.map { foods ->
Elf(foods.split("\n").map { Food(it.toInt()) })
}
.maxBy { elf -> elf.foods.sumOf { it.calories } }
}
fun part2(input: String): List<Elf> {
return input.split("\n\n")
.map { foods ->
Elf(foods.split("\n").map { Food(it.toInt()) })
}
.sortedByDescending { it.foods.sumOf { it.calories } }
.take(3)
}
// test if implementation meets criteria from the description, like:
val testInput = readInputAsText("Day01")
println(part1(testInput).totalCalories)
println(part2(testInput).sumOf(Elf::totalCalories))
}
@JvmInline
value class Food(val calories: Int)
data class Elf(val foods: List<Food>) {
val totalCalories: Int get() = foods.sumOf { it.calories }
} | 0 | Kotlin | 0 | 0 | b72036968769fc67c222a66b97a11abfd610f6ce | 911 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/days/Day19.kt | poqueque | 430,806,840 | false | {"Kotlin": 101024} | package days
import Coor3
import kotlin.math.abs
class Day19 : Day(19) {
class Scanner {
var position: Coor3? = null
var rotation: Int? = null
val beacons = mutableListOf<Coor3>()
fun add(c: Coor3) {
beacons.add(c)
}
fun rotated(faced: Int): Scanner {
val s = Scanner()
for (b in beacons)
s.add(face(b, faced))
return s
}
fun move(c: Coor3): Scanner {
val s = Scanner()
for (b in beacons)
s.add(b + c)
return s
}
private fun face(c: Coor3, face: Int): Coor3 {
if (face == 0) return Coor3(c.x, c.y, c.z)
if (face == 1) return Coor3(-c.x, c.y, c.z)
if (face == 2) return Coor3(c.x, -c.y, c.z)
if (face == 3) return Coor3(c.x, c.y, -c.z)
if (face == 4) return Coor3(-c.x, -c.y, c.z)
if (face == 5) return Coor3(-c.x, c.y, -c.z)
if (face == 6) return Coor3(c.x, -c.y, -c.z)
if (face == 7) return Coor3(-c.x, -c.y, -c.z)
// if (face >= 8) return rotate(face(c, face % 8), face / 8)
if (face >= 8) return face(rotate(c, face / 8), face % 8)
return Coor3(0, 0, 0)
}
private fun rotate(c: Coor3, rotated: Int): Coor3 {
if (rotated == 0) return Coor3(c.x,c.y,c.z)
if (rotated == 1) return Coor3(c.x,c.z,c.y)
if (rotated == 2) return Coor3(c.y,c.x,c.z)
if (rotated == 3) return Coor3(c.y,c.z,c.x)
if (rotated == 4) return Coor3(c.z,c.x,c.y)
if (rotated == 5) return Coor3(c.z,c.y,c.x)
return rotate(c,rotated%6)
}
}
private val scanners = mutableMapOf<Int, Scanner>()
init {
var s = 0
inputList.forEach { line ->
if (line.startsWith("---")) {
s = line.split(" ")[2].toInt()
if (scanners[s] == null) scanners[s] = Scanner()
} else if (line.contains(",")) {
val (a, b, c) = line.split(",").map { it.trim().toInt() }
scanners[s]!!.add(Coor3(a, b, c))
}
}
scanners[0]!!.position = Coor3(0, 0, 0)
scanners[0]!!.rotation = 0
}
override fun partOne(): Any {
val beacons = mutableListOf<Coor3>()
beacons.addAll(scanners[0]!!.beacons)
var bSize = 0
while(beacons.size>bSize) {
bSize = beacons.size
for (j in scanners.keys.indices)
for (r in 0 until 48) {
val s = scanners[j]!!.rotated(r)
val difs = mutableListOf<Coor3>()
for (b1 in beacons)
for (b2 in s.beacons)
difs.add(b2 - b1)
val coincidences: Map<Coor3, Int> =
difs.groupingBy { it }.eachCount().filter { it.value > 1 }
val difOk = coincidences.filter { it.value >= 4 }.keys.firstOrNull()
if (difOk != null) {
// println("FOUND: coincide ($j): $coincidences")
// println("Scanner $j on Scanner 0 coordinates")
for (b in s.beacons) {
val c = b - difOk
if (!beacons.contains(c)) {
beacons.add(c)
// println("Added $c from scanner $j")
}
}
scanners[j]!!.position = Coor3(0,0,0) - difOk
scanners[j]!!.rotation = r
// println("Scanner $j abs POS: ${scanners[j]!!.position}")
}
}
}
beacons.sortBy { it.z }
beacons.sortBy { it.y }
beacons.sortBy { it.x }
// println("${beacons.size} beacons found:")
// for (b in beacons)
// println(b)
return beacons.size
}
override fun partTwo(): Any {
var max = 0
for (s1 in scanners.values)
for (s2 in scanners.values) {
var md = abs(s1.position!!.x - s2.position!!.x)
md += abs(s1.position!!.y - s2.position!!.y)
md += abs(s1.position!!.z - s2.position!!.z)
if (md > max) max = md
}
return max
}
}
| 0 | Kotlin | 0 | 0 | 4fa363be46ca5cfcfb271a37564af15233f2a141 | 4,682 | adventofcode2021 | MIT License |
advent-of-code-2022/src/Day10.kt | osipxd | 572,825,805 | false | {"Kotlin": 141640, "Shell": 4083, "Scala": 693} | fun main() {
val testInput = readInput("Day10_test")
val input = readInput("Day10")
"Part 1 + 2" {
println()
solve(testInput) shouldBe 13140
println()
answer(solve(input))
}
}
private const val START_OFFSET = 20
private const val WIDTH = 40
private fun solve(commands: List<List<String>>): Int {
var cycle = 0
var register = 1
var signalStrength = 0
fun tick(argument: Int = 0) {
// Start new cycle
cycle++
// Part 1
if ((cycle + START_OFFSET) % WIDTH == 0) signalStrength += cycle * register
// Part 2
val isFilled = (cycle - 1) % WIDTH in register - 1..register + 1
print(if (isFilled) "██" else "░░")
if (cycle % WIDTH == 0) println()
// Finish cycle
register += argument
}
for (parts in commands) {
tick()
if (parts[0] == "addx") tick(parts[1].toInt())
}
return signalStrength
}
private fun readInput(name: String) = readLines(name).map { it.split(" ") }
| 0 | Kotlin | 0 | 5 | 6a67946122abb759fddf33dae408db662213a072 | 1,053 | advent-of-code | Apache License 2.0 |
src/main/aoc2021/Day9.kt | nibarius | 154,152,607 | false | {"Kotlin": 963896} | package aoc2021
import Grid
import Pos
class Day9(input: List<String>) {
private val rangeX = input.first().indices
private val rangeY = input.indices
val grid = Grid.parse(input)
private fun findLowPoints(): List<Pos> {
return grid.keys
.filter { it.y in rangeY } // real input is square, but example input has y < x
.filter { pos ->
pos.allNeighbours()
.filter { it.x in rangeX && it.y in rangeY }
.all { grid[it] > grid[pos] } // All neighbours are larger than current ==> minimum
}
}
// Return a list of all points part of the basin around the given low point
private fun findBasin(lowPoint: Pos): Set<Pos> {
val ret = mutableSetOf<Pos>()
val toCheck = mutableSetOf(lowPoint)
while (toCheck.isNotEmpty()) {
val curr = toCheck.first()
toCheck.remove(curr)
ret.add(curr)
val next = curr.allNeighbours().filter {
it.x in rangeX && it.y in rangeY && it !in ret && grid[it] != '9'
}
toCheck.addAll(next)
}
return ret
}
fun solvePart1(): Int {
return findLowPoints().sumOf { 1 + grid[it].digitToInt() }
}
fun solvePart2(): Int {
return findLowPoints()
.map { findBasin(it).size }
.sorted()
.takeLast(3)
.reduce(Int::times)
}
} | 0 | Kotlin | 0 | 6 | f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22 | 1,471 | aoc | MIT License |
2020/src/year2021/day06/code.kt | eburke56 | 436,742,568 | false | {"Kotlin": 61133} | package year2021.day06
import util.readAllLines
fun main() {
part1()
part2()
}
private fun part1() {
run(80, "input.txt")
}
private fun part2() {
run(256, "input.txt")
}
private fun run(times: Int, file: String) {
val size = readAllLines(file).first().split(",")
.map { it.toInt() }
.sumOf { value ->
(1 + countSpawned(times, value % 7))
}
println(size)
}
private val cache = mutableMapOf<Int, Long>()
private fun countSpawned(totalTimes: Int, startTime: Int, indent: String = ""): Long =
when {
startTime > totalTimes -> 0
else -> {
var result = 0L
for (i in startTime until totalTimes step 7) {
val nextTime = i + 9
val spawned = if (cache.containsKey(nextTime)) {
cache[nextTime]!!
} else {
countSpawned(totalTimes, nextTime, "$indent ").also { cache[nextTime] = it }
}
result += 1L + spawned
}
result
}
}
| 0 | Kotlin | 0 | 0 | 24ae0848d3ede32c9c4d8a4bf643bf67325a718e | 1,079 | adventofcode | MIT License |
src/Day06.kt | erikthered | 572,804,470 | false | {"Kotlin": 36722} | fun main() {
fun markerLocation(input: String, size: Int): Int {
input.windowed(size).forEachIndexed { index, s ->
if(s.toCharArray().toSet().size == size) {
return index + s.length
}
}
throw IllegalArgumentException("Marker not found")
}
fun part1(input: String) = markerLocation(input, 4)
fun part2(input: String) = markerLocation(input, 14)
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day06_test")
testInput.zip(arrayOf(7, 5, 6, 10, 11)).forEach { (line, expected) ->
check(part1(line) == expected)
}
testInput.zip(arrayOf(19, 23, 23, 29, 26)).forEach { (line, expected) ->
check(part2(line) == expected)
}
val input = readInput("Day06")
println(part1(input.first()))
println(part2(input.first()))
}
| 0 | Kotlin | 0 | 0 | 3946827754a449cbe2a9e3e249a0db06fdc3995d | 890 | aoc-2022-kotlin | Apache License 2.0 |
src/medium/_29DivideTwoIntegers.kt | ilinqh | 390,190,883 | false | {"Kotlin": 382147, "Java": 32712} | package medium
import kotlin.math.abs
class _29DivideTwoIntegers {
class Solution {
fun divide(a: Int, b: Int): Int {
var dividend = Math.abs(a.toLong())
val divisor = Math.abs(b.toLong())
var quotient = 0L
for (i in 31 downTo 0) {
if ((dividend shr i) >= divisor) {
quotient += 1L shl i
dividend -= divisor shl i
}
}
if ((a xor b) < 0) {
quotient = quotient.inv() + 1
}
if (quotient == (1L shl 31)) {
return (quotient - 1).toInt()
}
return quotient.toInt()
}
}
// Other
class OtherSolution {
fun divide(dividend: Int, divisor: Int): Int {
if (dividend == Integer.MIN_VALUE && divisor == -1) {
return Integer.MAX_VALUE
}
if (divisor == -1)
return -dividend
if (divisor == 1)
return dividend
var sign = -1
if (dividend > 0 && divisor > 0)
sign = 1
if (dividend < 0 && divisor < 0)
sign = 1
val result = div(0L, abs(dividend.toLong()), abs(dividend.toLong()), abs(divisor.toLong()))
if (result > Integer.MAX_VALUE) {
return Integer.MAX_VALUE * sign
}
return result.toInt() * sign
}
fun div(left: Long, right: Long, dividend: Long, divisor: Long): Long {
val e = left + ((right - left) shr 1)
if ((e + 1) * divisor == dividend) {
return e + 1
}
if (e * divisor == dividend) {
return e
}
if (e * divisor < dividend) {
if ((e + 1) * divisor > dividend)
return e
}
if ((e + 1) * divisor < dividend) {
return div(e + 1, right, dividend, divisor)
}
if (e * divisor > dividend) {
return div(left, e - 1, dividend, divisor)
}
return 0
}
}
} | 0 | Kotlin | 0 | 0 | 8d2060888123915d2ef2ade293e5b12c66fb3a3f | 2,211 | AlgorithmsProject | Apache License 2.0 |
src/Day1/Day1.kt | tomashavlicek | 571,148,506 | false | {"Kotlin": 3033} | package Day1
import readInputAsInts
fun main() {
fun part1(input: List<Int>): Int {
return input.windowed(size = 2).count { it.first() < it.last() }
}
fun part2(input: List<Int>): Int {
// return input.windowed(size = 3).windowed(2).count {
// (firstWindow, secondWindow) -> firstWindow.sum() < secondWindow.sum()
// }
// A + B + C <=> B + C + D ==> A <=> D
return input.windowed(size = 4).count {
it.first() < it.last()
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInputAsInts("Day1/Day1_test")
check(part1(testInput) == 7)
check(part2(testInput) == 5)
val input = readInputAsInts("Day1/Day1")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 52f7febaacaab3ee9809899d21077fecac39c13b | 808 | aoc-2021-in-kotlin | Apache License 2.0 |
src/main/kotlin/me/grison/aoc/y2021/Day22.kt | agrison | 315,292,447 | false | {"Kotlin": 267552} | package me.grison.aoc.y2021
import me.grison.aoc.*
import kotlin.collections.component1
import kotlin.collections.component2
import kotlin.collections.component3
import kotlin.collections.component4
import kotlin.collections.component5
import kotlin.collections.set
import kotlin.math.max
import kotlin.math.min
import kotlin.ranges.LongRange.Companion.EMPTY
class Day22 : Day(22, 2021) {
override fun title() = "Reactor Reboot"
override fun partOne(): Int {
val cubes = mutableMapOf<Any, String>()
for ((state, xrange, yrange, zrange) in cuboids())
for (x in xrange.intersection(-50..50L))
for (y in yrange.intersection(-50..50L))
for (z in zrange.intersection(-50..50L))
cubes[Triple(x, y, z)] = state
return cubes.values.count { it == "on" }
}
override fun partTwo(): Long {
val cuboids = cuboids(inclusive = 1)
return cuboids.foldIndexed(0L) { i, acc, cube ->
acc + if (cube.state == "on") countCubes(cube, cuboids.sub(i + 1)) else 0L
}
}
private fun countCubes(cuboid: Cuboid, rest: List<Cuboid>): Long {
val intersections = rest.mapNotNull { it.intersection(cuboid) }
return intersections.foldIndexed(cuboid.volume()) { i, acc, cube ->
acc - countCubes(cube, intersections.sub(i + 1))
}
}
private fun cuboids(inclusive: Int = 0) = inputList.map {
val (xa, xb, ya, yb, za, zc) = it.allLongs(includeNegative = true)
Cuboid(it.before(" "), xa..xb + inclusive, ya..yb + inclusive, za..zc + inclusive)
}
}
private fun LongRange.length() = last - start
private fun LongRange.intersection(range: LongRange) =
if (last < range.first || first > range.last) EMPTY
else min(max(first, range.first), range.last)..min(max(last, range.first), range.last)
data class Cuboid(val state: String = "", val xrange: LongRange, val yrange: LongRange, val zrange: LongRange) {
fun volume() = xrange.length() * yrange.length() * zrange.length()
fun intersection(other: Cuboid) =
Cuboid(
state, xrange.intersection(other.xrange), yrange.intersection(other.yrange),
zrange.intersection(other.zrange)
).let {
if (it.valid()) it else null
}
fun valid() = !xrange.isEmpty() && !yrange.isEmpty() && !zrange.isEmpty()
} | 0 | Kotlin | 3 | 18 | ea6899817458f7ee76d4ba24d36d33f8b58ce9e8 | 2,407 | advent-of-code | Creative Commons Zero v1.0 Universal |
src/day6/Day6.kt | blundell | 572,916,256 | false | {"Kotlin": 38491} | package day6
import readInput
fun main() {
fun detectStartOfPacket(input: List<String>, startOfMessageMarkerSize: Int): Int {
var lastFour = ""
for ((index, c) in input[0].withIndex()) {
if (lastFour.length < startOfMessageMarkerSize) {
lastFour += c
continue
}
lastFour = lastFour.removeRange(0, 1)
lastFour += c
var unique = true
for ((i1, cF) in lastFour.withIndex()) {
for ((i2, cf2) in lastFour.withIndex()) {
if (i1 == i2) {
continue
}
if (cF == cf2) {
unique = false
}
}
}
if (unique) {
return index + 1
}
}
throw IllegalStateException("No marker in [$input].")
}
fun part1(input: List<String>): Int {
return detectStartOfPacket(input, 4)
}
fun part2(input: List<String>): Int {
return detectStartOfPacket(input, 14)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("day6/Day6_test")
val testResult = part1(testInput)
check(testResult == 7) { "Expected 7 got [$testResult]" }
val input = readInput("day6/Day6")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f41982912e3eb10b270061db1f7fe3dcc1931902 | 1,434 | kotlin-advent-of-code-2022 | Apache License 2.0 |
leetcode/src/Q35.kt | zhangweizhe | 387,808,774 | false | null | fun main() {
// https://leetcode-cn.com/problems/search-insert-position/
//println(searchInsert(intArrayOf(3,5,7,9,10), 8))
println(binSearch1(intArrayOf(1), 1))
}
fun searchInsert(nums: IntArray, target: Int): Int {
return binSearch(nums, target, 0, nums.size - 1)
}
fun binSearch(nums: IntArray, target: Int, start: Int, end: Int):Int {
if (start >= end) {
if (nums[start] >= target) {
return start
}else{
return start + 1
}
}
var center = (start + end) / 2
if (target == nums[center]) {
return center
}
if (target < nums[center]) {
return binSearch(nums, target, start, center - 1)
}else {
return binSearch(nums, target, center + 1, end)
}
}
fun binSearch1(nums: IntArray, target: Int):Int {
val n = nums.size
var left = 0
var right = n - 1
while (left <= right) {
var mid = (left + right) / 2
when {
nums[mid] == target -> {
return mid
}
nums[mid] > target -> {
right = mid - 1
}
else -> {
left = mid + 1
}
}
}
println("left: $left, right: $right")
return -1
} | 0 | Kotlin | 0 | 0 | 1d213b6162dd8b065d6ca06ac961c7873c65bcdc | 1,259 | kotlin-study | MIT License |
2021/src/main/kotlin/Day2.kt | osipxd | 388,214,845 | false | null | /**
* # 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?
*
* --- Part Two ---
*
* Based on your calculations, the planned course doesn't seem to make any sense.
* You find the submarine manual and discover that the process is actually
* slightly more complicated.
*
* In addition to horizontal position and depth, you'll also need to track
* a third value, aim, which also starts at 0. The commands also mean something
* entirely different than you first thought:
* - down X increases your aim by X units.
* - up X decreases your aim by X units.
* - forward X does two things:
* - It increases your horizontal position by X units.
* - It increases your depth by your aim multiplied by X.
*
* Again note that since you're on a submarine, down and up do the opposite
* of what you might expect: "down" means aiming in the positive direction.
*
* Now, the above example does something different:
*
* - forward 5 adds 5 to your horizontal position, a total of 5.
* Because your aim is 0, your depth does not change.
* - down 5 adds 5 to your aim, resulting in a value of 5.
* - forward 8 adds 8 to your horizontal position, a total of 13.
* Because your aim is 5, your depth increases by 8*5=40.
* - up 3 decreases your aim by 3, resulting in a value of 2.
* - down 8 adds 8 to your aim, resulting in a value of 10.
* - forward 2 adds 2 to your horizontal position, a total of 15.
* Because your aim is 10, your depth increases by 2*10=20 to a total of 60.
*
* After following these new instructions, you would have a horizontal position
* of 15 and a depth of 60. (Multiplying these produces 900.)
*
* Using this new interpretation of the commands, 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?
*/
object Day2 {
fun part1(commands: Sequence<String>): Int = commands.calculateResult(P1Location())
fun part2(commands: Sequence<String>): Int = commands.calculateResult(P2Location())
private fun Sequence<String>.calculateResult(handler: BaseLocation): Int {
return fold(handler) { location, command ->
val (direction, distance) = command.split(" ")
location.handleCommand(direction, distance.toInt())
}.getResult()
}
class P1Location : BaseLocation() {
override fun handleCommand(direction: String, distance: Int): BaseLocation {
when (direction) {
"forward" -> x += distance
"up" -> y -= distance
"down" -> y += distance
}
return this
}
}
class P2Location : BaseLocation() {
private var aim = 0
override fun handleCommand(direction: String, distance: Int): BaseLocation {
when (direction) {
"forward" -> {
x += distance
y += aim * distance
}
"up" -> aim -= distance
"down" -> aim += distance
}
return this
}
}
abstract class BaseLocation {
protected var x: Int = 0
protected var y: Int = 0
abstract fun handleCommand(direction: String, distance: Int): BaseLocation
fun getResult(): Int = x * y
}
}
| 0 | Kotlin | 0 | 0 | 66553923d8d221bcd1bd108f701fceb41f4d1cbf | 4,832 | advent-of-code | MIT License |
leetcode2/src/leetcode/kthSmallest.kt | hewking | 68,515,222 | false | null | package leetcode
/**
* @Classname kthSmallest
* @Description TODO
* @Date 2020-05-16 14:00
* @Created by jianhao
* 给你一个 m * n 的矩阵 mat,以及一个整数 k ,矩阵中的每一行都以非递减的顺序排列。
你可以从每一行中选出 1 个元素形成一个数组。返回所有可能数组中的第 k 个 最小 数组和。
示例 1:
输入:mat = [[1,3,11],[2,4,6]], k = 5
输出:7
解释:从每一行中选出一个元素,前 k 个和最小的数组分别是:
[1,2], [1,4], [3,2], [3,4], [1,6]。其中第 5 个的和是 7 。
示例 2:
输入:mat = [[1,3,11],[2,4,6]], k = 9
输出:17
示例 3:
输入:mat = [[1,10,10],[1,4,5],[2,3,6]], k = 7
输出:9
解释:从每一行中选出一个元素,前 k 个和最小的数组分别是:
[1,1,2], [1,1,3], [1,4,2], [1,4,3], [1,1,6], [1,5,2], [1,5,3]。其中第 7 个的和是 9 。
示例 4:
输入:mat = [[1,1,10],[2,2,9]], k = 7
输出:12
*/
object KthSmallest {
class Solution {
fun kthSmallest(mat: Array<IntArray>, k: Int): Int {
val list = kthSmallestCombiles(mutableListOf(),mat)
val list2 = list.map { it -> it.reduce { acc, i ->
acc + i
} }
list2.sorted()
return list2[k]
}
fun kthSmallestCombiles(list:List<IntArray>,mat:Array<IntArray>): List<IntArray> {
val len = mat.size
return list
}
fun findArray(list:MutableList<IntArray>,mat:Array<IntArray>,res:IntArray){
if (res.size == mat.size) {
list.add(res)
return
}
}
}
} | 0 | Kotlin | 0 | 0 | a00a7aeff74e6beb67483d9a8ece9c1deae0267d | 1,679 | leetcode | MIT License |
LeetCode/0215. Kth Largest Element in an Array/Solution.kt | InnoFang | 86,413,001 | false | {"C++": 501928, "Kotlin": 291271, "Python": 280936, "Java": 78746, "Go": 43858, "JavaScript": 27490, "Rust": 6410} | /**
* Created by <NAME> on 2018/2/28.
*/
/**
* 31 / 31 test cases passed.
* Status: Accepted
* Runtime: 480 ms
*/
class Solution {
fun findKthLargest(nums: IntArray, k: Int): Int {
return partition(nums, k, 0, nums.lastIndex)
}
private fun partition(nums: IntArray, k: Int, start: Int, end: Int): Int {
var lo = start
var hi = end
while (lo < hi) {
while (lo < hi && nums[hi] <= nums[start]) hi--
while (lo < hi && nums[lo] >= nums[start]) lo++
if (lo < hi) (nums[hi] to nums[lo]).run { nums[lo] = first; nums[hi] = second }
}
(nums[start] to nums[hi]).run { nums[start] = second; nums[hi] = first }
return when {
lo == k - 1 -> {
nums[lo]
}
lo > k - 1 -> partition(nums, k, start, lo - 1)
else -> partition(nums, k, lo + 1, end)
}
}
}
/**
* 31 / 31 test cases passed.
* Status: Accepted
* Runtime: 332 ms
*/
class Solution2 {
fun findKthLargest(nums: IntArray, k: Int): Int {
val que = java.util.PriorityQueue<Int>()
nums.forEach {
que.offer(it)
if (que.size > k) que.poll()
}
return que.peek()
}
}
fun main(args: Array<String>) {
Solution2().findKthLargest(intArrayOf(3, 5, 9, 1, 4, 7, 2, 6, 8, 0), 3).let(::println)
} | 0 | C++ | 8 | 20 | 2419a7d720bea1fd6ff3b75c38342a0ace18b205 | 1,385 | algo-set | Apache License 2.0 |
src/day01/Day01.kt | tschens95 | 573,743,557 | false | {"Kotlin": 32775} | fun main() {
fun part1(input: String): Int {
val elves = input.split("\r\n\r\n")
val mapElveToCalories = elves.map { it.split("\r\n").sumOf { ele -> Integer.parseInt(ele) } }
return mapElveToCalories.max()
}
fun part2(input: String): Int {
val elves = input.split("\r\n\r\n")
val mapElveToCalories = elves.map { it.split("\r\n").sumOf { ele -> Integer.parseInt(ele) } }
val mutableList = mapElveToCalories.toMutableList()
var tempSum = 0
for (i in 0..2) {
val currMax = mutableList.max()
tempSum += currMax
mutableList.remove(currMax)
}
return tempSum
}
val input = readText("01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 2 | 9d78a9bcd69abc9f025a6a0bde923f53c2d8b301 | 773 | AdventOfCode2022 | Apache License 2.0 |
src/002.kt | brunopessanha | 269,604,204 | false | null | package bruno.euler
/**
* PROBLEM 2
*
* Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
* 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
* By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
*/
const val finalValue = 4e6
tailrec fun fibonacci(n: Int, first: Int = 1, second: Int = 2) : Int = when (n) {
1 -> first
2 -> second
else -> fibonacci(n-1, second, first + second)
}
private fun isEven(value: Int) = value % 2 == 0
private fun saveFibonacciTermsUntilLimit() : List<Int> {
val list = mutableListOf<Int>()
var n = 0
var currentValue = 0
while (currentValue < finalValue) {
currentValue = fibonacci(n)
list.add(currentValue)
n++
}
return list
}
private fun sumEvenFibonacciTerms(list: List<Int>) : Int {
return list.filter { isEven(it) }.sum()
}
fun main() {
val begin = System.currentTimeMillis()
val fibonacciTerms = saveFibonacciTermsUntilLimit()
val sum = sumEvenFibonacciTerms(fibonacciTerms)
val end = System.currentTimeMillis()
println("Time Elapsed: ${end - begin}ms # Value = $sum")
}
| 0 | Kotlin | 0 | 0 | f3533b81013f7f0486dbea3e49e158201793c115 | 1,297 | euler-kt | Apache License 2.0 |
kotlin/src/com/s13g/aoc/aoc2019/Day13.kt | shaeberling | 50,704,971 | false | {"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245} | package com.s13g.aoc.aoc2019
import com.s13g.aoc.Result
import com.s13g.aoc.Solver
import java.lang.RuntimeException
/** https://adventofcode.com/2019/day/13 */
class Day13 : Solver {
override fun solve(lines: List<String>): Result {
val programA = lines[0].split(",").map { it.toLong() }.toMutableList()
programA.addAll(Array(1000) { 0L })
val gameA = Game(VM19(programA, mutableListOf()))
gameA.run()
val countA = gameA.map.values.count { it == 2L }
val programB = lines[0].split(",").map { it.toLong() }.toMutableList()
programB.addAll(Array(1000) { 0L })
programB[0] = 2L // Play for free
val gameB = Game(VM19(programB, mutableListOf()))
gameB.run()
return Result("$countA", "${gameB.score}")
}
private class Game(val vm: VM19) : VM19.VmIO {
val map = hashMapOf<XY, Long>()
var score = 0L
val ballPos = XY(0, 0)
val paddlePos = XY(0, 0)
var outCounter = 0
val lastOut = Out(0L, 0L, 0L)
init {
vm.vmIo = this
}
fun run() {
while (true) {
if (!vm.step()) {
return
}
}
}
override fun onInput(): Long {
// Move the paddle where the ball is.
if (ballPos.x > paddlePos.x) {
return 1
} else if (ballPos.x < paddlePos.x) {
return -1
} else {
return 0
}
}
override fun onOutput(v: Long) {
if (outCounter == 0) {
lastOut.a = v
} else if (outCounter == 1) {
lastOut.b = v
} else {
lastOut.c = v
onOutput(lastOut)
}
outCounter = (outCounter + 1) % 3
}
private fun onOutput(out: Out) {
if (out.a == -1L && out.b == 0L) {
score = out.c
} else {
map[XY(out.a, out.b)] = out.c
if (out.c == 4L) {
ballPos.x = out.a
ballPos.y = out.b
} else if (out.c == 3L) {
paddlePos.x = out.a
paddlePos.y = out.b
}
}
}
private fun printMap() {
val minX = map.keys.map { it.x }.min()!!
val maxX = map.keys.map { it.x }.max()!!
val minY = map.keys.map { it.y }.min()!!
val maxY = map.keys.map { it.y }.max()!!
for (y in minY..maxY) {
for (x in minX..maxX) {
print(getChar(map[XY(x, y)]))
}
println()
}
}
private fun getChar(c: Long?) = when (c) {
0L -> " "
1L -> "#"
2L -> "*"
3L -> "-"
4L -> "o"
null -> " "
else -> throw RuntimeException("Illegal tile type")
}
}
private data class Out(var a: Long, var b: Long, var c: Long)
private data class XY(var x: Long, var y: Long)
} | 0 | Kotlin | 1 | 2 | 7e5806f288e87d26cd22eca44e5c695faf62a0d7 | 2,670 | euler | Apache License 2.0 |
src/Day10.kt | WilsonSunBritten | 572,338,927 | false | {"Kotlin": 40606} | fun main() {
fun part1(input: List<String>): Int {
val xIterator = input.map {
if (it == "noop") {
NOOP()
} else {
ADD(it.split(" ")[1].toInt())
}
}.flatMap { command ->
when(command) {
is NOOP -> { listOf({ x: Int -> x}) }
is ADD -> { listOf({x: Int -> x}, {x: Int -> x + command.value })}
}
}.iterator()
val cycleStream = generateSequence(1) { it + 1 }
val cyclePoints = cycleStream.runningFold(1) { currentXRegister, cycleIndex ->
val nextCommandValueChange = xIterator.next()
nextCommandValueChange.invoke(currentXRegister)
}.takeWhile { xIterator.hasNext() }.toList()
return listOf(
20, 60, 100, 140, 180, 220
).map { it * cyclePoints[it - 1] }
.sum()
}
fun part2(input: List<String>): String {
val xIterator = input.map {
if (it == "noop") {
NOOP()
} else {
ADD(it.split(" ")[1].toInt())
}
}.flatMap { command ->
when(command) {
is NOOP -> { listOf({ x: Int -> x}) }
is ADD -> { listOf({x: Int -> x}, {x: Int -> x + command.value })}
}
}.iterator()
val cycleStream = generateSequence(1) { it + 1 }
val cyclePointsIterator = cycleStream.runningFold(1) { currentXRegister, cycleIndex ->
val nextCommandValueChange = xIterator.next()
nextCommandValueChange.invoke(currentXRegister)
}.takeWhile { xIterator.hasNext() }.toList().iterator()
val stringBuilder = StringBuilder()
// 40 by 6
(0 until 240).forEach { pixel ->
val position = pixel % 40
if (position == 0 && pixel != 0) {
stringBuilder.append('\n')
}
val cyclePointValue = cyclePointsIterator.next()
if (position in setOf(cyclePointValue - 1, cyclePointValue, cyclePointValue + 1)) {
stringBuilder.append('#')
} else {
stringBuilder.append('.')
}
}
return stringBuilder.toString()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day10_test")
val input = readInput("Day10")
val p1TestResult = part1(testInput)
println(p1TestResult)
check(p1TestResult == 13140)
println(part1(input))
println("Part 2")
val p2TestResult = part2(testInput)
println(p2TestResult)
check(p2TestResult == """##..##..##..##..##..##..##..##..##..##..
###...###...###...###...###...###...###.
####....####....####....####....####....
#####.....#####.....#####.....#####.....
######......######......######......####
#######.......#######.......#######.....""")
println(part2(input))
}
sealed interface Command {
val cycles: Int
}
class NOOP : Command {
override val cycles = 1
}
data class ADD(val value: Int) : Command {
override val cycles = 1
} | 0 | Kotlin | 0 | 0 | 363252ffd64c6dbdbef7fd847518b642ec47afb8 | 3,125 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/main/kotlin/nl/jackploeg/aoc/_2023/calendar/day12/Day12.kt | jackploeg | 736,755,380 | false | {"Kotlin": 318734} | package nl.jackploeg.aoc._2023.calendar.day12
import nl.jackploeg.aoc.generators.InputGenerator.InputGeneratorFactory
import nl.jackploeg.aoc.utilities.readStringFile
import nl.jackploeg.aoc.utilities.repeatString
import javax.inject.Inject
class Day12 @Inject constructor(
private val generatorFactory: InputGeneratorFactory,
) {
fun countValidPermutationsInLineFromIndex(
line: String,
requiredGroups: List<Int>,
index: Int = 0,
numberOfGroupsFound: Int = 0,
currentGroupSize: Int = 0,
cache: MutableMap<kotlin.Triple<Int, Int, Int>, Long> = mutableMapOf()
): Long {
val cacheKey = Triple(index, numberOfGroupsFound, currentGroupSize)
cache[cacheKey]?.let { return it }
if (index == line.length) {
// all required groups found and no extra group after it in the pattern
if (numberOfGroupsFound == requiredGroups.size && currentGroupSize == 0) {
return 1
}
// all required groups found, last group ends at end of pattern
if (numberOfGroupsFound == requiredGroups.size - 1 && requiredGroups[numberOfGroupsFound] == currentGroupSize) {
return 1
}
// too few or too many groups found
return 0
}
var possibleSolutionCount: Long = 0
val char = line[index]
// reached a group or still in a group
if (char == '#' || char == '?') {
possibleSolutionCount += countValidPermutationsInLineFromIndex(
line, requiredGroups, index + 1, numberOfGroupsFound, currentGroupSize + 1, cache
)
}
// not in a group or ending a group
if ((char == '.' || char == '?')) {
val notInAGroup = currentGroupSize == 0
if (notInAGroup) {
possibleSolutionCount += countValidPermutationsInLineFromIndex(
line, requiredGroups, index + 1, numberOfGroupsFound, 0, cache
)
} else if (
numberOfGroupsFound < requiredGroups.size &&
requiredGroups[numberOfGroupsFound] == currentGroupSize
) {
// found a group
possibleSolutionCount += countValidPermutationsInLineFromIndex(
line, requiredGroups, index + 1, numberOfGroupsFound + 1, 0, cache
)
}
}
// add to cache for next time we get here
cache[cacheKey] = possibleSolutionCount
return possibleSolutionCount
}
fun countValidPermutationsInFile(fileName: String, repeat: Int): Long {
val lines = readStringFile(fileName)
val rows: MutableList<String> = mutableListOf()
val scores: MutableList<List<Int>> = mutableListOf()
lines.forEach { it ->
val (group, score) = it.split(" ")
rows.add(repeatString(group, repeat, '?'))
scores.add(repeatString(score, repeat, ',').split(',').map { it.toInt() })
}
return rows.mapIndexed { index, row -> countValidPermutationsInLineFromIndex(row, scores[index]) }.sum()
}
}
| 0 | Kotlin | 0 | 0 | f2b873b6cf24bf95a4ba3d0e4f6e007b96423b76 | 2,855 | advent-of-code | MIT License |
src/Day19.kt | syncd010 | 324,790,559 | false | null | class Day19: Day {
private fun convert(input: List<String>) : List<Long> {
return input[0].split(",").map { it.toLong() }
}
override fun solvePartOne(input: List<String>): Int {
val initialMem = convert(input)
val computer = Intcode(initialMem)
val grid = List(50) { MutableList(50) { ' ' } }
for (x in 0..49) {
for (y in 0..49) {
computer.reset(initialMem)
val res = computer.execute(listOf(x.toLong(), y.toLong()))
grid[y][x] = if (res.first() == 1L) '#' else '.'
}
}
// grid.forEach() { println(it.joinToString("")) }
return grid.sumBy { it.count { it == '#' } }
}
override fun solvePartTwo(input: List<String>): Long {
val initialMem = convert(input)
val computer = Intcode(initialMem)
var y = 100L
var x = 0L
while (true) {
val bottomLeft = computer.run {
reset(initialMem)
execute(listOf(x, y))
}.first()
if (bottomLeft != 1L) {
x++
continue
}
val bottomRight = computer.run {
reset(initialMem)
execute(listOf(x + 99, y))
}.first()
val topLeft = computer.run {
reset(initialMem)
execute(listOf(x, y - 99))
}.first()
val topRight = computer.run {
reset(initialMem)
execute(listOf(x + 99, y - 99))
}.first()
if (topLeft != 1L || topRight != 1L || bottomRight != 1L) {
y++
continue
}
return x * 10000 + y - 99
}
}
} | 0 | Kotlin | 0 | 0 | 11c7c7d6ccd2488186dfc7841078d9db66beb01a | 1,834 | AoC2019 | Apache License 2.0 |
src/main/kotlin/Solution.kt | ShizoCactus | 666,096,274 | false | null |
import exceptions.NoSuchCourseException
import exceptions.NoSuchStudentException
import java.io.File
class Solution(
listVarientsFileName: String,
averageScoresFileName: String,
studentChoicesFileName: String
) {
private val courses = mutableListOf<Course>()
private val scores = mutableMapOf<String, List<Double>>()
private val uniqueStudentNames = mutableListOf<String>()
private val students = mutableListOf<Student>()
private val conflicts = mutableListOf<ConflictInfo>()
private var firstConflictedStudent: Student? = null
init {
File(listVarientsFileName).forEachLine { addStringAsCourseInfo(it) }
File(averageScoresFileName).forEachLine { addStringAsScoreInfo(it) }
File(studentChoicesFileName).forEachLine { addStringAsStudentInfo(it) }
}
private fun addStringAsCourseInfo(string: String){
val temp = string.split("\t")
val name = temp[0]
val maxStudentsCount = temp[1].toInt()
val groups = temp[2].split(",")
val students = mutableListOf<Student>()
val course = Course(name,0, maxStudentsCount, groups, students)
courses.add(course)
}
private fun addStringAsScoreInfo(string: String){
val temp = string.split("\t")
val name = temp[0]
val averageScores = mutableListOf<Double>()
temp.drop(1).forEach { averageScores.add(it.toDouble()) }
scores[name] = averageScores
}
private fun addStringAsStudentInfo(string: String){
val temp = string.split("\t").drop(1)
val name = temp[0]
val groupNumber = temp[1]
val priorities = temp.drop(2)
if (name in scores.keys){
if (name in uniqueStudentNames){
val oldStudent = findStudentByName(name)
students.remove(oldStudent)
}
else
uniqueStudentNames.add(name)
val averageScores = scores[name]
val newStudent = Student(name, groupNumber, priorities, averageScores!!)
students.add(newStudent)
}
}
private fun findStudentByName(name: String): Student{
for (student in students)
if (student.name == name)
return student
throw NoSuchStudentException()
}
private fun findCourseByName(name: String): Course{
for (course in courses)
if (course.name == name)
return course
throw NoSuchCourseException()
}
private fun compareWithLastOnCourse(student: Student, course: Course): Boolean{
return student.compareTo(course.students[course.maxStudentsCount - 1]) == 0
}
private fun distributeStudents(){
students.sortDescending()
for (i in 0 until students.size){
val student = students[i]
for (k in 0 until student.priorities.size){
val course = findCourseByName(student.priorities[k])
if (course.studentsCount < course.maxStudentsCount || compareWithLastOnCourse(student, course)){
val res = course.addStudent(student)
if (res) {
if (course.studentsCount == course.maxStudentsCount + 1 && firstConflictedStudent == null)
firstConflictedStudent = student
break
}
}
}
}
}
private fun collectConflictInfo(){
for (course in courses){
if (course.getOccupancy() > 100){
val conflict = ConflictInfo(course.name)
for (student in course.students)
if (compareWithLastOnCourse(student, course))
conflict.students.add(student)
conflicts.add(conflict)
}
}
}
private fun getDistributionInfo(): String{
var str = ""
for (course in courses) {
str += "Курс $course заполнен на ${course.getOccupancy()}%\n"
str += "На курсе будут учиться:\n"
for (student in course.students)
str += "\t" + student
str += "\n\n"
}
return str
}
private fun getConflictInfo(): String{
var str = ""
for (conflict in conflicts){
str += "Направлении ${conflict.courseName} переполнено, потому что есть ${conflict.students.size} студентов с одинаковыми баллами\n"
for (student in conflict.students)
str += "\t" + student
str += "\n"
}
return str
}
private fun getFirstConflictedStudentInfo(): String {
return if (firstConflictedStudent == null)
"Проблем нет"
else
"Первый студент, расширивший направление - $firstConflictedStudent"
}
private fun printDistribution(){
println(getDistributionInfo())
}
private fun printConflictInfo(){
println(getConflictInfo())
}
private fun printFirstConflictedStudentInfo(){
println(getFirstConflictedStudentInfo())
}
private fun saveDistribution(){
val file = File("distribution.txt")
file.writeText(getDistributionInfo(), charset = Charsets.UTF_8)
}
private fun saveConflictInfo(){
val file = File("conflict_info.txt")
file.writeText(getConflictInfo(), charset = Charsets.UTF_8)
}
private fun saveFirstConflictedStudentInfo(){
val file = File("first_conflicted_student.txt")
file.writeText(getFirstConflictedStudentInfo(), charset = Charsets.UTF_8)
}
private fun printResult(){
printDistribution()
println()
printConflictInfo()
println()
printFirstConflictedStudentInfo()
}
private fun saveResult(){
saveDistribution()
saveConflictInfo()
saveFirstConflictedStudentInfo()
}
fun solve(){
distributeStudents()
collectConflictInfo()
printResult()
saveResult()
}
} | 0 | Kotlin | 0 | 0 | 41b6b4251998f670bc6054b17741b3419d59d959 | 6,201 | uchebnaya-praktika-leti-compose | Apache License 2.0 |
src/main/kotlin/me/peckb/aoc/_2015/calendar/day24/Day24.kt | peckb1 | 433,943,215 | false | {"Kotlin": 956135} | package me.peckb.aoc._2015.calendar.day24
import javax.inject.Inject
import me.peckb.aoc.generators.InputGenerator.InputGeneratorFactory
import kotlin.math.min
class Day24 @Inject constructor(private val generatorFactory: InputGeneratorFactory) {
/**
* There are sums that hit our `evenThreePoint` using only five numbers, so find the smallest six
*/
fun partOne(filename: String) = generatorFactory.forFile(filename).readAs(::`package`) { input ->
val packages = input.toList()
val evenThreePoint = packages.sum() / 3
var bestSixSum = Long.MAX_VALUE
packages.indices.forEach { a ->
val pa = packages[a]
(a + 1 until packages.size).forEach { b ->
val pb = packages[b]
(b + 1 until packages.size).forEach { c ->
val pc = packages[c]
(c + 1 until packages.size).forEach { d ->
val pd = packages[d]
(d + 1 until packages.size).forEach { e ->
val pe = packages[e]
(e + 1 until packages.size).forEach { f ->
val pf = packages[f]
val sixSum = pa + pb + pc + pd + pe + pf
if (sixSum == evenThreePoint) {
bestSixSum = min(bestSixSum, pa * pb * pc * pd * pe * pf)
}
}
}
}
}
}
}
bestSixSum
}
/**
* There are sums that hit our `evenFourPoint` using only four numbers, so find the smallest five
*/
fun partTwo(filename: String) = generatorFactory.forFile(filename).readAs(::`package`) { input ->
val packages = input.toList()
val evenFourPoint = packages.sum() / 4
var bestFiveSum = Long.MAX_VALUE
packages.indices.forEach { a ->
val pa = packages[a]
(a + 1 until packages.size).forEach { b ->
val pb = packages[b]
(b + 1 until packages.size).forEach { c ->
val pc = packages[c]
(c + 1 until packages.size).forEach { d ->
val pd = packages[d]
(d + 1 until packages.size).forEach { e ->
val pe = packages[e]
val fiveSum = pa + pb + pc + pd + pe
if (fiveSum == evenFourPoint) {
bestFiveSum = min(bestFiveSum, pa * pb * pc * pd * pe)
}
}
}
}
}
}
bestFiveSum
}
private fun `package`(line: String) = line.toLong()
}
| 0 | Kotlin | 1 | 3 | 2625719b657eb22c83af95abfb25eb275dbfee6a | 2,396 | advent-of-code | MIT License |
src/day04/Main.kt | nikwotton | 572,814,041 | false | {"Kotlin": 77320} | package day04
import java.io.File
const val workingDir = "src/day04"
fun main() {
val sample = File("$workingDir/sample.txt")
val input1 = File("$workingDir/input_1.txt")
println("Step 1a: ${runStep1(sample)}")
println("Step 1b: ${runStep1(input1)}")
println("Step 2a: ${runStep2(sample)}")
println("Step 2b: ${runStep2(input1)}")
}
fun runStep1(input: File): String {
return input.readLines().map {
val (a, b) = it.split(",")
val (amin, amax) = a.split("-").map { it.toInt() }
val (bmin, bmax) = b.split("-").map { it.toInt() }
if ((amin <= bmin && amax >= bmax) || (bmin <= amin && bmax >= amax)) 1 else 0
}.sum().toString()
}
fun runStep2(input: File): String {
return input.readLines().map {
val (a, b) = it.split(",")
val (amin, amax) = a.split("-").map { it.toInt() }
val (bmin, bmax) = b.split("-").map { it.toInt() }
if (((amin..amax).intersect(bmin..bmax)).isEmpty()) 0 else 1
}.sum().toString()
}
| 0 | Kotlin | 0 | 0 | dee6a1c34bfe3530ae6a8417db85ac590af16909 | 1,016 | advent-of-code-2022 | Apache License 2.0 |
plugins/core/src/main/kotlin/de/fayard/refreshVersions/core/internal/ArtifactVersionKeysReading.kt | Splitties | 150,827,271 | false | {"Kotlin": 808317, "Shell": 2793, "Just": 1182, "Java": 89, "Groovy": 24} | package de.fayard.refreshVersions.core.internal
import de.fayard.refreshVersions.core.ModuleId
@InternalRefreshVersionsApi
abstract class ArtifactVersionKeyReader private constructor(
val getRemovedDependenciesVersionsKeys: () -> Map<ModuleId.Maven, String>
) {
abstract fun readVersionKey(group: String, name: String): String?
companion object {
fun fromRules(
filesContent: List<String>,
getRemovedDependenciesVersionsKeys: () -> Map<ModuleId.Maven, String> = { emptyMap() }
): ArtifactVersionKeyReader {
val rules = filesContent.flatMap { parseArtifactVersionKeysRules(it) }.sortedDescending()
return object : ArtifactVersionKeyReader(getRemovedDependenciesVersionsKeys) {
override fun readVersionKey(group: String, name: String): String? {
var foundRule: ArtifactVersionKeyRule? = null
for (rule in rules) if (rule.matches(group, name)) {
if (foundRule == null) foundRule = rule
// Let exact matches take precedence, even if they're not the longest matching rule.
if (rule.onlyExactMatches()) {
foundRule = rule
break
}
}
return foundRule?.key(group, name)
}
}
}
}
}
internal fun parseArtifactVersionKeysRules(fileContent: String): List<ArtifactVersionKeyRule> {
val lines = fileContent.lineSequence()
.map {
val indexOfLineComment = it.indexOf("//")
if (indexOfLineComment == -1) it else it.substring(startIndex = 0, endIndex = indexOfLineComment)
}
.filter { it.isNotBlank() }
.map { it.trimEnd() }
.toList()
require(lines.size % 2 == 0) {
"Every artifact version key rule is made of two lines, but an odd count of rules lines has been found."
}
return MutableList(lines.size / 2) { i ->
ArtifactVersionKeyRule(
artifactPattern = lines[i * 2],
versionKeyPattern = lines[i * 2 + 1]
)
}
}
| 113 | Kotlin | 109 | 1,606 | df624c0fb781cb6e0de054a2b9d44808687e4fc8 | 2,195 | refreshVersions | MIT License |
src/medium/_17LetterCombinationsOfAPhoneNumber.kt | ilinqh | 390,190,883 | false | {"Kotlin": 382147, "Java": 32712} | package medium
class _17LetterCombinationsOfAPhoneNumber {
class Solution {
fun letterCombinations(digits: String): List<String> {
if (digits.isEmpty()) {
return emptyList()
}
val sb = StringBuffer()
val resultList: ArrayList<String> = ArrayList()
backtrack(resultList, digits, 0, sb)
return resultList
}
private fun backtrack(resultList: ArrayList<String>, digits: String, index: Int, sb: StringBuffer) {
if (index == digits.length) {
resultList.add(sb.toString())
return
}
val array = getArrayByChar(digits[index])
for (char in array) {
sb.append(char)
backtrack(resultList, digits, index + 1, sb)
sb.delete(index, sb.length)
}
}
private fun getArrayByChar(char: Char): String {
when (char) {
'2' -> return "abc"
'3' -> return "def"
'4' -> return "ghi"
'5' -> return "jkl"
'6' -> return "mno"
'7' -> return "pqrs"
'8' -> return "tuv"
'9' -> return "wxyz"
}
return ""
}
}
class BestSolution {
fun letterCombinations(digits: String): List<String> {
val str = arrayOf("abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz")
var list = mutableListOf<String>()
for (element in digits) {
list = traceback(str[(element - 2).toString().toInt()], list)
}
return list
}
private fun traceback(str: String, list: List<String>): MutableList<String> {
val lists = mutableListOf<String>()
if (list.isNotEmpty()) {
for (i in list) {
for (j in str) {
lists.add(i + j)
}
}
} else {
for (element in str) {
lists.add(element.toString())
}
}
return lists
}
}
} | 0 | Kotlin | 0 | 0 | 8d2060888123915d2ef2ade293e5b12c66fb3a3f | 2,076 | AlgorithmsProject | Apache License 2.0 |
src/test/kotlin/chapter4/solutions/ex6/listing.kt | DavidGomesh | 680,857,367 | false | {"Kotlin": 204685} | package chapter4.solutions.ex6
import chapter4.Either
import chapter4.Left
import chapter4.Right
import chapter4.flatMap
import io.kotest.matchers.shouldBe
import io.kotest.core.spec.style.WordSpec
//tag::init[]
fun <E, A, B> Either<E, A>.map(f: (A) -> B): Either<E, B> =
when (this) {
is Left -> this
is Right -> Right(f(this.value))
}
fun <E, A> Either<E, A>.orElse(f: () -> Either<E, A>): Either<E, A> =
when (this) {
is Left -> f()
is Right -> this
}
fun <E, A, B, C> map2(
ae: Either<E, A>,
be: Either<E, B>,
f: (A, B) -> C
): Either<E, C> =
ae.flatMap { a -> be.map { b -> f(a, b) } }
//end::init[]
class Solution6 : WordSpec({
val right: Either<Throwable, Int> = Right(1)
val left: Either<Throwable, Int> = Left(Throwable("boom"))
"Either.map" should {
"transform a right value" {
right.map { it.toString() } shouldBe Right("1")
}
"pass over a left value" {
left.map { it.toString() } shouldBe left
}
}
"Either.orElse" should {
"return the either if it is right" {
right.orElse { left } shouldBe right
}
"pass the default value if either is left" {
left.orElse { right } shouldBe right
}
}
"Either.flatMap" should {
"apply a function yielding an either to a right either" {
right.flatMap { a ->
Right(a.toString())
} shouldBe Right("1")
}
"pass on the left value" {
left.flatMap { a ->
Right(a.toString())
} shouldBe left
}
}
"Either.map2" should {
val right1: Right<Int> = Right(3)
val right2: Right<Int> = Right(2)
val left1: Either<Throwable, Int> =
Left(IllegalArgumentException("boom"))
val left2: Either<Throwable, Int> =
Left(IllegalStateException("pow"))
"combine two either right values using a binary function" {
map2(
right1,
right2
) { a, b ->
(a * b).toString()
} shouldBe Right("6")
}
"return left if either is left" {
map2(
right1,
left1
) { a, b ->
(a * b).toString()
} shouldBe left1
}
"return the first left if both are left" {
map2(
left1,
left2
) { a, b ->
(a * b).toString()
} shouldBe left1
}
}
})
| 0 | Kotlin | 0 | 0 | 41fd131cd5049cbafce8efff044bc00d8acddebd | 2,623 | fp-kotlin | MIT License |
solution/#3 Longest Substring Without Repeating Characters/Solution.kt | enihsyou | 116,918,868 | false | {"Java": 179666, "Python": 36379, "Kotlin": 32431, "Shell": 367} | package leetcode.q3.kotlin;
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.Arguments
import org.junit.jupiter.params.provider.MethodSource
class Solution {
fun lengthOfLongestSubstring(s: String): Int {
val n = s.length
var max = 0
val cache = mutableMapOf<Char, Int>() // <当前包含的字符, 出现的index>
var j = 0
var i = 0
while (j < n) {
val current_char = s[j]
if (cache.containsKey(current_char)) {
/*如果在下一个字符发现了重复,可以直接跳到j的下一个,因为[i, j]都被最后两个重复字符给可惜掉了*/
i = Integer.max(cache[current_char]!!, i)
}
max = Integer.max(max, j - i + 1) // +1是因为自身算一个
cache.put(current_char, j + 1) // 如果发生了重复,下一个搜索起点在这
j++
}
return max
}
fun lengthOfLongestSubstring2(s: String): Int {
val array = s.toCharArray()
var max = 0
for (index in array.indices) {
val cache = mutableSetOf<Char>()
var p = index
do {
cache += array[p]
p++
} while (p < array.size && !cache.contains(array[p]))
max = Integer.max(max, p - index)
}
return max
}
}
class SolutionTest {
private val solution = Solution()
@ParameterizedTest(name = "lengthOfLongestSubstring({0}) = {1}")
@MethodSource("provider")
fun lengthOfLongestSubstring(input: String, output: Int) {
Assertions.assertEquals(solution.lengthOfLongestSubstring(input), output)
}
companion object {
@JvmStatic
fun provider(): List<Arguments> {
return listOf(
Arguments.of("abcabcbb", 3),
Arguments.of("bbbbb", 1),
Arguments.of("pwwkew", 3),
Arguments.of("dfaergsbcsbfrehsddf", 9),
Arguments.of("tmmzuxt", 5)
)
}
}
}
| 1 | Java | 0 | 0 | 230325d1dfd666ee53f304edf74c9c0f60f81d75 | 2,136 | LeetCode | MIT License |
src/main/kotlin/com/jackchapman/adventofcode/Day06.kt | crepppy | 317,691,375 | false | null | package com.jackchapman.adventofcode
fun solveDay6(): Pair<Int, Int> {
val groupAnswers = getInput(6).joinToString("\n").split("\n\n")
val answered = groupAnswers.map { questionsAnswered(it) }
val commonAnswers = groupAnswers.map { questionsEveryoneAnswered(it) }
return answered.sum() to commonAnswers.sum()
}
// Completed in 1min 58seconds
fun questionsAnswered(group: String): Int {
val s = group.toCharArray().toMutableSet()
s.remove('\n')
return s.size
}
// Completed in 3mins 26seconds
fun questionsEveryoneAnswered(group: String): Int {
val questions = group.toCharArray().toMutableSet()
val size = group.lines().size
questions.remove('\n')
return questions.count { group.count { c -> c == it } == size }
}
| 0 | Kotlin | 0 | 0 | b49bb8f62b4542791626950846ca07d1eff4f2d1 | 765 | aoc2020 | The Unlicense |
src/main/kotlin/codes/jakob/aoc/solution/Solution.kt | The-Self-Taught-Software-Engineer | 433,875,929 | false | {"Kotlin": 56277} | @file:Suppress("unused")
package codes.jakob.aoc.solution
import java.io.File
import java.nio.file.Path
import java.nio.file.Paths
import java.util.*
abstract class Solution {
abstract fun solvePart1(input: String): Any
abstract fun solvePart2(input: String): Any
private val identifier: String = getClassName()
fun solve() {
val input: String = retrieveInput()
println("Solution for part 1: ${solvePart1(input)}")
println("Solution for part 2: ${solvePart2(input)}")
}
private fun retrieveInput(): String {
val inputDirectoryPath: Path = Paths.get("").resolve(INPUT_PATH).toAbsolutePath()
return File("$inputDirectoryPath/$identifier.$INPUT_FILE_EXTENSION").readText()
}
private fun getClassName(): String = this::class.simpleName.toString()
companion object {
const val INPUT_PATH = "src/main/resources/inputs"
const val INPUT_FILE_EXTENSION = "txt"
}
}
fun String.splitMultiline(): List<String> = split("\n")
fun Int.isEven(): Boolean = this % 2 == 0
fun Int.isOdd(): Boolean = !isEven()
fun <E> List<E>.middleOrNull(): E? {
return if (this.count().isOdd()) this[this.count() / 2] else null
}
fun <T> Iterable<T>.productOf(selector: (T) -> Int): Int {
var product = 1
for (element in this) product *= selector(element)
return product
}
/**
* Calculates the [triangular number](https://en.wikipedia.org/wiki/Triangular_number) of the given number.
*/
fun Long.triangular(): Long = ((this * (this + 1)) / 2)
fun CharSequence.toSingleChar(): Char {
require(this.count() == 1) { "The given CharSequence has more than one element" }
return this.first()
}
operator fun <T> T.plus(collection: Collection<T>): List<T> {
val result = ArrayList<T>(collection.size + 1)
result.add(this)
result.addAll(collection)
return result
}
fun <T, K> Collection<T>.countBy(keySelector: (T) -> K): Map<K, Int> {
return this.groupingBy(keySelector).eachCount()
}
fun List<Int>.binaryToDecimal(): Int {
require(this.all { it == 0 || it == 1 }) { "Expected bit string, but received $this" }
return Integer.parseInt(this.joinToString(""), 2)
}
fun Int.bitFlip(): Int {
require(this == 0 || this == 1) { "Expected bit, but received $this" }
return this.xor(1)
}
fun String.toBitString(): List<Int> {
val bits: List<String> = split("").filter { it.isNotBlank() }
require(bits.all { it == "0" || it == "1" }) { "Expected bit string, but received $this" }
return bits.map { it.toInt() }
}
/**
* [Transposes](https://en.wikipedia.org/wiki/Transpose) the given list of nested lists (a matrix, in essence).
*
* This function is adapted from this [post](https://stackoverflow.com/a/66401340).
*/
fun <T> List<List<T>>.transpose(): List<List<T>> {
val result: MutableList<MutableList<T>> = (this.first().indices).map { mutableListOf<T>() }.toMutableList()
this.forEach { columns -> result.zip(columns).forEach { (rows, cell) -> rows.add(cell) } }
return result
}
/**
* Returns any given [Map] with its keys and values reversed (i.e., the keys becoming the values and vice versa).
* Note in case of duplicate values, they will be overridden in the key-set unpredictably.
*/
fun <K, V> Map<K, V>.reversed(): Map<V, K> {
return HashMap<V, K>(this.count()).also { reversedMap: HashMap<V, K> ->
this.entries.forEach { reversedMap[it.value] = it.key }
}
}
fun <E> Stack<E>.peekOrNull(): E? {
return if (this.isNotEmpty()) this.peek() else null
}
| 0 | Kotlin | 0 | 6 | d4cfb3479bf47192b6ddb9a76b0fe8aa10c0e46c | 3,541 | advent-of-code-2021 | MIT License |
scripts/profiling/SummarizeCSV.kts | TIBHannover | 197,416,205 | false | {"Kotlin": 3096016, "Cypher": 217169, "Python": 4881, "Groovy": 1936, "Shell": 1803, "HTML": 240} | #!/usr/bin/env kscript
import java.io.File
val file = args.getOrElse(0) { "result.csv" }
val results = readCSV(file)
var totalTimeA: Long = 0
var totalTimeB: Long = 0
var totalMethodCount = 0
results.forEach { (repo, measurements) ->
val methodToResult = computeMethodResults(measurements)
var time: Long = 0
var methodCount = 0
println("$repo:")
methodToResult.forEach { (method, result) ->
print(" ")
print("avg: ${result.average} ")
print("median: ${result.median} ")
println(method)
time += result.average
methodCount++
}
println("Repository average: ${time.toDouble() / methodCount}")
println()
totalTimeA += time
totalMethodCount += methodCount
}
println("Total average: ${totalTimeA.toDouble() / totalMethodCount}")
fun computeMethodResults(measurements: List<Measurement>): Map<String, ProfilingResult> {
val methodToResult: MutableMap<String, MutableList<Long>> = mutableMapOf()
measurements.forEach {
methodToResult.getOrPut(it.method) { mutableListOf() } += it.time
}
return methodToResult.mapValues { (_, times) ->
ProfilingResult(times.sum() / times.size, times.median())
}
}
fun readCSV(csv: String): MutableMap<String, MutableList<Measurement>> {
val result: MutableMap<String, MutableList<Measurement>> = mutableMapOf()
File(csv).useLines { lines ->
lines.forEach { line ->
val split = line.split(",")
val measurement = Measurement(
repository = split[0],
method = split[1],
time = split[2].toLong()
)
result.getOrPut(measurement.repository) { mutableListOf() } += measurement
}
}
return result
}
data class Measurement(
val repository: String,
val method: String,
val time: Long
)
data class ProfilingResult(
val average: Long,
val median: Long
)
fun List<Long>.median() =
sorted().let {
if (size % 2 == 0)
(this[size / 2] + this[(size - 1) / 2]) / 2
else
this[size / 2]
}
| 0 | Kotlin | 1 | 4 | bcc5b31678df9610bb2128dd14fd5fe34461eea8 | 2,126 | orkg-backend | MIT License |
src/day11/Day11.kt | Puju2496 | 576,611,911 | false | {"Kotlin": 46156} | package day11
import println
import readInput
import java.util.*
import kotlin.math.abs
import kotlin.collections.MutableList
fun main() {
// test if implementation meets criteria from the description, like:
val input = readInput("src/day11", "Day11")
println("Part1")
part1(input)
println("Part2")
part2(input)
}
private fun part1(inputs: List<String>) {
val monkeyList: MutableList<MonkeyData> = mutableListOf()
var monkeyData = MonkeyData(ArrayDeque(), Operation(' ', 0), 0, 0, 0)
inputs.forEachIndexed { index: Int, value: String ->
when (index % 7) {
1 -> {
val values = value.split(":", ",").toMutableList()
values.removeAt(0)
val worryLevelList = monkeyData.worryLevelList
worryLevelList.addAll(values.map {
it.trim().toInt()
})
monkeyData = monkeyData.copy(worryLevelList = worryLevelList)
}
2 -> {
val values = value.split(" ")
val operationNumber = if (values[values.size - 1].toIntOrNull() != null) values[values.size - 1].toInt() else -1
val operator = values[values.size - 2].last()
monkeyData = monkeyData.copy(operation = Operation(operator, operationNumber))
}
3 -> {
val values = value.split(" ")
val divisibleIndex = values[values.size - 1].toInt()
monkeyData = monkeyData.copy(divisible = divisibleIndex)
}
4 -> {
val values = value.split(" ")
val trueIndex = values[values.size - 1].toInt()
monkeyData = monkeyData.copy(onTrue = trueIndex)
}
5 -> {
val values = value.split(" ")
val falseIndex = values[values.size - 1].toInt()
monkeyData = monkeyData.copy(onFalse = falseIndex)
}
6 -> {
monkeyList.add(monkeyData)
monkeyData = MonkeyData(ArrayDeque(), Operation(' ', 0), 0, 0, 0)
}
}
}
monkeyList.add(monkeyData)
monkeyData = MonkeyData(ArrayDeque(), Operation(' ', 0), 0, 0, 0)
val activeMonkey = Array(monkeyList.size) {
0
}
for (k in 0 until 20) {
for (i in 0 until monkeyList.size) {
var monkey = monkeyList[i]
for (j in 0 until monkey.worryLevelList.size) {
val worryLevel = monkey.worryLevelList.peek()
if (worryLevel != 0) {
activeMonkey[i] = activeMonkey[i] + 1
}
var operatedLevel: Int = when (monkey.operation.sign) {
'*' -> {
if (monkey.operation.number == -1) {
worryLevel * worryLevel
} else {
worryLevel * monkey.operation.number
}
}
'+' -> {
if (monkey.operation.number == -1) {
worryLevel + worryLevel
} else {
worryLevel + monkey.operation.number
}
}
'-' -> {
if (monkey.operation.number == -1) {
worryLevel - worryLevel
} else {
worryLevel - monkey.operation.number
}
}
'/' -> {
if (monkey.operation.number == -1) {
worryLevel / worryLevel
} else {
worryLevel / monkey.operation.number
}
}
else -> 0
}
operatedLevel = Math.floor((operatedLevel.toDouble() / 3)).toInt()
if (operatedLevel % monkey.divisible == 0) {
var monkeyTrue = monkeyList[monkey.onTrue]
val list = monkeyTrue.worryLevelList
list.add(operatedLevel)
monkeyTrue = monkeyTrue.copy(worryLevelList = list)
monkeyList[monkey.onTrue] = monkeyTrue
} else {
var monkeyFalse = monkeyList[monkey.onFalse]
val list = monkeyFalse.worryLevelList
list.add(operatedLevel)
monkeyFalse = monkeyFalse.copy(worryLevelList = list)
monkeyList[monkey.onFalse] = monkeyFalse
}
val index = monkeyList.indexOf(monkey)
monkey.worryLevelList.remove()
monkey = monkey.copy(worryLevelList = monkey.worryLevelList)
monkeyList[index] = monkey
}
}
}
println("inputs - $monkeyList")
var max = 0
var max2 = 0
for (i in activeMonkey) {
if (i > max)
max = i
}
for (i in activeMonkey) {
if (i in (max2 + 1) until max)
max2 = i
}
println("max - $max - $max2 - ${max * max2}")
}
private fun part2(inputs: List<String>) {
val monkeyList: MutableList<MonkeyData2> = mutableListOf()
var monkeyData = MonkeyData2(ArrayDeque(), Operation(' ', 0), 0, 0, 0)
inputs.forEachIndexed { index: Int, value: String ->
when (index % 7) {
1 -> {
val values = value.split(":", ",").toMutableList()
values.removeAt(0)
val worryLevelList = monkeyData.worryLevelList
worryLevelList.addAll(values.map {
it.trim().toLong()
})
monkeyData = monkeyData.copy(worryLevelList = worryLevelList)
}
2 -> {
val values = value.split(" ")
val operationNumber = if (values[values.size - 1].toIntOrNull() != null) values[values.size - 1].toInt() else -1
val operator = values[values.size - 2].last()
monkeyData = monkeyData.copy(operation = Operation(operator, operationNumber))
}
3 -> {
val values = value.split(" ")
val divisibleIndex = values[values.size - 1].toInt()
monkeyData = monkeyData.copy(divisible = divisibleIndex)
}
4 -> {
val values = value.split(" ")
val trueIndex = values[values.size - 1].toInt()
monkeyData = monkeyData.copy(onTrue = trueIndex)
}
5 -> {
val values = value.split(" ")
val falseIndex = values[values.size - 1].toInt()
monkeyData = monkeyData.copy(onFalse = falseIndex)
}
6 -> {
monkeyList.add(monkeyData)
monkeyData = MonkeyData2(ArrayDeque(), Operation(' ', 0), 0, 0, 0)
}
}
}
monkeyList.add(monkeyData)
monkeyData = MonkeyData2(ArrayDeque(), Operation(' ', 0), 0, 0, 0)
val activeMonkey = Array(monkeyList.size) {
0L
}
var modBy = 1
for (monkey in monkeyList) {
modBy *= monkey.divisible
}
for (k in 0 until 10000) {
for (i in 0 until monkeyList.size) {
var monkey = monkeyList[i]
for (j in 0 until monkey.worryLevelList.size) {
val worryLevel = monkey.worryLevelList.peek()
if (worryLevel != 0L) {
activeMonkey[i] = activeMonkey[i] + 1
}
var operatedLevel: Long = when (monkey.operation.sign) {
'*' -> {
if (monkey.operation.number == -1) {
worryLevel * worryLevel
} else {
worryLevel * monkey.operation.number
}
}
'+' -> {
if (monkey.operation.number == -1) {
worryLevel + worryLevel
} else {
worryLevel + monkey.operation.number
}
}
'-' -> {
if (monkey.operation.number == -1) {
worryLevel - worryLevel
} else {
worryLevel - monkey.operation.number
}
}
'/' -> {
if (monkey.operation.number == -1) {
worryLevel / worryLevel
} else {
worryLevel / monkey.operation.number
}
}
else -> 0
}
operatedLevel %= modBy
if (operatedLevel % monkey.divisible == 0L) {
var monkeyTrue = monkeyList[monkey.onTrue]
val list = monkeyTrue.worryLevelList
list.add(operatedLevel)
monkeyTrue = monkeyTrue.copy(worryLevelList = list)
monkeyList[monkey.onTrue] = monkeyTrue
} else {
var monkeyFalse = monkeyList[monkey.onFalse]
val list = monkeyFalse.worryLevelList
list.add(operatedLevel)
monkeyFalse = monkeyFalse.copy(worryLevelList = list)
monkeyList[monkey.onFalse] = monkeyFalse
}
val index = monkeyList.indexOf(monkey)
monkey.worryLevelList.remove()
monkey = monkey.copy(worryLevelList = monkey.worryLevelList)
monkeyList[index] = monkey
}
}
}
println("inputs - $monkeyList")
var max = 0L
var max2 = 0L
for (i in activeMonkey) {
if (i > max)
max = i
}
for (i in activeMonkey) {
if (i in (max2 + 1) until max)
max2 = i
}
println("max - $max - $max2 - ${max * max2}")
}
data class MonkeyData(val worryLevelList: Queue<Int>, val operation: Operation, val divisible: Int, val onTrue: Int, val onFalse: Int)
data class Operation(val sign: Char, val number: Int)
data class MonkeyData2(val worryLevelList: Queue<Long>, val operation: Operation, val divisible: Int, val onTrue: Int, val onFalse: Int) | 0 | Kotlin | 0 | 0 | e04f89c67f6170441651a1fe2bd1f2448a2cf64e | 10,628 | advent-of-code-2022 | Apache License 2.0 |
program/add-two-matrices/AddTwoMatrices.kt | codinasion | 540,856,406 | false | null | fun main() {
print("Enter the two matrices line separated: \n")
val size = 3
val a = readMatrix(size)
readln()
val b = readMatrix(size)
val c = addMatrices(a, b)
println("Result of adding the matrices: \n")
printMatrix(c)
}
// Takes number of rows and columns and reads the matrix from input
fun readMatrix(rows : Int): ArrayList<ArrayList<Int>>{
val matrix = arrayListOf<ArrayList<Int>>()
for(row in 0 until rows){
val line = readln().trim().split(' ')
matrix.add(ArrayList())
for(number in line){
matrix[row].add(Integer.valueOf(number))
}
}
return matrix
}
// prints a matrix
fun printMatrix(matrix : ArrayList<ArrayList<Int>>){
for (row in matrix){
for (cell in row){
print("$cell ")
}
println()
}
}
// adds two matrices and return the result in a new matrix
fun addMatrices(a : ArrayList<ArrayList<Int>>, b : ArrayList<ArrayList<Int>>) : ArrayList<ArrayList<Int>>{
val c = a.clone() as ArrayList<ArrayList<Int>>
for(i in 0 until b.size){
for(j in 0 until b.size){
c[i][j] += b[i][j]
}
}
return c
}
| 951 | Java | 550 | 300 | d8880e34c1ff4713c2ff8fbe9cdfbed3f209844a | 1,188 | program | MIT License |
src/main/kotlin/sschr15/aocsolutions/Day15.kt | sschr15 | 317,887,086 | false | {"Kotlin": 184127, "TeX": 2614, "Python": 446} | package sschr15.aocsolutions
import sschr15.aocsolutions.util.Challenge
import sschr15.aocsolutions.util.ReflectivelyUsed
import sschr15.aocsolutions.util.challenge
import sschr15.aocsolutions.util.findLongs
/**
* AOC 2023 [Day 15](https://adventofcode.com/2023/day/15)
* Challenge: Baby's first hashmap
*/
object Day15 : Challenge {
@ReflectivelyUsed
override fun solve() = challenge(2023, 15) {
splitBy(",")
// test()
part1 {
inputLines.sumOf {
it.trim('\n').fold(0.toLong()) { acc, c -> (acc + c.code) * 17 and 0xff }
}
}
part2 {
val boxes = Array<MutableList<Pair<String, Int>>>(256) { mutableListOf() }
inputLines.forEach { s ->
val label = s
.takeWhile { it.isLetter() }
val hash = label
.fold(0.toLong()) { acc, c -> (acc + c.code) * 17 and 0xff }
val result = s.findLongs().singleOrNull()
if (result == null) boxes[hash.toInt()].removeIf { (toRemove, _) -> toRemove == label }
else {
val list = boxes[hash.toInt()]
val index = list.indexOfFirst { (toRemove, _) -> toRemove == label }
if (index == -1) list.add(label to result.toInt())
else list[index] = label to result.toInt()
}
}
boxes.mapIndexed { i, lenses ->
lenses.mapIndexed { index, (_, strength) ->
strength * (i + 1) * (index + 1)
}.sum()
}.sum()
}
}
@JvmStatic
fun main(args: Array<String>) = println("Time: ${solve()}")
}
| 0 | Kotlin | 0 | 0 | e483b02037ae5f025fc34367cb477fabe54a6578 | 1,737 | advent-of-code | MIT License |
2023/src/main/kotlin/Advent2306.kt | jkesanen | 737,123,947 | false | {"Kotlin": 22721} | import java.io.File
import kotlin.math.max
class Advent2306 {
private fun chargeToDistance(charge: Long, duration: Long): Long {
val timeLeft = duration - charge
return charge * max(0, timeLeft)
}
private fun getBestResults(filename: String): List<Pair<Long, Long>> {
val times = mutableListOf<Long>()
val distances = mutableListOf<Long>()
File(this::class.java.getResource(filename)!!.file).forEachLine { line ->
val parts = line.split(":")
when (parts[0]) {
"Time" -> times += Regex("""\d+""").findAll(parts[1]).map { it.value.toLong() }.toList()
"Distance" -> distances += Regex("""\d+""").findAll(parts[1]).map { it.value.toLong() }.toList()
}
}
assert(times.size == distances.size)
val races = mutableListOf<Pair<Long, Long>>()
for (i in 0..<times.size) {
races += Pair(times[i], distances[i])
}
return races
}
fun getWaysToWin1(filename: String): Int {
val races = getBestResults(filename)
var waysToWinMultiplied = 0
races.forEach {
val duration = it.first
val distance = it.second
var wins = 0
for (charge in 0..<duration) {
if (chargeToDistance(charge, duration) > distance) {
wins++
}
}
waysToWinMultiplied = if (waysToWinMultiplied == 0) {
wins
} else {
waysToWinMultiplied * wins
}
}
return waysToWinMultiplied
}
private fun getResult(filename: String): Pair<Long, Long> {
var duration = 0L
var distance = 0L
File(this::class.java.getResource(filename)!!.file).forEachLine { line ->
val parts = line.split(":")
when (parts[0]) {
"Time" -> duration = parts[1].replace(" ", "").toLong()
"Distance" -> distance = parts[1].replace(" ", "").toLong()
}
}
return Pair(duration, distance)
}
fun getWaysToWin2(filename: String): Int {
val result = getResult(filename)
var waysToWin = 0
for (charge in 0..<result.first) {
if (chargeToDistance(charge, result.first) > result.second) {
++waysToWin
}
}
return waysToWin
}
}
| 0 | Kotlin | 0 | 0 | e4be0577f8e6654a306c3c9c3cf4f0620db93b8b | 2,452 | adventofcode | MIT License |
year2022/src/cz/veleto/aoc/year2022/Day13.kt | haluzpav | 573,073,312 | false | {"Kotlin": 164348} | package cz.veleto.aoc.year2022
import cz.veleto.aoc.core.AocDay
import kotlin.jvm.JvmInline
import kotlin.math.min
class Day13(config: Config) : AocDay(config) {
override fun part1(): String = input.chunked(3)
.mapIndexed { pairIndex, (leftString, rightString) ->
val left = parseList(leftString)
val right = parseList(rightString)
alignLists(left, right)
val isInRightOrder = compareLists(left, right)
if (isInRightOrder) pairIndex + 1 else 0
}.sum().toString()
override fun part2(): String {
val indexOf2 = countBefore("""[[2]]""") + 1
val indexOf6 = countBefore("""[[6]]""") + 2
return (indexOf2 * indexOf6).toString()
}
private fun parseList(string: String): Element.List {
val root = Element.List()
val lists = mutableListOf<Element.List>()
var lastOneIndex: Int? = null
for (c in string) {
when (c) {
'[' -> lists += if (lists.isEmpty()) root else Element.List().also { lists.last().list += it }
'1' -> {
lists.last().list += Element.Int(1)
lastOneIndex = 0
}
in '0'..'9' -> {
val int = c.digitToInt().let {
if (lastOneIndex == 1) {
lists.last().list.removeLast()
it + 10
} else {
it
}
}
lists.last().list += Element.Int(int)
}
']' -> lists.removeLast()
',' -> Unit
else -> error("undefined char $c")
}
lastOneIndex?.let { lastOneIndex = it + 1 }
}
check(lists.isEmpty())
return root
}
private fun alignLists(left: Element.List, right: Element.List) {
val listsToGoThrough = mutableListOf(left to right)
while (listsToGoThrough.isNotEmpty()) {
val (l, r) = listsToGoThrough.removeFirst()
(l.list zip r.list).forEachIndexed { index, (le, re) ->
when {
le is Element.Int && re is Element.List -> l.list[index] = Element.List(mutableListOf(le))
.also { listsToGoThrough += it to re }
le is Element.List && re is Element.Int -> r.list[index] = Element.List(mutableListOf(re))
.also { listsToGoThrough += le to it }
le is Element.List && re is Element.List -> listsToGoThrough += le to re
}
}
}
}
private fun compareLists(left: Element.List, right: Element.List): Boolean {
val listsToGoThrough = mutableListOf(Triple(left, right, 0))
while (listsToGoThrough.isNotEmpty()) {
val (l, r, startIndex) = listsToGoThrough.removeLast()
var finished = true
for (i in startIndex until min(l.list.size, r.list.size)) {
val le = l.list[i]
val re = r.list[i]
when {
le is Element.List && re is Element.List -> {
listsToGoThrough += Triple(l, r, i + 1)
listsToGoThrough += Triple(le, re, 0)
finished = false
break
}
le is Element.Int && re is Element.Int && le.int < re.int -> return true
le is Element.Int && re is Element.Int && le.int > re.int -> return false
}
}
if (finished) {
when {
l.list.size < r.list.size -> return true
l.list.size > r.list.size -> return false
}
}
}
error("the list are the same?!")
}
private fun countBefore(string: String) : Int = input
.filter { it.isNotBlank() }
.count {
val left = parseList(it)
val right = parseList(string)
alignLists(left, right)
compareLists(left, right)
}
private sealed interface Element {
@JvmInline
value class Int(val int: kotlin.Int) : Element {
override fun toString(): String = int.toString()
}
@JvmInline
value class List(val list: MutableList<Element> = mutableListOf()) : Element {
override fun toString(): String = list.toString()
}
}
}
| 0 | Kotlin | 0 | 1 | 32003edb726f7736f881edc263a85a404be6a5f0 | 4,587 | advent-of-pavel | Apache License 2.0 |
src/main/kotlin/_2023/Day04.kt | novikmisha | 572,840,526 | false | {"Kotlin": 145780} | package _2023
import Day
import InputReader
import inc
import kotlin.math.pow
class Day04 : Day(2023, 4) {
override val firstTestAnswer = 13
override val secondTestAnswer = 30
override fun first(input: InputReader) = input.asLines()
.sumOf { card ->
val (winningNumbers, cardNumbers) = card.dropWhile { it != ':' }.drop(1).split("|").map {
it.trim().split(" ").mapNotNull { number -> number.trim().toIntOrNull() }.toSet()
}
val wonNumbers = winningNumbers.intersect(cardNumbers).size
if (wonNumbers != 0) (2.0).pow(wonNumbers - 1).toInt() else 0
}
override fun second(input: InputReader): Int {
val cards = input.asLines()
val cardAmount = cards.associateTo(mutableMapOf()) { it.drop(5).takeWhile { it != ':' }.trim().toInt() to 1 }
cards.forEach { card ->
val cardNumber = card.drop(5).takeWhile { it != ':' }.trim().toInt()
val (winningNumbers, cardNumbers) = card.dropWhile { it != ':' }.drop(1).split("|").map {
it.trim().split(" ").mapNotNull { number -> number.trim().toIntOrNull() }.toSet()
}
val wonNumbers = winningNumbers.intersect(cardNumbers).size
for (wonCard in cardNumber + 1..cardNumber + wonNumbers) {
cardAmount.inc(wonCard, cardAmount[cardNumber]!!)
}
}
return cardAmount.values.sum()
}
}
fun main() {
Day04().solve()
} | 0 | Kotlin | 0 | 0 | 0c78596d46f3a8bf977bf356019ea9940ee04c88 | 1,499 | advent-of-code | Apache License 2.0 |
2023/01/Solution.kt | AdrianMiozga | 588,519,359 | false | {"Kotlin": 110785, "Python": 11275, "Assembly": 3369, "C": 2378, "Pawn": 1390, "Dart": 732} | import java.io.File
import kotlin.math.max
import kotlin.math.min
private const val FILENAME = "2023/01/input.txt"
private val digitsRegex = Regex("""\D""")
fun main() {
partOne()
partTwo()
}
private fun partOne() {
val file = File(FILENAME).readLines()
var result = 0
for (line in file) {
val digits = line.replace(digitsRegex, "")
result += "${digits.first()}${digits.last()}".toInt()
}
println(result)
}
private fun partTwo() {
val mapping = mapOf(
"one" to "1",
"two" to "2",
"three" to "3",
"four" to "4",
"five" to "5",
"six" to "6",
"seven" to "7",
"eight" to "8",
"nine" to "9"
)
val file = File(FILENAME).readLines()
var result = 0
for (line in file) {
var firstDigit = ""
var lastDigit = ""
var index = 0
while (firstDigit.isEmpty()) {
val window = line.slice(0..min(index + 2, line.length - 1))
val numbers = window.replace(digitsRegex, "")
if (numbers.isNotEmpty()) {
firstDigit = numbers.first().toString()
} else {
for (map in mapping) {
if (window.contains(map.key)) {
firstDigit = map.value
}
}
}
index++
}
index = line.length
while (lastDigit.isEmpty()) {
val window = line.slice(max(index - 3, 0) until line.length)
val numbers = window.replace(digitsRegex, "")
if (numbers.isNotEmpty()) {
lastDigit = numbers.last().toString()
} else {
for (map in mapping) {
if (window.contains(map.key)) {
lastDigit = map.value
}
}
}
index--
}
result += (firstDigit + lastDigit).toInt()
}
println(result)
}
| 0 | Kotlin | 0 | 0 | c9cba875089d8d4fb145932c45c2d487ccc7e8e5 | 2,011 | Advent-of-Code | MIT License |
src/Day17.kt | kipwoker | 572,884,607 | false | null | import kotlin.math.max
class Rock(val cells: List<Point>, var shift: Point) {
fun getCoords(): List<Point> {
return cells.map { x -> x.sum(shift) }
}
fun hasCollision(points: Set<Point>, move: Point): Boolean {
val newPosition = this.getCoords()
.map { it.sum(move) }
val hasBoundsCollision = newPosition.any { p -> p.x == -1 || p.y == -1 || p.x == 7 }
if (hasBoundsCollision) {
return true
}
val hasCollision = newPosition
.intersect(points)
.isNotEmpty()
if (hasCollision) {
return true
}
return false
}
companion object {
fun create(index: Int, init: Point): Rock {
return when (val number = index % 5) {
// ####
0 -> Rock(
listOf(
Point(0, 0),
Point(1, 0),
Point(2, 0),
Point(3, 0)
),
init
)
// +
1 -> Rock(
listOf(
Point(1, 0),
Point(0, 1),
Point(1, 1),
Point(2, 1),
Point(1, 2)
),
init
)
// _|
2 -> Rock(
listOf(
Point(0, 0),
Point(1, 0),
Point(2, 0),
Point(2, 1),
Point(2, 2)
),
init
)
// |
3 -> Rock(
listOf(
Point(0, 0),
Point(0, 1),
Point(0, 2),
Point(0, 3)
),
init
)
// square
4 -> Rock(
listOf(
Point(0, 0),
Point(1, 0),
Point(0, 1),
Point(1, 1)
),
init
)
else -> throw RuntimeException("Unexpected $number")
}
}
}
}
@Suppress("DuplicatedCode")
fun main() {
data class State(
val stoppedRocksCount: Long,
val ground: Set<Point>,
val maxY: Int
)
fun parse(input: List<String>): List<Direction> {
return input[0].toCharArray().map { c -> if (c == '<') Direction.Left else Direction.Right }
}
fun print(rocks: List<Rock>) {
val points = rocks.flatMap { r -> r.getCoords() }.toSet()
val maxY = points.maxOf { c -> c.y }
for (y in maxY downTo 0) {
for (x in 0..6) {
if (points.contains(Point(x, y))) {
print('#')
} else {
print('.')
}
}
println()
}
println()
println()
}
fun calculateState(
topLevelMap: MutableMap<Int, Int>,
stopped: Long,
maxY: Int
): State {
val minY = topLevelMap.minOf { t -> t.value }
val newGround = topLevelMap.map { t -> Point(t.key, (t.value - minY)) }.toSet()
return State(stopped, newGround, maxY)
}
fun removeUnreachable(
topLevelMap: MutableMap<Int, Int>,
ground: MutableSet<Point>
) {
val minLevel = topLevelMap.values.min()
ground.removeIf { it.y < minLevel }
}
fun actualizeTopLevels(
coords: List<Point>,
topLevelMap: MutableMap<Int, Int>
) {
for (coord in coords) {
val top = topLevelMap[coord.x]
if (top == null || top < coord.y) {
topLevelMap[coord.x] = coord.y
}
}
}
fun play(directions: List<Direction>, rocksLimit: Long, initGround: Set<Point>): List<State> {
var directionIterator = 0
var rockIterator = 0
var shift = Point(2, 3)
val ground = initGround.toMutableSet()
var stopped = 0L
val topLevelMap = mutableMapOf<Int, Int>()
var activeRock: Rock? = null
var maxY = 0
val states = mutableListOf<State>()
val dy = Point(0, -1)
while (stopped < rocksLimit) {
if (activeRock == null) {
activeRock = Rock.create(rockIterator, shift)
++rockIterator
}
val direction = directions[directionIterator]
val dx = if (direction == Direction.Left) Point(-1, 0) else Point(1, 0)
if (!activeRock.hasCollision(ground, dx)) {
activeRock.shift = activeRock.shift.sum(dx)
}
if (!activeRock.hasCollision(ground, dy)) {
activeRock.shift = activeRock.shift.sum(dy)
} else {
++stopped
val coords = activeRock.getCoords()
actualizeTopLevels(coords, topLevelMap)
ground.addAll(coords)
removeUnreachable(topLevelMap, ground)
maxY = max(maxY, topLevelMap.values.max() + 1)
shift = Point(shift.x, maxY + 3)
activeRock = null
}
directionIterator = (directionIterator + 1) % directions.size
if (directionIterator == 0) {
states.add(calculateState(topLevelMap, stopped, maxY))
if (states.size > 1) {
break
}
}
}
if (states.size <= 1) {
states.add(calculateState(topLevelMap, stopped, maxY))
}
return states
}
fun findMax(directions: List<Direction>, totalRocks: Long): Long {
val defaultGround = (0..6).map { Point(it, -1) }.toSet()
val states = play(directions, totalRocks, defaultGround).reversed()
val lastRocksCount = states[0].stoppedRocksCount
val maxY = states[0].maxY
val leftRocks = totalRocks - lastRocksCount
if (leftRocks == 0L) {
return maxY.toLong()
}
val deltaRocks = lastRocksCount - states[1].stoppedRocksCount
val deltaY = states[0].maxY - states[1].maxY
val mult = leftRocks / deltaRocks
val sliceY = deltaY * mult
val restRocks = leftRocks % deltaRocks
val (_, _, maxY1) = play(
directions,
restRocks,
states[0].ground
)[0]
return maxY + sliceY + maxY1 - 1
}
fun part1(input: List<String>): Long {
return findMax(parse(input), 2022L)
}
fun part2(input: List<String>): Long {
return findMax(parse(input), 1000000000000L)
}
// ==================================================================== //
val day = "17"
fun test() {
val testInput = readInput("Day${day}_test")
assert(part1(testInput), 3068L)
assert(part2(testInput), 1514285714288L)
}
fun run() {
val input = readInput("Day$day")
println(part1(input))
println(part2(input))
}
// test()
run()
}
| 0 | Kotlin | 0 | 0 | d8aeea88d1ab3dc4a07b2ff5b071df0715202af2 | 7,365 | aoc2022 | Apache License 2.0 |
aoc_2023/src/main/kotlin/problems/day23/HikingSol.kt | Cavitedev | 725,682,393 | false | {"Kotlin": 228779} | package problems.day23
import kotlin.math.max
class HikingSol(val hikingMap: HikingMap) {
val startCell = hikingMap.startCell()
val endCell = hikingMap.endCell()
fun solve(): Int {
var longestPath = 0
val startNode = HikingNode(startCell, 0, null, mutableSetOf())
val openedNodes = mutableListOf(startNode)
while (openedNodes.isNotEmpty()) {
val nextNode = openedNodes.removeLast()
if (nextNode.cell == endCell) {
longestPath = max(longestPath, nextNode.gCost)
println("longest: $longestPath nodes ${openedNodes.size}")
nextNode.removeUntilNode(openedNodes.lastOrNull()?.previousNode)
continue
}
nextNode.prevCells.add(nextNode.cell)
val neighbours = findNeighbours(nextNode).filter { neighbour ->
neighbour.cell.canWalk && !neighbour.hasVisitedCell()
}
for (neighbour in neighbours) {
openedNodes.add(neighbour)
}
if (neighbours.isEmpty()) {
if (openedNodes.isEmpty()) break
nextNode.removeUntilNode(openedNodes.lastOrNull()?.previousNode)
}
}
return longestPath
}
fun findNeighbours(node: HikingNode): List<HikingNode> {
val nextPos = node.cell.getNeighbours(this.hikingMap.map)
return nextPos.map { pos ->
val nextCell = this.hikingMap.map[pos.first][pos.second]
node.nextNode(nextCell)
}
}
} | 0 | Kotlin | 0 | 1 | aa7af2d5aa0eb30df4563c513956ed41f18791d5 | 1,578 | advent-of-code-2023 | MIT License |
src/Day14.kt | jrmacgill | 573,065,109 | false | {"Kotlin": 76362} | import utils.*
import java.lang.Integer.max
import java.lang.Math.min
class Day14 {
val grid = MutableGrid(100000,1000) { _ -> '.' }
fun Point.down() : Point {
return Point(this.x, this.y+1)
}
fun Point.left() : Point {
return Point(this.x-1, this.y+1)
}
fun Point.right() : Point {
return Point(this.x+1, this.y+1)
}
val start = Point(500,0)
var active = start
var count = 1
var maxY = 0;
fun parse(line : String) {
line.split("->").windowed(2).forEach {
println(it)
var a = it[0].split(",").map { a -> a.trim().toInt() }
var b = it[1].split(",").map { a -> a.trim().toInt() }
for (x in min(a[0], b[0])..max(a[0], b[0])) {
for (y in min(a[1], b[1])..max(a[1], b[1])) {
println("x " + x + " y " + y)
maxY = max(y, maxY)
grid.set(Point(x, y), '#')
}
}
}
}
fun step() {
when {
(grid.get(active.down()) == '.') -> { active = active.down(); println("air")}
(grid.get(active.left()) == '.') -> { active = active.left(); println("air to left")}
(grid.get(active.right()) == '.') -> { active = active.right(); println("air to right")}
(active == start) -> throw Exception("full")
else -> {grid.set(active, 'o'); count++; active=start}
}
}
fun go() {
grid.set(start, '+')
var lines =readInput("dayForteen")
lines.forEach{
parse(it)
}
maxY += 2
parse("0,$maxY -> 10000,$maxY")
try {
while(true) {
step()
}
} finally {
println(grid.formatted())
println(count-1)
}
}
}
fun main() {
Day14().go()
} | 0 | Kotlin | 0 | 1 | 3dcd590f971b6e9c064b444139d6442df034355b | 1,885 | aoc-2022-kotlin | Apache License 2.0 |
solutions/aockt/y2022/Y2022D11.kt | Jadarma | 624,153,848 | false | {"Kotlin": 435090} | package aockt.y2022
import io.github.jadarma.aockt.core.Solution
object Y2022D11 : Solution {
/** Regex that extracts information on monkeys. */
private val inputRegex = Regex(
"""
Monkey (?<id>\d+):
{2}Starting items: (?<startingItems>[0-9, ]+)
{2}Operation: new = old (?<operator>[*+]) (?<operand>\d+|old)
{2}Test: divisible by (?<divisibilityTest>\d+)
{4}If true: throw to monkey (?<monkeyIfTrue>\d+)
{4}If false: throw to monkey (?<monkeyIfFalse>\d+)
""".trimIndent()
)
/** Parse the [input] and return the list of [Monkey]s playing with items. */
private fun parseInput(input: String): List<Monkey> =
input
.splitToSequence("\n\n")
.map { inputRegex.matchEntire(it)!!.groups as MatchNamedGroupCollection }
.map { groups ->
Monkey(
id = groups["id"]!!.value.toInt(),
operation = run {
val operand = groups["operand"]!!.value.toLongOrNull()
when (groups["operator"]!!.value) {
"*" -> { x -> x * (operand ?: x) }
"+" -> { x -> x + (operand ?: x) }
else -> error("Invalid input.")
}
},
divisibility = groups["divisibilityTest"]!!.value.toLong(),
monkeyIfTrue = groups["monkeyIfTrue"]!!.value.toInt(),
monkeyIfFalse = groups["monkeyIfFalse"]!!.value.toInt(),
startingItems = groups["startingItems"]!!.value.split(", ").map(String::toLong)
)
}
.toList()
/**
* A simulated monkey brain tasked with tossing items based on worry levels.
* @property id An identifier.
* @property operation How the worry level modifies upon inspection.
* @property divisibility The number used to test divisibility and decide on where to throw the item next.
*/
private class Monkey(
val id: Int,
private val operation: (Long) -> Long,
val divisibility: Long,
monkeyIfTrue: Int,
monkeyIfFalse: Int,
startingItems: List<Long>,
) {
/** Worry levels associated with each item this monkey handles. */
private val items: MutableList<Long> = startingItems.toMutableList()
/** Total number of items inspected during this monkey's lifetime. */
var inspections: Long = 0L
private set
/** Based on an item's worry level, returns the id of the monkey to throw it to. */
private val testAndThrow: (Long) -> Int = { worryLevel ->
if (worryLevel.rem(divisibility) == 0L) monkeyIfTrue else monkeyIfFalse
}
/** Catch an item from another monkey. */
fun receive(itemWithWorryLevel: Long) {
items.add(itemWithWorryLevel)
}
/**
* Simulate the monkey's turn and throw out all carried items and return a list of pairs between the worry level
* of the item to be thrown and the ID of the monkey to throw it to.
*
* @param isVeryWorried If true, worry levels won't be reduced after an inspection.
* @param worryCycle The product of all [divisibility] numbers of the monkeys in the round, needed as an
* optimisation if simulating lots of rounds to prevent overflows.
*/
fun throwItems(isVeryWorried: Boolean = false, worryCycle: Long? = null): List<Pair<Long, Int>> =
items
.asSequence()
.onEach { inspections++ }
.map(operation)
.map { if (isVeryWorried) it else it / 3L }
.map { if (worryCycle != null) it.rem(worryCycle) else it }
.map { it to testAndThrow(it) }
.toList()
.also { items.clear() }
}
/**
* Simulate the monkey tossing game and return the product of the number of items carried by the two most burdened
* monkeys at the end of the simulation.
*
* @param input The problem input which configures the monkey brains.
* @param rounds How many rounds to play.
* @param isVeryWorried Whether worry drop-off after monkey inspection is disabled.
*/
private fun simulateMonkeyBehavior(input: String, rounds: Int, isVeryWorried: Boolean): Long =
parseInput(input)
.apply {
val worryCycle = map { it.divisibility }.reduce(Long::times)
repeat(rounds) {
forEach { monkey ->
monkey
.throwItems(isVeryWorried, worryCycle)
.forEach { (itemWithWorryLevel, toMonkey) -> get(toMonkey).receive(itemWithWorryLevel) }
}
}
}
.sortedByDescending { it.inspections }
.take(2)
.map { it.inspections }
.reduce(Long::times)
override fun partOne(input: String) = simulateMonkeyBehavior(input, 20, false)
override fun partTwo(input: String) = simulateMonkeyBehavior(input, 10000, true)
}
| 0 | Kotlin | 0 | 3 | 19773317d665dcb29c84e44fa1b35a6f6122a5fa | 5,246 | advent-of-code-kotlin-solutions | The Unlicense |
src/main/kotlin/g2901_3000/s2901_longest_unequal_adjacent_groups_subsequence_ii/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2901_3000.s2901_longest_unequal_adjacent_groups_subsequence_ii
// #Medium #Array #String #Dynamic_Programming
// #2023_12_27_Time_305_ms_(100.00%)_Space_47.6_MB_(75.00%)
class Solution {
fun getWordsInLongestSubsequence(n: Int, words: Array<String>, groups: IntArray): List<String> {
val check = IntArray(groups.size)
val before = IntArray(groups.size)
check.fill(1)
before.fill(-1)
var index = 0
var max = 1
for (i in 1 until n) {
for (j in i - 1 downTo 0) {
if (groups[i] != groups[j] && ham(words[i], words[j]) && check[j] + 1 > check[i]) {
check[i] = check[j] + 1
before[i] = j
if (check[i] > max) {
max = check[i]
index = i
}
}
}
}
val ans: MutableList<String> = ArrayList()
while (index >= 0) {
ans.add(words[index])
index = before[index]
}
ans.reverse()
return ans
}
private fun ham(s1: String, s2: String): Boolean {
if (s1.length != s2.length) {
return false
}
var count = 0
for (i in s1.indices) {
if (s1[i] != s2[i]) {
count++
}
if (count > 1) {
return false
}
}
return count == 1
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,476 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/Puzzle3.kt | darwineee | 578,563,140 | false | {"Kotlin": 17166} | import java.io.File
fun puzzle3Part1(args: Array<String>) {
var sum = 0
File(args[0])
.readLines()
.forEach {
val commonItem = it.toCharArray().getCommonItem()
if (commonItem != null) {
sum += commonItem.toPriorityPoint()
}
}
println(sum)
}
private fun CharArray.getCommonItem(): Char? {
// as the requirement, the array item always have size is even number
// and always have common item
val compartmentSize = this.size / 2
val compartmentLeft = this.take(compartmentSize).toHashSet()
val compartmentRight = this.takeLast(compartmentSize).toHashSet()
compartmentLeft.forEach {
if (it in compartmentRight) return it
}
return null
}
fun puzzle3Part2(args: Array<String>) {
var sum = 0
File(args[0])
.readLines()
.chunked(3)
.forEach {
val groupBadge = it.getGroupBadge()
if (groupBadge != null) {
sum += groupBadge.toPriorityPoint()
}
}
println(sum)
}
private fun List<String>.getGroupBadge(): Char? {
val (rucksack1, rucksack2, rucksack3) = this.map { it.toCharArray().toHashSet() }
return when {
rucksack1.size * 2 < rucksack2.size + rucksack3.size -> {
getGroupBadge(rucksack1, rucksack2, rucksack3)
}
rucksack2.size * 2 < rucksack1.size + rucksack3.size -> {
getGroupBadge(rucksack2, rucksack1, rucksack3)
}
else -> {
getGroupBadge(rucksack3, rucksack1, rucksack2)
}
}
}
private fun getGroupBadge(rucksack1: HashSet<Char>, rucksack2: HashSet<Char>, rucksack3: HashSet<Char>): Char? {
rucksack1.forEach {
if (it in rucksack2 && it in rucksack3) return it
}
return null
}
private fun Char.toPriorityPoint(): Int {
return if (this.isUpperCase()) {
this.code - 38
} else this.code - 96
} | 0 | Kotlin | 0 | 0 | f4354b88b657a6d6f803632bc6b43b5abb6943f1 | 1,948 | adventOfCode2022 | Apache License 2.0 |
2019/src/main/kotlin/com/github/jrhenderson1988/adventofcode2019/day22/BigDeck.kt | jrhenderson1988 | 289,786,400 | false | {"Kotlin": 216891, "Java": 166355, "Go": 158613, "Rust": 124111, "Scala": 113820, "Elixir": 112109, "Python": 91752, "Shell": 37} | package com.github.jrhenderson1988.adventofcode2019.day22
import java.math.BigInteger
/**
* Solution came primarily from this insight:
* https://www.reddit.com/r/adventofcode/comments/ee0rqi/comment/fbnkaju/
*/
class BigDeck(
private val offset: BigInteger,
private val increment: BigInteger,
private val cards: BigInteger
) {
private fun dealIntoNewStack() =
BigDeck(
this.offset.add(this.increment.multiply(BigInteger("-1")).mod(this.cards))
.add(this.cards).mod(this.cards),
this.increment.multiply(BigInteger("-1")).mod(this.cards),
this.cards
)
private fun cut(n: BigInteger) =
BigDeck(this.offset.add(this.increment.multiply(n)).mod(cards), this.increment, this.cards)
private fun dealWithIncrement(n: BigInteger) =
BigDeck(offset, inv(n).multiply(this.increment).mod(this.cards), cards)
private fun inv(n: BigInteger) = n.modPow((this.cards.subtract(BigInteger.TWO)), this.cards)
fun execute(instruction: String) = when {
instruction.startsWith(DEAL_WITH_INCREMENT) -> dealWithIncrement(parseParam(instruction))
instruction.startsWith(CUT) -> cut(parseParam(instruction))
instruction.startsWith(DEAL_INTO_NEW_STACK) -> dealIntoNewStack()
else -> error("Invalid instruction")
}
fun execute(instructions: List<String>) =
instructions.fold(this) { deck, instruction -> deck.execute(instruction) }
fun shuffle(instructions: List<String>, times: BigInteger): BigDeck {
val nd = this.execute(instructions)
val increment = nd.increment.modPow(times, nd.cards)
val offset = nd.offset.multiply(BigInteger.ONE.subtract(increment))
.multiply(inv(BigInteger.ONE.subtract(nd.increment).mod(nd.cards)))
val modOffset = offset.mod(cards)
return BigDeck(modOffset, increment, nd.cards)
}
fun get(n: BigInteger): BigInteger = this.offset.add(n.multiply(this.increment)).mod(this.cards)
override fun toString() = "($offset, $increment, $cards)"
companion object {
const val DEAL_WITH_INCREMENT = "deal with increment"
const val CUT = "cut"
const val DEAL_INTO_NEW_STACK = "deal into new stack"
fun parseParam(input: String) = input.trim().split(' ').last().toBigInteger()
}
} | 0 | Kotlin | 0 | 0 | 7b56f99deccc3790c6c15a6fe98a57892bff9e51 | 2,351 | advent-of-code | Apache License 2.0 |
src/main/kotlin/leetcode/problem0005/LongestPalindromicSubstring.kt | ayukatawago | 456,312,186 | false | {"Kotlin": 266300, "Python": 1842} | package leetcode.problem0005
import kotlin.math.max
class LongestPalindromicSubstring {
fun longestPalindrome(s: String): String {
if (s.isEmpty()) {
return ""
}
var startIndex = 0
var endIndex = 0
for (index in 0..s.length) {
val temp1 = findPalindrome(s, index, index)
val temp2 = findPalindrome(s, index, index + 1)
val maxPalindromeLength = max(temp1, temp2)
if (maxPalindromeLength > endIndex - startIndex) {
startIndex = index - (maxPalindromeLength - 1) / 2
endIndex = index + maxPalindromeLength / 2 + 1
}
}
return s.substring(startIndex, endIndex)
}
private fun findPalindrome(s: String, start: Int, end: Int): Int {
var length = end - start
for (index in 0..s.length) {
if (start - index < 0 || end + index >= s.length || s[start - index] != s[end + index]) {
break
}
length += 2
}
return length - 1
}
}
| 0 | Kotlin | 0 | 0 | f9602f2560a6c9102728ccbc5c1ff8fa421341b8 | 1,078 | leetcode-kotlin | MIT License |
src/main/kotlin/aoc2016/FirewallRules.kt | komu | 113,825,414 | false | {"Kotlin": 395919} | package komu.adventofcode.aoc2016
import komu.adventofcode.utils.nonEmptyLines
fun firewallRules1(input: String): UInt =
FirewallRule.parseRules(input).mergeSuccessive().first().high + 1u
fun firewallRules2(input: String): UInt =
FirewallRule.parseRules(input).mergeSuccessive().zipWithNext().sumOf { (r1, r2) -> r1.gap(r2) }
private fun List<FirewallRule>.mergeSuccessive(): List<FirewallRule> {
val result = mutableListOf<FirewallRule>()
val rules = this.sortedBy { it.low }
val it = rules.iterator()
var last = it.next()
while (it.hasNext()) {
val current = it.next()
if (current.low - 1u <= last.high)
last = last.merge(current)
else {
result.add(last)
last = current
}
}
result.add(last)
return result
}
private data class FirewallRule(val low: UInt, val high: UInt) {
operator fun contains(number: UInt) = number in low..high
fun merge(r: FirewallRule) =
FirewallRule(minOf(low, r.low), maxOf(high, r.high))
fun gap(r: FirewallRule) =
r.low - high - 1u
companion object {
fun parseRules(s: String) =
s.nonEmptyLines().map { parse(it) }
private fun parse(s: String): FirewallRule {
val (l, h) = s.split('-')
return FirewallRule(l.toUInt(), h.toUInt())
}
}
} | 0 | Kotlin | 0 | 0 | 8e135f80d65d15dbbee5d2749cccbe098a1bc5d8 | 1,381 | advent-of-code | MIT License |
src/main/kotlin/be/tabs_spaces/advent2021/days/Day12.kt | janvryck | 433,393,768 | false | {"Kotlin": 58803} | package be.tabs_spaces.advent2021.days
class Day12 : Day(12) {
private val caveSystem = CaveSystem(inputList)
override fun partOne() = caveSystem.findExitFromStart().size
override fun partTwo() = caveSystem.findExitFromStart(maxDuplicateSmallCaves = 1).size
class CaveSystem(rawInput: List<String>) {
private val connections = mapTwoWayConnections(rawInput)
private fun mapTwoWayConnections(rawInput: List<String>) = rawInput
.map { it.split("-") }
.flatMap { (from, to) -> listOf(from to to, to to from) }
.filterNot { it.second.isStart() }
.groupBy({ it.first }, { it.second })
fun findExitFromStart(maxDuplicateSmallCaves: Int = 0) = appendPaths(mutableListOf("start"), maxDuplicateSmallCaves)
private fun appendPaths(
currentPath: MutableList<String>,
maxDuplicateSmallCaves: Int
) = connections[currentPath.last()]!!
.map { currentPath + it }
.flatMap { appendNextPaths(it, maxDuplicateSmallCaves) }
private fun appendNextPaths(
path: List<String>,
maxDuplicateSmallCaves: Int
): List<List<String>> = when {
path.last().isEnd() -> listOf(path)
hasTooManyDuplicateVisit(path, maxDuplicateSmallCaves) -> emptyList()
else -> appendPaths(path.toMutableList(), maxDuplicateSmallCaves)
}
private fun hasTooManyDuplicateVisit(it: List<String>, maxDuplicateVisits: Int) = it
.filter { it.isLowercase() }
.groupingBy { it }
.eachCount()
.values
.let { occurrences -> occurrences.count { it > 1 } > maxDuplicateVisits || occurrences.any { it > 2 } }
private fun String.isStart() = this == "start"
private fun String.isEnd() = this == "end"
private fun String.isLowercase() = this.lowercase() == this
}
} | 0 | Kotlin | 0 | 0 | f6c8dc0cf28abfa7f610ffb69ffe837ba14bafa9 | 1,941 | advent-2021 | Creative Commons Zero v1.0 Universal |
Algorithm/HackerRank/src/BiggerIsGreater.kt | chaking | 180,269,329 | false | {"JavaScript": 118156, "HTML": 97206, "Jupyter Notebook": 93471, "C++": 19666, "Kotlin": 14457, "Java": 8536, "Python": 4928, "Swift": 3893, "Makefile": 2257, "Scala": 890, "Elm": 191, "CSS": 56} | import java.io.*
import java.math.*
import java.security.*
import java.text.*
import java.util.*
import java.util.concurrent.*
import java.util.function.*
import java.util.regex.*
import java.util.stream.*
import kotlin.collections.*
import kotlin.comparisons.*
import kotlin.io.*
import kotlin.jvm.*
import kotlin.jvm.functions.*
import kotlin.jvm.internal.*
import kotlin.ranges.*
import kotlin.sequences.*
import kotlin.text.*
fun recursive(w: String, best: String, bestFlag: Boolean, next: String, nextFlag: Boolean, index: Int): String {
val subset = w.substring(1)
val subsets = subset.mapIndexed { subIndex, char ->
var a: CharArray = w.toCharArray()
val temp = a[index]
a[index] = char
a[subIndex] = temp
a.joinToString("")
}
subsets.sorted().forEach{ println(it) }
println(subsets)
return ""
}
// Complete the biggerIsGreater function below.
fun biggerIsGreater(w: String): String {
return recursive(w, w, false, "", false, 0)
}
fun main(args: Array<String>) {
// val inputs = arrayOf("ab", "bb", "hefg", "dhck", "dkhc")
val inputs = arrayOf("hefg")
inputs.forEach { (biggerIsGreater(it)) }
// inputs.forEach { println(biggerIsGreater(it)) }
}
| 0 | JavaScript | 0 | 0 | a394f100155fa4eb1032c09cdc85816b7104804b | 1,238 | study | MIT License |
test/leetcode/NumberOfStudentsUnableToEatLunch.kt | andrej-dyck | 340,964,799 | false | null | package leetcode
import lib.IntArrayArg
import org.assertj.core.api.Assertions
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.converter.ConvertWith
import org.junit.jupiter.params.provider.CsvSource
/**
* https://leetcode.com/problems/number-of-students-unable-to-eat-lunch/
*
* 1700. Number of Students Unable to Eat Lunch
* [Easy]
*
* The school cafeteria offers circular and square sandwiches at lunch break,
* referred to by numbers 0 and 1 respectively.
* All students stand in a queue. Each student either prefers square or circular sandwiches.
*
* The number of sandwiches in the cafeteria is equal to the number of students.
* The sandwiches are placed in a stack. At each step:
* - If the student at the front of the queue prefers the sandwich on the top of the stack,
* they will take it and leave the queue.
* - Otherwise, they will leave it and go to the queue's end.
*
* This continues until none of the queue students want to take the top sandwich and are thus unable to eat.
*
* You are given two integer arrays students and sandwiches where sandwiches[i] is the type of the i-th sandwich
* in the stack (i = 0 is the top of the stack) and students[j] is the preference of the j-th student
* in the initial queue (j = 0 is the front of the queue). Return the number of students that are unable to eat.
*
* Constraints:
* - 1 <= students.length, sandwiches.length <= 100
* - students.length == sandwiches.length
* - sandwiches[i] is 0 or 1.
* - students[i] is 0 or 1.
*/
typealias SandwichType = Int
typealias StudentPreferences = Array<SandwichType>
typealias SandwichRequests = Map<SandwichType, Int>
typealias Sandwiches = Array<SandwichType>
fun hungryStudents(students: StudentPreferences, sandwiches: Sandwiches) =
satisfyRequests(requests = students.groupingBy { it }.eachCount(), sandwiches)
tailrec fun satisfyRequests(requests: SandwichRequests, sandwiches: Sandwiches): Int =
when {
sandwiches.none() || requests.noneFor(sandwiches.first()) -> requests.sum()
else -> satisfyRequests(
requests.decrementFor(sandwiches.first()),
sandwiches.withoutFirst()
)
}
fun SandwichRequests.noneFor(sandwich: SandwichType) = getOrDefault(sandwich, 0) == 0
fun SandwichRequests.sum() = values.sum()
fun SandwichRequests.decrementFor(sandwich: SandwichType) =
mapValues { (k, v) -> if (k == sandwich) v - 1 else v }
fun Sandwiches.withoutFirst() = drop(1).toTypedArray()
/**
* Unit Tests
*/
class NumberOfStudentsUnableToEatLunchTest {
@ParameterizedTest
@CsvSource(
"[1]; [0]; 1",
"[0]; [1]; 1",
"[0]; [0]; 0",
"[1]; [1]; 0",
"[1,0]; [0,1]; 0",
"[1,0]; [0,0]; 1",
"[1,1]; [0,0]; 2",
"[1,1]; [0,1]; 2",
"[0,1]; [0,0]; 1",
"[0,1]; [1,0]; 0",
"[0,1]; [0,1]; 0",
"[0,0]; [0,1]; 1",
"[0,0]; [1,0]; 2",
"[0,0]; [0,0]; 0",
"[1,1,0,0]; [0,1,0,1]; 0",
"[1,1,0,0]; [0,1,0]; 1",
"[1,1,0]; [0,1,1,0]; 0",
"[1,1,0]; [0,1,0,1]; 1",
"[1,1,1,0,0,1]; [1,0,0,0,1,1]; 3",
delimiter = ';'
)
fun `the number of students that are unable to eat`(
@ConvertWith(IntArrayArg::class) studentPreferences: StudentPreferences,
@ConvertWith(IntArrayArg::class) sandwiches: Sandwiches,
expectedHungryStudents: Int
) {
Assertions.assertThat(
hungryStudents(studentPreferences, sandwiches)
).isEqualTo(
expectedHungryStudents
)
}
} | 0 | Kotlin | 0 | 0 | 3e3baf8454c34793d9771f05f330e2668fda7e9d | 3,606 | coding-challenges | MIT License |
src/Day12_2.kt | lsimeonov | 572,929,910 | false | {"Kotlin": 66434} |
import readInput
import java.util.LinkedList
import java.util.Queue
fun main() {
data class RowCol(
val row: Int,
val col: Int
)
var sourceP: RowCol? = null
var destP: RowCol? = null
val sourceDestinations = mutableListOf<RowCol>()
fun List<String>.initMatrix(matrix: Array<CharArray>) {
val rowSize = size
val colSize = this[0].length
for (row in 0 until rowSize) {
for (col in 0 until colSize) {
matrix[row][col] = this[row][col]
if (matrix[row][col] == 'S') {
sourceP = RowCol(row, col)
sourceDestinations.add(RowCol(row, col))
}
if (matrix[row][col] == 'a'){
sourceDestinations.add(RowCol(row, col))
}
if (matrix[row][col] == 'E') {
destP = RowCol(row, col)
}
}
}
}
fun Array<CharArray>.printMatrix() {
for (i in 0 until this.size) {
for (j in 0 until this[0].size) {
print(this[i][j])
print(" ")
}
println()
}
}
fun findShortestPath(srcDest: RowCol, grid: Array<CharArray>): Int {
val rowInbound = grid.indices
val colInbound = 0 until grid[0].size
val queue: Queue<Pair<RowCol, Int>> = LinkedList()
queue.add(Pair(srcDest, 0))
val visited = hashSetOf<RowCol>()
visited.add(srcDest)
while (queue.isNotEmpty()) {
val (nodeP, distance) = queue.remove()
if (nodeP == destP) return distance
var currentElevation = grid[nodeP.row][nodeP.col]
if (currentElevation == 'S') currentElevation = 'a'
fun up() {
val up = RowCol(nodeP.row - 1, nodeP.col)
if (up.row !in rowInbound || up.col !in colInbound) return
var nextElevation = grid[up.row][up.col]
if (nextElevation == 'E') nextElevation = 'z'
if (
currentElevation == nextElevation ||
currentElevation + 1 == nextElevation ||
currentElevation > nextElevation
){
if (!visited.contains(up)){
visited.add(up)
queue.add(Pair(up, distance + 1))
}
}
}
fun down() {
val down = RowCol(nodeP.row + 1, nodeP.col)
if (down.row !in rowInbound || down.col !in colInbound) return
var nextElevation = grid[down.row][down.col]
if (nextElevation == 'E') nextElevation = 'z'
if (
currentElevation == nextElevation ||
currentElevation + 1 == nextElevation ||
currentElevation > nextElevation
){
if (!visited.contains(down)){
visited.add(down)
queue.add(Pair(down, distance + 1))
}
}
}
fun left() {
val left = RowCol(nodeP.row, nodeP.col - 1)
if (left.row !in rowInbound || left.col !in colInbound) return
var nextElevation = grid[left.row][left.col]
if (nextElevation == 'E') nextElevation = 'z'
if (
currentElevation == nextElevation ||
currentElevation + 1 == nextElevation ||
currentElevation > nextElevation
){
if (!visited.contains(left)){
visited.add(left)
queue.add(Pair(left, distance + 1))
}
}
}
fun right() {
val right = RowCol(nodeP.row, nodeP.col + 1)
if (right.row !in rowInbound || right.col !in colInbound) return
var nextElevation = grid[right.row][right.col]
if (nextElevation == 'E') nextElevation = 'z'
if (
currentElevation == nextElevation ||
currentElevation + 1 == nextElevation ||
currentElevation > nextElevation
){
if (!visited.contains(right)){
visited.add(right)
queue.add(Pair(right, distance + 1))
}
}
}
up()
down()
left()
right()
}
return -1
}
fun part1(input: List<String>): Int {
val rowSize = input.size
val colSize = input[0].length
val grid = Array(rowSize) { CharArray(colSize) }
input.initMatrix(grid)
return findShortestPath(sourceP!!, grid)
}
fun part2(input: List<String>): Int {
val rowSize = input.size
val colSize = input[0].length
val grid = Array(rowSize) { CharArray(colSize) }
input.initMatrix(grid)
var short = Int.MAX_VALUE
sourceDestinations.forEach {
val result = findShortestPath(it, grid)
if (result < short && result != -1){
short = result
}
}
return short
}
val testInput = readInput("/Day12_test")
println(part1(testInput))
println(part2(testInput))
println("----------------------------------------------")
val input = readInput("/Day12")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 9d41342f355b8ed05c56c3d7faf20f54adaa92f1 | 5,703 | advent-of-code-2022 | Apache License 2.0 |
src/test/kotlin/be/brammeerten/y2023/Day2Test.kt | BramMeerten | 572,879,653 | false | {"Kotlin": 170522} | package be.brammeerten.y2023
import be.brammeerten.extractRegexGroups
import be.brammeerten.readFile
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import java.util.regex.Pattern
import kotlin.math.max
class Day2Test {
@Test
fun `part 1`() {
val lines = readFile("2023/day2/exampleInput.txt");
val sum = lines
.map { line ->
val matcher = extractRegexGroups("^Game ([0-9]+): (.+)$", line)
val games = matcher[1].split("; ")
(matcher[0] to extractGames(games))
}
.filter { games ->
games.second.none {
it["red"]!! > 12 || it["green"]!! > 13 || it["blue"]!! > 14
}
}
.sumOf { Integer.parseInt(it.first) }
assertThat(sum).isEqualTo(8);
// assertThat(sum).isEqualTo(2169);
}
@Test
fun `part 2`() {
val lines = readFile("2023/day2/exampleInput.txt");
val sum = lines
.map { line ->
val matcher = extractRegexGroups("^Game ([0-9]+): (.+)$", line)
val games = matcher[1].split("; ")
(matcher[0] to extractGames(games))
}
.map { games ->
val acc = games.second.fold(games.second[0]) { acc, game ->
return acc.keys.forEach {
acc[it] = max(acc[it]!!, game[it]!!)
}
}
acc.values.reduce { acc, elem -> acc * elem }
}
.sumOf { it }
assertThat(sum).isEqualTo(2286);
// assertThat(sum).isEqualTo(60948);
}
private fun extractGames(games: List<String>): List<MutableMap<String, Int>> {
return games.map {
val dice = mutableMapOf("red" to 0, "green" to 0, "blue" to 0);
it.split(", ").forEach { g ->
val s = g.split(" ")
dice[s[1]] = Integer.parseInt(s[0])
}
dice
}
}
} | 0 | Kotlin | 0 | 0 | 1defe58b8cbaaca17e41b87979c3107c3cb76de0 | 2,068 | Advent-of-Code | MIT License |
src/main/kotlin/ru/amai/study/hackerrank/practice/interviewPreparationKit/sorting/merge/CountInversions.kt | slobanov | 200,526,003 | false | null | package ru.amai.study.hackerrank.practice.interviewPreparationKit.sorting.merge
import java.util.*
fun countInversions(arr: IntArray): Long =
mergeSortSupport(arr, IntArray(arr.size), 0, arr.size)
fun mergeSortSupport(arr: IntArray, temp: IntArray, left: Int, right: Int): Long =
if (right - left > 1) {
var inversionCnt: Long
val mid = (right + left) / 2
inversionCnt = mergeSortSupport(arr, temp, left, mid)
inversionCnt += mergeSortSupport(arr, temp, mid, right)
inversionCnt += merge(arr, temp, left, mid, right)
inversionCnt
} else 0L
fun merge(arr: IntArray, temp: IntArray, left: Int, mid: Int, right: Int): Long {
var inversionCnt = 0L
var i: Int = left
var j: Int = mid
var k: Int = left
while (i < mid && j < right) {
if (arr[i] <= arr[j]) {
temp[k++] = arr[i++]
} else {
temp[k++] = arr[j++]
inversionCnt += (mid - i)
}
}
(i until mid).forEach { temp[k++] = arr[it] }
(j until right).forEach { temp[k++] = arr[it] }
(left until right).forEach { arr[it] = temp[it] }
return inversionCnt
}
fun main() {
val scan = Scanner(System.`in`)
val t = scan.nextLine().trim().toInt()
for (tItr in 1..t) {
scan.nextLine().trim().toInt()
val arr = scan.nextLine().split(" ").map { it.trim().toInt() }.toIntArray()
val result = countInversions(arr)
println(result)
}
}
| 0 | Kotlin | 0 | 0 | 2cfdf851e1a635b811af82d599681b316b5bde7c | 1,487 | kotlin-hackerrank | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MinimizeMaximumOfArray.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import kotlin.math.max
/**
* 2439. Minimize Maximum of Array
* @see <a href="https://leetcode.com/problems/minimize-maximum-of-array/">Source</a>
*/
fun interface MinimizeMaximumOfArray {
fun minimizeArrayValue(nums: IntArray): Int
}
class MinimizeMaximumOfArrayPrefixSum : MinimizeMaximumOfArray {
override fun minimizeArrayValue(nums: IntArray): Int {
var sum: Long = 0
var res: Long = 0
for (i in nums.indices) {
sum += nums[i]
res = max(res, (sum + i) / (i + 1))
}
return res.toInt()
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,215 | kotlab | Apache License 2.0 |
src/day05/Day05.kt | veronicamengyan | 573,063,888 | false | {"Kotlin": 14976} | package day05
import java.lang.StringBuilder
import java.util.ArrayDeque
import readInput
fun main() {
fun findTopCrates(input: List<String>): String {
var top = mutableListOf<String>()
val bottom = mutableListOf<String>()
var isInstruction = false;
for(item in input) {
if(item.isEmpty()) {
isInstruction = true
continue
}
if (!isInstruction) {
top.add(item)
} else {
bottom.add(item)
}
}
val numbers = top.takeLast(1).get(0)
top = top.subList(0, top.size-1)
val numberOfStack = numbers.substring(numbers.length-1, numbers.length).toInt()
val stacks = MutableList(numberOfStack){ArrayDeque<String>()}
for (item in top) {
item.chunked(4).forEachIndexed{
idx, value ->
if (value.substring(1,2).isNotBlank()) {
stacks[idx].push(value.substring(1,2))
}
}
}
for (item in bottom) {
val matches = Regex("\\d+").findAll(item).toList()
repeat(matches[0].value.toInt()) {
stacks[matches[2].value.toInt()-1].add(stacks[matches[1].value.toInt()-1].removeLast())
}
}
val result = StringBuilder()
stacks.forEach{ stack -> result.append(stack.peekLast())}
return result.toString()
}
fun findTopCrates2(input: List<String>): String {
var top = mutableListOf<String>()
val bottom = mutableListOf<String>()
var isInstruction = false;
for(item in input) {
if(item.isEmpty()) {
isInstruction = true
continue
}
if (!isInstruction) {
top.add(item)
} else {
bottom.add(item)
}
}
val numbers = top.takeLast(1).get(0)
top = top.subList(0, top.size-1)
val numberOfStack = numbers.substring(numbers.length-1, numbers.length).toInt()
val stacks = MutableList(numberOfStack){ArrayDeque<String>()}
for (item in top) {
item.chunked(4).forEachIndexed{
idx, value ->
if (value.substring(1,2).isNotBlank()) {
stacks[idx].push(value.substring(1,2))
}
}
}
for (item in bottom) {
val matches = Regex("\\d+").findAll(item).toList()
val local = mutableListOf<String>()
repeat(matches[0].value.toInt()) {
local.add(stacks[matches[1].value.toInt()-1].removeLast())
}
stacks[matches[2].value.toInt()-1].addAll(local.reversed())
}
val result = StringBuilder()
stacks.forEach{ stack -> result.append(stack.peekLast())}
return result.toString()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("day05/Day05_test")
println(findTopCrates(testInput))
check(findTopCrates(testInput) == "CMZ")
println(findTopCrates2(testInput))
check(findTopCrates2(testInput) == "MCD")
val input = readInput("day05/Day05")
println(findTopCrates(input))
println(findTopCrates2(input))
} | 0 | Kotlin | 0 | 0 | d443cfa49e9d8c9f76fdb6303ecf104498effb88 | 3,350 | aoc-2022-in-kotlin | Apache License 2.0 |
src/day06/Day06.kt | sanyarajan | 572,663,282 | false | {"Kotlin": 24016} | @file:Suppress("SpellCheckingInspection")
package day06
import readInputText
fun main() {
fun findDistinctSequenceOfLength(input: String, sequenceLength:Int): Int {
(0..input.length - sequenceLength).forEach { i ->
val sub = input.subSequence(i, i + sequenceLength)
val set = sub.toSet()
if (set.size == sequenceLength) {
return i + sequenceLength
}
}
return 0
}
fun part1(input: String): Int {
// find the first set of 4 characters that are different
return findDistinctSequenceOfLength(input, 4)
}
fun part2(input: String): Int {
return findDistinctSequenceOfLength(input, 14)
}
// test if implementation meets criteria from the description, like:
check(part1("mjqjpqmgbljsphdztnvjfqwrcgsmlb") == 7)
check(part1("bvwbjplbgvbhsrlpgdmjqwftvncz") == 5)
check(part1("nppdvjthqldpwncqszvftbrmjlhg") == 6)
check(part1("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg") == 10)
check(part1("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw") == 11)
check(part2("mjqjpqmgbljsphdztnvjfqwrcgsmlb") == 19)
check(part2("bvwbjplbgvbhsrlpgdmjqwftvncz") == 23)
check(part2("nppdvjthqldpwncqszvftbrmjlhg") == 23)
check(part2("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg") == 29)
check(part2("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw") == 26)
// check(part2(testInput) == "MCD")
val input = readInputText("day06/day06")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | e23413357b13b68ed80f903d659961843f2a1973 | 1,513 | Kotlin-AOC-2022 | Apache License 2.0 |
src/main/kotlin/me/circuitrcay/euler/challenges/oneToTwentyFive/Problem4.kt | adamint | 134,989,381 | false | null | package me.circuitrcay.euler.challenges.oneToTwentyFive
import me.circuitrcay.euler.Problem
class Problem4 : Problem<String>() {
override fun calculate(): Any {
var largest = PalindromeResult(0, 0, 0)
for (i in 100..999) {
for (j in 100..999) {
if (isPal(i, j) && i * j > largest.product) largest = PalindromeResult(i, j)
}
}
return "${largest.first} * ${largest.second} = ${largest.product}"
}
private fun isPal(i: Int, j: Int): Boolean {
val str = (i * j).toString()
return str.substring(0, Math.floor(str.length / 2.0).toInt()) == str.substring(Math.ceil(str.length / 2.0).toInt(), str.length).reversed()
}
}
data class PalindromeResult(val first: Int, val second: Int, val product: Int = first * second)
| 0 | Kotlin | 0 | 0 | cebe96422207000718dbee46dce92fb332118665 | 816 | project-euler-kotlin | Apache License 2.0 |
Add_Two_Numbers_II.kt | xiekch | 166,329,519 | false | {"C++": 165148, "Java": 103273, "Kotlin": 97031, "Go": 40017, "Python": 22302, "TypeScript": 17514, "Swift": 6748, "Rust": 6579, "JavaScript": 4244, "Makefile": 349} | import java.util.*
// https://leetcode.com/problems/add-two-numbers-ii/discuss/92623/Easy-O(n)-Java-Solution-using-Stackhttps://leetcode.com/problems/add-two-numbers-ii/discuss/92623/Easy-O(n)-Java-Solution-using-Stack
// Definition for singly-linked list.
// Example:
// var li = ListNode(5)
// var v = li.`val`
// Definition for singly-linked list.
//class ListNode(var `val`: Int) {
// var next: ListNode? = null
//}
class Solution {
fun addTwoNumbers(l1: ListNode?, l2: ListNode?): ListNode? {
var p1 = l1
var p2 = l2
val st1 = Stack<Int>();
val st2 = Stack<Int>()
while (p1 != null) {
st1.push(p1.`val`)
p1 = p1.next
}
while (p2 != null) {
st2.push(p2.`val`)
p2 = p2.next
}
var carry = 0
var head: ListNode? = null
while (!st1.isEmpty() || !st2.isEmpty() || carry == 1) {
val sum = (if (st1.isEmpty()) 0 else st1.pop()) + (if (st2.isEmpty()) 0 else st2.pop()) + carry
val t = ListNode(sum % 10)
// println("%d %d".format(sum, t.`val`))
t.next = head
head = t
carry = sum / 10
}
return head
}
}
fun main() {
val solution = Solution()
val testset = arrayOf(
arrayOf(
intArrayOf(7, 2, 4, 3),
intArrayOf(5, 6, 4)
),
arrayOf(
intArrayOf(5),
intArrayOf(5)
)
)
for (test in testset) {
val l1 = ListUtils.buildList(test[0])
val l2 = ListUtils.buildList(test[1])
ListUtils.printList(solution.addTwoNumbers(l1, l2))
}
} | 0 | C++ | 0 | 0 | eb5b6814e8ba0847f0b36aec9ab63bcf1bbbc134 | 1,726 | leetcode | MIT License |
src/Day06.kt | kecolk | 572,819,860 | false | {"Kotlin": 22071} | fun main() {
fun isDistinct(buffer: List<Char>): Boolean =
buffer.all { chr -> buffer.count { it == chr } == 1 }
fun findStart(input: String, size: Int): Int {
val signal = input.toList()
signal.windowed(size = size, step = 1, partialWindows = false)
.forEachIndexed { index, window ->
if (isDistinct(window)) return index + size
}
return 0
}
fun part1(input: String): Int {
return findStart(input, 4)
}
fun part2(input: String): Int {
return findStart(input, 14)
}
val testInput = readTextInput("Day06_test").first()
val input = readTextInput("Day06").first()
check(part1(testInput) == 7)
check(part2(testInput) == 19)
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 72b3680a146d9d05be4ee209d5ba93ae46a5cb13 | 813 | kotlin_aoc_22 | Apache License 2.0 |
dataStructuresAndAlgorithms/src/main/java/dev/funkymuse/datastructuresandalgorithms/trees/avl/AVLTree.kt | FunkyMuse | 168,687,007 | false | {"Kotlin": 1728251} | package dev.funkymuse.datastructuresandalgorithms.trees.avl
import kotlin.math.max
class AVLTree<T : Comparable<T>> {
var root: AVLNode<T>? = null
fun insert(value: T) {
root = insert(root, value)
}
fun remove(value: T) {
root = remove(root, value)
}
private fun remove(node: AVLNode<T>?, value: T): AVLNode<T>? {
node ?: return null
when {
value == node.value -> {
if (node.leftChild == null && node.rightChild == null) {
return null
}
if (node.leftChild == null) {
return node.rightChild
}
if (node.rightChild == null) {
return node.leftChild
}
node.rightChild?.min?.value?.let {
node.value = it
}
node.rightChild = remove(node.rightChild, node.value)
}
value < node.value -> node.leftChild = remove(node.leftChild, value)
else -> node.rightChild = remove(node.rightChild, value)
}
val balancedNode = balanced(node)
balancedNode.height = max(
balancedNode.leftHeight,
balancedNode.rightHeight
) + 1
return balancedNode
}
override fun toString() = root?.toString() ?: "empty tree"
fun contains(value: T): Boolean {
var current = root
while (current != null) {
if (current.value == value) {
return true
}
current = if (value < current.value) {
current.leftChild
} else {
current.rightChild
}
}
return false
}
private fun balanced(node: AVLNode<T>): AVLNode<T> {
return when (node.balanceFactor) {
2 -> {
if (node.leftChild?.balanceFactor == -1) {
leftRightRotate(node)
} else {
rightRotate(node)
}
}
-2 -> {
if (node.rightChild?.balanceFactor == 1) {
rightLeftRotate(node)
} else {
leftRotate(node)
}
}
else -> node
}
}
private fun leftRotate(node: AVLNode<T>): AVLNode<T> {
val pivot = node.rightChild!!
node.rightChild = pivot.leftChild
pivot.leftChild = node
node.height = max(node.leftHeight, node.rightHeight) + 1
pivot.height = max(pivot.leftHeight, pivot.rightHeight) + 1
return pivot
}
private fun rightRotate(node: AVLNode<T>): AVLNode<T> {
val pivot = node.leftChild!!
node.leftChild = pivot.rightChild
pivot.rightChild = node
node.height = max(node.leftHeight, node.rightHeight) + 1
pivot.height = max(pivot.leftHeight, pivot.rightHeight) + 1
return pivot
}
private fun rightLeftRotate(node: AVLNode<T>): AVLNode<T> {
val rightChild = node.rightChild ?: return node
node.rightChild = rightRotate(rightChild)
return leftRotate(node)
}
private fun leftRightRotate(node: AVLNode<T>): AVLNode<T> {
val leftChild = node.leftChild ?: return node
node.leftChild = rightRotate(leftChild)
return rightRotate(node)
}
private fun insert(node: AVLNode<T>?, value: T): AVLNode<T> {
node ?: return AVLNode(value)
if (value < node.value) {
node.leftChild = insert(node.leftChild, value)
} else {
node.rightChild = insert(node.rightChild, value)
}
val balancedNode = balanced(node)
balancedNode.height = max(
balancedNode.leftHeight,
balancedNode.rightHeight
) + 1
return balancedNode
}
}
| 0 | Kotlin | 92 | 771 | e2afb0cc98c92c80ddf2ec1c073d7ae4ecfcb6e1 | 3,924 | KAHelpers | MIT License |
src/Day01.kt | dmdrummond | 573,289,191 | false | {"Kotlin": 9084} | fun main() {
fun buildList(input: List<String>): List<Int> {
val calorieList = mutableListOf<Int>()
var calories = 0
input.forEach {
if (it.isEmpty()) {
calorieList.add(calories)
calories = 0
} else {
calories += (it.toInt())
}
}
calorieList.add(calories)
return calorieList
}
fun part1(input: List<Int>) = input.max()
fun part2(input: List<Int>) = input.sorted().takeLast(3).sum()
val testInput = readInput("Day01_test")
val parsedTestList = buildList(testInput)
check(part1(parsedTestList) == 24000)
check(part2(parsedTestList) == 45000)
val input = readInput("Day01")
val parsedList = buildList(input)
println("Part 1: ${part1(parsedList)}")
println("Part 2: ${part2(parsedList)}")
}
| 0 | Kotlin | 0 | 0 | 2493256124c341e9d4a5e3edfb688584e32f95ec | 870 | AoC2022 | Apache License 2.0 |
src/main/kotlin/days/aoc2020/Day21.kt | bjdupuis | 435,570,912 | false | {"Kotlin": 537037} | package days.aoc2020
import days.Day
class Day21: Day(2020, 21) {
override fun partOne(): Any {
var potentialIngredientsForAllergen = mutableMapOf<String, MutableSet<String>>()
val allIngredients = mutableMapOf<String, Int>()
inputList.forEach {
Regex("(.*) \\(contains (.*)\\)").matchEntire(it)?.destructured?.let { (ingredients, allergens) ->
val potentialIngredients = ingredients.split(" ")
potentialIngredients.forEach { ingredient ->
allIngredients[ingredient] = allIngredients.getOrDefault(ingredient, 0) + 1
}
allergens.split(", ").forEach { allergen ->
if (!potentialIngredientsForAllergen.containsKey(allergen)) {
potentialIngredientsForAllergen[allergen] = mutableSetOf()
potentialIngredientsForAllergen[allergen]!!.addAll(potentialIngredients)
}
potentialIngredientsForAllergen[allergen] = potentialIngredientsForAllergen[allergen]?.intersect(potentialIngredients)?.toMutableSet() ?: mutableSetOf()
}
}
}
return allIngredients.filter { ingredient ->
potentialIngredientsForAllergen.values.none { it.contains(ingredient.key) }
}.map {
it.value
}.sum()
}
override fun partTwo(): Any {
var potentialIngredientsForAllergen = mutableMapOf<String, MutableSet<String>>()
val allIngredients = mutableMapOf<String, Int>()
inputList.forEach {
Regex("(.*) \\(contains (.*)\\)").matchEntire(it)?.destructured?.let { (ingredients, allergens) ->
val potentialIngredients = ingredients.split(" ")
potentialIngredients.forEach { ingredient ->
allIngredients[ingredient] = allIngredients.getOrDefault(ingredient, 0) + 1
}
allergens.split(", ").forEach { allergen ->
if (!potentialIngredientsForAllergen.containsKey(allergen)) {
potentialIngredientsForAllergen[allergen] = mutableSetOf()
potentialIngredientsForAllergen[allergen]!!.addAll(potentialIngredients)
}
potentialIngredientsForAllergen[allergen] = potentialIngredientsForAllergen[allergen]?.intersect(potentialIngredients)?.toMutableSet() ?: mutableSetOf()
}
}
}
do {
val knownBadIngredients = potentialIngredientsForAllergen.filter { ingredientMap ->
ingredientMap.value.size == 1
}.map { it.value.first() }.toSet()
potentialIngredientsForAllergen.filter { it.value.size > 1 && it.value.intersect(knownBadIngredients).isNotEmpty() }.forEach { candidate ->
candidate.value.removeIf { knownBadIngredients.contains(it) }
}
} while(potentialIngredientsForAllergen.count { it.value.size > 1 } > 0)
return potentialIngredientsForAllergen.toSortedMap().map {
it.value.first()
}.joinToString(",")
}
} | 0 | Kotlin | 0 | 1 | c692fb71811055c79d53f9b510fe58a6153a1397 | 3,170 | Advent-Of-Code | Creative Commons Zero v1.0 Universal |
src/main/kotlin/com/jaspervanmerle/aoc2021/day/Day11.kt | jmerle | 434,010,865 | false | {"Kotlin": 60581} | package com.jaspervanmerle.aoc2021.day
class Day11 : Day("1719", "232") {
private data class Point(val x: Int, val y: Int)
private val width = input.lines()[0].length
private val height = input.lines().size
private val directions = listOf(
-1 to 0,
1 to 0,
0 to -1,
0 to 1,
-1 to -1,
-1 to 1,
1 to -1,
1 to 1
)
override fun solvePartOne(): Any {
return simulateFlashes().take(100).sum()
}
override fun solvePartTwo(): Any {
return simulateFlashes().withIndex().first { it.value == width * height }.index + 1
}
private fun simulateFlashes(): Sequence<Int> {
return sequence {
val energyLevels = input
.lines()
.map { line -> line.toCharArray().map { it.digitToInt() }.toMutableList() }
while (true) {
var flashes = 0
val queue = ArrayDeque<Point>()
for (y in 0 until height) {
for (x in 0 until width) {
energyLevels[y][x]++
if (energyLevels[y][x] > 9) {
energyLevels[y][x] = 0
flashes++
queue.add(Point(x, y))
}
}
}
while (!queue.isEmpty()) {
val (currentX, currentY) = queue.removeFirst()
for ((dx, dy) in directions) {
val newX = currentX + dx
val newY = currentY + dy
if (newX !in 0 until width || newY !in 0 until height) {
continue
}
if (energyLevels[newY][newX] == 0) {
continue
}
energyLevels[newY][newX]++
if (energyLevels[newY][newX] > 9) {
energyLevels[newY][newX] = 0
flashes++
queue.add(Point(newX, newY))
}
}
}
yield(flashes)
}
}
}
}
| 0 | Kotlin | 0 | 0 | dcac2ac9121f9bfacf07b160e8bd03a7c6732e4e | 2,295 | advent-of-code-2021 | MIT License |
adventofcode/1/main.kt | seirion | 17,619,607 | false | {"C++": 801740, "HTML": 42242, "Kotlin": 37689, "Python": 21759, "C": 3798, "JavaScript": 294} | // part 1
fun main() {
val abc = "ABC"
val xyz = "XYZ"
var out = 0
while (true) {
val input = readLine() ?: break
val (a, b) = input.split(" ").map { it.first() }
out += score(abc.indexOf(a), xyz.indexOf(b))
}
println(out)
}
fun score(a: Int, b: Int): Int {
return (1 + b) + if (a == b) 3
else if (b == (a + 1) % 3) 6
else 0
}
// part 2
fun main() {
val abc = "ABC"
var out = 0
while (true) {
val input = readLine() ?: break
val (a, b) = input.split(" ").map { it.first() }
val aa = abc.indexOf(a)
val bb = if (b == 'X') (aa + 2) % 3 // lose
else if (b == 'Y') aa // draw
else (aa + 1) % 3 // win
out += score(aa, bb)
}
println(out)
}
fun score(a: Int, b: Int): Int {
return (1 + b) + if (a == b) 3
else if (b == (a + 1) % 3) 6
else 0
}
| 0 | C++ | 4 | 4 | a59df98712c7eeceabc98f6535f7814d3a1c2c9f | 787 | code | Apache License 2.0 |
src/Day23.kt | abeltay | 572,984,420 | false | {"Kotlin": 91982, "Shell": 191} | fun main() {
fun parseInput(input: List<String>): MutableList<Pair<Int, Int>> {
val elves = mutableListOf<Pair<Int, Int>>()
for (i in input.indices) {
for (j in input[i].indices) {
if (input[i][j] == '#') {
elves.add(Pair(i, j))
}
}
}
return elves
}
fun isVerticalSidesOccupied(elves: List<Pair<Int, Int>>, location: Pair<Int, Int>): Boolean {
return elves.contains(Pair(location.first - 1, location.second)) ||
elves.contains(Pair(location.first, location.second)) ||
elves.contains(Pair(location.first + 1, location.second))
}
fun isHorizontalSidesOccupied(elves: List<Pair<Int, Int>>, location: Pair<Int, Int>): Boolean {
return elves.contains(Pair(location.first, location.second - 1)) ||
elves.contains(Pair(location.first, location.second)) ||
elves.contains(Pair(location.first, location.second + 1))
}
val directions = listOf(
fun(elves: List<Pair<Int, Int>>, elf: Pair<Int, Int>): Pair<Int, Int>? {
val next = Pair(elf.first - 1, elf.second)
return if (!isHorizontalSidesOccupied(elves, next)) {
next
} else {
null
}
},
fun(elves: List<Pair<Int, Int>>, elf: Pair<Int, Int>): Pair<Int, Int>? {
val next = Pair(elf.first + 1, elf.second)
return if (!isHorizontalSidesOccupied(elves, next)) {
next
} else {
null
}
},
fun(elves: List<Pair<Int, Int>>, elf: Pair<Int, Int>): Pair<Int, Int>? {
val next = Pair(elf.first, elf.second - 1)
return if (!isVerticalSidesOccupied(elves, next)) {
next
} else {
null
}
},
fun(elves: List<Pair<Int, Int>>, elf: Pair<Int, Int>): Pair<Int, Int>? {
val next = Pair(elf.first, elf.second + 1)
return if (!isVerticalSidesOccupied(elves, next)) {
next
} else {
null
}
}
)
fun hasMoved(elves: MutableList<Pair<Int, Int>>, direction: Int): Boolean {
var stationary = 0
val proposed = mutableListOf<Pair<Int, Int>>()
for (elf in elves) {
var found = false
for (i in elf.first - 1..elf.first + 1) {
for (j in elf.second - 1..elf.second + 1) {
if (i == elf.first && j == elf.second) continue
if (elves.contains(Pair(i, j)))
found = true
}
}
if (!found) {
stationary++
proposed.add(elf)
continue
}
found = false
for (i in 0..3) {
val next = directions[(direction + i) % 4](elves, elf)
if (next != null) {
proposed.add(next)
found = true
break
}
}
if (!found) proposed.add(elf)
}
for (i in proposed.indices) {
val next = if (proposed.count { it == proposed[i] } > 1) {
elves.first()
} else {
proposed[i]
}
elves.removeFirst()
elves.add(next)
}
if (stationary == proposed.size) {
return true
}
return false
}
fun part1(input: List<String>): Int {
val elves = parseInput(input)
for (i in 0..9) {
hasMoved(elves, i % 4)
}
val x = elves.maxOf { it.second } - elves.minOf { it.second } + 1
val y = elves.maxOf { it.first } - elves.minOf { it.first } + 1
return (x * y) - elves.size
}
fun part2(input: List<String>): Int {
val elves = parseInput(input)
var rounds = 0
while(true) {
if (hasMoved(elves, rounds % 4)){
return rounds +1
}
rounds++
}
}
val testInput = readInput("Day23_test")
check(part1(testInput) == 110)
check(part2(testInput) == 20)
val input = readInput("Day23")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | a51bda36eaef85a8faa305a0441efaa745f6f399 | 4,389 | advent-of-code-2022 | Apache License 2.0 |
src/Day21.kt | Aldas25 | 572,846,570 | false | {"Kotlin": 106964} | fun main() {
abstract class Operation() {
abstract fun doOperation(x: Long, y: Long): Long
abstract fun getLeft(req: Long, y: Long): Long
abstract fun getRight(req: Long, x: Long): Long
}
class AddOperation() : Operation() {
override fun doOperation(x: Long, y: Long): Long {
return x + y
}
override fun getLeft(req: Long, y: Long): Long {
return req - y
}
override fun getRight(req: Long, x: Long): Long {
return req - x
}
}
class SubtractOperation() : Operation() {
override fun doOperation(x: Long, y: Long): Long {
return x - y
}
override fun getLeft(req: Long, y: Long): Long {
return req + y
}
override fun getRight(req: Long, x: Long): Long {
return x - req
}
}
class MultiplyOperation() : Operation() {
override fun doOperation(x: Long, y: Long): Long {
return x * y
}
override fun getLeft(req: Long, y: Long): Long {
return req / y
}
override fun getRight(req: Long, x: Long): Long {
return req / x
}
}
class DivideOperation() : Operation() {
override fun doOperation(x: Long, y: Long): Long {
return x / y
}
override fun getLeft(req: Long, y: Long): Long {
return req * y
}
override fun getRight(req: Long, x: Long): Long {
return x / req
}
}
abstract class Node(val name: String) {
var parent: Node? = null
var onPath = false
abstract fun getResult(): Long
abstract fun solvePart2(reqNumber: Long): Long
fun markPath() {
onPath = true
if (parent != null)
parent!!.markPath()
}
}
class OperationNode(name: String) : Node(name) {
lateinit var left: Node
lateinit var right: Node
lateinit var op: Operation
fun setValues(left: Node, right: Node, op: Operation) {
this.left = left
this.right = right
this.op = op
}
override fun getResult(): Long {
return op.doOperation(left.getResult(), right.getResult())
}
override fun solvePart2(reqNumber: Long): Long {
if (name == "humn") return reqNumber
if (name == "root") {
if (!left.onPath) {
val req = left.getResult()
return right.solvePart2(req)
}
val req = right.getResult()
return left.solvePart2(req)
}
if (!left.onPath) {
val req = op.getRight(reqNumber, left.getResult())
return right.solvePart2(req)
}
val req = op.getLeft(reqNumber, right.getResult())
return left.solvePart2(req)
}
}
class LeafNode(name: String) : Node(name) {
var value = 0L
override fun getResult(): Long {
return value
}
override fun solvePart2(reqNumber: Long): Long {
return reqNumber
}
}
fun part1(nodes: List<Node>, nameToNode: Map<String, Node>): Long {
return nameToNode["root"]!!.getResult()
}
fun part2(nodes: List<Node>, nameToNode: Map<String, Node>): Long {
nameToNode["humn"]!!.markPath()
return nameToNode["root"]!!.solvePart2(-1)
}
fun parseInput(input: List<String>): Pair<List<Node>, Map<String, Node>> {
val list: MutableList<Node> = mutableListOf()
val map: MutableMap<String, Node> = mutableMapOf()
for (line in input) {
val name = line.split(":")[0]
lateinit var node: Node
if (line.length > 15)
node = OperationNode(name)
else
node = LeafNode(name)
list.add(node)
map[name] = node
}
fun getOperation(s: String): Operation {
return when (s) {
"+" -> AddOperation()
"-" -> SubtractOperation()
"*" -> MultiplyOperation()
else -> DivideOperation()
}
}
fun parseLine(line: String) {
val parts = line.split(": ", " ")
val name = parts[0]
val node = map[name]!!
if (node is LeafNode) {
node as LeafNode
node.value = parts[1].toLong()
} else {
node as OperationNode
val left = map[parts[1]]!!
val op = getOperation(parts[2])
val right = map[parts[3]]!!
left.parent = node
right.parent = node
node.setValues(left, right, op)
}
}
for (line in input)
parseLine(line)
return Pair(list, map)
}
val filename =
// "inputs/day21_sample"
"inputs/day21"
val input = readInput(filename)
val pair1 = parseInput(input)
val pair2 = parseInput(input)
println("Part 1: ${part1(pair1.first, pair1.second)}")
println("Part 2: ${part2(pair2.first, pair2.second)}")
} | 0 | Kotlin | 0 | 0 | 80785e323369b204c1057f49f5162b8017adb55a | 5,331 | Advent-of-Code-2022 | Apache License 2.0 |
app/src/main/java/eu/kanade/tachiyomi/data/library/LibraryUpdateRanker.kt | zeredouni | 537,907,731 | true | {"Kotlin": 2272674, "Shell": 1179} | package eu.kanade.tachiyomi.data.library
import eu.kanade.tachiyomi.data.database.models.Manga
import kotlin.math.abs
/**
* This class will provide various functions to Rank mangaList to efficiently schedule mangaList to update.
*/
object LibraryUpdateRanker {
val rankingScheme = listOf(
(this::lexicographicRanking)(),
(this::latestFirstRanking)(),
(this::nextFirstRanking)()
)
/**
* Provides a total ordering over all the MangaList.
*
* Orders the manga based on the distance between the next expected update and now.
* The comparator is reversed, placing the smallest (and thus closest to updating now) first.
*/
fun nextFirstRanking(): Comparator<Manga> {
val time = System.currentTimeMillis()
return Comparator {
mangaFirst: Manga,
mangaSecond: Manga,
->
compareValues(abs(mangaSecond.next_update - time), abs(mangaFirst.next_update - time))
}.reversed()
}
/**
* Provides a total ordering over all the MangaList.
*
* Assumption: An active [Manga] mActive is expected to have been last updated after an
* inactive [Manga] mInactive.
*
* Using this insight, function returns a Comparator for which mActive appears before mInactive.
* @return a Comparator that ranks manga based on relevance.
*/
fun latestFirstRanking(): Comparator<Manga> {
return Comparator {
mangaFirst: Manga,
mangaSecond: Manga,
->
compareValues(mangaSecond.last_update, mangaFirst.last_update)
}
}
/**
* Provides a total ordering over all the MangaList.
*
* Order the manga lexicographically.
* @return a Comparator that ranks manga lexicographically based on the title.
*/
fun lexicographicRanking(): Comparator<Manga> {
return Comparator {
mangaFirst: Manga,
mangaSecond: Manga,
->
compareValues(mangaFirst.title, mangaSecond.title)
}
}
}
| 32 | Kotlin | 0 | 0 | f6bb0a0b34ee9ccb761a126b4066193a71815e86 | 2,107 | Neko-master | Apache License 2.0 |
src/lexer/Lexer.kt | q-lang | 128,704,097 | false | null | package lexer
import io.File
import re.Regex
import java.io.StringReader
import kotlin.coroutines.experimental.buildSequence
private fun stringLines(string: String) = buildSequence {
StringReader(string).useLines { yieldAll(it) }
}
data class Lexer(
val vocabulary: Map<String, String>,
val keywords: Set<String> = setOf(),
val ignore_pattern: String = """\s+""",
val EOF: String = "<EOF>") {
val regex: Regex
val tags: MutableMap<String, String> = mutableMapOf()
val symbols: MutableMap<String, String> = mutableMapOf()
val ignoreGroup: String = "<IGNORE>"
val ignoreTag = "I${tags.size}"
class Builder(val ignore_pattern: String = """\s+""", val EOF: String = "<EOF>") {
val vocabulary: MutableMap<String, String> = mutableMapOf()
val keywords: MutableSet<String> = mutableSetOf()
fun rule(name: String, patterns: List<String>) = apply {
rule(name, patterns.joinToString("|"))
}
fun rule(name: String, pattern: String) = apply {
vocabulary[name] = pattern
}
fun keyword(name: String) = apply {
keywords.add(name)
}
fun build() = Lexer(vocabulary, keywords, ignore_pattern, EOF)
}
init {
val duplicates = vocabulary.keys.intersect(keywords)
if (duplicates.isNotEmpty())
throw DuplicateSymbols(duplicates)
for ((symbol, pattern) in vocabulary) {
if (symbol.isEmpty())
throw EmptySymbolName()
if (pattern.isEmpty())
throw EmptyVocabularyPattern(symbol)
}
for (symbol in keywords) {
if (symbol.isEmpty())
throw EmptySymbolName()
}
tags[ignoreGroup] = ignoreTag
symbols[ignoreTag] = ignoreGroup
val patternGroups = mutableListOf("(?<$ignoreTag>$ignore_pattern)")
for ((symbol, pattern) in vocabulary) {
val tag = "R${tags.size}"
tags[symbol] = tag
symbols[tag] = symbol
patternGroups += "(?<$tag>$pattern)"
}
for (symbol in keywords) {
val tag = "K${tags.size}"
tags[symbol] = tag
symbols[tag] = symbol
var pattern = ""
for (c in symbol)
pattern += if (c.isLetterOrDigit()) "$c" else "\\$c"
patternGroups += "(?<$tag>$pattern)"
}
regex = Regex(patternGroups.joinToString("|"))
val endStateToTags = mutableMapOf<Int, Set<String>>()
for ((tagName, group) in regex.fsm.groups) {
if (tagName[0].isDigit())
continue
endStateToTags[group.end] = endStateToTags[group.end].orEmpty().union(setOf(tagName))
}
val mainEndState = setOf(regex.fsm.groups[re.MAIN_GROUP]!!.end)
val keywordsEndStates = keywords.map { regex.fsm.groups[tags[it]]!!.end }.toSet()
for (state in regex.fsm.dfa.vertices.keys) {
val possibleEndStates = endStateToTags.keys.intersect(state) - mainEndState - keywordsEndStates
if (possibleEndStates.size > 1) {
val ambiguousTags = possibleEndStates.map { endStateToTags[it]!! }.flatten().toSet()
throw AmbiguousVocabulary(ambiguousTags)
}
}
}
fun tokenize(lines: Sequence<String>) = buildSequence {
var row = 0
var lastEnd = 0
for (line in lines) {
for (match in regex.matches(line)) {
var matched: String? = null
for ((tag, group) in match.groups) {
val symbol = symbols[tag]!!
if (group.end != match.end)
continue
if (symbol in keywords) {
matched = symbol
break
}
assert(matched == null)
matched = symbol
}
assert(matched != null)
// If it's not the group for ignore_pattern, yield that result
if (matched!! != ignoreGroup)
yield(Token(matched, line.slice(match.start until match.end), row, match.start))
lastEnd = match.end
}
row++
}
yield(Token(EOF, "", row - 1, lastEnd))
}
fun tokenize(string: String): Sequence<Token> {
return tokenize(stringLines(string))
}
fun tokenize(file: File): Sequence<Token> {
return tokenize(file.lines())
}
}
| 0 | Kotlin | 1 | 0 | 2d8a8b4d32ae8ec5b8ed9cce099bd58f37838833 | 4,050 | q-lang | MIT License |
Day5/src/IntState.kt | gautemo | 225,219,298 | false | null | import java.io.File
fun main(){
val state = File(Thread.currentThread().contextClassLoader.getResource("input.txt")!!.toURI()).readText()
val arr = toArr(state)
transform(arr)
}
fun transform(start: List<Int>): List<Int>{
val arr = start.toMutableList()
var i = 0
loop@ while (i < arr.size){
val de = arr[i] % 100
val c = arr[i] % 1000 / 100
val b = arr[i] % 10000 / 1000
val a = arr[i] % 100000 / 10000
when(de){
1 -> {
val value = op(getVal(arr, i+1, c==0), getVal(arr, i+2, b==0), Int::plus)
if(a == 0) arr[arr[i+3]] = value else arr[i+3] = value
i+=4
}
2 -> {
val value = op(getVal(arr, i+1, c==0), getVal(arr, i+2, b==0), Int::times)
if(a == 0) arr[arr[i+3]] = value else arr[i+3] = value
i+=4
}
3 -> {
val part1 = false
val input = if(part1) 1 else 5
if(c == 0) arr[arr[i+1]] = input else arr[i+1] = input
i+=2
}
4 -> {println(arr[arr[i+1]]); i+=2}
5 -> {
val param1 = getVal(arr, i+1, c==0)
i = if(param1 != 0) getVal(arr, i+2, b==0) else i + 3
}
6 -> {
val param1 = getVal(arr, i+1, c==0)
i = if(param1 == 0) getVal(arr, i+2, b==0) else i + 3
}
7 -> {
val isLess = getVal(arr, i+1, c==0) < getVal(arr, i+2, b==0)
val value = if(isLess) 1 else 0
if(a == 0) arr[arr[i+3]] = value else arr[i+3] = value
i+=4
}
8 -> {
val isEq = getVal(arr, i+1, c==0) == getVal(arr, i+2, b==0)
val value = if(isEq) 1 else 0
if(a == 0) arr[arr[i+3]] = value else arr[i+3] = value
i+=4
}
99 -> break@loop
else -> println("Should not happen!")
}
}
return arr
}
fun getVal(arr: List<Int>, pos: Int, positional: Boolean): Int{
return if(positional) arr[arr[pos]] else arr[pos]
}
fun op(val1: Int, val2: Int, op: (Int, Int) -> Int) = op(val1, val2)
fun toArr(line: String) = line.split(',').map { it.trim().toInt() }.toMutableList()
| 0 | Kotlin | 0 | 0 | f8ac96e7b8af13202f9233bb5a736d72261c3a3b | 2,362 | AdventOfCode2019 | MIT License |
src/Day01.kt | aeisele | 572,478,307 | false | {"Kotlin": 4468} | import java.util.*
import kotlin.math.max
fun main() {
fun part1(input: List<String>): Int {
var max = 0;
var cur = 0;
for (line in input) {
if (line.isBlank()) {
max = max(max, cur);
cur = 0;
} else {
cur += line.toInt();
}
}
max = max(max, cur);
return max;
}
fun part2(input: List<String>): Int {
val pq = PriorityQueue<Int>();
var cur = 0;
for (line in input) {
if (line.isBlank()) {
pq.offer(cur);
if (pq.size > 3) {
pq.poll();
}
cur = 0;
} else {
cur += line.toInt();
}
}
pq.offer(cur);
if (pq.size > 3) {
pq.poll();
}
var sum = 0;
while (!pq.isEmpty()) {
sum += pq.poll();
}
return sum;
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 40a867c599fda032660724b81b0c12070ac5ba87 | 1,282 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/aoc2020/ex15.kt | noamfree | 433,962,392 | false | {"Kotlin": 93533} | package aoc2020
import kotlin.math.sign
fun main() {
println(nThNumber("8,11,0,19,1,2", 30_000_000))
error("")
require(nThNumber("1,3,2", 2020) == 1)
require(nThNumber("2,1,3", 2020) == 10)
require(nThNumber("1,2,3", 2020) == 27)
require(nThNumber("2,3,1", 2020) == 78)
require(nThNumber("3,2,1", 2020) == 438)
require(nThNumber("3,1,2", 2020) == 1836)
assertNValue("0,3,6", 30_000_000, 175594)
assertNValue("1,3,2", 30_000_000, 2578)
assertNValue("2,1,3", 30_000_000, 3544142)
assertNValue("1,2,3", 30_000_000, 261214)
assertNValue("2,3,1", 30_000_000, 6895259)
assertNValue("3,2,1", 30_000_000, 18)
assertNValue("3,1,2", 30_000_000, 362)
}
private fun assertNValue(numbers: String, n: Int, expected: Int) {
val res = nThNumber(numbers, n)
if (res == expected) {
println("got $res !!!")
} else {
println("got $res instead of $expected")
error("")
}
}
private fun nThNumber(input: String, n: Int): Int {
val lines = input.lines()
require(lines.size == 1)
val startingNumbers = lines[0].split(",").map { it.toInt() }
return play(startingNumbers, n).last()
}
private data class NumberSpeak(val last: Int, val before: Int) {
fun add(time: Int) = NumberSpeak(last = time, before = this.last)
fun diff() = if (before == -1) 0 else last - before
companion object {
val EMPTY = NumberSpeak(-1, -1)
}
}
fun play(starters: List<Int>, turns: Int): List<Int> {
val lastTimes = mutableMapOf<Int, NumberSpeak>()
val allTimes = mutableListOf<Int>()
if (turns <= starters.size) return starters.take(turns)
var lastNumber = 0
(0 until turns).forEach { turn ->
if (turn % 1_000 == 0) println(turn)
val current = if (turn < starters.size) {
starters[turn]
} else {
val lastTime = lastTimes[lastNumber]!!
lastTime.diff()
}
allTimes.add(current)
val lastSpeak = lastTimes[current] ?: NumberSpeak.EMPTY
lastTimes[current] = lastSpeak.add(turn)
lastNumber = current
}
return allTimes
} | 0 | Kotlin | 0 | 0 | 566cbb2ef2caaf77c349822f42153badc36565b7 | 2,139 | AOC-2021 | MIT License |
aoc-2022/src/commonMain/kotlin/fr/outadoc/aoc/twentytwentytwo/Day03.kt | outadoc | 317,517,472 | false | {"Kotlin": 183714} | package fr.outadoc.aoc.twentytwentytwo
import fr.outadoc.aoc.scaffold.Day
import fr.outadoc.aoc.scaffold.intersectAll
import fr.outadoc.aoc.scaffold.readDayInput
import kotlin.jvm.JvmInline
class Day03 : Day<Int> {
@JvmInline
private value class Item(val id: Char)
private val allowedItems: List<Char> =
('a'..'z').toList() + ('A'..'Z').toList()
private val Item.priority: Int
get() = allowedItems.indexOf(id) + 1
private data class Rucksack(
val compartmentA: Set<Item>,
val compartmentB: Set<Item>
) {
val allItems = compartmentA + compartmentB
}
private val input: Sequence<Rucksack> =
readDayInput()
.lineSequence()
.map { line -> line.toCharArray().map { c -> Item(c) } }
.map { items ->
val compartments: List<Set<Item>> = items.chunked(items.size / 2) { it.toSet() }
Rucksack(
compartmentA = compartments[0],
compartmentB = compartments[1]
)
}
private val Rucksack.commonItems: Set<Item>
get() = compartmentA.intersect(compartmentB)
override fun step1(): Int =
input.sumOf { sack ->
sack.commonItems.sumOf { item ->
item.priority
}
}
override val expectedStep1: Int = 7_831
override fun step2(): Int =
input.chunked(3)
.map { group ->
group.map { it.allItems }
.intersectAll()
.sumOf { item -> item.priority }
}
.also { println("set: ${it.toList()}") }
.sum()
override val expectedStep2: Int = 2_683
}
| 0 | Kotlin | 0 | 0 | 54410a19b36056a976d48dc3392a4f099def5544 | 1,733 | adventofcode | Apache License 2.0 |
day22/part2.kts | bmatcuk | 726,103,418 | false | {"Kotlin": 214659} | // --- Part Two ---
// Disintegrating bricks one at a time isn't going to be fast enough. While it
// might sound dangerous, what you really need is a chain reaction.
//
// You'll need to figure out the best brick to disintegrate. For each brick,
// determine how many other bricks would fall if that brick were disintegrated.
//
// Using the same example as above:
//
// - Disintegrating brick A would cause all 6 other bricks to fall.
// - Disintegrating brick F would cause only 1 other brick, G, to fall.
// - Disintegrating any other brick would cause no other bricks to fall. So, in
// this example, the sum of the number of other bricks that would fall as a
// result of disintegrating each brick is 7.
//
// For each brick, determine how many other bricks would fall if that brick
// were disintegrated. What is the sum of the number of other bricks that would
// fall?
import java.io.*
import kotlin.math.max
import kotlin.math.min
operator fun <T> List<T>.component6() = this[5]
fun IntRange.intersects(other: IntRange) = max(this.start, other.start) <= min(this.endInclusive, other.endInclusive)
class Brick(coords: String) : Comparable<Brick> {
val supports = mutableListOf<Brick>()
val supportedBy = mutableListOf<Brick>()
var x: IntRange
var y: IntRange
var z: IntRange
init {
val (x1, y1, z1, x2, y2, z2) = coords.split(',', '~').map(String::toInt)
this.x = min(x1, x2)..max(x1, x2)
this.y = min(y1, y2)..max(y1, y2)
this.z = min(z1, z2)..max(z1, z2)
}
fun moveDownTo(z: Int): Unit {
val dz = this.z.first - z
this.z = z..(this.z.endInclusive - dz)
}
fun intersectsXY(other: Brick): Boolean {
return this.x.intersects(other.x) && this.y.intersects(other.y)
}
override operator fun compareTo(other: Brick): Int {
return this.z.start - other.z.start
}
override fun toString() = "${this.x.first},${this.y.first},${this.z.first}~${this.x.endInclusive},${this.y.endInclusive},${this.z.endInclusive}"
}
// .map(::Brick) threw a _really_ weird compiler error, despite documentation
// saying it should have worked ¯\_(ツ)_/¯
val bricks = File("input.txt").readLines().map { Brick(it) }.toMutableList()
bricks.sort()
for (i in bricks.indices) {
val brick = bricks[i]
if (brick.z.first == 1) {
continue
}
var supportedBy = bricks.subList(0, i).filter { it.intersectsXY(brick) }
if (supportedBy.size > 0) {
val maxz = supportedBy.maxOf { it.z.endInclusive }
supportedBy = supportedBy.filter { it.z.endInclusive == maxz }
brick.moveDownTo(maxz + 1)
brick.supportedBy.addAll(supportedBy)
supportedBy.forEach { it.supports.add(brick) }
} else {
brick.moveDownTo(1)
}
}
// val counts = mutableMapOf<Brick, Int>()
// fun countSupportedBricks(brick: Brick): Int {
// return counts[brick] ?: brick.supports
// .filter { it.supportedBy.size == 1 }
// .let { it.size + it.sumOf(::countSupportedBricks) }
// .also { counts[brick] = it }
// }
fun countSupportedBricks(brick: Brick, falling: MutableSet<Brick> = mutableSetOf(brick)): Int {
return brick.supports
.filter { it !in falling && it.supportedBy.all { it in falling } }
.let {
falling.addAll(it)
it.size + it.sumOf { countSupportedBricks(it, falling) }
}
}
val result = bricks.sumOf(::countSupportedBricks)
println(result)
| 0 | Kotlin | 0 | 0 | a01c9000fb4da1a0cd2ea1a225be28ab11849ee7 | 3,338 | adventofcode2023 | MIT License |
app/src/main/kotlin/com/github/ilikeyourhat/kudoku/solving/sat/SatSolver.kt | ILikeYourHat | 139,063,649 | false | {"Kotlin": 166134} | package com.github.ilikeyourhat.kudoku.solving.sat
import com.github.ilikeyourhat.kudoku.solving.SolutionCount
import com.github.ilikeyourhat.kudoku.model.Field
import com.github.ilikeyourhat.kudoku.model.Sudoku
import com.github.ilikeyourhat.kudoku.solving.SudokuSolutionChecker
import com.github.ilikeyourhat.kudoku.solving.SudokuSolver
class SatSolver: SudokuSolver, SudokuSolutionChecker {
override fun solve(sudoku: Sudoku): Sudoku {
return Command(sudoku).solve()
}
override fun checkSolutions(sudoku: Sudoku): SolutionCount {
return Command(sudoku).checkSolutions()
}
private class Command(private val sudoku: Sudoku) {
private val indexEncoder = IndexEncoder(sudoku.sizeX(), sudoku.sizeY(), sudoku.type.possibleValues)
private val engine = SatEngine()
fun solve(): Sudoku {
initEngine(sudoku)
val model = engine.findModel()
val result = sudoku.copy()
if (model != null) {
result.applyModel(model)
}
return result
}
fun checkSolutions(): SolutionCount {
initEngine(sudoku)
return engine.detectSolutions()
}
private fun initEngine(sudoku: Sudoku) {
addCausesForRegions(sudoku)
addCausesForFields(sudoku)
}
private fun Sudoku.applyModel(model: List<Int>) {
model.filter { index -> index > 0 }
.forEach { index ->
val (x, y) = indexEncoder.decodePoint(index)
val value = indexEncoder.decodeValue(index)
at(x, y)!!.set(value)
}
}
private fun addCausesForFields(sudoku: Sudoku) {
for (field in sudoku.allFields) {
engine.addExactly(createValues(field))
if (!field.isEmpty) {
val index = indexEncoder.encode(field.position(), field.value())
engine.addClause(listOf(index))
}
}
}
private fun addCausesForRegions(sudoku: Sudoku) {
for (possibleValue in 1..sudoku.type.possibleValues) {
for (region in sudoku.regions) {
val list = mutableListOf<Int>()
for ((position) in region) {
val index = indexEncoder.encode(position, possibleValue)
list.add(index)
}
engine.addExactly(list)
}
}
}
private fun createValues(field: Field): List<Int> {
val list = mutableListOf<Int>()
for (value in 1..sudoku.type.possibleValues) {
val index = indexEncoder.encode(field.position(), value)
list.add(index)
}
return list
}
}
}
| 1 | Kotlin | 0 | 0 | b234b2de2edb753844c88ea3cd573444675fc1cf | 2,905 | Kudoku | Apache License 2.0 |
src/day3/second/Solution.kt | verwoerd | 224,986,977 | false | null | package day3.second
import tools.Coordinate
import tools.origin
import tools.timeSolution
import java.util.PriorityQueue
import kotlin.test.fail
fun slowMain() = timeSolution { // Took 32 seconds
val points = mutableListOf<Coordinate>()
var last = origin
readLine()!!.split(",").forEach { current ->
// assumption: a circuit does not cross itself
val size = current.substring(1).toInt()
last = when (current[0]) {
'R' -> (last.x + 1..(last.x) + size).map {
Coordinate(
it,
last.y
)
}.toCollection(points).run { Coordinate(last.x + size, last.y) }
'L' -> (last.x - size until last.x).map {
Coordinate(
it,
last.y
)
}.reversed().toCollection(points).run { Coordinate(last.x - size, last.y) }
'U' -> (last.y + 1..(last.y) + size).map { Coordinate(last.x, it) }.toCollection(points).run {
Coordinate(
last.x,
last.y + size
)
}
'D' -> (last.y - size until last.y).map {
Coordinate(
last.x,
it
)
}.reversed().toCollection(points).run { Coordinate(last.x, last.y - size) }
else -> fail("Illegal direction $current")
}
}
points.remove(origin)
last = origin
val intersections = PriorityQueue<Int>()
var index = 1 // compensate for initial circuit to be off by 1
readLine()!!.split(",").forEach { current ->
val size = current.substring(1).toInt()
last = when (current[0]) {
'R' -> (last.x + 1..(last.x) + size).map { Pair(++index, Coordinate(it, last.y)) }.filter { it.second in points }
.map { it.first + points.indexOf(it.second) }.toCollection(intersections).run {
Coordinate(
last.x + size,
last.y
)
}
'L' -> (last.x - size until last.x).reversed().map {
Pair(
++index,
Coordinate(it, last.y)
)
}.filter { it.second in points }
.map { it.first + points.indexOf(it.second) }.toCollection(intersections).run {
Coordinate(
last.x - size,
last.y
)
}
'U' -> (last.y + 1..(last.y) + size).map { Pair(++index, Coordinate(last.x, it)) }.filter { it.second in points }
.map { it.first + points.indexOf(it.second) }.toCollection(intersections).run {
Coordinate(
last.x,
last.y + size
)
}
'D' -> (last.y - size until last.y).reversed().map {
Pair(
++index,
Coordinate(last.x, it)
)
}.filter { it.second in points }
.map { it.first + points.indexOf(it.second) }.toCollection(intersections).run {
Coordinate(
last.x,
last.y - size
)
}
else -> fail("Illegal direction $current")
}
}
println(intersections.peek())
}
fun main() = timeSolution {
// reduced to 200ms
val points = mutableSetOf<Coordinate>()
val pointsTimeIndexes = mutableMapOf<Coordinate, Int>()
var last = origin
var index = 0
readLine()!!.split(",").forEach { current ->
// assumption: a circuit does not cross itself
val size = current.substring(1).toInt()
last = when (current[0]) {
'R' -> (last.x + 1..(last.x) + size).map {
Pair(
Coordinate(it, last.y),
++index
)
}.filter { points.add(it.first) }.associateByTo(pointsTimeIndexes, { it.first }, { it.second })
.run { Coordinate(last.x + size, last.y) }
'L' -> (last.x - size until last.x).map { Pair(Coordinate(it, last.y), ++index) }.reversed().filter {
points.add(
it.first
)
}
.associateByTo(pointsTimeIndexes, { it.first }, { it.second }).run { Coordinate(last.x - size, last.y) }
'U' -> (last.y + 1..(last.y) + size).map { Pair(Coordinate(last.x, it), ++index) }.filter { points.add(it.first) }
.associateByTo(pointsTimeIndexes, { it.first }, { it.second }).run { Coordinate(last.x, last.y + size) }
'D' -> (last.y - size until last.y).map { Pair(Coordinate(last.x, it), ++index) }.reversed().filter {
points.add(
it.first
)
}
.associateByTo(pointsTimeIndexes, { it.first }, { it.second }).run { Coordinate(last.x, last.y - size) }
else -> fail("Illegal direction $current")
}
}
points.remove(origin)
last = origin
val intersections = PriorityQueue<Int>()
index = 0
readLine()!!.split(",").forEach { current ->
val size = current.substring(1).toInt()
last = when (current[0]) {
'R' -> (last.x + 1..(last.x) + size).map { Pair(++index, Coordinate(it, last.y)) }.filter { it.second in points }
.map { it.first + pointsTimeIndexes[it.second]!! }.toCollection(intersections).run {
Coordinate(
last.x + size,
last.y
)
}
'L' -> (last.x - size until last.x).reversed().map {
Pair(
++index,
Coordinate(it, last.y)
)
}.filter { it.second in points }
.map { it.first + pointsTimeIndexes[it.second]!! }.toCollection(intersections).run {
Coordinate(
last.x - size,
last.y
)
}
'U' -> (last.y + 1..(last.y) + size).map { Pair(++index, Coordinate(last.x, it)) }.filter { it.second in points }
.map { it.first + pointsTimeIndexes[it.second]!! }.toCollection(intersections).run {
Coordinate(
last.x,
last.y + size
)
}
'D' -> (last.y - size until last.y).reversed().map {
Pair(
++index,
Coordinate(last.x, it)
)
}.filter { it.second in points }
.map { it.first + pointsTimeIndexes[it.second]!! }.toCollection(intersections).run {
Coordinate(
last.x,
last.y - size
)
}
else -> fail("Illegal direction $current")
}
}
println(intersections.peek())
}
| 0 | Kotlin | 0 | 0 | 554377cc4cf56cdb770ba0b49ddcf2c991d5d0b7 | 6,178 | AoC2019 | MIT License |
src/main/kotlin/com/jackchapman/adventofcode/Day08.kt | crepppy | 317,691,375 | false | null | package com.jackchapman.adventofcode
fun solveDay8(): Pair<Int, Int> {
val instructions = getInput(8)
return calculateAccBeforeRepeat(instructions) to calculateAccAfterInstructionChange(instructions)
}
// Completed in 4mins 5seconds
fun calculateAccBeforeRepeat(instructions: List<String>): Int {
return runInstructions(instructions).second
}
// Refactored instruction running and completed below function in 8mins 23seconds
fun calculateAccAfterInstructionChange(instructions: List<String>): Int {
for ((index, inst) in instructions.withIndex()) {
if (inst.take(3) != "acc") {
val changedInstructions = instructions.toMutableList()
changedInstructions[index] = (if (inst.take(3) == "nop") "jmp" else "nop") + inst.drop(3)
val result = runInstructions(changedInstructions)
if (result.first >= changedInstructions.size - 1)
return result.second
}
}
return -1
}
private fun runInstructions(instructions: List<String>): Pair<Int, Int> {
var instLoc = 0
var acc = 0
val visited: MutableSet<Int> = mutableSetOf()
while (instLoc !in visited && instLoc < instructions.size) {
val instruction = instructions[instLoc]
visited.add(instLoc)
when (instruction.take(3)) {
"acc" -> acc += instruction.drop(4).toInt()
"jmp" -> {
instLoc += instruction.drop(4).toInt()
continue
}
}
instLoc++
}
return instLoc to acc
}
| 0 | Kotlin | 0 | 0 | b49bb8f62b4542791626950846ca07d1eff4f2d1 | 1,544 | aoc2020 | The Unlicense |
src/main/kotlin/leetcode/Problem2064.kt | fredyw | 28,460,187 | false | {"Java": 1280840, "Rust": 363472, "Kotlin": 148898, "Shell": 604} | package leetcode
import kotlin.math.max
/**
* https://leetcode.com/problems/minimized-maximum-of-products-distributed-to-any-store/
*/
class Problem2064 {
fun minimizedMaximum(n: Int, quantities: IntArray): Int {
var min = 1
var max = quantities[0]
for (i in 1 until quantities.size) {
max = max(max, quantities[i])
}
var answer = 0
while (min <= max) {
val mid = (min + max) / 2
if (canDistribute(n, quantities, mid)) {
max = mid - 1
answer = mid
} else {
min = mid + 1
}
}
return answer
}
private fun canDistribute(stores: Int, quantities: IntArray, x: Int): Boolean {
var n = stores
for (quantity in quantities) {
n -= if (quantity % x == 0) quantity / x else (quantity / x) + 1
if (n < 0) {
return false
}
}
return true
}
}
| 0 | Java | 1 | 4 | a59d77c4fd00674426a5f4f7b9b009d9b8321d6d | 1,005 | leetcode | MIT License |
src/main/kotlin/_2023/Day08.kt | novikmisha | 572,840,526 | false | {"Kotlin": 145780} | package _2023
import Day
import InputReader
import lcm
class Day08 : Day(2023, 8) {
override val firstTestAnswer = 6
override val secondTestAnswer = 6L
override fun first(input: InputReader): Int {
val (unparsedSteps, unparsedMap) = input.asGroups()
val steps = unparsedSteps.first()
val map = unparsedMap.associate {
val (currentNode, path) = it.split(" = ")
val (left, right) = path.replace(")", "").replace("(", "").split(", ")
currentNode.trim() to Pair(left.trim(), right.trim())
}
var step = 0
var currentNode = "AAA"
while (currentNode != "ZZZ") {
val direction = steps[step.mod(steps.length)]
currentNode = if (direction == 'R') {
map[currentNode]!!.second
} else {
map[currentNode]!!.first
}
step++
}
return step
}
override fun second(input: InputReader): Long {
val (unparsedSteps, unparsedMap) = input.asGroups()
val steps = unparsedSteps.first()
val map = unparsedMap.associate {
val (currentNode, path) = it.split(" = ")
val (left, right) = path.replace(")", "").replace("(", "").split(", ")
currentNode.trim() to Pair(left.trim(), right.trim())
}
val currentNodes = map.keys.filter { it.endsWith('A') }
val currentNodeSteps = currentNodes.map { startNode ->
var step = 0L
var currentNode = startNode
while (!currentNode.endsWith('Z')) {
val direction = steps[step.mod(steps.length)]
currentNode = if (direction == 'R') {
map[currentNode]!!.second
} else {
map[currentNode]!!.first
}
step++
}
step
}
return currentNodeSteps.reduce { result, currentValue -> lcm(result, currentValue) }
}
}
fun main() {
Day08().solve(skipTest = true)
} | 0 | Kotlin | 0 | 0 | 0c78596d46f3a8bf977bf356019ea9940ee04c88 | 2,071 | advent-of-code | Apache License 2.0 |
src/main/kotlin/dev/thecoati/adventofcode/days/Day2.kt | TheCoati | 725,922,788 | false | {"Kotlin": 7934} | package dev.thecoati.adventofcode.days
import dev.thecoati.adventofcode.FileInput
class Day2: Day {
override fun day(): Int {
return 2
}
override fun title(): String {
return "Cube Conundrum"
}
override fun input(): FileInput {
return FileInput("day2")
}
override fun part1(input: FileInput): String {
val values = mutableListOf<Int>()
input.forEach {
val split = it.split(":")
val parse = this.parse(split)
values.addAll(parse.second)
}
return values.sum().toString()
}
override fun part2(input: FileInput): String {
val values = mutableListOf<Int>()
input.forEach {
val split = it.split(":")
val parse = this.parse(split)
values.add(parse.second[0] * parse.second[1] * parse.second[2])
}
return values.sum().toString()
}
private fun parse(data: List<String>): Pair<Int, List<Int>> {
val game = data[0].trim().replace("Game ", "").toInt()
var red = 0
var green = 0
var blue = 0
data[1].split(";").map { bag -> bag.trim() }.forEach { bag ->
bag.split(",").map { cube -> cube.trim() }.forEach { cube ->
val parts = cube.split(" ")
val color = parts[1]
val value = parts[0].toInt()
when (color) {
"red" -> if (value > red) red = parts[0].toInt()
"green" -> if (value > green) green = parts[0].toInt()
"blue" -> if (value > blue) blue = parts[0].toInt()
}
}
}
return Pair(game, listOf(red, green, blue))
}
} | 0 | Kotlin | 0 | 0 | 6d08b2f3fc26c8710bf28a907715168cdd12ce7f | 1,749 | Advent-of-Code-2023 | MIT License |
strings/MaximumNumberOfVowelsInASubstringOfGivenLength/kotlin/Solution.kt | YaroslavHavrylovych | 78,222,218 | false | {"Java": 284373, "Kotlin": 35978, "Shell": 2994} | /**
* Given a string s and an integer k.
* Return the maximum number of vowel letters in any
* substring of s with length k.
* Vowel letters in English are (a, e, i, o, u).
* <br>
* https://leetcode.com/problems/maximum-number-of-vowels-in-a-substring-of-given-length/
*/
class Solution {
val vows = setOf('a', 'e', 'i', 'o', 'u')
fun maxVowels(s: String, k: Int): Int {
//init
var cVow = 0
var i = 0
while(i < k) {
if(vows.contains(s[i])) cVow += 1
i += 1
}
var max = cVow
while(i < s.length) {
if(vows.contains(s[i - k])) cVow -= 1
if(vows.contains(s[i])) cVow += 1
if(cVow > max) max = cVow
i += 1
}
return max
}
}
fun main() {
println("Maximum Number of Vowels in a Substring of Given Length" +
": test is not implemented")
}
| 0 | Java | 0 | 2 | cb8e6f7e30563e7ced7c3a253cb8e8bbe2bf19dd | 834 | codility | MIT License |
ceria/07/src/main/kotlin/Solution.kt | VisionistInc | 433,099,870 | false | {"Kotlin": 91599, "Go": 87605, "Ruby": 65600, "Python": 21104} | import java.io.File;
import kotlin.math.abs;
fun main(args : Array<String>) {
val input = File(args.first()).readLines().first().split(",").map { it.toInt() }
println("Solution 1: ${solution1(input)}")
println("Solution 2: ${solution2(input)}")
}
private fun solution1(input: List<Int>) :Int {
val min = input.minOrNull() ?: 0
val max = input.maxOrNull() ?: 0
val fuels = mutableListOf<Int>()
for (possibleXValue in min..max) {
var fuel = 0
for (crabPos in input) {
fuel += abs(crabPos - possibleXValue)
}
fuels.add(fuel)
}
return fuels.minOrNull() ?: 0
}
private fun solution2(input: List<Int>) :Int {
val min = input.minOrNull() ?: 0
val max = input.maxOrNull() ?: 0
val fuels = mutableListOf<Int>()
for (possibleXValue in min..max) {
var fuel = 0
for (crabPos in input) {
val distance = abs(crabPos - possibleXValue)
for (n in 0..distance) {
fuel += n
}
}
fuels.add(fuel)
}
return fuels.minOrNull() ?: 0
}
| 0 | Kotlin | 4 | 1 | e22a1d45c38417868f05e0501bacd1cad717a016 | 1,114 | advent-of-code-2021 | MIT License |
src/2020/Day01.kt | mathijs81 | 572,837,783 | false | {"Kotlin": 167658, "Python": 725, "Shell": 57} | package aoc2020
import Solver
private const val EXPECTED_1 = 514579
private const val EXPECTED_2 = 241861950
private class Day01(isTest: Boolean) : Solver(isTest, "/2020") {
fun part1(): Any {
val seen = mutableSetOf<Int>()
readAsLines().forEach {
val value = it.toInt()
val remainder = 2020 - value
if (remainder in seen) {
return remainder * value
}
seen.add(value)
}
check(false)
return 0
}
fun part2(): Any {
val list = readAsLines().map { it.toInt() }.sorted()
val numberSet = mutableSetOf<Int>()
for (i in 0 until list.size) {
for (j in i+1 until list.size) {
val remainder = 2020 - list[i] - list[j]
if (remainder in numberSet) {
return remainder * list[i] * list[j]
}
}
numberSet.add(list[i])
}
check(false)
return 0
}
}
fun main() {
val testInstance = Day01(true)
val instance = Day01(false)
testInstance.part1().let { check(it == EXPECTED_1) { "part1: $it != $EXPECTED_1" } }
println(instance.part1())
testInstance.part2().let { check(it == EXPECTED_2) { "part2: $it != $EXPECTED_2" } }
println(instance.part2())
}
| 0 | Kotlin | 0 | 2 | 92f2e803b83c3d9303d853b6c68291ac1568a2ba | 1,342 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/_0039_CombinationSum.kt | ryandyoon | 664,493,186 | false | null | // https://leetcode.com/problems/combination-sum
fun combinationSum(candidates: IntArray, target: Int): List<List<Int>> {
return mutableListOf<List<Int>>().also {
buildCombinations(candidates, startIndex = 0, target = target, combination = mutableListOf(), combinations = it)
}
}
private fun buildCombinations(
candidates: IntArray,
startIndex: Int,
target: Int,
combination: MutableList<Int>,
combinations: MutableList<List<Int>>
) {
if (target == 0) {
combinations.add(combination.toList())
return
}
for (index in startIndex..candidates.lastIndex) {
val candidate = candidates[index]
if (candidate <= target) {
combination.add(candidate)
buildCombinations(
candidates = candidates,
startIndex = index,
target = target - candidate,
combination = combination,
combinations = combinations
)
combination.removeLast()
}
}
}
| 0 | Kotlin | 0 | 0 | 7f75078ddeb22983b2521d8ac80f5973f58fd123 | 1,042 | leetcode-kotlin | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/TotalSteps.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import kotlin.math.max
/**
* 2289. Steps to Make Array Non-decreasing
* @see <a href="https://leetcode.com/problems/steps-to-make-array-non-decreasing/">Source</a>
*/
fun interface TotalSteps {
operator fun invoke(nums: IntArray): Int
}
class TotalStepsDp : TotalSteps {
override operator fun invoke(nums: IntArray): Int {
val n: Int = nums.size
var res = 0
var j = -1
val dp = IntArray(n)
val stack = IntArray(n)
for (i in n - 1 downTo 0) {
while (j >= 0 && nums[i] > nums[stack[j]]) {
dp[i] = max(++dp[i], dp[stack[j--]])
res = max(res, dp[i])
}
stack[++j] = i
}
return res
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,371 | kotlab | Apache License 2.0 |
Hyperskill/Unit-Converter/Main.kt | Alphabeater | 435,048,407 | false | {"Kotlin": 69566, "Python": 5974} | package converter
enum class Units(val names: List<String>, val value: Double, val type: Char) {
METER(listOf("meters", "meter", "m"), 1.0, 'd'),
KILOMETER(listOf("kilometers", "kilometer", "km"), 1000.0, 'd'),
CENTIMETER(listOf("centimeters", "centimeter", "cm"), 0.01, 'd'),
MILLIMETER(listOf("millimeters", "millimeter", "mm"), 0.001, 'd'),
MILE(listOf("miles", "mile", "mi"), 1609.35, 'd'),
YARD(listOf("yards", "yard", "yd"), 0.9144, 'd'),
FOOT(listOf("feet", "foot", "ft"), 0.3048, 'd'),
INCH(listOf("inches", "inch", "in"), 0.0254, 'd'),
GRAM(listOf("grams", "gram", "g"), 1.0, 'w'),
KILOGRAM(listOf("kilograms", "kilogram", "kg"), 1000.0, 'w'),
MILLIGRAM(listOf("milligrams", "milligram", "mg"), 0.001, 'w'),
POUND(listOf("pounds", "pound", "lb"), 453.592, 'w'),
OUNCE(listOf("ounces", "ounce", "oz"), 28.3495, 'w'),
CELCIUS(listOf("degrees celsius", "degree celsius", "celsius", "dc", "c"), 0.0, 't'),
FAHRENHEIT(listOf("degrees fahrenheit", "degree fahrenheit", "fahrenheit", "df", "f"), 0.0, 't'),
KELVIN(listOf("kelvins", "kelvin", "k"), 0.0, 't'),
ERROR(listOf("???"), 0.0, 'e');
companion object {
fun returnEnum(input: String): Units {
for (element in values()) {
if (input in element.names) return element
}
return ERROR
}
fun convert(inputValue: Double, inputEnum: Units, outputEnum: Units, inverse: Boolean = false): Double {
var outputValue = 0.0
if (inputEnum.type == 'd' || inputEnum.type == 'w') {
outputValue = if (outputEnum == METER || outputEnum == GRAM) {
inputValue * if (!inverse) inputEnum.value else 1.0 / inputEnum.value
} else {
if (inputEnum.type == 'd') convert(inputValue * inputEnum.value, outputEnum, METER, true)
else convert(inputValue * inputEnum.value, outputEnum, GRAM, true)
}
} else {
outputValue = when (inputEnum) {
CELCIUS -> when (outputEnum) {
KELVIN -> inputValue + 273.15
FAHRENHEIT -> inputValue * 9 / 5 + 32
else -> inputValue
}
FAHRENHEIT -> when (outputEnum) {
KELVIN -> (inputValue + 459.67) * 5 / 9
CELCIUS -> (inputValue - 32) * 5 / 9
else -> inputValue
}
KELVIN -> when (outputEnum) {
CELCIUS -> inputValue - 273.15
FAHRENHEIT -> inputValue * 9 / 5 - 459.67
else -> inputValue
}
else -> -1.0
}
}
return outputValue
}
}
}
fun Double.isUnit() = this % 1 == 0.0 && this.toInt() == 1
fun main() {
loop@do {
print("Enter what you want to convert (or exit): ")
try {
val line = readLine()!!.split(" ")
if (line[0] == "exit") break@loop
val inputValue = line[0].toDouble()
val inputEnum = Units.returnEnum((line[1] +
if (line[1].contains("degree", true)) {
' ' + line[2]
} else "").toLowerCase())
val outputEnum = Units.returnEnum((
if (line[line.lastIndex - 1].contains("degree", true)) {
line[line.lastIndex - 1] + ' '
} else { "" } + line.last()).toLowerCase())
if (inputEnum == Units.ERROR || outputEnum == Units.ERROR || inputEnum.type != outputEnum.type) {
println("Conversion from ${inputEnum.names[0]} to ${outputEnum.names[0]} is impossible\n")
continue@loop
} else if (inputValue < 0) {
if (inputEnum.type == 'd') {
println("Length shouldn't be negative\n")
continue@loop
}
else if (inputEnum.type == 'w') {
println("Weight shouldn't be negative\n")
continue@loop
}
}
val outputValue = Units.convert(inputValue, inputEnum, outputEnum)
println("$inputValue ${if (inputValue.isUnit()) inputEnum.names[1] else inputEnum.names[0]} is " +
"$outputValue ${if (outputValue.isUnit()) outputEnum.names[1] else outputEnum.names[0]}\n")
} catch (e: Exception) {
println("Parse error\n")
}
} while (true)
}
| 0 | Kotlin | 0 | 0 | 05c8d4614e025ed2f26fef2e5b1581630201adf0 | 4,660 | Archive | MIT License |
src/Day11.kt | ech0matrix | 572,692,409 | false | {"Kotlin": 116274} | fun main() {
fun solve(monkeys: List<Monkey>, numRounds: Int): Long {
for(i in 0 until numRounds) {
for(monkey in monkeys) {
monkey.testItems(monkeys)
}
}
val inspectCounts = monkeys.map { it.numInspected }
println(inspectCounts)
println()
val shenanigans = inspectCounts.sortedDescending().take(2).reduce{ a, b -> a * b }
println(shenanigans)
println()
return shenanigans
}
val testDivisor = 23L * 19L * 13L * 17L
val testInput = listOf(
Monkey(
mutableListOf(79L, 98L),
{ it * 19L },
{ it / 3L },
{ it % 23L == 0L},
2,
3
),
Monkey(
mutableListOf(54L,65L,75L,74L),
{ it + 6L },
{ it / 3L },
{ it % 19L == 0L},
2,
0
),
Monkey(
mutableListOf(79L,60L,97L),
{ it * it },
{ it / 3L },
{ it % 13L == 0L},
1,
3
),
Monkey(
mutableListOf(74L),
{ it + 3L },
{ it / 3L },
{ it % 17L == 0L},
0,
1
)
)
check(solve(testInput, 20) == 10605L)
val testInput2 = listOf(
Monkey(
mutableListOf(79L, 98L),
{ it * 19L },
{ item -> item % testDivisor },
{ it % 23L == 0L},
2,
3
),
Monkey(
mutableListOf(54L,65L,75L,74L),
{ it + 6L },
{ item -> item % testDivisor },
{ it % 19L == 0L},
2,
0
),
Monkey(
mutableListOf(79L,60L,97L),
{ it * it },
{ item -> item % testDivisor },
{ it % 13L == 0L},
1,
3
),
Monkey(
mutableListOf(74L),
{ it + 3L },
{ item -> item % testDivisor },
{ it % 17L == 0L},
0,
1
)
)
check(solve(testInput2, 10000) == 2713310158L)
//
// Omitting hard-coded inputs as part of check-in
//
// val input = listOf<Monkey>(...)
// val divisor = ...
// val input2 = listOf<Monkey>(...)
// println(solve(input, 20))
// println(solve(input2, 10000))
}
data class Monkey(
private val items: MutableList<Long>,
private val operation: (Long) -> (Long),
private val reduceWorry: (Long) -> (Long),
private val test: (Long) -> Boolean,
private val trueMonkey: Int,
private val falseMonkey: Int
) {
var numInspected = 0L
fun testItems(monkeys: List<Monkey>) {
while (items.isNotEmpty()) {
// Per item:
// 1) Inspect operation
// 2) Reduce worry (divide 3)
// 3) Test item & throw
val inspectedItem = items.removeFirst()
.let { operation(it) }
.let { reduceWorry(it) }
check (inspectedItem >= 0)
val throwToMonkey = if (test(inspectedItem)) {
trueMonkey
} else {
falseMonkey
}
monkeys[throwToMonkey].items.add(inspectedItem)
numInspected++
}
}
} | 0 | Kotlin | 0 | 0 | 50885e12813002be09fb6186ecdaa3cc83b6a5ea | 3,362 | aoc2022 | Apache License 2.0 |
src/main/aoc2016/Day14.kt | nibarius | 154,152,607 | false | {"Kotlin": 963896} | package aoc2016
import md5
class Day14(private val salt: String) {
private fun String.threeInARowChar(): Char? {
if (length < 3) {
return null
}
for (i in 2 until length) {
if (this[i - 2] == this[i - 1] && this[i - 1] == this[i]) {
return this[i]
}
}
return null
}
private fun String.allFiveInARowChars(): List<Char> {
val ret = mutableListOf<Char>()
if (length < 5) {
return ret
}
var i = 4
while (i < length) {
if (this[i - 4] == this[i - 3] && this[i - 3] == this[i - 2] && this[i - 2] == this[i - 1] && this[i - 1] == this[i]) {
if (!ret.contains(this[i])) {
ret.add(this[i])
}
i += 5
} else {
i++
}
}
return ret
}
private data class InterestingIndex(val hash: String, val three: Char, val five: List<Char>)
private val interestingIndices = mutableMapOf<Int, InterestingIndex>()
private val keys = mutableListOf<Pair<Int, String>>()
private fun stretch(s: String, times: Int): String {
var ret = s
repeat(times) {ret = ret.md5()}
return ret
}
private fun doHashes(stretchAmount: Int): Int {
var index = 0
val toCheck = mutableListOf<IntRange>()
while (keys.size < 64) {
// Generate hashes
val hash = stretch("$salt$index", stretchAmount)
val triplet = hash.threeInARowChar()
if (triplet != null) {
interestingIndices[index] = InterestingIndex(hash, triplet, hash.allFiveInARowChars())
toCheck.add(index + 1..index + 1000)
}
// Check for keys when we have 1000 hashes generated after a hash with three characters in a row
if (toCheck.isNotEmpty() && toCheck[0].last == index) {
val range = toCheck.removeAt(0)
// The key candidate is on the index just before the 1000 item long range
val keyCandidateIndex = range.first - 1
val charToSearchFor = interestingIndices[keyCandidateIndex]!!.three
val isKey = interestingIndices
.filterKeys { it >= range.first && it <= range.last }
.filter { it.value.five.contains(charToSearchFor) }
.isNotEmpty()
if (isKey) {
keys.add(Pair(keyCandidateIndex, interestingIndices[keyCandidateIndex]!!.hash))
}
}
index++
}
return keys.last().first
}
fun solvePart1(): Int {
return doHashes(1)
}
fun solvePart2(): Int {
return doHashes(2017)
}
}
| 0 | Kotlin | 0 | 6 | f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22 | 2,852 | aoc | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.