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/g2001_2100/s2092_find_all_people_with_secret/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2001_2100.s2092_find_all_people_with_secret
// #Hard #Sorting #Depth_First_Search #Breadth_First_Search #Graph #Union_Find
// #2023_06_28_Time_1086_ms_(100.00%)_Space_104.2_MB_(100.00%)
import java.util.Arrays
@Suppress("NAME_SHADOWING")
class Solution {
fun findAllPeople(n: Int, meetings: Array<IntArray>, firstPerson: Int): List<Int> {
Arrays.sort(meetings) { a: IntArray, b: IntArray -> a[2] - b[2] }
val uf = UF(n)
// base
uf.union(0, firstPerson)
// for every time we have a pool of people that talk to each other
// if someone knows a secret proir to this meeting - all pool will too
// if not - reset unions from this pool
var i = 0
while (i < meetings.size) {
val curTime = meetings[i][2]
val pool: MutableSet<Int> = HashSet()
while (i < meetings.size && curTime == meetings[i][2]) {
val currentMeeting = meetings[i]
uf.union(currentMeeting[0], currentMeeting[1])
pool.add(currentMeeting[0])
pool.add(currentMeeting[1])
i++
}
// meeting that took place now should't affect future
// meetings if people don't know the secret
for (j in pool) {
if (!uf.connected(0, j)) {
uf.reset(j)
}
}
}
// if the person is conneted to 0 - they know a secret
val ans: MutableList<Int> = ArrayList()
for (j in 0 until n) {
if (uf.connected(j, 0)) {
ans.add(j)
}
}
return ans
}
// regular union find
private class UF(n: Int) {
private val parent: IntArray
private val rank: IntArray
init {
parent = IntArray(n)
rank = IntArray(n)
for (i in 0 until n) {
parent[i] = i
}
}
fun union(p: Int, q: Int) {
val rootP = find(p)
val rootQ = find(q)
if (rootP == rootQ) {
return
}
if (rank[rootP] < rank[rootQ]) {
parent[rootP] = rootQ
} else {
parent[rootQ] = rootP
rank[rootP]++
}
}
fun find(p: Int): Int {
var p = p
while (parent[p] != p) {
p = parent[parent[p]]
}
return p
}
fun connected(p: Int, q: Int): Boolean {
return find(p) == find(q)
}
fun reset(p: Int) {
parent[p] = p
rank[p] = 0
}
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 2,713 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/com/askrepps/advent/advent2023/day02/Advent2023Day02.kt | askrepps | 726,566,200 | false | {"Kotlin": 302802} | /*
* MIT License
*
* Copyright (c) 2023 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.askrepps.advent.advent2023.day02
import com.askrepps.advent.util.getInputLines
import java.io.File
import kotlin.math.max
data class Game(
val id: Int,
val maxRedCubes: Int,
val maxGreenCubes: Int,
val maxBlueCubes: Int
)
fun String.toGame(): Game {
val (idComponent, mainComponent) = split(": ")
val id = idComponent.split(" ").last().toInt()
var maxRed = 0
var maxGreen = 0
var maxBlue = 0
val rounds = mainComponent.split("; ")
for (round in rounds) {
val pulls = round.split(", ")
for (pull in pulls) {
val (valueString, color) = pull.split(" ")
val value = valueString.toInt()
when (color) {
"red" -> maxRed = max(maxRed, value)
"green" -> maxGreen = max(maxGreen, value)
"blue" -> maxBlue = max(maxBlue, value)
else -> error("Unrecognized color: $color")
}
}
}
return Game(id, maxRed, maxGreen, maxBlue)
}
fun getPart1Answer(games: List<Game>) =
games.filter { it.maxRedCubes <= 12 && it.maxGreenCubes <= 13 && it.maxBlueCubes <= 14 }
.sumOf { it.id }
fun getPart2Answer(games: List<Game>) =
games.fold(0) { total, game ->
total + game.maxRedCubes * game.maxGreenCubes * game.maxBlueCubes
}
fun main() {
val games = File("src/main/resources/2023/input-2023-day02.txt")
.getInputLines().map { it.toGame() }
println("The answer to part 1 is ${getPart1Answer(games)}")
println("The answer to part 2 is ${getPart2Answer(games)}")
}
| 0 | Kotlin | 0 | 0 | 5ce2228b0951db49a5cf2a6d974112f57e70030c | 2,728 | advent-of-code-kotlin | MIT License |
src/main/kotlin/tr/emreone/adventofcode/Day22Github.kt | EmRe-One | 568,569,073 | false | {"Kotlin": 166986} | package tr.emreone.adventofcode
import tr.emreone.kotlin_utils.Direction4.Companion.DOWN
import tr.emreone.kotlin_utils.Direction4.Companion.LEFT
import tr.emreone.kotlin_utils.Direction4.Companion.RIGHT
import tr.emreone.kotlin_utils.Direction4.Companion.UP
import tr.emreone.kotlin_utils.*
import tr.emreone.kotlin_utils.dim3d.*
const val OPEN = '.'
const val WALL = '#'
const val OUT = ' '
class Day22Github : Day(22, 2022, "Monkey Map") {
val p = inputAsGroups
val map = p.first().map(String::toList).fixed(' ').show()
val op = p.last().single().let {
val walk = it.sequenceContainedIntegers()
val turn = "$it ".filterNot(Char::isDigit).asSequence()
walk.zip(turn).toList()
}.show("operations")
override fun part1(): Int {
log { map.formatted() }
val area = map.area
val startPos = map.searchIndices(OPEN).first()
var p = startPos
var h = RIGHT
for ((w, t) in op) {
for (j in 1..w) {
var np = p + h
if (np !in area || map[np] == OUT) np = when (h) {
RIGHT -> areaOf(0 to p.y, p).allPoints().toList()
LEFT -> areaOf(p, area.right to p.y).allPoints().toList().reversed()
UP -> areaOf(p.x to area.bottom, p).allPoints().toList().reversed()
else -> areaOf(p.x to 0, p).allPoints().toList()
}.first { map[it] != OUT }
if (map[np] == WALL) break
p = np
}
h = when (t) {
'L' -> h.left
'R' -> h.right
else -> h
}
}
return result(p, h)
}
override fun part2(): Int {
val cube = CubeOrigami(map)
log { cube }
var p = cube.startingPositionOnPaper
var h = RIGHT
val trace = cube.toMutableGrid()
trace[p] = h.symbol
for ((walk, turn) in op) {
log { "We are at $p and will walk $walk x $h" }
log { trace.formatted() }
for (w in 1..walk) {
val (newP, newH) = cube.walkOnPaper(p, h)
if (cube[newP] == WALL) break
p = newP
h = newH
trace[p] = h.symbol
}
h = when (turn) {
'L' -> h.left
'R' -> h.right
else -> h
}
trace[p] = h.symbol
log { "Now at $p heading $h\n" }
}
log { trace.formatted() }
return result(p, h)
}
private fun result(p: Point, h: Direction4) = 1000 * (p.y + 1) + 4 * (p.x + 1) + when (h) {
RIGHT -> 0
DOWN -> 1
LEFT -> 2
else -> 3
}
}
fun main() {
solve<Day22Github> {
"""
...#
.#..
#...
....
...#.......#
........#...
..#....#....
..........#.
...#....
.....#..
.#......
......#.
10R5L5R10L4R5L5""".trimIndent() part1 6032 part2 5031
}
}
data class CubeFace(val up: Point3D = unitVecZ, val right: Point3D = unitVecY) {
val faceVector = right x up
fun down() = CubeFace(up.rotateAround(right), right)
fun up() = CubeFace(up.rotateAround(-right), right)
fun left() = CubeFace(up, right.rotateAround(-up))
fun right() = CubeFace(up, right.rotateAround(up))
}
infix fun CubeFace.opposite(other: CubeFace) = faceVector == -other.faceVector
class CubeOrigami(val paper: Grid<Char>) : Grid<Char> by paper {
val paperArea = paper.area
val faceDimension = gcd(paper.width, paper.height)
val folding = run {
var c = 'A'
MutableGrid(paper.width / faceDimension, paper.height / faceDimension) {
if (paper[it * faceDimension] != OUT) c++
else ' '
}.also { check(c == 'G') { "Not exactly 6 sides could be detected in the paper" } }
} as Grid<Char>
val faces = buildMap<Char, CubeFace> {
this['A'] = CubeFace()
val q = ArrayDeque(listOf('A'))
while (q.isNotEmpty()) {
val c = q.removeFirst()
val i = folding.indexOfOrNull(c)!!
val v = this[c]!!
log { "$c vec $v" }
i.directNeighbors(folding.area).map { it to folding[it] }
.filter { (_, c) -> c != ' ' && c !in this }
.forEach { (p, c) ->
this[c] = when (Direction4.ofVector(i, p)) {
DOWN -> v.down()
UP -> v.up()
LEFT -> v.left()
else -> v.right()
}
q.add(c)
}
}
('A'..'F').forEach { s ->
log { "$s opposite of ${this@buildMap.entries.single { it.value.faceVector == -this@buildMap[s]!!.faceVector }}" }
}
}
val startingPositionOnPaper = paper.searchIndices(OPEN).first()
fun walkOnPaper(from: Point, heading: Direction4): Pair<Point, Direction4> {
// first, simply try to stay on the paper
val onPaper = from + heading
if (onPaper in paperArea && paper[onPaper] != OUT) return onPaper to heading
// when leaving the paper area, consider the cube faces and find the destination face
val fromFaceId = folding[from / faceDimension]
val face = faces[fromFaceId] ?: error("No face for ID '$fromFaceId'")
val facePos = from % faceDimension
val requiredFace = when (heading) {
UP -> face.up()
DOWN -> face.down()
LEFT -> face.left()
else -> face.right()
}
log { "Currently on $fromFaceId($face) - required face is $requiredFace" }
val (toFaceId, toFace) = faces.entries.single { it.value.faceVector == requiredFace.faceVector }
log { "Walk from $fromFaceId to $toFaceId! " }
log { "Need up to be ${requiredFace.up} but found ${toFace.up}" }
var rot = 0
var rotUp = toFace.up
var rotHeading = heading
while (rotUp != requiredFace.up) {
rotUp = rotUp.rotateAround(toFace.faceVector)
rotHeading = rotHeading.left
rot++
}
log { "Achieved with $rot rotations" }
val last = faceDimension - 1
val base = folding.indexOfOrNull(toFaceId)!! * faceDimension
return (base + with(facePos) {
when (heading to rotHeading) {
DOWN to DOWN -> x to 0
UP to UP -> x to last
LEFT to LEFT -> last to y
RIGHT to RIGHT -> 0 to y
RIGHT to UP -> y to last
RIGHT to DOWN -> last - y to 0
RIGHT to LEFT -> last to last - y
DOWN to UP -> last - x to last
DOWN to LEFT -> last to x
LEFT to RIGHT -> 0 to last - y
LEFT to DOWN -> y to 0
UP to RIGHT -> 0 to x
else -> error("unsupported rotation $heading to $rotHeading (x $rot)")
}
} to rotHeading)
return (base + when (rot) {
// 0 -> when (heading) {
// DOWN -> facePos.x to 0
// UP -> facePos.x to last
// LEFT -> last to facePos.y
// else -> 0 to facePos.y
// } // no rot
// 1 -> when (heading) {
// LEFT -> facePos.y to 0
// RIGHT -> facePos.y to last
// else -> error(heading)
// } // left
2 -> when (heading) {
// DOWN -> last - facePos.x to last
UP -> last - facePos.x to 0
// RIGHT -> last to last - facePos.y
// else -> 0 to last - facePos.y
} // opposite
3 -> when (heading) {
// DOWN -> last to facePos.x
// UP -> 0 to facePos.x
// RIGHT -> last - facePos.y to 0
else -> error("BOOM $heading")
} // 3x left = right
else -> error("rot == $rot")
} to rotHeading).also { log { "on $toFaceId we are at ${it.first} ${it.second}" } }
}
override fun toString(): String {
return """
|Cube Origami with face dimension $faceDimension
|${folding.formatted(showHeaders = false)}
""".trimMargin()
}
} | 0 | Kotlin | 0 | 0 | a951d2660145d3bf52db5cd6d6a07998dbfcb316 | 8,432 | advent-of-code-2022 | Apache License 2.0 |
sublist/src/main/kotlin/Relationship.kt | sirech | 189,113,734 | false | null | enum class Relationship {
EQUAL, SUBLIST, SUPERLIST, UNEQUAL
}
private enum class Case {
EMPTY_CASE,
FIRST_BIGGER_OR_EQUAL,
FIRST_SMALLER
}
fun <T> List<T>.relationshipTo(other: List<T>): Relationship {
return when (case(this, other)) {
Case.EMPTY_CASE -> emptyCase(this, other)
Case.FIRST_BIGGER_OR_EQUAL -> generalCase(this, other, Relationship.SUPERLIST)
Case.FIRST_SMALLER -> generalCase(other, this, Relationship.SUBLIST)
}
}
private fun <T> case(first: List<T>, second: List<T>): Case {
if (first.isEmpty() || second.isEmpty()) return Case.EMPTY_CASE
if (first.size >= second.size) return Case.FIRST_BIGGER_OR_EQUAL
return Case.FIRST_SMALLER
}
private fun <T> emptyCase(first: List<T>, second: List<T>): Relationship {
if (first.isEmpty() && second.isEmpty()) return Relationship.EQUAL
if (first.isEmpty()) return Relationship.SUBLIST
return Relationship.SUPERLIST
}
private fun <T> generalCase(first: List<T>, second: List<T>, case: Relationship): Relationship {
for (i in 0..(first.size - second.size)) {
for (j in 0 until second.size) {
if (first[i+j] != second[j]) {
break;
}
if (j + 1 == second.size) {
if (first.size == second.size) return Relationship.EQUAL
return case;
}
}
}
return Relationship.UNEQUAL
}
| 1 | Kotlin | 0 | 0 | 253f4636f16f83f6b96f21532a3ca8fa16dace46 | 1,426 | exercism-kotlin | MIT License |
y2015/src/main/kotlin/adventofcode/y2015/Day16.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2015
import adventofcode.io.AdventSolution
object Day16 : AdventSolution(2015, 16, "<NAME>") {
override fun solvePartOne(input: String) = parseInput(input)
.indexOfFirst { candidate ->
candidate.all { (k, v) -> actualAunt[k] == v }
} + 1
override fun solvePartTwo(input: String) = parseInput(input)
.indexOfFirst {
it.all { (k, v) ->
when (k) {
"cats", "trees" -> actualAunt.getValue(k) < v
"pomeranians", "goldfish" -> actualAunt.getValue(k) > v
else -> actualAunt[k] == v
}
}
} + 1
private fun parseInput(input: String) = input.lineSequence()
.map {
it.substringAfter(":")
.split(',').associate { i -> parseItem(i) }
}
private fun parseItem(item: String) = item.substringBefore(':').trim() to
item.substringAfter(":").trim().toInt()
private val actualAunt = mapOf(
"children" to 3,
"cats" to 7,
"samoyeds" to 2,
"pomeranians" to 3,
"akitas" to 0,
"vizslas" to 0,
"goldfish" to 5,
"trees" to 3,
"cars" to 2,
"perfumes" to 1
)
} | 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 1,282 | advent-of-code | MIT License |
src/Day01.kt | vlsolodilov | 573,277,339 | false | {"Kotlin": 19518} | fun main() {
fun getElfCaloriesList(input: List<String>): List<Int> {
var currentSumCalories = 0
val calorieList = mutableListOf<Int>()
input.forEach {
if (it.isNotBlank()) {
currentSumCalories += it.toInt()
} else {
calorieList.add(currentSumCalories)
currentSumCalories = 0
}
}
return calorieList
}
fun part1(input: List<String>): Int =
getElfCaloriesList(input).max()
fun part2(input: List<String>): Int =
getElfCaloriesList(input).sortedDescending().take(3).sum()
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | b75427b90b64b21fcb72c16452c3683486b48d76 | 909 | aoc22 | Apache License 2.0 |
dcp_kotlin/src/main/kotlin/dcp/day004/day004.kt | sraaphorst | 182,330,159 | false | {"C++": 577416, "Kotlin": 231559, "Python": 132573, "Scala": 50468, "Java": 34742, "CMake": 2332, "C": 315} | package dcp.day004
// day004.kt
// By <NAME>, 2020.
import kotlin.math.abs
// Unfortunately, to make this code as efficient as possible and have it run in linear time and constant space,
// we must use an imperative approach and mutability, along with an array to avoid linked list access times.
// This is a very finicky algorithm that relies on bizarre array manipulation, hence all the documentation.
fun findFirstPositiveMissingInteger(array: IntArray): Int {
if (array.isEmpty())
return 1
// We don't want to deal with 0 and it has no relevance, so change it to -1, which doesn't affect the final results.
// (Any negative number would do.)
// We will use the signs of the elements to indicate their presence, with array position 0 indicating positive integer 1,
// array position 1 indicating positive integer 2, etc.
// Since there can be negative numbers in the array, we have to be careful about how we use this approach.
// We first partition the list into negative numbers and positive numbers by moving all the negative numbers
// to the left.
var pivot: Int = 0
for (i in array.indices) {
if (array[i] == 0)
array[i] = -1
if (array[i] <= 0) {
val tmp: Int = array[i]
array[i] = array[pivot]
array[pivot] = tmp
++pivot
}
}
// Now everything to the left of pivot should be negative. Everything to the right of pivot should be positive.
// We only need to process elements to the right of pivot since we are only interested in the appearance of positive
// integers in the array. Take their absolute value and mark their index value - 1 as swapped. (The subtraction is
// as detailed above: we don't care about 0, so the position 0 of the array indicates incidence of element 1 in the
// array, etc.)
for (i in pivot until array.size) {
// We have to detect duplicate (or more) entries of a number or it will flip its sign back and seem like it
// never appeared in the array.
if (abs(array[i]) <= array.size) {
if ((abs(array[i]) - 1 < pivot && array[abs(array[i]) - 1] > 0) ||
(abs(array[i]) - 1 >= pivot && array[abs(array[i]) - 1] < 0))
continue
// Reverse the sign of abs(array[i]) - 1 to indicate that array[i], a positive integer, is in the array.
array[abs(array[i]) - 1] = -array[abs(array[i]) - 1]
}
}
// Check to see for missing elements. Everything before the pivot should be positive if 1..pivot appear in the
// array and everything after the pivot should be negative if (pivot+1)..(array.size) appears in the array.
// If everything appears in the array, then the first missing number is array.size + 1.
for (i in 0 until pivot)
if (array[i] < 0)
return i + 1
for (i in pivot until array.size)
if (array[i] > 0)
return i + 1
return array.size + 1
}
/**
* Functional method. Check for missing elements and if there are none, the first missing element is the size of the array + 1.
*/
fun findFirstPositiveMissingIntegerFM(array: IntArray): Int =
(1..array.size).find { it !in array } ?: (array.size + 1)
| 0 | C++ | 1 | 0 | 5981e97106376186241f0fad81ee0e3a9b0270b5 | 3,298 | daily-coding-problem | MIT License |
archive/315/solve.kt | daniellionel01 | 435,306,139 | false | null | /*
=== #315 Digital root clocks - Project Euler ===
Sam and Max are asked to transform two digital clocks into two "digital root" clocks.
A digital root clock is a digital clock that calculates digital roots step by step.
When a clock is fed a number, it will show it and then it will start the calculation, showing all the intermediate values until it gets to the result.
For example, if the clock is fed the number 137, it will show: "137" → "11" → "2" and then it will go black, waiting for the next number.
Every digital number consists of some light segments: three horizontal (top, middle, bottom) and four vertical (top-left, top-right, bottom-left, bottom-right).
Number "1" is made of vertical top-right and bottom-right, number "4" is made by middle horizontal and vertical top-left, top-right and bottom-right. Number "8" lights them all.
The clocks consume energy only when segments are turned on/off.
To turn on a "2" will cost 5 transitions, while a "7" will cost only 4 transitions.
Sam and Max built two different clocks.
Sam's clock is fed e.g. number 137: the clock shows "137", then the panel is turned off, then the next number ("11") is turned on, then the panel is turned off again and finally the last number ("2") is turned on and, after some time, off.
For the example, with number 137, Sam's clock requires:"137"
:
(2 + 5 + 4) × 2 = 22 transitions ("137" on/off).
"11"
:
(2 + 2) × 2 = 8 transitions ("11" on/off).
"2"
:
(5) × 2 = 10 transitions ("2" on/off).
For a grand total of 40 transitions.
Max's clock works differently. Instead of turning off the whole panel, it is smart enough to turn off only those segments that won't be needed for the next number.
For number 137, Max's clock requires:"137"
:
2 + 5 + 4 = 11 transitions ("137" on)
7 transitions (to turn off the segments that are not needed for number "11").
"11"
:
0 transitions (number "11" is already turned on correctly)
3 transitions (to turn off the first "1" and the bottom part of the second "1";
the top part is common with number "2").
"2"
:
4 transitions (to turn on the remaining segments in order to get a "2")
5 transitions (to turn off number "2").
For a grand total of 30 transitions.
Of course, Max's clock consumes less power than Sam's one.
The two clocks are fed all the prime numbers between A = 107 and B = 2×107.
Find the difference between the total number of transitions needed by Sam's clock and that needed by Max's one.
Difficulty rating: 20%
*/
fun solve(x: Int): Int {
return x*2;
}
fun main() {
val a = solve(10);
println("solution: $a");
} | 0 | Kotlin | 0 | 1 | 1ad6a549a0a420ac04906cfa86d99d8c612056f6 | 2,583 | euler | MIT License |
src/main/kotlin/aoc2017/HeardYouLikeRegisters.kt | komu | 113,825,414 | false | {"Kotlin": 395919} | package komu.adventofcode.aoc2017
import komu.adventofcode.utils.nonEmptyLines
fun heardYouLikeRegisters(input: String): Pair<Int, Int> {
val ops = input.nonEmptyLines().map(Operation.Companion::parse)
val registers = mutableMapOf<String, Int>()
var max = 0
for (op in ops) {
val conditionValue = registers[op.conditionRegister] ?: 0
if (op.conditionOperator(conditionValue, op.conditionConstant)) {
val value = op.mode.eval(registers[op.register] ?: 0, op.amount)
registers[op.register] = value
max = max.coerceAtLeast(value)
}
}
return Pair(registers.values.maxOrNull() ?: 0, max)
}
private class Operation(val register: String,
val mode: Mode,
val amount: Int,
val conditionRegister: String,
val conditionOperator: RelOp,
val conditionConstant: Int) {
companion object {
private val regex = Regex("""(\w+) (inc|dec) (-?\d+) if (\w+) ([=!<>]+) (-?\d+)""")
fun parse(s: String): Operation {
val m = regex.matchEntire(s) ?: error("no match for '$s'")
return Operation(
register = m.groupValues[1],
mode = Mode.valueOf(m.groupValues[2].toUpperCase()),
amount = m.groupValues[3].toInt(),
conditionRegister = m.groupValues[4],
conditionOperator = parseRelOp(m.groupValues[5]),
conditionConstant = m.groupValues[6].toInt())
}
}
}
private enum class Mode {
INC {
override fun eval(x: Int, y: Int): Int = x + y
},
DEC {
override fun eval(x: Int, y: Int): Int = x - y
};
abstract fun eval(x: Int, y: Int): Int
}
private typealias RelOp = (Int, Int) -> Boolean
fun parseRelOp(s: String): RelOp = when (s) {
"==" -> { x, y -> x == y }
"!=" -> { x, y -> x != y }
"<" -> { x, y -> x < y }
"<=" -> { x, y -> x <= y }
">" -> { x, y -> x > y }
">=" -> { x, y -> x >= y }
else -> error("invalid operator '$s'")
}
| 0 | Kotlin | 0 | 0 | 8e135f80d65d15dbbee5d2749cccbe098a1bc5d8 | 2,157 | advent-of-code | MIT License |
implementation/src/main/kotlin/io/github/tomplum/aoc/ferry/docking/program/BitMask.kt | TomPlum | 317,142,882 | false | null | package io.github.tomplum.aoc.ferry.docking.program
/**
* A bit-mask consisting of either 0, 1 or X.
*
* An X indicates a 'Floating Bit' that is in a state of super-position and is therefore
* simultaneously a 0 and a 1. This means that every [mask] with a floating-bit has
* 2^N permutations wheres N is the number of floating-bits.
*
* @param mask The string of bits.
*/
data class BitMask(private val mask: String) {
/**
* Masks the given [value] with the [mask] bits.
* Any floating-bits (X) are ignored.
*
* E.g;
* [value]: 000000000000000000000000000000001011 (decimal 11)
* [mask]: XXXXXXXXXXXXXXXXXXXXXXXXXXXXX1XXXX0X
* result: 000000000000000000000000000001001001 (decimal 73)
*
* @return The binary representation of the masked [value].
*/
fun applyTo(value: Int): String {
return mask.zip(value.to36bit()) { mask, bit ->
when (mask) {
'0', '1' -> mask
else -> bit
}
}.joinToString("")
}
/**
* Masks the given [value] with the [mask] bits.
* Floating-bits are taken into account and so all mask permutations are applied.
*
* E.g;
*
* First, [applyIgnoreFloating] masks the [value] and ignores floating-bits.
* [value]: 000000000000000000000000000000101010 (decimal 42)
* [mask]: 000000000000000000000000000000X1001X
* result: 000000000000000000000000000000X1101X
*
* Then, [getFloatingPermutations] generates all combinations of masks.
* 000000000000000000000000000000011010 (decimal 26)
* 000000000000000000000000000000011011 (decimal 27)
* 000000000000000000000000000000111010 (decimal 58)
* 000000000000000000000000000000111011 (decimal 59)
*
* @return The binary representations of all the masked values.
*/
fun applyFloatingTo(value: Int): List<String> {
val floatingMask = applyIgnoreFloating(value)
return getFloatingPermutations(floatingMask, mutableListOf())
}
/**
* Masks the given [value] with only literal floating and 1 bits.
* 0 bits are ignored.
*
* E.g;
* [value]: 000000000000000000000000000000101010 (decimal 42)
* [mask]: 000000000000000000000000000000X1001X
* result: 000000000000000000000000000000X1101X
*
* @return The masked value with floating bits intact.
*/
private fun applyIgnoreFloating(value: Int): String {
return mask.zip(value.to36bit()) { mask, bit ->
when (mask) {
'X', '1' -> mask
else -> bit
}
}.joinToString("")
}
/**
* Generates all the combinations of masks by resolving the floating-bits state of
* super-position. For a [mask] with N floating-bits, 2^N masks will be produced.
* @param mask The mask containing 'X' floating-bit values.
* @param masks The list to collect the mask combinations in.
* @return A list of all mask combinations.
*/
private fun getFloatingPermutations(mask: String, masks: MutableList<String>): List<String> {
if (mask.contains('X')) {
val firstCandidate = mask.replaceFirst('X', '0')
if (!masks.contains(firstCandidate)) {
getFloatingPermutations(firstCandidate, masks)
}
val secondCandidate = mask.replaceFirst('X', '1')
if (!masks.contains(secondCandidate)) {
getFloatingPermutations(secondCandidate, masks)
}
}
if (!mask.contains('X')) masks.add(mask)
return masks
}
/**
* Pads a binary string with 0s until it is 36 bits in length.
* @return A 36-bit representation of the given binary string.
*/
private fun Int.to36bit(): String = toString(2).padStart(36, '0')
} | 1 | Kotlin | 0 | 0 | 73b3eacb7cb8a7382f8891d3866eda983b6ea7a9 | 3,867 | advent-of-code-2020 | Apache License 2.0 |
src/main/kotlin/day3.kt | mattianeroni | 725,705,827 | false | {"Kotlin": 7277} | package day3
import java.io.File
import java.util.PriorityQueue
val nums = Array<String>(10){ it.toString() }.toSet()
fun exercise1 ()
{
val filename = "./inputs/day3ex1.txt"
var total: Int = 0
val allLines = File(filename).readLines().toList()
for ((row, line) in allLines.withIndex())
{
var cnum: String = ""
var toAdd: Boolean = false
for (col in 0..line.length - 1)
{
val x: String = line[col].toString()
if (!nums.contains(x)) {
if (toAdd)
total += cnum.toInt()
cnum = ""
toAdd = false
continue
}
cnum = cnum.plus(line[col])
extloop@ for (i in row-1..row+1)
{
if (i < 0 || i >= allLines.size) continue
for (j in col-1..col+1)
{
if (j < 0 || j >= line.length) continue
val str = allLines[i][j].toString()
if (str != "." && !nums.contains(str)) {
toAdd = true
break@extloop
}
}
}
} // end line
if (toAdd) {
total += cnum.toInt()
}
}
println("Total: ${total}")
}
data class Symbol(val name: String, val row: Int, val col: Int)
fun exercise2 ()
{
val filename = "./inputs/day3ex2.txt"
var total: Int = 0
val allLines = File(filename).readLines().toList()
for ((row, line) in allLines.withIndex())
{
for (col in 0..line.length - 1)
{
if (line[col].toString() != "*") continue
var neighbourNums = ArrayList<Int>()
// Read the neighbourhood
var explored = HashSet<Symbol>()
var neighbours = ArrayList<Symbol>()
for (i in row - 1..row + 1)
for (j in col - 1..col + 1)
if (nums.contains(allLines[i][j].toString())) {
neighbours.add(Symbol(name = allLines[i][j].toString(), row = i, col = j))
}
if (neighbours.size == 0) continue
for (neighbour in neighbours)
{
if (explored.contains(neighbour)) continue
var cnum: String = neighbour.name
// Left numbers
var pointer: Symbol = neighbour
while (nums.contains(pointer.name) && pointer.col > 0)
{
pointer = Symbol(
name=allLines[pointer.row][pointer.col - 1].toString(),
row=pointer.row,
col=pointer.col - 1
)
if (nums.contains(pointer.name)) {
cnum = pointer.name.plus(cnum)
explored.add(pointer)
}
}
// RIGHT numbers
pointer = neighbour
while (nums.contains(pointer.name) && pointer.col < line.length - 1)
{
pointer = Symbol(
name=allLines[pointer.row][pointer.col + 1].toString(),
row=pointer.row,
col=pointer.col + 1
)
if (nums.contains(pointer.name)) {
cnum = cnum.plus(pointer.name)
explored.add(pointer)
}
}
neighbourNums.add(cnum.toInt())
}
if (neighbourNums.size < 2) continue
total += neighbourNums.reduce { acc, i -> acc * i }
}
}
println("Total: ${total}")
} | 0 | Kotlin | 0 | 0 | cbbe6f80325931936a36157669ab161f968af659 | 3,771 | aoc | Apache License 2.0 |
src/main/kotlin/net/mguenther/adventofcode/day10/Day10.kt | mguenther | 115,937,032 | false | null | package net.mguenther.adventofcode.day10
/**
* @author <NAME> (<EMAIL>)
*/
class KnotHash(val size: Int) {
private val suffix: IntArray = intArrayOf(17, 31, 73, 47, 23)
private var knot: IntArray = IntArray(size)
private var offset: Int = 0
private var skip: Int = 0
init {
for (i in 0 until knot.size) knot[i] = i
}
fun checksum(input: String): String {
return checksum(input, 64)
}
fun checksum(input: String, times: Int): String {
val inputWithSuffix = combine(input.toCharArray().map { c -> c.toInt() }.toIntArray(), suffix)
return knot(inputWithSuffix, times)
}
private fun combine(left: IntArray, right: IntArray): IntArray {
val combinedLength = left.size + right.size
val combinedArray = IntArray(combinedLength)
var pos = 0
for (element in left) {
combinedArray[pos] = element
pos++
}
for (element in right) {
combinedArray[pos] = element
pos++
}
return combinedArray
}
private fun knot(lengths: IntArray, times: Int): String {
for (i in 0 until times) lengths.forEach { length -> knot(length) }
return encode(knot)
}
private fun encode(lengths: IntArray): String {
var hash = ""
for (i in 0 until 16) {
var sparseNumber = 0
for (j in 0 until 16) {
sparseNumber = sparseNumber.xor(lengths[i * 16 + j])
}
var hex = sparseNumber.toString(16)
if (hex.length < 2) hex = "0" + hex
hash += hex
}
return hash
}
private fun knot(length: Int) {
if (length > knot.size) return
reverse(offset, tailOffset(offset, length-1), length)
offset = nextOffset(offset, length)
increaseSkip()
}
private fun reverse(head: Int, tail: Int, length: Int) {
val adjustedKnot = knot.copyOf()
var i = 0
while (i < length) {
adjustedKnot[copyToOffset(tail, i)] = knot[(head + i).rem(knot.size)]
i++
}
knot = adjustedKnot
}
private fun tailOffset(offset: Int, length: Int): Int = (offset + length).rem(knot.size)
private fun nextOffset(offset: Int, length: Int): Int = (offset + length + skip).rem(knot.size)
private fun copyToOffset(tail: Int, i: Int): Int = when {
(tail - i) < 0 -> (knot.size - Math.abs(tail-i)).rem(knot.size)
else -> Math.abs(tail-i).rem(knot.size)
}
private fun increaseSkip() { skip++ }
override fun toString(): String {
return knot.contentToString()
}
}
| 0 | Kotlin | 0 | 0 | c2f80c7edc81a4927b0537ca6b6a156cabb905ba | 2,722 | advent-of-code-2017 | MIT License |
Algorithms/src/main/kotlin/Search2DMatrix.kt | ILIYANGERMANOV | 557,496,216 | false | {"Kotlin": 74485} | /**
* # Search a 2D Matrix
* Problem:
* https://leetcode.com/problems/search-a-2d-matrix/
*/
class Search2DMatrix {
fun searchMatrix(matrix: Array<IntArray>, target: Int): Boolean {
val rowsCount = matrix.size
if (rowsCount == 1) return binarySearchRow(matrix[0], target)
return binarySearchMatrix(
matrix = matrix,
target = target,
lowIndex = 0,
highIndex = rowsCount - 1
)
}
private fun binarySearchMatrix(
matrix: Array<IntArray>,
target: Int,
lowIndex: Int,
highIndex: Int
): Boolean {
if (lowIndex > highIndex) return false
val mid = (lowIndex + highIndex) / 2
val row = matrix[mid]
val rowFirst = row[0]
val rowLast = row.last()
return when {
target in rowFirst..rowLast -> binarySearchRow(row, target)
target < rowLast ->
// search lower row
binarySearchMatrix(
matrix = matrix,
target = target,
lowIndex = 0,
highIndex = mid - 1
)
else ->
// search higher row
binarySearchMatrix(
matrix = matrix,
target = target,
lowIndex = mid + 1,
highIndex = highIndex
)
}
}
private fun binarySearchRow(
row: IntArray,
target: Int,
low: Int = 0,
high: Int = row.size - 1
): Boolean {
if (low > high) return false
val mid = (low + high) / 2
val midValue = row[mid]
if (target == midValue) return true
return if (target > midValue) {
// search right
binarySearchRow(
row = row,
target = target,
low = mid + 1,
high = high
)
} else {
// search left
binarySearchRow(
row = row,
target = target,
low = low,
high = mid - 1
)
}
}
} | 0 | Kotlin | 0 | 1 | 4abe4b50b61c9d5fed252c40d361238de74e6f48 | 2,208 | algorithms | MIT License |
src/main/kotlin/Cleanup.kt | alebedev | 573,733,821 | false | {"Kotlin": 82424} | // Day4
fun main() {
val sections = readInput()
val fullyContained = sections.count { fullyContains(it.first, it.second) || fullyContains(it.second, it.first) }
val overlapping = sections.count { overlaps(it.first, it.second) }
println("# of fully contained ${fullyContained}")
println("# of overlapping ${overlapping}")
}
private fun readInput(): Iterable<Section> {
val result = mutableListOf<Section>()
generateSequence(::readLine).forEach {
val segments = it.split(',').map(::parsePair)
result.add(Pair(segments[0], segments[1]))
}
return result
}
private typealias Segment = Pair<Int, Int>
private typealias Section = Pair<Segment, Segment>
private fun parsePair(string: String) : Pair<Int, Int> {
val parts = string.split('-')
return Pair(parts[0].toInt(10), parts[1].toInt(10))
}
private fun fullyContains(a: Segment, b: Segment) = a.first <= b.first && a.second >= b.second
private fun overlaps(a: Segment, b: Segment) = (a.first <= b.first && a.second >= b.first) || (a.first <= b.second && a.second >= b.first) | 0 | Kotlin | 0 | 0 | d6ba46bc414c6a55a1093f46a6f97510df399cd1 | 1,084 | aoc2022 | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/NumberOfWaysToStay.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import dev.shtanko.algorithms.MOD
import kotlin.math.min
/**
* 1269. Number of Ways to Stay in the Same Place After Some Steps
* @see <a href="https://leetcode.com/problems/number-of-ways-to-stay-in-the-same-place-after-some-steps">Source</a>
*/
fun interface NumberOfWaysToStay {
operator fun invoke(steps: Int, arrLen: Int): Int
}
/**
* Approach 1: Top-Down Dynamic Programming
*/
class NumberOfWaysToStayTopDown : NumberOfWaysToStay {
lateinit var memo: Array<IntArray>
private var arrLen = 0
override fun invoke(steps: Int, arrLen: Int): Int {
this.arrLen = min(arrLen, steps)
memo = Array(arrLen) { IntArray(steps + 1) { -1 } }
return dp(0, steps)
}
private fun dp(curr: Int, remain: Int): Int {
if (remain == 0) {
return if (curr == 0) {
1
} else {
0
}
}
if (memo[curr][remain] != -1) {
return memo[curr][remain]
}
var ans = dp(curr, remain - 1)
if (curr > 0) {
ans = (ans + dp(curr - 1, remain - 1)) % MOD
}
if (curr < arrLen - 1) {
ans = (ans + dp(curr + 1, remain - 1)) % MOD
}
memo[curr][remain] = ans
return ans
}
}
/**
* Approach 2: Bottom-Up Dynamic Programming
*/
class NumberOfWaysToStayBottomUp : NumberOfWaysToStay {
override fun invoke(steps: Int, arrLen: Int): Int {
val len = min(arrLen, steps)
val dp = Array(len) { IntArray(steps + 1) }
dp[0][0] = 1
for (remain in 1..steps) {
for (curr in len - 1 downTo 0) {
var ans = dp[curr][remain - 1]
if (curr > 0) {
ans = (ans + dp[curr - 1][remain - 1]) % MOD
}
if (curr < len - 1) {
ans = (ans + dp[curr + 1][remain - 1]) % MOD
}
dp[curr][remain] = ans
}
}
return dp[0][steps]
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,663 | kotlab | Apache License 2.0 |
day3/src/main/kotlin/day3/LifeSupport.kt | snv | 434,384,799 | false | {"Kotlin": 99328} | package day3
import kotlin.math.roundToInt
fun lifeSupportRating(diagnosticReport : List<List<Int>>) :Int = oxygenRating(diagnosticReport) * co2ScrubberRating(diagnosticReport)
fun co2ScrubberRating(diagnosticReport: List<List<Int>>): Int = binaryCo2Rating(diagnosticReport).toInt(2)
fun binaryCo2Rating(diagnosticReport: List<List<Int>>): String = findBestMatch(
diagnosticReport
.map{ it.joinToString("") }
.map { Candidate(it, it) },
BitCriteria.CO2
)
fun oxygenRating(diagnosticReport: List<List<Int>>): Int = binaryOxygenRating(diagnosticReport).toInt(2)
fun binaryOxygenRating(diagnosticReport: List<List<Int>>): String = findBestMatch(
diagnosticReport
.map{ it.joinToString("") }
.map { Candidate(it, it) },
BitCriteria.OXYGEN
)
data class Candidate(val suffix: String, val originalLine: String)
enum class BitCriteria(val flipped: Boolean) {
OXYGEN(false),
CO2( true)
}
tailrec fun findBestMatch(
remainingCandidates: List<Candidate>,
mode: BitCriteria,
): String =
if (remainingCandidates.size == 1) remainingCandidates.first().originalLine else {
val winningBit = remainingCandidates
.sumOf { it.suffix.first().digitToInt() }
.toDouble()
.let { it / remainingCandidates.size }
.roundToInt()
.let { if (mode.flipped) flipBit(it) else it }
.toString()
findBestMatch(
remainingCandidates
.filter { it.suffix.startsWith(winningBit) }
.map { it.copy(suffix = it.suffix.removePrefix(winningBit)) },
mode
)
} | 0 | Kotlin | 0 | 0 | 0a2d94f278defa13b52f37a938a156666314cd13 | 1,647 | adventOfCode21 | The Unlicense |
src/test/kotlin/aoc/Day5.kt | Lea369 | 728,236,141 | false | {"Kotlin": 36118} | package aoc
import org.junit.jupiter.api.Nested
import java.nio.file.Files
import java.nio.file.Paths
import java.util.stream.Collectors
import kotlin.test.Test
import kotlin.test.assertEquals
class Day5 {
data class Conversion(val range: LongRange, val diff: Long)
@Nested
internal inner class Day5Test {
private val day5: Day5 = Day5()
@Test
fun testPart1() {
val expected = 107430936L
assertEquals(
expected, day5.solveP1(
"./src/test/resources/input5"
)
)
}
@Test
fun testPart2() {
val expected = 46L
assertEquals(
expected, day5.solveP2(
"./src/test/resources/inputExample5"
)
)
}
}
private fun solveP1(s: String): Long {
val rawLines: List<String> = Files.lines(Paths.get(s)).collect(Collectors.toList())
val inputNumbers: List<Long> =
rawLines[0].split(":")[1].split(" ").filter { it != "" }.map { it.toLong() }
val maps: List<List<Conversion>> = rawLines.filterIndexed() { i, _ -> i != 0 }.filter { it.isNotEmpty() }
.fold(mutableListOf<MutableList<Conversion>>()) { acc, rawline ->
if (acc.isEmpty() || !rawline[0].isDigit()) {
acc.add(mutableListOf())
} else {
val rawlist = rawline.split(" ").filter { it.isNotEmpty() }.map { it.toLong() }
acc.last().add(Conversion(rawlist[1]..rawlist[1] + rawlist[2], rawlist[0] - rawlist[1]))
acc.last().sortBy { it.range.first }
}
acc
}
return inputNumbers.map {
var result: Long = it
maps.forEach { result = processNumber(result, it) }
result
}.min()
}
private fun processNumber(result: Long, conversions: List<Conversion>): Long {
val conversion = conversions.filter { result in it.range }
return if (conversion.size == 1) {
result + conversion[0].diff
} else result
}
private fun solveP2(s: String): Long {
val rawLines: List<String> = Files.lines(Paths.get(s)).collect(Collectors.toList())
val inputRanges: List<LongRange> = rawLines[0].split(":")[1].split(" ")
.filter { it != "" }
.map { it.toLong() }
.chunked(2)
.map { it.first()..it.first() + it.last() }
val maps: List<List<Conversion>> = rawLines.filterIndexed() { i, _ -> i != 0 }.filter { it.isNotEmpty() }
.fold(mutableListOf<MutableList<Conversion>>()) { acc, rawline ->
if (acc.isEmpty() || !rawline[0].isDigit()) {
acc.add(mutableListOf())
} else {
val rawlist = rawline.split(" ").filter { it.isNotEmpty() }.map { it.toLong() }
acc.last().add(Conversion(rawlist[1]..<rawlist[1] + rawlist[2], rawlist[0] - rawlist[1]))
}
acc
}
return inputRanges.minOf { range ->
processRanges(listOf(range), maps)
}
}
private fun processRanges(inputRanges: List<LongRange>, maps: List<List<Conversion>>): Long {
var result: List<LongRange> = inputRanges
maps.forEach { map -> result = result.flatMap { range -> processOneRangeInOneMap(range, map) } }
return result.minOf { it.first }
}
private fun processOneRangeInOneMap(range: LongRange, conversions: List<Conversion>): List<LongRange> {
val boundaries =
(conversions.flatMap { listOf(it.range.first, it.range.last + 1) } + listOf(
range.first,
range.last + 1
)).sorted().filter { it >= range.first && it <= range.last + 1 }
return boundaries.asSequence()
.mapIndexed { index, number -> if (index < boundaries.size - 1) number..<boundaries[index + 1] else 0L..0L }
.filter { it != 0L..0L }
.map { r ->
val diff =
conversions.filter { conv -> r.first in conv.range }.getOrElse(0) { Conversion(0L..0L, 0L) }.diff
(r.first + diff)..<(r.last + diff)
}.toList()
}
} | 0 | Kotlin | 0 | 0 | 1874184df87d7e494c0ff787ea187ea3566fbfbb | 4,355 | AoC | Apache License 2.0 |
src/main/java/Exercise11-part2.kt | cortinico | 317,667,457 | false | null | fun main() {
val input: List<CharArray> =
object {}
.javaClass
.getResource("input-11.txt")
.readText()
.split("\n")
.map(String::toCharArray)
var array1 = Array(input.size) { i -> CharArray(input[i].size) { j -> input[i][j] } }
var array2 = Array(input.size) { i -> CharArray(input[i].size) { ' ' } }
var occupiedPlaces: Int
do {
var countedChanges = 0
occupiedPlaces = 0
for (i in array1.indices) {
for (j in array1[i].indices) {
array2[i][j] =
when (array1[i][j]) {
'.' -> '.'
'#' -> {
if (countVisibleOccupied(array1, i, j, '#') >= 5) {
countedChanges++
'L'
} else {
occupiedPlaces++
'#'
}
}
else -> { // L
if (countVisibleOccupied(array1, i, j, '#') <= 0) {
countedChanges++
occupiedPlaces++
'#'
} else {
'L'
}
}
}
}
}
array1 = array2
array2 = Array(input.size) { i -> CharArray(input[i].size) { ' ' } }
} while (countedChanges != 0)
println(occupiedPlaces)
}
fun countVisibleOccupied(array: Array<CharArray>, i: Int, j: Int, target: Char) =
listOf(
-1 to 0,
-1 to -1,
-1 to +1,
0 to -1,
0 to +1,
+1 to 0,
+1 to -1,
+1 to +1,
)
.map { (dirX, dirY) -> toVisible(array, i, j, dirX, dirY) }
.count { it == target }
fun toVisible(array: Array<CharArray>, i: Int, j: Int, dirX: Int, dirY: Int): Char {
var nexti = i + dirX
var nextj = j + dirY
while (nexti >= 0 && nexti < array.size && nextj >= 0 && nextj < array[0].size) {
array[nexti][nextj].let { if (it != '.') return it }
nexti += dirX
nextj += dirY
}
return '.'
}
| 1 | Kotlin | 0 | 4 | a0d980a6253ec210433e2688cfc6df35104aa9df | 2,326 | adventofcode-2020 | MIT License |
calendar/day04/Day4.kt | mpetuska | 571,764,215 | false | {"Kotlin": 18073} | package day04
import Day
import Lines
import kotlin.math.max
import kotlin.math.min
class Day4 : Day() {
override fun part1(input: Lines): Any {
return input.map { it.split(",") }
.map { (a, b) -> a.split("-") to b.split("-") }
.map { (a, b) -> a.let { (s, f) -> s.toInt()..f.toInt() } to b.let { (s, f) -> s.toInt()..f.toInt() } }
.count { (a, b) -> (a.first <= b.first && a.last >= b.last) || (b.first <= a.first && b.last >= a.last) }
}
override fun part2(input: Lines): Any {
return input.map { it.split(",") }
.map { (a, b) -> a.split("-") to b.split("-") }
.map { (a, b) -> a.let { (s, f) -> s.toInt()..f.toInt() } to b.let { (s, f) -> s.toInt()..f.toInt() } }
.count { (a, b) -> max(a.first, b.first) <= min(a.last, b.last) }
}
} | 0 | Kotlin | 0 | 0 | be876f0a565f8c14ffa8d30e4516e1f51bc3c0c5 | 791 | advent-of-kotlin-2022 | Apache License 2.0 |
year2016/src/main/kotlin/net/olegg/aoc/year2016/day14/Day14.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2016.day14
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.utils.md5
import net.olegg.aoc.year2016.DayOf2016
/**
* See [Year 2016, Day 14](https://adventofcode.com/2016/day/14)
*/
object Day14 : DayOf2016(14) {
private val MATCH_3 = "(.)(\\1)(\\1)".toRegex()
override fun first(): Any? {
val cache = mutableMapOf<Int, String>()
val hash = { n: Int ->
cache.getOrPut(n) {
"$data$n".md5()
}
}
return solve(64, hash)
}
override fun second(): Any? {
val cache = mutableMapOf<Int, String>()
val hash = { n: Int ->
cache.getOrPut(n) {
(0..2016).fold("$data$n") { acc, _ ->
acc.md5()
}
}
}
return solve(64, hash)
}
private fun solve(
count: Int,
hash: (Int) -> String
): Int {
return generateSequence(0) { it + 1 }
.map { it to hash(it) }
.filter { MATCH_3.containsMatchIn(it.second) }
.filter { (i, hashed) ->
val (match) = checkNotNull(MATCH_3.find(hashed)).destructured
val next = match.repeat(5)
(i + 1..i + 1000).any { value -> next in hash(value) }
}
.drop(count - 1)
.first()
.first
}
}
fun main() = SomeDay.mainify(Day14)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 1,253 | adventofcode | MIT License |
src/main/kotlin/aoc08/aoc08.kt | dnene | 317,653,484 | false | null | package aoc08
import arrow.core.Either
import arrow.core.flatMap
import arrow.core.left
import arrow.core.right
import java.io.File
enum class Operation(val str: String, val accFunc: (Int, Int, Int) -> Pair<Int, Int>) {
Accumulate("acc", { index, acc, offset -> index + 1 to acc + offset }),
Jump("jmp", { index, acc, offset -> index + offset to acc }),
NoOp("nop", { index, acc, _ -> index + 1 to acc });
companion object {
private val operations = values().map { it.str to it }.toMap()
operator fun get(str: String) = operations[str]!!
}
}
typealias Instruction = Pair<Operation, Int>
fun Instruction.step(index: Int, accumulator: Int) = first.accFunc(index, accumulator, second)
fun Pair<Int, Int>.toProcessor(executed: Set<Int>) = Processor(first, second, executed)
fun Operation.switchJumpsNoops() = when (this) {
Operation.Accumulate -> Operation.Accumulate
Operation.Jump -> Operation.NoOp
Operation.NoOp -> Operation.Jump
}
fun List<Instruction>.switchAt(index: Int) =
toMutableList().apply { set(index, elementAt(index).let { it.first.switchJumpsNoops() to it.second }) }
data class Processor(val index: Int, val accumulator: Int, val executed: Set<Int>) {
fun step(instructions: List<Instruction>): Either<Processor, Processor> =
if (index in executed) left()
else if (index >= instructions.size) this.right()
else instructions[index].step(index, accumulator).toProcessor(executed + index).right()
}
fun process(processor: Processor, instructions: List<Instruction>): Either<Processor, Processor> =
processor.step(instructions).flatMap {
if (processor.index >= instructions.size) it.right()
else process(it, instructions)
}
fun main() {
val instructions = File("data/inputs/aoc08.txt")
.readLines()
.map {
it
.trim()
.replace("+", "")
.split(" ")
.let { Operation[it[0]]!! to it[1].toInt() }
}
// part 1
process(Processor(0, 0, setOf()), instructions).mapLeft { println(it.accumulator) }
// part 2
instructions.mapIndexedNotNull { index, pair ->
if (pair.first == Operation.Accumulate) {
null
} else {
val result = process(Processor(0, 0, setOf()), instructions.switchAt(index))
when (result) {
is Either.Left -> null
is Either.Right -> result.b.accumulator
}
}
}.forEach { println(it) }
} | 0 | Kotlin | 0 | 0 | db0a2f8b484575fc3f02dc9617a433b1d3e900f1 | 2,542 | aoc2020 | MIT License |
src/main/kotlin/charizard/WinningCombinations.kt | mohakapt | 677,036,849 | false | null | package charizard
/**
* Stores the winning combinations for a given board size.
*/
object WinningCombinations {
private fun generate(boardSize: Int): List<Long> {
val wins = mutableListOf<Long>()
val cellCount = boardSize * boardSize
for (i in 0..<cellCount) {
val row = i / boardSize
val col = i % boardSize
// Row combination
if (col <= 0)
wins.add(((1L shl boardSize) - 1) shl (row * boardSize + col))
// Column combination
if (row <= 0) {
val columnMask = (1..<boardSize).fold(1L) { acc, j -> acc or (1L shl (j * boardSize)) }
wins.add(columnMask shl i)
}
// Diagonal combination (from top-left to bottom-right)
if (row == col && row <= 0)
wins.add((1..<boardSize).fold(1L) { acc, j -> acc or (1L shl (j * (boardSize + 1))) })
// Diagonal combination (from top-right to bottom-left)
if (row + col == boardSize - 1 && row <= 0)
wins.add((1..<boardSize).fold(1L shl (boardSize - 1)) { acc, j -> acc or (1L shl ((j + 1) * (boardSize - 1))) })
}
return wins
}
private val cache = mutableMapOf<Int, List<Long>>()
/**
* Gets the winning combinations for a given board size.
*
* @param boardSize The size of the board.
* @return A list of the winning combinations as bitmasks.
*/
fun get(boardSize: Int): List<Long> = cache.computeIfAbsent(boardSize, ::generate)
}
| 0 | Kotlin | 0 | 2 | fd67f349b9bb33c15b4bdd48d9d1fef76dd35ed8 | 1,570 | Minimax | MIT License |
src/Day14.kt | IvanChadin | 576,061,081 | false | {"Kotlin": 26282} | import kotlin.math.max
import kotlin.math.sign
fun main() {
val inputName = "Day14_test"
fun part1(): Int {
val a = Array(1000) { BooleanArray(1000) { false } }
var maxRow = -1
for (s in readInput(inputName)) {
val points = s.split(" -> ").map {
it.split(",")
.map { str -> str.toInt() }
}
var row = -1
var col = -1
for (pt in points) {
if (row == -1) {
col = pt[0]
row = pt[1]
maxRow = max(maxRow, row)
a[row][col] = true
} else {
do {
row += sign(pt[1] - row * 1.0).toInt()
col += sign(pt[0] - col * 1.0).toInt()
a[row][col] = true
maxRow = max(maxRow, row)
} while (row != pt[1] || col != pt[0])
}
}
}
var ans = 0
val dRow = intArrayOf(1, 1, 1)
val dCol = intArrayOf(0, -1, 1)
while (true) {
var row = 0
var col = 500
var ok = true
while (ok) {
ok = false
for (i in 0..2) {
val nRow = row + dRow[i]
val nCol = col + dCol[i]
if (nRow in a.indices && nCol in a[nRow].indices && !a[nRow][nCol]) {
row = nRow
col = nCol
ok = true
break
}
}
if (row > maxRow) {
break
}
}
if (row > maxRow) {
break
}
a[row][col] = true
ans++
}
return ans
}
fun part2(): Int {
val a = Array(1000) { BooleanArray(1000) { false } }
var maxRow = -1
for (s in readInput(inputName)) {
val points = s.split(" -> ").map {
it.split(",")
.map { str -> str.toInt() }
}
var row = -1
var col = -1
for (pt in points) {
if (row == -1) {
col = pt[0]
row = pt[1]
maxRow = max(maxRow, row)
a[row][col] = true
} else {
do {
row += sign(pt[1] - row * 1.0).toInt()
col += sign(pt[0] - col * 1.0).toInt()
a[row][col] = true
maxRow = max(maxRow, row)
} while (row != pt[1] || col != pt[0])
}
}
}
for (c in a[maxRow].indices) {
a[maxRow + 2][c] = true
}
var ans = 0
val dRow = intArrayOf(1, 1, 1)
val dCol = intArrayOf(0, -1, 1)
while (!a[0][500]) {
var row = 0
var col = 500
var ok = true
while (ok) {
ok = false
for (i in 0..2) {
val nRow = row + dRow[i]
val nCol = col + dCol[i]
if (nRow in a.indices && nCol in a[nRow].indices && !a[nRow][nCol]) {
row = nRow
col = nCol
ok = true
break
}
}
}
a[row][col] = true
ans++
}
return ans
}
val result = part2()
println(result)
} | 0 | Kotlin | 0 | 0 | 2241437e6c3a20de70306a0cb37b6fe2ed8f9e3a | 3,704 | aoc-2022 | Apache License 2.0 |
src/pl/shockah/aoc/y2017/Day8.kt | Shockah | 159,919,224 | false | null | package pl.shockah.aoc.y2017
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
import pl.shockah.aoc.AdventTask
import java.util.regex.Pattern
import kotlin.math.max
class Day8: AdventTask<List<Day8.Instruction>, Int, Int>(2017, 8) {
private val inputPattern: Pattern = Pattern.compile("(\\w+) (inc|dec) (-?\\d+) if (\\w+) (==|!=|>|<|>=|<=) (-?\\d+)")
enum class Operator(
val symbol: String,
private val lambda: (Int, Int) -> Boolean
) {
Equals("==", { a, b -> a == b }),
NotEquals("!=", { a, b -> a != b }),
Greater(">", { a, b -> a > b }),
Lower("<", { a, b -> a < b }),
GreaterOrEqual(">=", { a, b -> a >= b }),
LowerOrEqual("<=", { a, b -> a <= b });
operator fun invoke(a: Int, b: Int): Boolean {
return lambda(a, b)
}
companion object {
val bySymbol = values().associateBy { it.symbol }
}
}
data class Instruction(
val register: String,
val adding: Int,
val conditionRegister: String,
val conditionOperator: Operator,
val conditionValue: Int
)
override fun parseInput(rawInput: String): List<Instruction> {
return rawInput.lines().map {
val matcher = inputPattern.matcher(it)
require(matcher.find())
val register = matcher.group(1)
val adding = matcher.group(3).toInt() * (if (matcher.group(2) == "dec") -1 else 1)
val conditionRegister = matcher.group(4)
val conditionOperator = Operator.bySymbol[matcher.group(5)]!!
val conditionValue = matcher.group(6).toInt()
return@map Instruction(register, adding, conditionRegister, conditionOperator, conditionValue)
}
}
private enum class Mode {
FinalMaxValue, MaxValueEver
}
@Suppress("NOTHING_TO_INLINE")
private inline fun task(input: List<Instruction>, mode: Mode): Int {
val registers = mutableMapOf<String, Int>()
var maxValue = 0
for (instruction in input) {
if (instruction.conditionOperator(registers[instruction.conditionRegister] ?: 0, instruction.conditionValue)) {
registers[instruction.register] = (registers[instruction.register] ?: 0) + instruction.adding
if (mode == Mode.MaxValueEver)
maxValue = max(maxValue, registers[instruction.register]!!)
}
}
return when (mode) {
Mode.FinalMaxValue -> registers.values.maxOrNull()!!
Mode.MaxValueEver -> maxValue
}
}
override fun part1(input: List<Instruction>): Int {
return task(input, Mode.FinalMaxValue)
}
override fun part2(input: List<Instruction>): Int {
return task(input, Mode.MaxValueEver)
}
class Tests {
private val task = Day8()
private val rawInput = """
b inc 5 if a > 1
a inc 1 if b < 5
c dec -10 if a >= 1
c inc -20 if c == 10
""".trimIndent()
@Test
fun part1() {
val input = task.parseInput(rawInput)
Assertions.assertEquals(1, task.part1(input))
}
@Test
fun part2() {
val input = task.parseInput(rawInput)
Assertions.assertEquals(10, task.part2(input))
}
}
} | 0 | Kotlin | 0 | 0 | 9abb1e3db1cad329cfe1e3d6deae2d6b7456c785 | 2,898 | Advent-of-Code | Apache License 2.0 |
examples/bowlingKata/FunctionalBowling.kt | uberto | 624,365,748 | false | null | data class GameState(val rolls: List<Int> = listOf())
fun roll(gameState: GameState, pins: Int): GameState = GameState(gameState.rolls + pins)
fun score(gameState: GameState): Int = calculateScore(gameState.rolls, 0, 0)
private tailrec fun calculateScore(rolls: List<Int>, frameIndex: Int, frame: Int): Int =
if (frame == 10) 0
else when {
isStrike(rolls, frameIndex) -> 10 + strikeBonus(rolls, frameIndex) + calculateScore(rolls, frameIndex + 1, frame + 1)
isSpare(rolls, frameIndex) -> 10 + spareBonus(rolls, frameIndex) + calculateScore(rolls, frameIndex + 2, frame + 1)
else -> sumOfBallsInFrame(rolls, frameIndex) + calculateScore(rolls, frameIndex + 2, frame + 1)
}
fun calcBowlingScore(rolls: List<Pins>): Int {
fun getRoll(roll: Int): Int = rolls.getOrElse(roll){ Pins.zero }.number
fun isStrike(frameIndex: Int): Boolean =
getRoll(frameIndex) == 10
fun sumOfBallsInFrame(frameIndex: Int): Int =
getRoll(frameIndex) + getRoll(frameIndex + 1)
fun spareBonus(frameIndex: Int): Int =
getRoll(frameIndex + 2)
fun strikeBonus(frameIndex: Int): Int =
getRoll(frameIndex + 1) + getRoll(frameIndex + 2)
fun isSpare(frameIndex: Int): Boolean =
getRoll(frameIndex) + getRoll(frameIndex + 1) == 10
var score = 0
var frameIndex = 0
for (frame in 0..9) {
if (isStrike(frameIndex)) {
score += 10 + strikeBonus(frameIndex)
frameIndex++
} else if (isSpare(frameIndex)) {
score += 10 + spareBonus(frameIndex)
frameIndex += 2
} else {
score += sumOfBallsInFrame(frameIndex)
frameIndex += 2
}
}
return score
}
private fun isStrike(rolls: List<Int>, frameIndex: Int): Boolean = rolls.getOrNull(frameIndex) == 10
private fun sumOfBallsInFrame(rolls: List<Int>, frameIndex: Int): Int =
rolls.getOrNull(frameIndex).orZero() + rolls.getOrNull(frameIndex + 1).orZero()
private fun spareBonus(rolls: List<Int>, frameIndex: Int): Int = rolls.getOrNull(frameIndex + 2).orZero()
private fun strikeBonus(rolls: List<Int>, frameIndex: Int): Int =
rolls.getOrNull(frameIndex + 1).orZero() + rolls.getOrNull(frameIndex + 2).orZero()
private fun isSpare(rolls: List<Int>, frameIndex: Int): Boolean =
rolls.getOrNull(frameIndex).orZero() + rolls.getOrNull(frameIndex + 1).orZero() == 10
private fun Int?.orZero(): Int = this ?: 0
| 0 | Kotlin | 0 | 2 | 4f41f9f23bd1d0db9267ca19561263ece0d4022e | 2,455 | prompts | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/EvalRPN.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import java.util.Stack
import java.util.function.BiFunction
/**
* Evaluate Reverse Polish Notation
* @see <a href="https://leetcode.com/problems/evaluate-reverse-polish-notation">Source</a>
*/
fun interface EvalRPN {
operator fun invoke(tokens: Array<String>): Int
}
/**
* Approach 1: Reducing the List In-place
*/
class RPNInPlace : EvalRPN {
override operator fun invoke(tokens: Array<String>): Int {
var currentPosition = 0
var length: Int = tokens.size // We need to keep track of this ourselves.
while (length > 1) {
// Move the position pointer to the next operator token.
while (!OPERATIONS.containsKey(tokens[currentPosition])) {
currentPosition++
}
// Extract the operation and numbers to apply operation too.
val operation = tokens[currentPosition]
val number1 = tokens[currentPosition - 2].toInt()
val number2 = tokens[currentPosition - 1].toInt()
// Calculate the result to overwrite the operator with.
val operator: BiFunction<Int, Int, Int>? = OPERATIONS[operation]
val value = operator?.apply(number1, number2)
tokens[currentPosition] = value.toString()
// Delete numbers and point pointers correctly.
delete2AtIndex(tokens, currentPosition - 2, length)
currentPosition--
length -= 2
}
return tokens[0].toInt()
}
private fun delete2AtIndex(tokens: Array<String>, d: Int, length: Int) {
for (i in d until length - 2) {
tokens[i] = tokens[i + 2]
}
}
// Ensure this only gets done once for ALL test cases.
companion object {
private val OPERATIONS: MutableMap<String, BiFunction<Int, Int, Int>> = HashMap()
init {
OPERATIONS["+"] = BiFunction { a: Int, b: Int -> a + b }
OPERATIONS["-"] = BiFunction { a, b -> a - b }
OPERATIONS["*"] = BiFunction { a, b -> a * b }
OPERATIONS["/"] = BiFunction { a, b -> a / b }
}
}
}
/**
* Approach 2: Evaluate with Stack
*/
class RPNStack : EvalRPN {
override operator fun invoke(tokens: Array<String>): Int {
val stack: Stack<Int> = Stack()
for (token in tokens) {
if (!"+-*/".contains(token)) {
stack.push(Integer.valueOf(token))
continue
}
val number2: Int = stack.pop()
val number1: Int = stack.pop()
var result = 0
when (token) {
"+" -> result = number1 + number2
"-" -> result = number1 - number2
"*" -> result = number1 * number2
"/" -> result = number1 / number2
}
stack.push(result)
}
return stack.pop()
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 3,525 | kotlab | Apache License 2.0 |
src/main/kotlin/adventofcode2017/Day03SpiralMemory.kt | n81ur3 | 484,801,748 | false | {"Kotlin": 476844, "Java": 275} | package adventofcode2017
import adventofcode2017.Direction.*
import kotlin.math.absoluteValue
class Day03SpiralMemory
data class Coordinate(val x: Int, val y: Int)
enum class Direction {
RIGHT,
LEFT,
UP,
DOWN
}
class SpiralMemory(private val input: Int = 1) {
private val memory = mutableMapOf<Int, Coordinate>()
private val stressTestMemory = mutableMapOf<Coordinate, Int>()
private var maxX = 1
private var minX = -1
private var maxY = 1
private var minY = -1
private var currentDirection = RIGHT
init {
buildMemory()
}
private fun buildMemory() {
var currentValue = 1
var currentPosition = Coordinate(0, 0)
while (currentValue <= input) {
memory[currentValue++] = currentPosition
currentPosition = getNextPosition(currentPosition)
}
}
private fun buildStressTestMemory(targetValue: Int) {
var currentValue = 1
var currentPosition = Coordinate(0, 0)
stressTestMemory[currentPosition] = currentValue
currentPosition = getNextPosition(currentPosition)
do {
currentValue = sumOfNeighborsAtPos(currentPosition.x, currentPosition.y)
stressTestMemory[currentPosition] = currentValue
currentPosition = getNextPosition(currentPosition)
} while (currentValue < targetValue)
}
fun stressTest(targetValue: Int): Int {
buildStressTestMemory(targetValue)
return stressTestMemory.values.last()
}
private fun sumOfNeighborsAtPos(x: Int, y: Int): Int {
val offsets = listOf(
-1 to 0,
-1 to 1,
-1 to -1,
0 to 1,
0 to -1,
1 to 0,
1 to 1,
1 to -1
)
val neighbors = offsets.mapNotNull { offset ->
stressTestMemory.keys.find { it.x == x + offset.first && it.y == y + offset.second }
}
return stressTestMemory.filter { it.key in neighbors }.values.sum()
}
fun manhattanDistanceForCell(value: Int): Int {
memory[value]?.let { coordinate ->
return (coordinate.x.absoluteValue + coordinate.y.absoluteValue)
} ?: return 0
}
private fun getNextPosition(currentPosition: Coordinate): Coordinate {
when (currentDirection) {
RIGHT -> {
return if (currentPosition.x == maxX) {
currentDirection = UP
maxX++
Coordinate(currentPosition.x, currentPosition.y - 1)
} else {
Coordinate(currentPosition.x + 1, currentPosition.y)
}
}
UP -> {
return if (currentPosition.y == minY) {
currentDirection = LEFT
minY--
Coordinate(currentPosition.x - 1, currentPosition.y)
} else {
Coordinate(currentPosition.x, currentPosition.y - 1)
}
}
LEFT -> {
return if (currentPosition.x == minX) {
currentDirection = DOWN
minX--
Coordinate(currentPosition.x, currentPosition.y + 1)
} else {
Coordinate(currentPosition.x - 1, currentPosition.y)
}
}
DOWN -> {
return if (currentPosition.y == maxY) {
currentDirection = RIGHT
maxY++
Coordinate(currentPosition.x + 1, currentPosition.y)
} else {
Coordinate(currentPosition.x, currentPosition.y + 1)
}
}
}
}
} | 0 | Kotlin | 0 | 0 | fdc59410c717ac4876d53d8688d03b9b044c1b7e | 3,965 | kotlin-coding-challenges | MIT License |
src/main/kotlin/com/leetcode/P131.kt | antop-dev | 229,558,170 | false | {"Kotlin": 695315, "Java": 213000} | package com.leetcode
// https://github.com/antop-dev/algorithm/issues/297
class P131 {
fun partition(s: String): List<List<String>> {
// dynamic programming
val dp = Array(s.length) { IntArray(s.length) }.apply {
for (i in s.indices) this[i][i] = 1
for (i in 1 until s.length) {
if (s[i - 1] == s[i]) {
this[i - 1][i] = 1
}
}
for (start in 2 until s.length) {
var i = 0
var j = start
while (j < s.length) {
if (s[i] == s[j] && this[i + 1][j - 1] == 1) {
this[i][j] = 1
}
i++
j++
}
}
}
// backtracking
val answer = mutableListOf<List<String>>()
val pool = mutableListOf<String>()
dfs(dp, answer, pool, s, 0)
return answer
}
private fun dfs(
dp: Array<IntArray>,
answer: MutableList<List<String>>,
pool: MutableList<String>,
s: String,
p: Int
) {
if (p == s.length) {
answer += pool.toList()
return
}
for (i in p until s.length) {
if (dp[p][i] == 1) {
pool.add(s.substring(p, i + 1))
dfs(dp, answer, pool, s, i + 1)
pool.removeAt(pool.lastIndex)
}
}
}
}
| 1 | Kotlin | 0 | 0 | 9a3e762af93b078a2abd0d97543123a06e327164 | 1,488 | algorithm | MIT License |
codeforces/round637/b.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package codeforces.round637
private val digits = listOf("1110111", "0010010", "1011101", "1011011", "0111010",
"1101011", "1101111", "1010010", "1111111", "1111011").map { it.toInt(2) }
fun main() {
val (n, k) = readInts()
val a = List(n) {
val shown = readLn().toInt(2)
digits.mapIndexedNotNull { d, digit ->
(d to Integer.bitCount(digit xor shown)).takeIf { digit.inv() and shown == 0 }
}
}
val can = List(n + 1) { BooleanArray(k + 1) }
can[n][0] = true
for (i in a.indices.reversed()) {
for ((_, need) in a[i]) {
for (j in 0..k - need) if (can[i + 1][j]) can[i][j + need] = true
}
}
var x = k
println(if (!can[0][x]) -1 else a.indices.joinToString("") { i ->
val (d, need) = a[i].last { can[i + 1].getOrFalse(x - it.second) }
x -= need
d.toString()
})
}
private fun BooleanArray.getOrFalse(index: Int) = getOrNull(index) ?: false
private fun readLn() = readLine()!!
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 1,012 | competitions | The Unlicense |
src/main/kotlin/g0601_0700/s0640_solve_the_equation/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g0601_0700.s0640_solve_the_equation
// #Medium #String #Math #Simulation #2023_02_10_Time_170_ms_(66.67%)_Space_35.3_MB_(66.67%)
class Solution {
fun solveEquation(equation: String): String {
val eqs = equation.split("=".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
val arr1 = evaluate(eqs[0])
val arr2 = evaluate(eqs[1])
return if (arr1[0] == arr2[0] && arr1[1] == arr2[1]) {
"Infinite solutions"
} else if (arr1[0] == arr2[0]) {
"No solution"
} else {
"x=" + (arr2[1] - arr1[1]) / (arr1[0] - arr2[0])
}
}
private fun evaluate(eq: String): IntArray {
val arr = eq.toCharArray()
var f = false
var a = 0
var b = 0
var i = 0
if (arr[0] == '-') {
f = true
i++
}
while (i < arr.size) {
if (arr[i] == '-') {
f = true
i++
} else if (arr[i] == '+') {
i++
}
val sb = StringBuilder()
while (i < arr.size && Character.isDigit(arr[i])) {
sb.append(arr[i])
i++
}
val n = sb.toString()
if (i < arr.size && arr[i] == 'x') {
var number: Int
number = if (n == "") {
1
} else {
n.toInt()
}
if (f) {
number = -number
}
a += number
i++
} else {
var number = n.toInt()
if (f) {
number = -number
}
b += number
}
f = false
}
val op = IntArray(2)
op[0] = a
op[1] = b
return op
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,901 | LeetCode-in-Kotlin | MIT License |
src/Day01.kt | jdpaton | 578,869,545 | false | {"Kotlin": 10658} | fun main() {
fun part1() {
val testInput = readInput("Day01_test")
var elfIndex = 1
var currentTotal = 0
val elfMap = mutableMapOf<Int, Int>()
testInput.forEach { line ->
if (line.isNotEmpty()) {
currentTotal += line.toInt()
} else {
elfMap[elfIndex] = currentTotal
currentTotal = 0
elfIndex += 1
}
}
val biggestElfIdx = elfMap.maxBy { it.value }
println(biggestElfIdx)
}
fun part2() {
val testInput = readInput("Day01_test")
var elfIndex = 1
var currentTotal = 0
val elfMap = mutableMapOf<Int, Int>()
testInput.forEach { line ->
if (line.isNotEmpty()) {
currentTotal += line.toInt()
} else {
elfMap[elfIndex] = currentTotal
currentTotal = 0
elfIndex += 1
}
}
val topThree = mutableSetOf<Pair<Int,Int>>()
for(i in 1..3) {
val elf = elfMap.maxBy { it.value }
topThree.add(elf.toPair())
elfMap.remove(elf.key)
}
println(topThree.sumOf { it.second })
}
part1()
part2()
}
| 0 | Kotlin | 0 | 0 | f6738f72e2a6395815840a13dccf0f6516198d8e | 1,278 | aoc-2022-in-kotlin | Apache License 2.0 |
solutions/aockt/y2021/Y2021D06.kt | Jadarma | 624,153,848 | false | {"Kotlin": 435090} | package aockt.y2021
import io.github.jadarma.aockt.core.Solution
object Y2021D06 : Solution {
/**
* A simulation model of a population of lantern fish.
* @constructor Initializes this population based on the days left of each fish's reproductive cycle.
*/
private class LanternFishPopulation(seed: List<Int>) {
private val cycles = LongArray(9) { 0L }
init {
seed.forEach { cycle ->
require(cycle in 0..8) { "Invalid reproduction cycle for a LanternFish." }
cycles[cycle]++
}
}
/** Pass a day in the simulation, and give birth to more fish. */
fun simulateDay() {
val fishThatWillGiveBirth = cycles[0]
for (age in 0..7) cycles[age] = cycles[age + 1]
cycles[8] = fishThatWillGiveBirth
cycles[6] += cycles[8]
}
/** Returns the total number of live fish at this point in the simulation. */
fun populationCount(): Long = cycles.sum()
}
/** Parse the input and return the [LanternFishPopulation] described in the input. */
private fun parseInput(input: String): LanternFishPopulation =
input
.splitToSequence(',')
.map { cycle -> cycle.toIntOrNull() ?: throw IllegalArgumentException() }
.let { LanternFishPopulation(it.toList()) }
override fun partOne(input: String) =
parseInput(input)
.apply { repeat(80) { simulateDay() } }
.populationCount()
override fun partTwo(input: String) =
parseInput(input)
.apply { repeat(256) { simulateDay() } }
.populationCount()
}
| 0 | Kotlin | 0 | 3 | 19773317d665dcb29c84e44fa1b35a6f6122a5fa | 1,688 | advent-of-code-kotlin-solutions | The Unlicense |
src/day-3/part-2/solution-day-3-part-2.kts | d3ns0n | 572,960,768 | false | {"Kotlin": 31665} | import java.io.File
fun groupElves(rucksacks: List<String>): List<Triple<String, String, String>> {
val elfGroups = mutableListOf<Triple<String, String, String>>()
for (i in 0..rucksacks.size - 1 step 3) {
elfGroups.add(Triple(rucksacks[i], rucksacks[i + 1], rucksacks[i + 2]))
}
return elfGroups
}
fun findDuplicates(elfGroup: Triple<String, String, String>): Char =
elfGroup.first.toCharArray()
.first { elfGroup.second.contains(it) && elfGroup.third.contains(it) }
fun getPriority(character: Char): Int {
if (character.code in 65..90) {
return character.code - 38
}
return character.code - 96
}
var result = groupElves(File("../input.txt").readLines())
.map { findDuplicates(it) }
.map { getPriority(it) }
.sum()
println(result)
assert(result == 2552)
| 0 | Kotlin | 0 | 0 | 8e8851403a44af233d00a53b03cf45c72f252045 | 829 | advent-of-code-22 | MIT License |
src/day-2/part-2/solution-day-2-part-2.kts | d3ns0n | 572,960,768 | false | {"Kotlin": 31665} | import java.io.File
fun convertToPair(string: String): Pair<Char, Char> {
val split = string.split(" ")
return Pair(split.get(0).first(), split.get(1).first())
}
fun letterValue(char: Char): Int {
return mapOf('A' to 1, 'B' to 2, 'C' to 3, 'X' to 1, 'Y' to 2, 'Z' to 3).getOrDefault(char, 0)
}
fun calculateOwnLetterValue(number: Int): Int = number.mod(3).let { if (it == 0) 3 else it }
var result = File("../input.txt")
.readLines()
.map { convertToPair(it) }
.map {
when (it.second) {
'X' -> calculateOwnLetterValue(letterValue(it.first) + 2)//loose
'Y' -> letterValue(it.first) + 3//draw
else -> calculateOwnLetterValue(letterValue(it.first) + 1) + 6//win
}
}.sum()
println(result)
assert(result == 14470)
| 0 | Kotlin | 0 | 0 | 8e8851403a44af233d00a53b03cf45c72f252045 | 795 | advent-of-code-22 | MIT License |
src/Day05/Day05.kt | AllePilli | 572,859,920 | false | {"Kotlin": 47397} | package Day05
import checkAndPrint
import measureAndPrintTimeMillis
import readInput
import java.util.ArrayDeque
@ExperimentalStdlibApi
fun main() {
val moveRgx = """move (\d+) from (\d) to (\d)""".toRegex()
fun getStartingConfig(input: List<String>): List<ArrayDeque<Char>> {
val digitLineIdx = input.indexOfFirst { it[1].isDigit() }
val stackAmt = input.first { it[1].isDigit() }
.last(Char::isDigit)
.digitToInt()
val charAmtInRow = 4 * stackAmt - 1
return (0 ..< stackAmt).map { col ->
val charCol = 1 + col * 4
ArrayDeque<Char>().apply {
(0 ..< digitLineIdx).mapNotNull { row ->
val line = input[row].takeIf { it.length == charAmtInRow }
?: input[row].let { it + " ".repeat(charAmtInRow - it.length) }
line[charCol].takeIf { it.isLetter() }
}.asReversed().forEach(::push)
}
}
}
fun getMoves(input: List<String>): List<Triple<Int, Int, Int>> = input
.indexOfFirst { it.isEmpty() || it.isBlank() }
.let { input.drop(it + 1) }
.map { moveLine ->
moveRgx.find(moveLine)!!.groupValues
.drop(1)
.let { (amt, col, dest) ->
Triple(amt.toInt(), col.toInt() - 1, dest.toInt() - 1)
}
}
fun part1(input: List<String>): String {
val config = getStartingConfig(input)
val moves = getMoves(input)
moves.forEach { (amt, start, dest) ->
for (i in 0 ..< amt) {
config[dest].push(config[start].pop())
}
}
return config.joinToString(separator = "") { it.peek()!!.toString() }
}
fun part2(input: List<String>): String {
val config = getStartingConfig(input)
val moves = getMoves(input)
moves.forEach { (amt, start, dest) ->
(0 ..< amt).map { config[start].pop() }
.asReversed()
.forEach { config[dest].push(it) }
}
return config.joinToString(separator = "") { it.peek()!!.toString() }
}
val inputTest = readInput("Day05_test")
check(part1(inputTest) == "CMZ")
check(part2(inputTest) == "MCD")
val input = readInput("Day05")
measureAndPrintTimeMillis {
checkAndPrint(part1(input), "VQZNJMWTR")
}
measureAndPrintTimeMillis {
checkAndPrint(part2(input), "NLCDCLVMQ")
}
} | 0 | Kotlin | 0 | 0 | 614d0ca9cc925cf1f6cfba21bf7dc80ba24e6643 | 2,519 | AdventOfCode2022 | Apache License 2.0 |
src/main/kotlin/tr/emreone/adventofcode/days/Day10.kt | EmRe-One | 726,902,443 | false | {"Kotlin": 95869, "Python": 18319} | package tr.emreone.adventofcode.days
import tr.emreone.kotlin_utils.automation.Day
import java.util.*
class Day10 : Day(10, 2023, "Pipe Maze") {
class Maze(input: List<List<Char>>) {
val NORTH_EAST = '└' // oder 'L'
val NORTH_WEST = '┘' // oder 'J'
val SOUTH_EAST = '┌' // oder 'F'
val SOUTH_WEST = '┐' // oder '7'
val NORTH_SOUTH = '│' // oder '|'
val WEST_EAST = '─' // oder '-'
val EMPTY_CELL_CHAR = '∙' // '.'
val FILLED_CELL_CHAR = '#'
private val PIPES_TO_NORTH = listOf(NORTH_SOUTH, NORTH_WEST, NORTH_EAST)
val width = input.first().size
val height = input.size
val grid = input.mapIndexed { y, line ->
line.mapIndexed { x, p ->
Pipe(x, y, convertChar(p))
}
}
/**
* convert the char for a better visualization
*/
private fun convertChar(c: Char): Char {
return when (c) {
'L' -> NORTH_EAST
'J' -> NORTH_WEST
'|' -> NORTH_SOUTH
'F' -> SOUTH_EAST
'7' -> SOUTH_WEST
'-' -> WEST_EAST
'S' -> 'S'
else -> EMPTY_CELL_CHAR
}
}
val allowedPipesInDirection: Map<Char, List<Char>> = mapOf(
'N' to listOf(NORTH_SOUTH, SOUTH_WEST, SOUTH_EAST, 'S'),
'E' to listOf(WEST_EAST, NORTH_WEST, SOUTH_WEST, 'S'),
'S' to listOf(NORTH_SOUTH, NORTH_WEST, NORTH_EAST, 'S'),
'W' to listOf(WEST_EAST, SOUTH_EAST, NORTH_EAST, 'S')
)
private fun getNeighbours(pipe: Pipe): Map<Char, Pipe> {
return buildMap {
if (pipe.y > 0) {
this['N'] = this@Maze.grid[pipe.y - 1][pipe.x]
}
if (pipe.x < this@Maze.width - 1) {
this['E'] = this@Maze.grid[pipe.y][pipe.x + 1]
}
if (pipe.y < <EMAIL>.height - 1) {
this['S'] = this@Maze.grid[pipe.y + 1][pipe.x]
}
if (pipe.x > 0) {
this['W'] = this@Maze.grid[pipe.y][pipe.x - 1]
}
}
}
fun getValidNeighbours(pipe: Pipe): List<Pipe> {
val neighboursCompass = getNeighbours(pipe).filter {
it.value.pipeChar != EMPTY_CELL_CHAR
}
val lookAtDirection = when (pipe.pipeChar) {
'S' -> listOf('N', 'E', 'S', 'W')
NORTH_SOUTH -> listOf('N', 'S')
WEST_EAST -> listOf('W', 'E')
NORTH_EAST -> listOf('N', 'E')
NORTH_WEST -> listOf('N', 'W')
SOUTH_WEST -> listOf('S', 'W')
SOUTH_EAST -> listOf('S', 'E')
else -> throw IllegalArgumentException()
}
return neighboursCompass.mapNotNull {
if (it.key in lookAtDirection && it.value.pipeChar in allowedPipesInDirection[it.key]!!) {
it.value
} else {
null
}
}
}
fun getLoop(startPipe: Pipe): List<Pipe>? {
val stack = ArrayDeque<Triple<Pipe, List<Pipe>, List<Pipe>>>()
stack.add(Triple(startPipe, emptyList(), emptyList()))
while (stack.isNotEmpty()) {
val (currentPipe, visited, path) = stack.removeLast()
// in order to make a loop, the path should be at least 3
if (currentPipe.pipeChar == 'S' && path.size >= 3) return path
if (currentPipe in visited) continue
for (p in getValidNeighbours(currentPipe)) {
stack.add(Triple(p, visited + currentPipe, path + currentPipe))
}
}
return null
}
fun isCellEnclosed(x: Int, y: Int): Boolean {
if (grid[y][x].pipeChar != EMPTY_CELL_CHAR) return false
val crossingPipes = if (x < width / 2) {
grid[y].subList(0, x).count {
it.pipeChar in PIPES_TO_NORTH
}
} else {
grid[y].subList(x, this.width).count {
it.pipeChar in PIPES_TO_NORTH
}
}
if (crossingPipes.mod(2) == 1) {
this.grid[y][x].pipeChar = FILLED_CELL_CHAR
return true
}
return false
}
fun print() {
this.grid.forEach { line ->
println(line.joinToString { it.pipeChar.toString() })
}
println()
}
}
class Pipe(val x: Int, val y: Int, var pipeChar: Char) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Pipe
if (x != other.x) return false
if (y != other.y) return false
if (pipeChar != other.pipeChar) return false
return true
}
override fun hashCode(): Int {
var result = x
result = 31 * result + y
result = 31 * result + pipeChar.hashCode()
return result
}
override fun toString(): String {
return "Pipe '$pipeChar' ($x|$y) "
}
}
override fun part1(): Int {
val maze = Maze(inputAsGrid)
val start = maze.grid.flatten().first {
it.pipeChar == 'S'
}
val path = maze.getLoop(start) ?: return -1
return path.size / 2
}
override fun part2(): Int {
val maze = Maze(inputAsGrid)
val start = maze.grid.flatten().first {
it.pipeChar == 'S'
}
val path = maze.getLoop(start) ?: return -1
// remove unconnected pipe parts
maze.grid.flatten().forEach {
if (!path.contains(it)) {
maze.grid[it.y][it.x].pipeChar = maze.EMPTY_CELL_CHAR
}
}
val enclosed = maze.grid.flatten().count {
maze.isCellEnclosed(it.x, it.y)
}
maze.print()
return enclosed
}
}
| 0 | Kotlin | 0 | 0 | c75d17635baffea50b6401dc653cc24f5c594a2b | 6,310 | advent-of-code-2023 | Apache License 2.0 |
src/test/kotlin/adventofcode/day08/Day08.kt | jwcarman | 573,183,719 | false | {"Kotlin": 183494} | /*
* Copyright (c) 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package adventofcode.day08
import adventofcode.util.readAsLines
import adventofcode.util.table.Table
import adventofcode.util.takeWhileInclusive
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals
class Day08 {
@Test
fun example1() {
assertEquals(21, calculatePart1(readAsLines("day08-example.txt")))
}
@Test
fun part1() {
assertEquals(1803, calculatePart1(readAsLines("day08.txt")))
}
@Test
fun example2() {
assertEquals(8, calculatePart2(readAsLines("day08-example.txt")))
}
@Test
fun part2() {
assertEquals(268912, calculatePart2(readAsLines("day08.txt")))
}
private fun calculatePart1(input: List<String>): Int {
val forrest = Table(input.map { it.toList().map { c -> c - '0' } })
return forrest.cells().filter { it.isVisible() }.count()
}
private fun calculatePart2(input: List<String>): Int {
val forrest = Table(input.map { it.toList().map { c -> c - '0' } })
return forrest.cells().maxOf { it.scenicScore() }
}
private fun Table<Int>.Cell.scenicScore(): Int {
val maxHeight = value()
fun List<Table<Int>.Cell>.viewingDistance() = takeWhileInclusive { it.value() < maxHeight }.count()
return westOf().viewingDistance() *
eastOf().viewingDistance() *
northOf().viewingDistance() *
southOf().viewingDistance()
}
private fun Table<Int>.Cell.isVisible(): Boolean {
val height = value()
return westOf().all { it.value() < height } ||
eastOf().all { it.value() < height } ||
northOf().all { it.value() < height } ||
southOf().all { it.value() < height }
}
}
| 0 | Kotlin | 0 | 0 | d6be890aa20c4b9478a23fced3bcbabbc60c32e0 | 2,370 | adventofcode2022 | Apache License 2.0 |
kotlin/1091-shortest-path-in-binary-matrix.kt | neetcode-gh | 331,360,188 | false | {"JavaScript": 473974, "Kotlin": 418778, "Java": 372274, "C++": 353616, "C": 254169, "Python": 207536, "C#": 188620, "Rust": 155910, "TypeScript": 144641, "Go": 131749, "Swift": 111061, "Ruby": 44099, "Scala": 26287, "Dart": 9750} | class Solution {
fun shortestPathBinaryMatrix(grid: Array<IntArray>): Int {
if(grid[0][0] == 1 || grid[grid.lastIndex][grid.lastIndex] == 1) return -1
fun isValid(i: Int, j: Int) = i in (0..grid.lastIndex) && j in (0..grid.lastIndex) && grid[i][j] == 0
val q = ArrayDeque<Pair<Int, Int>>()
var distance = 0
q.add(0 to 0)
grid[0][0] = 1
while (q.isNotEmpty()) {
distance++
val size = q.size
repeat (size) {
val (i, j) = q.poll()
if(i == grid.lastIndex && j == grid.lastIndex) return distance
for(cell in cells) {
val nextI = i + cell[0]
val nextJ = j + cell[1]
if(isValid(nextI, nextJ)) {
q.add(nextI to nextJ)
grid[nextI][nextJ] = 1
}
}
}
}
return -1
}
companion object {
val cells = arrayOf(
intArrayOf(0,1),
intArrayOf(1,1),
intArrayOf(0,-1),
intArrayOf(1,-1),
intArrayOf(1,0),
intArrayOf(-1,-1),
intArrayOf(-1,0),
intArrayOf(-1, 1)
)
}
}
| 337 | JavaScript | 2,004 | 4,367 | 0cf38f0d05cd76f9e96f08da22e063353af86224 | 1,296 | leetcode | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MatrixDiagonalSum.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
/**
* 1572. Matrix Diagonal Sum
* https://leetcode.com/problems/matrix-diagonal-sum/
*/
fun interface MatrixDiagonalSum {
fun diagonalSum(mat: Array<IntArray>): Int
}
/**
* Approach: Iterating over Diagonal Elements
*/
class MatrixDiagonalSumIteration : MatrixDiagonalSum {
override fun diagonalSum(mat: Array<IntArray>): Int {
val n: Int = mat.size
var ans = 0
for (i in 0 until n) {
// Add elements from primary diagonal.
ans += mat[i][i]
// Add elements from secondary diagonal.
ans += mat[n - 1 - i][i]
}
// If n is odd, subtract the middle element as its added twice.
if (n % 2 != 0) {
ans -= mat[n / 2][n / 2]
}
return ans
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,418 | kotlab | Apache License 2.0 |
baparker/05/main.kt | VisionistInc | 433,099,870 | false | {"Kotlin": 91599, "Go": 87605, "Ruby": 65600, "Python": 21104} | import java.io.File
import kotlin.math.abs
fun getOverlapCount() {
var coordinateCount: MutableMap<String, Int> = mutableMapOf()
File("input.txt").forEachLine {
val line = it.split(" -> ")
val start = line[0].split(",")
val end = line[1].split(",")
if (start[0].equals(end[0])) {
val bounds = listOf(start[1].toInt(), end[1].toInt()).sorted()
for (y in bounds[0]..bounds[1]) {
val mapKey = start[0].plus(" ").plus(y.toString())
var mapValue = coordinateCount.get(mapKey)
if (mapValue != null) {
coordinateCount.put(mapKey, mapValue.inc())
} else {
coordinateCount.put(mapKey, 1)
}
}
} else if (start[1].equals(end[1])) {
// Yay for dupe code
val bounds = listOf(start[0].toInt(), end[0].toInt()).sorted()
for (x in bounds[0]..bounds[1]) {
val mapKey = x.toString().plus(" ").plus(start[1])
var mapValue = coordinateCount.get(mapKey)
if (mapValue != null) {
coordinateCount.put(mapKey, mapValue.inc())
} else {
coordinateCount.put(mapKey, 1)
}
}
} else {
val startX = start[0].toInt()
val startY = start[1].toInt()
val endX = end[0].toInt()
val endY = end[1].toInt()
val diffX = endX - startX
val diffY = endY - startY
if (abs(diffX) == abs(diffY)) {
var xModifier = 1
if (diffX < 0) {
xModifier = -1
}
var yModifier = 1
if (diffY < 0) {
yModifier = -1
}
for (i in 0..abs(diffX)) {
val mapKey =
(startX + (i * xModifier))
.toString()
.plus(" ")
.plus((startY + (i * yModifier)).toString())
var mapValue = coordinateCount.get(mapKey)
if (mapValue != null) {
coordinateCount.put(mapKey, mapValue.inc())
} else {
coordinateCount.put(mapKey, 1)
}
}
}
}
}
println(coordinateCount.values.filter({ count: Int -> count >= 2 }).size)
}
fun main() {
getOverlapCount()
}
| 0 | Kotlin | 4 | 1 | e22a1d45c38417868f05e0501bacd1cad717a016 | 2,611 | advent-of-code-2021 | MIT License |
year2023/src/cz/veleto/aoc/year2023/Day06.kt | haluzpav | 573,073,312 | false | {"Kotlin": 164348} | package cz.veleto.aoc.year2023
import cz.veleto.aoc.core.AocDay
import cz.veleto.aoc.core.solveQuadratic
import kotlin.math.ceil
import kotlin.math.floor
class Day06(config: Config) : AocDay(config) {
override fun part1(): String = cachedInput
.parsePart1()
.map { (t, d) -> countWaysToWin(t, d) }
.reduce(Long::times)
.toString()
override fun part2(): String {
val (t, d) = cachedInput.parsePart2()
return countWaysToWin(t, d).toString()
}
private fun countWaysToWin(t: Long, d: Long): Long {
val (h1, h2) = solveQuadratic(1.0, -t.toDouble(), d.toDouble())
check(h1.isFinite())
check(h2.isFinite())
val minHoldTime = floor(h1 + 1).toLong()
val maxHoldTime = ceil(h2 - 1).toLong()
return maxHoldTime - minHoldTime + 1
}
private fun List<String>.parsePart1(): List<Pair<Long, Long>> {
fun String.parseNumbers() = drop(10).split(' ').filter(String::isNotBlank).map { it.toLong() }
val times = this[0].parseNumbers()
val distances = this[1].parseNumbers()
check(times.size == distances.size)
return times.zip(distances)
}
private fun List<String>.parsePart2(): Pair<Long, Long> {
fun String.parseNumber() = drop(10).replace(" ", "").toLong()
return this[0].parseNumber() to this[1].parseNumber()
}
}
| 0 | Kotlin | 0 | 1 | 32003edb726f7736f881edc263a85a404be6a5f0 | 1,392 | advent-of-pavel | Apache License 2.0 |
src/main/kotlin/com/colinodell/advent2022/Day20.kt | colinodell | 572,710,708 | false | {"Kotlin": 105421} | package com.colinodell.advent2022
class Day20(private val input: List<Int>) {
fun solvePart1() = solve()
fun solvePart2() = solve(10, 811589153)
private fun solve(mixCount: Int = 1, decryptionKey: Int = 1) = input
.map { it.toLong() * decryptionKey }
.mapIndexed { index, value -> Number(index, value) }
.toMutableList()
.let { l -> mix(l, mixCount) }
.let { l ->
val zeroIndex = l.indexOfFirst { it.value == 0L }
fun valueAtOffset(index: Int) = l[(zeroIndex + index) % l.size].value
valueAtOffset(1000) + valueAtOffset(2000) + valueAtOffset(3000)
}
private data class Number(val originalIndex: Int, val value: Long) {
override fun toString() = "($originalIndex, $value)"
}
private fun mix(originalList: List<Number>, times: Int): List<Number> {
val list = originalList.toMutableList()
repeat(times) {
for (n in originalList) {
val index = list.indexOf(n)
list.removeAt(index)
val newIndex = when {
(index + n.value) < 0 -> ((index + n.value) % list.size + list.size) % list.size
else -> (index + n.value) % list.size
}.toInt()
list.add(newIndex, n)
}
}
return list
}
}
| 0 | Kotlin | 0 | 1 | 32da24a888ddb8e8da122fa3e3a08fc2d4829180 | 1,374 | advent-2022 | MIT License |
src/main/kotlin/hu/advent/of/code/year2019/day3/Puzzle3A.kt | sztojkatamas | 568,512,275 | false | {"Kotlin": 157914} | package hu.advent.of.code.year2019.day3
import hu.advent.of.code.AdventOfCodePuzzle
import hu.advent.of.code.BaseChallenge
import kotlin.math.abs
@AdventOfCodePuzzle
class Puzzle3A: BaseChallenge(2019) {
override fun run() {
printPuzzleName()
loadDataFromFile("data3.txt")
println("Minimum Manhattan distance is: ${getMinimalManhattanDistance(data[0], data[1])}")
}
fun makeVectorList(input:String): MutableCollection<Vector2D> {
var lastPoint = Point(0,0)
val list = mutableListOf<Vector2D>()
val split = input.split(",")
for (i in split.indices) {
val nextPoint = lastPoint.copy()
when (split[i].first()) {
'U' -> nextPoint.y += split[i].substring(1).toInt()
'D' -> nextPoint.y -= split[i].substring(1).toInt()
'R' -> nextPoint.x += split[i].substring(1).toInt()
'L' -> nextPoint.x -= split[i].substring(1).toInt()
}
list.add(Vector2D(lastPoint, nextPoint))
lastPoint = nextPoint.copy()
}
return list
}
fun intersectCheck(op1: Vector2D, op2: Vector2D): Boolean {
return doIntersect(op1.from, op1.to, op2.from, op2.to)
}
fun doIntersect(p1: Point, q1: Point, p2: Point, q2: Point): Boolean {
val o1: Int = orientation(p1, q1, p2)
val o2: Int = orientation(p1, q1, q2)
val o3: Int = orientation(p2, q2, p1)
val o4: Int = orientation(p2, q2, q1)
if (o1 != o2 && o3 != o4) return true
if (o1 == 0 && onSegment(p1, p2, q1)) return true
if (o2 == 0 && onSegment(p1, q2, q1)) return true
if (o3 == 0 && onSegment(p2, p1, q2)) return true
return (o4 == 0 && onSegment(p2, q1, q2))
}
fun orientation(p: Point, q: Point, r: Point): Int {
val orientation = (q.y - p.y) * (r.x - q.x) -
(q.x - p.x) * (r.y - q.y)
if (orientation == 0) return 0
return if (orientation > 0) 1 else 2
}
fun onSegment(p: Point, q: Point, r: Point): Boolean {
return (q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x) && q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y))
}
fun getIntersectionPoint(v1: Vector2D, v2: Vector2D): Point {
return v1.getPointOnSegment() + v2.getPointOnSegment()
}
fun getMinimalManhattanDistance(s1: String, s2: String): Manhattan {
var minDistance = Int.MAX_VALUE
var minWireLength = Int.MAX_VALUE
val v1List = makeVectorList(s1)
val v2List = makeVectorList(s2)
for (i in v1List) {
for (j in v2List) {
if(intersectCheck(i, j)) {
val p = getIntersectionPoint(i, j)
val localMin = abs(p.x) + abs(p.y)
if (localMin in 1 until minDistance) {
minDistance = localMin
}
val wireOneLength = getWireLength(v1List, i.from)
val wireTwoLength = getWireLength(v2List, j.from)
val total = wireOneLength + wireTwoLength + Vector2D(i.from, p).length + Vector2D(j.from, p).length
if (total in 1 until minWireLength) {
minWireLength = total
}
}
}
}
return Manhattan(minDistance, minWireLength)
}
fun getWireLength(vectorList: MutableCollection<Vector2D>, point: Point): Int {
var wireLength = 0
for (i in vectorList) {
wireLength += i.length
if (i.to == point) {
return wireLength
}
}
return 0
}
}
data class Manhattan(val minDistance:Int, val minWireLength:Int)
data class Point(var x:Int, var y:Int) {
operator fun plus(p2: Point): Point {
this.x += p2.x
this.y += p2.y
return this
}
}
data class Vector2D(val from: Point, val to: Point) {
val length = abs(from.x - to.x) + abs(from.y - to.y)
fun getPointOnSegment(): Point {
return when (from.x == to.x) {
true -> Point(from.x, 0)
else -> Point(0, from.y)
}
}
} | 0 | Kotlin | 0 | 0 | 6aa9e53d06f8cd01d9bb2fcfb2dc14b7418368c9 | 4,234 | advent-of-code-universe | MIT License |
kotlin-native/performance/numerical/src/main/kotlin/pi.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | /*
* Computation of the n'th decimal digit of \pi with very little memory.
* Written by <NAME> on January 8, 1997.
*
* We use a slightly modified version of the method described by Simon
* Plouffe in "On the Computation of the n'th decimal digit of various
* transcendental numbers" (November 1996). We have modified the algorithm
* to get a running time of O(n^2) instead of O(n^3log(n)^3).
*/
import kotlin.math.ln
import kotlin.math.sqrt
private fun mul_mod(a: Int, b: Int, m: Int)
= ((a.toLong() * b.toLong()) % m).toInt()
/* return the inverse of x mod y */
private fun inv_mod(x: Int, y: Int): Int {
var u = x
var v = y
var c = 1
var a = 0
do {
val q = v / u
var t = c
c = a - q * c
a = t
t = u
u = v - q * u
v = t
} while (u != 0)
a = a % y
if (a < 0)
a = y + a
return a
}
/* return (a^b) mod m */
private fun pow_mod(a: Int, b: Int, m: Int): Int {
var b = b
var r = 1
var aa = a
while (true) {
if (b and 1 != 0)
r = mul_mod(r, aa, m)
b = b shr 1
if (b == 0)
break
aa = mul_mod(aa, aa, m)
}
return r
}
/* return true if n is prime */
private fun is_prime(n: Int): Boolean {
if (n % 2 == 0)
return false
val r = sqrt(n.toDouble()).toInt()
var i = 3
while (i <= r) {
if (n % i == 0)
return false
i += 2
}
return true
}
/* return the prime number immediatly after n */
private fun next_prime(n: Int): Int {
var n = n
do {
n++
} while (!is_prime(n))
return n
}
fun pi_nth_digit(n: Int): Int {
val N = ((n + 20) * ln(10.0) / ln(2.0)).toInt()
var sum = 0.0
var a = 3
var t: Int
while (a <= 2 * N) {
val vmax = (ln((2 * N).toDouble()) / ln(a.toDouble())).toInt()
var av = 1
var i = 0
while (i < vmax) {
av = av * a
i++
}
var s = 0
var num = 1
var den = 1
var v = 0
var kq = 1
var kq2 = 1
var k = 1
while (k <= N) {
t = k
if (kq >= a) {
do {
t = t / a
v--
} while (t % a == 0)
kq = 0
}
kq++
num = mul_mod(num, t, av)
t = 2 * k - 1
if (kq2 >= a) {
if (kq2 == a) {
do {
t = t / a
v++
} while (t % a == 0)
}
kq2 -= a
}
den = mul_mod(den, t, av)
kq2 += 2
if (v > 0) {
t = inv_mod(den, av)
t = mul_mod(t, num, av)
t = mul_mod(t, k, av)
i = v
while (i < vmax) {
t = mul_mod(t, a, av)
i++
}
s += t
if (s >= av)
s -= av
}
k++
}
t = pow_mod(10, n - 1, av)
s = mul_mod(s, t, av)
sum = (sum + s.toDouble() / av.toDouble()) % 1.0
a = next_prime(a)
}
return (sum * 1e9).toInt()
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 3,337 | kotlin | Apache License 2.0 |
src/test/kotlin/be/brammeerten/y2022/Day20Test.kt | BramMeerten | 572,879,653 | false | {"Kotlin": 170522} | package be.brammeerten.y2022
import be.brammeerten.readFile
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
class Day20Test {
@Test
fun `part 1a`() {
val coordinates = readInput("2022/day20/exampleInput.txt")
val mix = mix(coordinates.mapIndexed { i, c -> i to c })
assertThat(mix.map { it.second }).isEqualTo(listOf(1L, 2L, -3L, 4L, 0L, 3L, -2L))
assertThat(get(mix, 1000)).isEqualTo(4L)
assertThat(get(mix, 2000)).isEqualTo(-3L)
assertThat(get(mix, 3000)).isEqualTo(2L)
assertThat(get(mix, 1000) + get(mix, 2000) + get(mix, 3000)).isEqualTo(3L)
}
@Test
fun `part 1b`() {
val coordinates = readInput("2022/day20/input.txt")
val mix = mix(coordinates.mapIndexed { i, c -> i to c })
assertThat(get(mix, 1000) + get(mix, 2000) + get(mix, 3000)).isEqualTo(7153L)
}
@Test
fun `part 2`() {
val coordinates = readInput("2022/day20/exampleInput.txt")
.map { it * 811589153L }
val input = coordinates.mapIndexed { i, c -> i to c }
var mix = mix(input)
mix = mix(mix)
mix = mix(mix)
mix = mix(mix)
mix = mix(mix)
mix = mix(mix)
mix = mix(mix)
mix = mix(mix)
mix = mix(mix)
mix = mix(mix)
assertThat(get(mix, 1000) + get(mix, 2000) + get(mix, 3000)).isEqualTo(1623178306L)
}
fun readInput(file: String) = readFile(file).map { it.toLong() }
fun mix(original: List<Pair<Int, Long>>): List<Pair<Int,Long>> {
val copy = ArrayList(original)
for (i in original.indices) {
val cur = copy.find { it.first == i }!!
val curI = copy.indexOf(cur)
val diff = (curI + cur.second)
val newI = if (diff > 0) (diff % (original.size-1)) else ((original.size-1) + (diff % (original.size-1)))
copy.remove(cur)
copy.add(newI.toInt(), i to cur.second)
}
return copy
}
fun get(list: List<Pair<Int, Long>>, index: Int): Long {
val ll = list.map { it.second }
val zeroI = ll.indexOf(0)
val i = (zeroI + index) % ll.size
return ll[i]
}
}
| 0 | Kotlin | 0 | 0 | 1defe58b8cbaaca17e41b87979c3107c3cb76de0 | 2,235 | Advent-of-Code | MIT License |
app/src/main/java/com/itscoder/ljuns/practise/algorithm/HeadSort.kt | ljuns | 148,606,057 | false | {"Java": 26841, "Kotlin": 25458} | package com.itscoder.ljuns.practise.algorithm
import java.util.Collections.swap
/**
* Created by ljuns at 2019/1/7.
* I am just a developer.
* 堆排序
* 大顶堆:根节点 >= 左子节点 && 根节点 >= 右子节点
* 小顶堆:根节点 <= 左子节点 && 根节点 <= 右子节点
* 1、升序构建大顶堆,降序构建小顶堆
* 2、交换根节点和最后一个子节点,此时的最后一个子节点不再参与排序
* 3、重复 1、2
*/
fun main(args: Array<String>) {
val arr = intArrayOf(3, 1, 1, 6, 2, 4, 19)
// val arr = intArrayOf(9,8,7,6,5,4,3,2,1)
headSort(arr)
for (i in arr) {
println(i)
}
}
fun headSort(arr: IntArray) {
/**
* 构造堆
*/
// for(int i = arr.size/2 -1; i >= 0; i --)
// start 是最后一个子节点不为空的节点
val start = arr.size / 2 - 1
for ((key, value) in (start downTo 0).withIndex()) {
// println("key: $value, value: ${arr[value]}")
headAdjust(arr, value, arr.size)
}
/**
* 交换位置,再次调整为堆
*/
for ((index, value) in (arr.size - 1 downTo 1).withIndex()) {
// 交换根节点后最后一个子节点
swap(arr, 0, value)
// 重新调整为大顶堆
// 为什么从 0 开始?因为交换了根节点和最后一个子节点,其他节点都不变,变得只是根节点,所以只需要看根节点
headAdjust(arr, 0, value)
}
}
/**
* 构建堆
*/
fun headAdjust(arr: IntArray, i: Int, len: Int) {
var temp = arr[i]
var i = i
// for (int j = 2 * i + 1; j < len; j = j * 2 + 1)
// 2 * i + 1 表示左子节点,2 * i + 2 表示右子节点
var start = 2 * i + 1
while (start < len) {
// 如果右子节点比左子节点大,用右子节点来比较
if (start + 1 < len && arr[start] < arr[start + 1]) {
start++
}
// 如果子节点比父节点大,调换位置
if (arr[start] > temp) {
arr[i] = arr[start]
i = start
} else {
//父节点比子节点都大,不需要调整
break
}
// start * 2 + 1:因为有可能子节点又不满足大顶堆了,需要再次调整
start = start * 2 + 1
arr[i] = temp
}
}
/**
* 交换根节点和最后一个子节点
*/
fun swap(arr: IntArray, origin: Int, target: Int) {
val temp = arr[origin]
arr[origin] = arr[target]
arr[target] = temp
} | 0 | Java | 0 | 0 | 365062b38a7ac55468b202ebeff1b760663fc676 | 2,515 | Practise | Apache License 2.0 |
src/main/kotlin/nl/jackploeg/aoc/_2023/calendar/day15/Day15.kt | jackploeg | 736,755,380 | false | {"Kotlin": 318734} | package nl.jackploeg.aoc._2023.calendar.day15
import nl.jackploeg.aoc.generators.InputGenerator.InputGeneratorFactory
import nl.jackploeg.aoc.utilities.readStringFile
import javax.inject.Inject
import kotlin.math.max
class Day15 @Inject constructor(
private val generatorFactory: InputGeneratorFactory,
) {
// sum of hashes
fun partOne(filename: String) = generatorFactory.forFile(filename).readOne { line ->
line.split(",").map(::hash).sum()
}
// sum of focal lengths
fun partTwo(fileName: String): Int
{
val instructions = readStringFile(fileName).first().split(',')
val boxes: List<MutableList<Lens>> = initBoxes()
instructions.forEach { instruction ->
val indexOfEq = instruction.indexOf('=')
val indexOfMinus = instruction.indexOf('-')
val separatorPos = max(indexOfMinus, indexOfEq)
val lensName = instruction.substring(0, separatorPos)
val box = hash(lensName)
if (instruction[separatorPos] == '-')
{
val lens = boxes[box].firstOrNull { it.name == lensName }
lens?.let { boxes[box].remove(it) }
}
if (instruction[separatorPos] == '=')
{
val focalLength = instruction.substring(separatorPos + 1, instruction.length).toInt()
val lens = boxes[box].firstOrNull { it.name == lensName }
if (lens != null)
{
lens.focalLength = focalLength
} else
{
boxes[box].add(Lens(lensName, focalLength))
}
}
}
return boxes.mapIndexed { boxIndex, lenses ->
lenses.mapIndexed { lensindex, lens ->
((boxIndex + 1) * (lensindex + 1) * lens.focalLength)
}.sum()
}.sum()
}
fun initBoxes(): List<MutableList<Lens>> =
List(size = 256) { mutableListOf() }
private fun hash(text: String) = text
.map { it.code }
.fold(0) { acc, next -> ((acc + next) * 17) % 256 }
data class Lens(val name: String, var focalLength: Int)
}
| 0 | Kotlin | 0 | 0 | f2b873b6cf24bf95a4ba3d0e4f6e007b96423b76 | 1,947 | advent-of-code | MIT License |
src/main/kotlin/pl/jpodeszwik/aoc2023/Day01.kt | jpodeszwik | 729,812,099 | false | {"Kotlin": 55101} | package pl.jpodeszwik.aoc2023
import java.lang.Long.parseLong
private val numbers = 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',
)
private fun part1(lines: List<String>) {
var sum = 0L
lines.forEach {
var first = ' '
var last = ' '
var str = it
while (str.isNotEmpty()) {
if (str[0].isDigit()) {
last = str[0]
if (first == ' ') {
first = str[0]
}
}
str = str.substring(1)
}
sum += parseLong("$first$last")
}
println(sum)
}
private fun part2(lines: List<String>) {
var sum = 0L
lines.forEach {
var first = ' '
var last = ' '
var str = it
while (str.isNotEmpty()) {
if (str[0].isDigit()) {
last = str[0]
if (first == ' ') {
first = str[0]
}
} else {
for (n in numbers) {
if (str.startsWith(n.key)) {
last = n.value
if (first == ' ') {
first = n.value
}
}
}
}
str = str.substring(1)
}
sum += parseLong("$first$last")
}
println(sum)
}
fun main() {
val lines = loadFile("/aoc2023/input1")
part1(lines)
part2(lines)
}
| 0 | Kotlin | 0 | 0 | 2b90aa48cafa884fc3e85a1baf7eb2bd5b131a63 | 1,587 | advent-of-code | MIT License |
src/main/kotlin/org/wagham/utils/CraftUtils.kt | kaironbot | 566,988,243 | false | {"Kotlin": 590249, "Dockerfile": 253} | package org.wagham.utils
import org.wagham.db.models.Character
import org.wagham.db.models.Item
import org.wagham.db.models.embed.CraftRequirement
fun CraftRequirement.quantityIsValid(amount: Int): Boolean =
(minQuantity == null || amount >= minQuantity!!) && (maxQuantity == null || amount <= maxQuantity!!)
fun CraftRequirement.characterHasBuildingRequirement(character: Character) =
buildings.isEmpty() || character.buildings.keys.map { it.split(":").first() }.any {
buildings.contains(it)
}
fun CraftRequirement.characterHasProficiencyRequirement(character: Character) =
tools.isEmpty() || character.proficiencies.map { it.name }.any { tools.contains(it) }
fun CraftRequirement.characterHasEnoughMaterials(character: Character, amount: Int) =
materials.mapValues {
(it.value * amount) - character.inventory.getOrDefault(it.key, 0)
}.all { (_, v) -> v <= 0 }
fun Item.selectCraftOptions(character: Character, amount: Int): List<Int> =
craft.mapIndexedNotNull { index, recipe ->
if(recipe.quantityIsValid(amount)
&& recipe.characterHasBuildingRequirement(character)
&& recipe.characterHasProficiencyRequirement(character)
&& recipe.characterHasEnoughMaterials(character, amount)
&& character.money >= (recipe.cost * amount)) index to recipe
else null
}.groupBy { (_, recipe) ->
setOf(
"${recipe.cost}",
"${recipe.timeRequired}"
) + recipe.materials.map { (k, v) -> "${k}x$v" }.toSet()
}.mapNotNull { (_, recipes) ->
recipes.firstOrNull()?.first
}
data class InvalidQuantity(val qty: Int, val min: Int?, val max: Int?)
data class MissingMaterialsReport(
val quantity: InvalidQuantity?,
val buildings: Set<String>?,
val tools: Set<String>?,
val missingMaterials: Map<String, Int>,
val money: Float?
)
fun Item.generateMissingMaterialsReport(character: Character, amount: Int): String =
craft.mapIndexed { index, recipe ->
val report = MissingMaterialsReport(
InvalidQuantity(amount, recipe.minQuantity, recipe.maxQuantity).takeIf { !recipe.quantityIsValid(amount) },
recipe.buildings.takeIf { !recipe.characterHasBuildingRequirement(character) },
recipe.tools.takeIf { !recipe.characterHasProficiencyRequirement(character) },
recipe.materials.filter { (k, v) ->
(v * amount) - character.inventory.getOrDefault(k, 0) >= 0
}.map { (k, v) ->
k to ((v * amount) - character.inventory.getOrDefault(k, 0)).toInt()
}.toMap(),
((recipe.cost * amount) - character.money).takeIf { it > 0 }
)
(recipe.label ?: "Recipe $index") to report
}.toMap().let { report ->
buildString {
append("You are missing some requirements on all the recipes.\n")
report.forEach { (recipeId, materials) ->
append("**$recipeId**:\n")
if(materials.quantity != null) {
append("\tQuantity ${materials.quantity.qty} is invalid:")
materials.quantity.max?.also {
append(" max is $it")
}
materials.quantity.min?.also {
append(" min is $it")
}
append("\n")
}
materials.buildings?.also {
append("\tMissing buildings: ")
append(it.joinToString(", "))
append("\n")
}
materials.tools?.also {
append("\tMissing tools: ")
append(it.joinToString(", "))
append("\n")
}
if(materials.missingMaterials.isNotEmpty()) {
append("\tMissing materials: ")
append(materials.missingMaterials.entries.joinToString(", ") { "${it.key} x${it.value}" })
append("\n")
}
materials.money?.also {
append("\tMissing money: $it\n")
}
append("\n")
}
}
}
fun CraftRequirement.summary() = buildString {
append(this@summary.cost)
append(" MO, ")
val minQty = this@summary.minQuantity
val maxQty = this@summary.maxQuantity
append(this@summary.materials.entries.joinToString(", ") {
if(minQty == maxQty && minQty != null) "${it.key} x${(it.value * minQty).toInt()}"
else "${it.key} x${it.value}"
})
this@summary.timeRequired?.also {
append(" - $it hours")
} ?: append(" - Instantaneous")
if(minQty == maxQty && minQty != null) {
append(" - Qty: $minQty")
} else {
this@summary.minQuantity?.also {
append(" - Min Qty: $it")
}
this@summary.maxQuantity?.also {
append(" - Max Qty: $it")
}
}
if(this@summary.buildings.isNotEmpty()) {
append(" - Buildings: ")
append(this@summary.buildings.joinToString(", "))
}
if(this@summary.tools.isNotEmpty()) {
append(" - Tool: ")
append(this@summary.tools.joinToString(", "))
}
} | 4 | Kotlin | 0 | 0 | 6d5217b5bbfcc2e1a30bf100a55c86bf3480a753 | 5,278 | kairon-bot | MIT License |
src/main/kotlin/Day04.kt | bent-lorentzen | 727,619,283 | false | {"Kotlin": 68153} | import java.time.LocalDateTime
import java.time.ZoneOffset
import kotlin.math.max
fun main() {
fun winningNumbers(line: String) = line.substringBefore("|").substringAfter(":").split(Regex(" +")).filterNot { it.isEmpty() }
fun personalNumbers(line: String) = line.substringAfter("|").split(Regex(" +")).filterNot { it.isEmpty() }
fun winCount(line: String) = personalNumbers(line).count { winningNumbers(line).contains(it) }
fun part1(input: List<String>): Int {
return input.sumOf { line ->
winCount(line).let { if (it <= 1) it else 1 shl (it - 1) }
}
}
fun part2(input: List<String>): Int {
val winCounts = input.map {
winCount(it)
}
val cardCount = mutableListOf<Int>()
winCounts.reversed().forEach { i ->
val sublist = cardCount.subList(max(cardCount.size - i, 0), cardCount.size)
cardCount.add(1 + sublist.sum())
}
return cardCount.sum()
}
val timer = LocalDateTime.now().toInstant(ZoneOffset.UTC).toEpochMilli()
val input = readLines("day04-input.txt")
val result1 = part1(input)
"Result1: $result1".println()
val result2 = part2(input)
"Result2: $result2".println()
println("${LocalDateTime.now().toInstant(ZoneOffset.UTC).toEpochMilli() - timer} ms")
}
| 0 | Kotlin | 0 | 0 | 41f376bd71a8449e05bbd5b9dd03b3019bde040b | 1,334 | aoc-2023-in-kotlin | Apache License 2.0 |
src/main/kotlin/pl/mrugacz95/aoc/day20/day20.kt | mrugacz95 | 317,354,321 | false | null | package pl.mrugacz95.aoc.day20
import java.lang.RuntimeException
import kotlin.math.sqrt
data class Tile(val id: Int, val sides: Map<Side, String>, val raw: List<String>) {
companion object {
const val EMPTY = '.'
const val FULL = '#'
fun fromRaw(definition: String): Tile {
val rows = definition.split("\n")
val id = rows[0].replace("Tile ", "").replace(":", "").toInt()
val rawImage = rows.subList(1, rows.size)
val sides = Side.values().associateBy({ it }, { getEdge(it, rawImage) })
return Tile(id, sides, rawImage)
}
private fun getEdge(side: Side, image: List<String>): String {
val edge = when (side) {
Side.TOP -> image.first().toList()
Side.BOTTOM -> image.last().toList()
Side.LEFT -> image.map { it.first() }
Side.RIGHT -> image.map { it.last() }
}
return edge.joinToString("")
}
}
enum class Side {
TOP, BOTTOM, LEFT, RIGHT;
}
override fun toString(): String {
return "<id:$id sides:${sides()}>"
}
fun rotateRight(): Sequence<Tile> = sequence {
var tile = this@Tile
for (r in 0..4) {
val newSides = mapOf(
Side.TOP to tile.sides[Side.LEFT]!!,
Side.BOTTOM to tile.sides[Side.RIGHT]!!,
Side.LEFT to tile.sides[Side.BOTTOM]!!,
Side.RIGHT to tile.sides[Side.TOP]!!,
)
val newRaw = tile.raw.withIndex().map { row -> tile.raw.map { it[row.index] }.reversed().joinToString("") }
tile = Tile(id, newSides, newRaw)
yield(tile)
}
}
fun flipAcross(): Sequence<Tile> = sequence {
yield(this@Tile)
yield(
Tile(
id, mapOf(
Side.TOP to sides[Side.TOP]!!.reversed(),
Side.BOTTOM to sides[Side.BOTTOM]!!.reversed(),
Side.LEFT to sides[Side.RIGHT]!!,
Side.RIGHT to sides[Side.LEFT]!!
),
raw.map { it.reversed() }
)
)
yield(
Tile(
id, mapOf(
Side.TOP to sides[Side.BOTTOM]!!,
Side.BOTTOM to sides[Side.TOP]!!,
Side.LEFT to sides[Side.LEFT]!!.reversed(),
Side.RIGHT to sides[Side.RIGHT]!!.reversed()
),
raw.reversed()
)
)
}
private fun matchSide(other: Tile?, side: Side): Boolean {
if (other == null) return true
val sideToMatch = this.sides[side]!!
return sideToMatch in other.sides.values ||
sideToMatch in other.sides.values.map { it.reversed() }
}
fun matchAnyEdge(other: Tile): Boolean {
return sides.values.any { it in other.sides.values } ||
sides.values.any { it.reversed() in other.sides.values }
}
fun countMatchingEdges(others: List<Tile>): Int {
var counter = 0
for (other in others) {
if (this.id == other.id) continue
if (this.matchAnyEdge(other)) {
counter += 1
}
}
return counter
}
fun isCorner(others: List<Tile>) = countMatchingEdges(others) == 2
fun isBorder(others: List<Tile>) = countMatchingEdges(others) == 3
override fun equals(other: Any?): Boolean {
if (other !is Tile) return false
return this.id == other.id
}
override fun hashCode(): Int {
return id
}
fun orientToMatch(neighbours: Map<Side, Tile?>): Tile {
for (flipped in flipAcross()) {
for (rotated in flipped.rotateRight()) {
if (neighbours.all { rotated.matchSide(it.value, it.key) }) {
return rotated
}
}
}
throw RuntimeException("No matching to neighbours found")
}
private fun top() = raw.first().toList()
private fun bottom() = raw.last().toList()
private fun left() = raw.map { it.first() }
private fun right() = raw.map { it.last() }
fun sides() = listOf(top(), bottom(), left(), right())
}
fun part1(tiles: List<Tile>): Long {
return tiles.filter { it.isCorner(tiles) }.fold(1L, { acc, tile -> acc * tile.id })
}
fun arrangeImage(tiles: List<Tile>): List<List<Tile>> {
val tilesLeft = tiles.toMutableList()
val imageSize = sqrt(tiles.size.toDouble()).toInt()
val firstCorner = tilesLeft.first { it.isCorner(tiles) }
tilesLeft.remove(firstCorner)
// collect first column
val firstColumn = mutableListOf(firstCorner)
for (y in 1 until imageSize) {
for (tile in tilesLeft) {
if (tile.isBorder(tiles) && tile.matchAnyEdge(firstColumn[y - 1]) && !firstColumn.contains(tile)) {
firstColumn.add(tile)
tilesLeft.remove(tile)
break
}
}
}
for (tile in tilesLeft) {
if (tile.isCorner(tiles) && tile.matchAnyEdge(firstColumn.last()) && !firstColumn.contains(tile)) {
firstColumn.add(tile)
tilesLeft.remove(tile)
break
}
}
// collect next columns left-to-right using other tiles
val fullImage = firstColumn.map { mutableListOf(it) }
for (x in 1 until imageSize) {
for (y in 0 until imageSize) {
val leftNeighbour = fullImage[y][x - 1]
for (tile in tilesLeft) {
if (tile.matchAnyEdge(leftNeighbour)) {
fullImage[y].add(tile)
tilesLeft.remove(tile)
break
}
}
}
}
// println(fullImage.joinToString("\n") { row -> row.joinToString { it.id.toString() } })
return fullImage
}
fun orientTiles(arrangedImage: List<List<Tile>>): MutableList<MutableList<Tile>> {
val result = MutableList(arrangedImage.size) { mutableListOf<Tile>() }
for ((rowId, row) in arrangedImage.withIndex()) {
for ((colId, tile) in row.withIndex()) {
val neighbours = mapOf(
Tile.Side.TOP to if (rowId == 0) null else arrangedImage[rowId - 1][colId],
Tile.Side.BOTTOM to if (rowId == arrangedImage.lastIndex) null else arrangedImage[rowId + 1][colId],
Tile.Side.LEFT to if (colId == 0) null else arrangedImage[rowId][colId - 1],
Tile.Side.RIGHT to if (colId == arrangedImage[0].lastIndex) null else arrangedImage[rowId][colId + 1]
)
val oriented = tile.orientToMatch(neighbours)
result[rowId].add(oriented)
}
}
return result
}
class Image(private val orientTiles: MutableList<MutableList<Tile>>) {
companion object {
val monster = listOf(
" # ",
"# ## ## ###",
" # # # # # # "
)
}
val tileSize = orientTiles.first().first().raw.size
private val withoutBorders = orientTiles.flatMap { tilesRow ->
val row = mutableListOf<String>()
for (y in 1 until tileSize - 1) {
row.add(tilesRow.joinToString("") { tile -> tile.raw[y].drop(1).dropLast(1) })
}
row
}
fun printWithBorders() {
for (row in orientTiles) {
for (y in row.first().raw.indices) {
println(row.joinToString(" ") { tile -> tile.raw[y] })
}
println()
}
}
fun printWithoutBorders() {
println(withoutBorders.joinToString("\n"))
}
private fun countMonsters(image: List<String>): Int {
var counter = 0
for (y in 0 until image.size - monster.size){
for (x in 0 until image.first().length - monster.first().length){
var found = true
monsterLoop@
for (my in monster.indices){
for (mx in monster.first().indices){
if(image[y + my][x + mx] != '#' && monster[my][mx] == '#'){
found = false
break@monsterLoop
}
}
}
if (found){
counter += 1
}
}
}
return counter
}
fun countMonstersWithTransformations(): Int {
val imageTile = Tile(0, mapOf(Tile.Side.TOP to "",Tile.Side.BOTTOM to "",Tile.Side.LEFT to "",Tile.Side.RIGHT to ""), withoutBorders)
for (flipped in imageTile.flipAcross()) {
for (rotated in flipped.rotateRight()) {
val count = countMonsters(rotated.raw)
if (count > 0) {
return count
}
}
}
return 0
}
fun countHashes(img : List<String>): Int {
return img.joinToString("").count { it == '#' }
}
fun countSafeWaters() : Int{
return countHashes(withoutBorders) - countHashes(monster) * countMonstersWithTransformations()
}
}
fun part2(tiles: List<Tile>): Int {
val arrangedImage = arrangeImage(tiles)
val image = Image(orientTiles(arrangedImage))
// image.printWithoutBorders()
return image.countSafeWaters()
}
fun main() {
val tiles = {}::class.java.getResource("/day20.in")
.readText()
.split("\n\n")
.map { Tile.fromRaw(it) }
println("Answer part 1: ${part1(tiles)}")
println("Answer part 2: ${part2(tiles)}")
} | 0 | Kotlin | 0 | 1 | a2f7674a8f81f16cd693854d9f564b52ce6aaaaf | 9,624 | advent-of-code-2020 | Do What The F*ck You Want To Public License |
day02/src/main/kotlin/Main.kt | rstockbridge | 225,212,001 | false | null | fun main() {
val input = resourceFile("input.txt")
.readLines()[0]
.split(',')
.map(String::toInt)
val ioProcessor = object : IOProcessor {
override fun setInput(state: List<Int>, noun: Int, verb: Int): List<Int> {
val result = state.toMutableList()
result[1] = noun
result[2] = verb
return result
}
override fun getOutput(state: List<Int>): Int {
return state[0]
}
}
println("Part I: the solution is ${solvePartI(input, ioProcessor, 12, 2)}.")
println("Part II: the solution is ${solvePartII(input, ioProcessor, 19690720)}.")
}
fun solvePartI(input: List<Int>, ioProcessor: IOProcessor, noun: Int, verb: Int): Int {
return getPartISolution(input, ioProcessor, noun, verb)
}
fun solvePartII(input: List<Int>, ioProcessor: IOProcessor, targetOutput: Int): Int {
for (noun: Int in 0..99) {
for (verb: Int in 0..99) {
val updatedInput = ioProcessor.setInput(input, noun, verb)
val finalState = runComputer(updatedInput)
val output = ioProcessor.getOutput(finalState)
if (output == targetOutput) {
return 100 * noun + verb
}
}
}
throw IllegalStateException("This line should not be reached.")
}
fun getPartISolution(input: List<Int>, ioProcessor: IOProcessor, noun: Int, verb: Int): Int {
val updatedInput = ioProcessor.setInput(input, noun, verb)
val finalState = runComputer(updatedInput)
return ioProcessor.getOutput(finalState)
}
interface IOProcessor {
fun setInput(state: List<Int>, noun: Int, verb: Int): List<Int>
fun getOutput(state: List<Int>): Int
}
private fun runComputer(state: List<Int>): List<Int> {
val mutableState = state.toMutableList()
var index = 0
while (true) {
val opcode = mutableState[index]
when (opcode) {
1 -> {
val input1Position = mutableState[index + 1]
val input2Position = mutableState[index + 2]
val outputPosition = mutableState[index + 3]
mutableState[outputPosition] = mutableState[input1Position] + mutableState[input2Position]
index += 4
}
2 -> {
val input1Position = mutableState[index + 1]
val input2Position = mutableState[index + 2]
val outputPosition = mutableState[index + 3]
mutableState[outputPosition] = mutableState[input1Position] * mutableState[input2Position]
index += 4
}
99 -> return mutableState
else -> throw IllegalStateException("This line should not be reached.")
}
}
}
| 0 | Kotlin | 0 | 0 | bcd6daf81787ed9a1d90afaa9646b1c513505d75 | 2,781 | AdventOfCode2019 | MIT License |
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[85]最大矩形.kt | maoqitian | 175,940,000 | false | {"Kotlin": 354268, "Java": 297740, "C++": 634} | import java.util.*
//给定一个仅包含 0 和 1 、大小为 rows x cols 的二维二进制矩阵,找出只包含 1 的最大矩形,并返回其面积。
//
//
//
// 示例 1:
//
//
//输入:matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"]
//,["1","0","0","1","0"]]
//输出:6
//解释:最大矩形如上图所示。
//
//
// 示例 2:
//
//
//输入:matrix = []
//输出:0
//
//
// 示例 3:
//
//
//输入:matrix = [["0"]]
//输出:0
//
//
// 示例 4:
//
//
//输入:matrix = [["1"]]
//输出:1
//
//
// 示例 5:
//
//
//输入:matrix = [["0","0"]]
//输出:0
//
//
//
//
// 提示:
//
//
// rows == matrix.length
// cols == matrix[0].length
// 0 <= row, cols <= 200
// matrix[i][j] 为 '0' 或 '1'
//
// Related Topics 栈 数组 哈希表 动态规划
// 👍 758 👎 0
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
fun maximalRectangle(matrix: Array<CharArray>): Int {
//单调栈 转化为 84 题解法 时间复杂度 O(mn) m n 为矩阵行列数
if(matrix.isEmpty()) return 0
//行列
val col = matrix.size
val row = matrix[0].size
//记录每一行数组中 1 的个数
val height = IntArray(row)
var res = 0
for(i in 0 until col){
for (j in 0 until row ){
if(matrix[i][j] == '1'){
height[j] += 1
}else{
height[j] = 0
}
}
res = Math.max(res,largeArea(height))
}
return res
}
private fun largeArea(height: IntArray): Int {
//当前行 1 最大面积
var res = 0
//使用栈
val stack = LinkedList<Int>()
val newHeight = IntArray(height.size + 2)
for (i in 1 until height.size+1){
newHeight[i] = height[i-1]
}
//计算面积
for (i in newHeight.indices){
while (!stack.isEmpty() && newHeight[stack.last] > newHeight[i]){
val cur = stack.removeLast()
res = Math.max(res,(i-stack.last-1)*newHeight[cur])
}
stack.addLast(i)
}
return res
}
}
//leetcode submit region end(Prohibit modification and deletion)
| 0 | Kotlin | 0 | 1 | 8a85996352a88bb9a8a6a2712dce3eac2e1c3463 | 2,343 | MyLeetCode | Apache License 2.0 |
src/main/kotlin/pl/jpodeszwik/aoc2023/Day16.kt | jpodeszwik | 729,812,099 | false | {"Kotlin": 55101} | package pl.jpodeszwik.aoc2023
import java.util.*
import kotlin.math.max
enum class Direction {
UP,
DOWN,
LEFT,
RIGHT,
}
data class NodeWithDirection(val node: MapCoord, val direction: Direction) {
val row get() = node.row
val col get() = node.col
fun up() = NodeWithDirection(node.up(), Direction.UP)
fun down() = NodeWithDirection(node.down(), Direction.DOWN)
fun left() = NodeWithDirection(node.left(), Direction.LEFT)
fun right() = NodeWithDirection(node.right(), Direction.RIGHT)
}
data class MapCoord(val row: Int, val col: Int) {
fun up() = MapCoord(row - 1, col)
fun down() = MapCoord(row + 1, col)
fun left() = MapCoord(row, col - 1)
fun right() = MapCoord(row, col + 1)
fun neighbours() = listOf(
Pair(Direction.UP, up()),
Pair(Direction.LEFT, left()),
Pair(Direction.DOWN, down()),
Pair(Direction.RIGHT, right()),
)
fun inDirection(direction: Direction, distance: Int): MapCoord = when (direction) {
Direction.UP -> MapCoord(row - distance, col)
Direction.DOWN -> MapCoord(row + distance, col)
Direction.LEFT -> MapCoord(row, col - distance)
Direction.RIGHT -> MapCoord(row, col + distance)
}
}
private fun nextNode(node: NodeWithDirection): NodeWithDirection {
return when (node.direction) {
Direction.UP -> node.up()
Direction.DOWN -> node.down()
Direction.LEFT -> node.left()
Direction.RIGHT -> node.right()
}
}
private fun splitHorizontal(node: NodeWithDirection): List<NodeWithDirection> {
return when (node.direction) {
Direction.UP, Direction.DOWN -> listOf(
node.left(),
node.right(),
)
Direction.LEFT -> listOf(node.left())
Direction.RIGHT -> listOf(node.right())
}
}
private fun splitVertical(node: NodeWithDirection): List<NodeWithDirection> {
return when (node.direction) {
Direction.UP -> listOf(node.up())
Direction.DOWN -> listOf(node.down())
Direction.LEFT, Direction.RIGHT -> listOf(
node.up(),
node.down(),
)
}
}
private fun mirrorSlash(node: NodeWithDirection): NodeWithDirection {
return when (node.direction) {
Direction.UP -> node.right()
Direction.DOWN -> node.left()
Direction.LEFT -> node.down()
Direction.RIGHT -> node.up()
}
}
private fun mirrorBackSlash(node: NodeWithDirection): NodeWithDirection {
return when (node.direction) {
Direction.UP -> node.left()
Direction.DOWN -> node.right()
Direction.LEFT -> node.up()
Direction.RIGHT -> node.down()
}
}
private fun countEnergized(initialNode: NodeWithDirection, map: List<String>): Int {
val visitedNodes = HashSet<NodeWithDirection>()
visitedNodes.add(initialNode)
val nodeQueue = LinkedList<NodeWithDirection>()
nodeQueue.add(initialNode)
val handleNode = { node: NodeWithDirection ->
if (node.row >= 0 && node.row < map.size && node.col >= 0 && node.col < map[0].length) {
if (visitedNodes.add(node)) {
nodeQueue.add(node)
}
}
}
while (nodeQueue.isNotEmpty()) {
val node = nodeQueue.pop()
when (map[node.row][node.col]) {
'.' -> handleNode(nextNode(node))
'|' -> splitVertical(node).forEach { handleNode(it) }
'-' -> splitHorizontal(node).forEach { handleNode(it) }
'/' -> handleNode(mirrorSlash(node))
'\\' -> handleNode(mirrorBackSlash(node))
}
}
return visitedNodes.groupBy { it.node }.count()
}
private fun part1(map: List<String>) {
val initialNode = NodeWithDirection(MapCoord(0, 0), Direction.RIGHT)
val result = countEnergized(initialNode, map)
println(result)
}
private fun part2(map: List<String>) {
val rowMax = map.indices.flatMap { row ->
listOf(
countEnergized(NodeWithDirection(MapCoord(row, 0), Direction.RIGHT), map),
countEnergized(NodeWithDirection(MapCoord(row, map[0].length - 1), Direction.LEFT), map)
)
}.max()
val colMax = map[0].indices.flatMap { col ->
listOf(
countEnergized(NodeWithDirection(MapCoord(0, col), Direction.DOWN), map),
countEnergized(NodeWithDirection(MapCoord(map.size - 1, col), Direction.UP), map)
)
}.max()
println(max(rowMax, colMax))
}
fun main() {
val input = loadFile("/aoc2023/input16")
part1(input)
part2(input)
}
| 0 | Kotlin | 0 | 0 | 2b90aa48cafa884fc3e85a1baf7eb2bd5b131a63 | 4,567 | advent-of-code | MIT License |
src/main/kotlin/com/hj/leetcode/kotlin/problem1601/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem1601
/**
* LeetCode page: [1601. Maximum Number of Achievable Transfer Requests](https://leetcode.com/problems/maximum-number-of-achievable-transfer-requests/);
*/
class Solution {
/* Complexity:
* Time O(n * 2^M) and Space O(n+M) where M is the size of requests;
*/
fun maximumRequests(n: Int, requests: Array<IntArray>): Int {
var result = 0
dfs(requests, 0, 0, IntArray(n)) { numAcceptedRequests ->
result = maxOf(result, numAcceptedRequests)
}
return result
}
private fun dfs(
requests: Array<IntArray>,
nextRequestIndex: Int,
numAcceptedRequests: Int,
netEmployeeChange: IntArray, // net change of each building
onAchievableTransfer: (numAcceptedRequests: Int) -> Unit
) {
if (nextRequestIndex == requests.size) {
if (isAchievableTransfer(netEmployeeChange)) {
onAchievableTransfer(numAcceptedRequests)
}
return
}
// Case that the request is not accepted
dfs(requests, nextRequestIndex + 1, numAcceptedRequests, netEmployeeChange, onAchievableTransfer)
// Case that the request is accepted. Apply backtracking on the netEmployeeChange.
val (from, to) = requests[nextRequestIndex]
netEmployeeChange[from]--
netEmployeeChange[to]++
dfs(requests, nextRequestIndex + 1, numAcceptedRequests + 1, netEmployeeChange, onAchievableTransfer)
netEmployeeChange[to]--
netEmployeeChange[from]++
}
private fun isAchievableTransfer(netEmployeeChange: IntArray): Boolean {
return netEmployeeChange.all { it == 0 }
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 1,726 | hj-leetcode-kotlin | Apache License 2.0 |
src/Day05.kt | bkosm | 572,912,735 | false | {"Kotlin": 17839} | typealias StackOfCrates = MutableList<Char>
class Ship(private val stacks: List<StackOfCrates>) {
data class MoveCommand(
val from: Int,
val to: Int,
val amount: Int,
)
fun move(command: MoveCommand, moveMultiple: Boolean = false) {
if (moveMultiple) {
stacks[command.from].takeLast(command.amount).onEach { _ ->
stacks[command.from].removeLastOrNull()
}.let {
stacks[command.to].addAll(it)
}
} else {
repeat(command.amount) {
stacks[command.from].removeLastOrNull()?.let {
stacks[command.to].add(it)
}
}
}
}
@Suppress("unused")
fun log(desc: Any? = null) {
println("=== Moved $desc")
stacks.forEachIndexed { index, stack ->
println("Stack ${index + 1}: ${stack.joinToString("")}")
}
}
fun tops() = stacks.map { it.lastOrNull() ?: " " }.joinToString("")
}
fun read(input: List<String>, columns: Int): Pair<List<StackOfCrates>, List<Ship.MoveCommand>> {
val setupLine = "^${(0 until columns).joinToString("\\ ") { "(\\ {3}|\\[[A-Z]\\])" }}\$".toRegex()
val moveLine = "^move (\\d*) from (\\d*) to (\\d*)\$".toRegex()
val commands = mutableListOf<Ship.MoveCommand>()
val stacks = mutableListOf<StackOfCrates>()
input.forEach { raw ->
val line = raw.trim('|') // had to add it cause reading trims whitespace by itself
setupLine.matchEntire(line)?.let { match ->
val values = match.groupValues.drop(1)
if (stacks.isEmpty()) values.forEach {
if (it.isBlank().not()) stacks.add(mutableListOf(it[1]))
else stacks.add(mutableListOf())
} else values.forEachIndexed { i, e ->
if (e.isBlank().not()) stacks[i].add(e[1])
}
}
moveLine.matchEntire(line)?.let {
commands.add(
Ship.MoveCommand(
from = it.groups[2]!!.value.toInt() - 1,
to = it.groups[3]!!.value.toInt() - 1,
amount = it.groups[1]!!.value.toInt(),
)
)
}
}
return stacks.map { it.reversed().toMutableList() } to commands
}
object Day05 : DailyRunner<String, String> {
override fun do1(input: List<String>, isTest: Boolean) =
read(input, if (isTest) 3 else 9).let { (stacks, commands) ->
Ship(stacks).apply {
commands.forEach { move(it) }
}.tops()
}
override fun do2(input: List<String>, isTest: Boolean) =
read(input, if (isTest) 3 else 9).let { (stacks, commands) ->
Ship(stacks).apply {
commands.forEach { move(it, moveMultiple = true) }
}.tops()
}
}
fun main() {
Day05.run()
}
| 0 | Kotlin | 0 | 1 | 3f9cccad1e5b6ba3e92cbd836a40207a2f3415a4 | 2,907 | aoc22 | Apache License 2.0 |
src/Day05.kt | Qdelix | 574,590,362 | false | null | fun main() {
fun initMap() = mutableMapOf<Int, MutableList<String>>(
1 to mutableListOf(),
2 to mutableListOf(),
3 to mutableListOf(),
4 to mutableListOf(),
5 to mutableListOf(),
6 to mutableListOf(),
7 to mutableListOf(),
8 to mutableListOf(),
9 to mutableListOf()
)
fun part1(input: List<String>): String {
val map = initMap()
val crates = input.take(8)
crates.forEach { line ->
line.drop(1).windowed(1, 4).forEachIndexed { index, s ->
if (s != " ") {
map[index + 1]?.add(0, s)
}
}
}
input.drop(10).forEach { line ->
val move = line.drop(5).takeWhile { c -> c.toString() != " " }.toInt()
val from = line.substringAfter("from ").take(1).toInt()
val to = line.substringAfter("to ").take(1).toInt()
for (i in 0 until move) {
map[from]?.last()?.let {
map[to]?.add(it)
map[from]?.removeLast()
}
}
}
var result = ""
map.forEach { l -> result += l.value.last() }
return result
}
fun part2(input: List<String>): String {
val map = initMap()
val crates = input.take(8)
crates.forEach { line ->
line.drop(1).windowed(1, 4).forEachIndexed { index, s ->
if (s != " ") {
map[index + 1]?.add(0, s)
}
}
}
input.drop(10).forEach { line ->
val move = line.drop(5).takeWhile { c -> c.toString() != " " }.toInt()
val from = line.substringAfter("from ").take(1).toInt()
val to = line.substringAfter("to ").take(1).toInt()
map[from]?.takeLast(move)?.let {
map[to]?.addAll(it)
}
for (i in 0 until move) {
map[from]?.removeLast()
}
}
var result = ""
map.forEach { l -> result += l.value.last() }
return result
}
val input = readInput("Day05")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 8e5c599d5071d9363c8f33b800b008875eb0b5f5 | 2,225 | aoc22 | Apache License 2.0 |
src/day09/Day09.kt | Ciel-MC | 572,868,010 | false | {"Kotlin": 55885} | package day09
import readInput
import kotlin.math.absoluteValue
import kotlin.reflect.KMutableProperty
enum class Direction {
UP, DOWN, LEFT, RIGHT;
companion object {
fun fromChar(char: Char): Direction = when (char) {
'U' -> UP
'D' -> DOWN
'L' -> LEFT
'R' -> RIGHT
else -> throw IllegalArgumentException("Invalid direction: $char")
}
}
}
interface Point {
val x: Int
val y: Int
operator fun component1(): Int = x
operator fun component2(): Int = y
}
interface Child {
val child: Child?
}
enum class RelativePosition(val v: Int) {
NEGATIVE(-1), ZERO(0), POSITIVE(1);
infix fun isOpposite(other: RelativePosition): Boolean = this.v == -other.v
operator fun unaryMinus(): RelativePosition = when (this) {
NEGATIVE -> POSITIVE
ZERO -> ZERO
POSITIVE -> NEGATIVE
}
companion object {
operator fun invoke(x: Int): RelativePosition = when (x) {
-1 -> NEGATIVE
0 -> ZERO
1 -> POSITIVE
else -> throw IllegalArgumentException("Invalid relative position: $x")
}
}
}
data class Relative(val x: RelativePosition, val y: RelativePosition) {
fun isOrthogonal() = x == RelativePosition.ZERO || y == RelativePosition.ZERO
fun isDiagonal() = x != RelativePosition.ZERO && y != RelativePosition.ZERO
fun isNeutral() = x == RelativePosition.ZERO && y == RelativePosition.ZERO
infix fun isInverse(other: Relative): Boolean = this.x isOpposite other.x && this.y isOpposite other.y
operator fun unaryMinus(): Relative = Relative(-x, -y)
fun isSignificant(other: Relative): Boolean {
if (this.isNeutral() || other.isNeutral()) return false
if ((this.x.v + other.x.v).absoluteValue == 2) return true
if ((this.y.v + other.y.v).absoluteValue == 2) return true
return false
}
companion object {
operator fun invoke(x: Int, y: Int): Relative = Relative(RelativePosition(x), RelativePosition(y))
}
}
interface Var<T> {
var value: T
}
fun <T> apply(value: KMutableProperty<T>, transformation: Var<T>.() -> Unit) {
object: Var<T> {
override var value: T
set(v) {
value.setter.call(v)
}
get() = value.getter.call()
}.transformation()
}
fun main() {
fun parseMoves(input: List<String>): List<Direction> {
val regex = Regex("""([UDLR]) (\d+)""")
return buildList {
input.forEach {
val (direction, distance) = regex.matchEntire(it)!!.destructured
repeat(distance.toInt()) { add(Direction.fromChar(direction[0])) }
}
}
}
data class SimplePoint(override val x: Int, override val y: Int): Point
fun Point.toSimplePoint(): SimplePoint = SimplePoint(x, y)
data class Tail(override var x: Int, override var y: Int, val id: Int, override var child: Tail? = null): Point,
Child {
constructor(id: Int, child: Tail? = null): this(0, 0, id, child)
val visited: MutableSet<SimplePoint> = mutableSetOf(this.toSimplePoint())
fun parentMove(fromX: Int, fromY: Int, toX: Int, toY: Int, debug: Boolean = false) {
val (oldX, oldY) = this
val relativeToMe = Relative(fromX - oldX, fromY - oldY)
val moveDirection = Relative(toX - fromX, toY - fromY)
if (!moveDirection.isSignificant(relativeToMe)) {
if (debug) println("Tail $id: Neutral move, early exit"); return
} // Diagonal moveRelative is only possible when there is more than one chain
if (moveDirection.isOrthogonal()) {
this.x = fromX
this.y = fromY
} else {
if (relativeToMe.x.v + moveDirection.x.v == 0) {
this.y += moveDirection.y.v
} else if (relativeToMe.y.v + moveDirection.y.v == 0) {
this.x += moveDirection.x.v
} else {
this.x += moveDirection.x.v
this.y += moveDirection.y.v
}
}
visited.add(this.toSimplePoint())
if (debug) println("from=($oldX,$oldY) to=($x,$y) $this")
child?.parentMove(oldX, oldY, x, y, debug)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Tail
if (x != other.x) return false
if (y != other.y) return false
return true
}
override fun hashCode(): Int {
var result = x
result = 31 * result + y
return result
}
}
data class Head(override var x: Int, override var y: Int, val child: Tail): Point {
fun move(direction: Direction, debug: Boolean = false) {
val (oldX, oldY) = this
when (direction) {
Direction.UP -> y++
Direction.DOWN -> y--
Direction.LEFT -> x--
Direction.RIGHT -> x++
}
if (debug) println("Moved from ($oldX, $oldY) to ($x, $y)")
child.parentMove(oldX, oldY, x, y, debug)
}
}
data class Visualize(val boardSize: Int, val xOff: Int = 0, val yOff: Int = 0)
fun getCharacter(renderX: Int, renderY: Int, head: Head): Char {
var tail: Tail? = null
val point = SimplePoint(renderX, renderY)
val childSequence = sequence {
var current: Tail? = head.child
while (current != null) {
yield(current)
current = current.child
}
}
if (renderX == 0 && renderY == 0) return 's'
if (head.toSimplePoint() == point) return 'H'
if (childSequence.firstOrNull { it.toSimplePoint() == point }?.let { point -> tail = point; true } == true) return tail!!.id.toString()[0]
if (point in childSequence.last().visited) return '#'
return '.'
}
fun List<Direction>.navigate(head: Head, visualize: Visualize? = null) {
var lastDirection: Direction? = null
forEach {
if (visualize != null/* && lastDirection != null && it != lastDirection*/) {
repeat(visualize.boardSize) { y ->
val renderY = visualize.boardSize - 1 - y - visualize.yOff
print(renderY.toString().padStart(2, ' ')+" ")
repeat(visualize.boardSize) { x ->
val renderX = x - visualize.xOff
print(getCharacter(renderX, renderY, head)+" ")
}
println()
}
print(" ".repeat(2))
repeat(visualize.boardSize) { print((it - visualize.xOff).toString().padStart(3, ' ')) }
println()
print("--".repeat(visualize.boardSize))
println()
}
head.move(it, visualize != null)
if (visualize != null) println(it)
lastDirection = it
}
}
fun part1(input: List<String>, visualize: Visualize? = null): Int {
val moves = parseMoves(input)
val head = Head(0, 0, Tail(1))
moves.navigate(head, visualize)
return head.child.visited.size
}
fun part2(input: List<String>, visualize: Visualize? = null): Int {
val last = Tail(9)
var current = last
repeat(8) {
current = Tail(8 - it, current)
}
val head = Head(0, 0, current)
parseMoves(input).navigate(head, visualize)
return last.visited.size
}
val testInput = readInput(9, true)
part1(testInput, Visualize(6)).let { check(it == 13) { println(it) } }
part2(testInput/*, Visualize(6)*/).let { check(it == 1) { println(it) } }
// part2(readInput("Day09_test_2")/*, Visualize(26, xOff = 11, yOff = 5)*/).let { check(it == 36) { println(it) } }
val input = readInput(9)
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 7eb57c9bced945dcad4750a7cc4835e56d20cbc8 | 8,205 | Advent-Of-Code | Apache License 2.0 |
src/main/kotlin/com/nibado/projects/advent/y2017/Day20.kt | nielsutrecht | 47,550,570 | false | null | package com.nibado.projects.advent.y2017
import com.nibado.projects.advent.Day
import com.nibado.projects.advent.resourceRegex
import java.lang.Math.abs
object Day20 : Day {
private val input = resourceRegex(2017, 20, Regex("p=<(-?[0-9]+),(-?[0-9]+),(-?[0-9]+)>, v=<(-?[0-9]+),(-?[0-9]+),(-?[0-9]+)>, a=<(-?[0-9]+),(-?[0-9]+),(-?[0-9]+)>"))
.map { it.subList(1, 10).map { it.toInt() } }
.map { Particle(it[0], it[1], it[2], it[3], it[4], it[5], it[6], it[7], it[8]) }
override fun part1(): String {
val list = input.toMutableList()
(1..500).forEach { list.forEachIndexed { i, p -> list[i] = p.next() } }
return list.indexOf(list.sortedBy { it.manhattan }.first()).toString()
}
override fun part2(): String {
val list = input.toMutableList()
(1..500).forEach {
list.forEachIndexed { i, p -> list[i] = p.next() }
val collisions = list.filter { needle -> list.count { needle.collides(it) } > 1 }
list.removeAll(collisions)
}
return list.size.toString()
}
data class Particle(val x: Int, val y: Int, val z: Int,
val vx: Int, val vy: Int, val vz: Int,
val ax: Int, val ay: Int, val az: Int) {
val manhattan = abs(x) + abs(y) + abs(z)
fun collides(other: Particle) = other.x == x && other.y == y && other.z == z
fun next(): Particle {
val vx = this.vx + ax
val vy = this.vy + ay
val vz = this.vz + az
return Particle(x + vx, y + vy, z + vz, vx, vy, vz, ax, ay, az)
}
}
} | 1 | Kotlin | 0 | 15 | b4221cdd75e07b2860abf6cdc27c165b979aa1c7 | 1,648 | adventofcode | MIT License |
src/algorithmdesignmanualbook/datastructures/NoInitializationArray.kt | realpacific | 234,499,820 | false | null | package algorithmdesignmanualbook.datastructures
import algorithmdesignmanualbook.print
import java.util.*
import kotlin.random.Random
import kotlin.test.assertFalse
import kotlin.test.assertTrue
/**
* Design a data structure that allows one to search, insert, and delete an integer
* X in O(1) time (i.e. , constant time, independent of the total number of integers
* stored). Assume that 1 ≤ X ≤ n and that there are m + n units of space available,
* where m is the maximum number of integers that can be in the table at any one
* time. (Hint: use two arrays A[1..n] and B[1..m].) You are not allowed to initialize
* either A or B, as that would take O(m) or O(n) operations. This means the arrays
* are full of random garbage to begin with, so you must be very careful.
*
* [Solution link](https://research.swtch.com/sparse):
*
* Two arrays both of them with garbage value
* * dense: contains actual elements in order of insertion
* * sparse: uses *value* of [dense] as index and stores the *index* at which the value is located
*
* So the search value v is legit iff index v of sparse array points to dense's index whose value is also v
*/
class NoInitializationArray(val maxValue: Int, val maxSize: Int) {
private val rand = Random(100)
private val dense = Array(maxSize) { getGarbage() }
private val sparse = Array(maxValue) { getGarbage() }
private var nextIndex = 0
private fun getGarbage() = rand.nextInt(maxValue + 1, maxValue + 1 + 200)
fun print() {
println("dense: ${Arrays.toString(dense)}")
println("sparse: ${Arrays.toString(sparse)}")
}
fun add(value: Int) {
require(value.isNotGarbage())
dense[nextIndex] = value
sparse[value] = nextIndex
nextIndex++
}
private fun hasLegitValue(sparseResult: Int): Boolean {
val value = dense.getOrNull(sparseResult) ?: return false
return value.print().isNotGarbage()
}
private fun Int.isNotGarbage() = this < maxValue
fun delete(value: Int) {
val index = sparse.getOrNull(value) ?: return
if (!hasLegitValue(index)) {
return
}
dense[index] = getGarbage()
sparse[value] = getGarbage()
}
fun search(value: Int): Boolean {
val index = sparse.getOrNull(value) ?: return false
return dense.getOrNull(index) == value
}
}
fun main() {
val solution = NoInitializationArray(maxValue = 20, maxSize = 10)
solution.add(10)
assertTrue { solution.search(10) }
solution.add(6)
assertTrue { solution.search(6) }
solution.add(9)
assertTrue { solution.search(9) }
solution.add(14)
assertTrue { solution.search(14) }
solution.print()
assertFalse { solution.search(100) }
solution.delete(10)
assertFalse { solution.search(10) }
solution.delete(6)
assertFalse { solution.search(6) }
solution.delete(9)
assertFalse { solution.search(9) }
solution.print()
} | 4 | Kotlin | 5 | 93 | 22eef528ef1bea9b9831178b64ff2f5b1f61a51f | 2,991 | algorithms | MIT License |
src/Day11.kt | diego09310 | 576,378,549 | false | {"Kotlin": 28768} | fun main() {
val DIVIDERS_MULTIPIED = (2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23)
data class Monkey (val id: Int) {
val items: MutableList<Long> = mutableListOf()
var op = ' '
lateinit var n: String
var test = 0L
var trueTest = 0
var falseTest = 0
var inspected = 0L
}
fun minimize(n: Long): Long {
return n % DIVIDERS_MULTIPIED
}
fun part1(input: List<String>): Long {
val monkeys = mutableListOf<Monkey>()
for (l in input) {
val words = l.split(' ').filter{ it != "" }
if (words.isEmpty()) {
continue
}
when (words[0]) {
"Monkey" -> {
val monkey = Monkey(words[1].removeSuffix(":").toInt())
monkeys.add(monkey)
}
"Starting" -> {
for (i in 2 until words.size) {
monkeys.last().items.add(words[i].removeSuffix(",").toLong())
}
}
"Operation:" -> {
monkeys.last().op = words[4].toCharArray()[0]
monkeys.last().n = words[5]
}
"Test:" -> monkeys.last().test = words[3].toLong()
"If" -> {
if (words[1] == "true:") {
monkeys.last().trueTest = words[5].toInt()
} else {
monkeys.last().falseTest = words[5].toInt()
}
}
}
}
for (i in 0 until 20) {
for (monkey in monkeys) {
monkey.items.sort()
for (item in monkey.items) {
monkey.inspected++
val n = if (monkey.n == "old") item else monkey.n.toLong()
val newItem = minimize((if (monkey.op == '+') item + n else item * n) / 3)
if (newItem % monkey.test == 0L) {
monkeys[monkey.trueTest].items.add(newItem)
} else {
monkeys[monkey.falseTest].items.add(newItem)
}
}
monkey.items.clear()
}
}
val inspected = monkeys.map{it.inspected}.toCollection(mutableListOf())
inspected.sortDescending()
return inspected[0] * inspected[1]
}
fun part2(input: List<String>): Long {
val monkeys = mutableListOf<Monkey>()
for (l in input) {
val words = l.split(' ').filter{ it != "" }
if (words.isEmpty()) {
continue
}
when (words[0]) {
"Monkey" -> {
val monkey = Monkey(words[1].removeSuffix(":").toInt())
monkeys.add(monkey)
}
"Starting" -> {
for (i in 2 until words.size) {
monkeys.last().items.add(words[i].removeSuffix(",").toLong())
}
}
"Operation:" -> {
monkeys.last().op = words[4].toCharArray()[0]
monkeys.last().n = words[5]
}
"Test:" -> monkeys.last().test = words[3].toLong()
"If" -> {
if (words[1] == "true:") {
monkeys.last().trueTest = words[5].toInt()
} else {
monkeys.last().falseTest = words[5].toInt()
}
}
}
}
for (i in 0 until 10000) {
for (monkey in monkeys) {
monkey.items.sort()
for (item in monkey.items) {
monkey.inspected++
val n = if (monkey.n == "old") item else monkey.n.toLong()
val newItem = minimize(if (monkey.op == '+') item + n else item * n)
if (newItem % monkey.test.toLong() == 0L) {
monkeys[monkey.trueTest].items.add(newItem)
} else {
monkeys[monkey.falseTest].items.add(newItem)
}
}
monkey.items.clear()
}
// if (i % 1000 == 0 || i == 20) {
// println("== After round $i ==")
// monkeys.forEach { println("Monkey ${it.id} ins items ${it.inspected} times") }
// }
}
val inspected = monkeys.map{it.inspected}.toCollection(mutableListOf())
inspected.sortDescending()
// println("${inspected[0]} * ${inspected[1]} = ${inspected[0] * inspected[1]}")
return inspected[0] * inspected[1]
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("../../11linput")
check(part1(testInput) == 10605L)
val input = readInput("../../11input")
println(part1(input))
check(part2(testInput) == 2713310158)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 644fee9237c01754fc1a04fef949a76b057a03fc | 5,100 | aoc-2022-kotlin | Apache License 2.0 |
src/Day04.kt | jamie23 | 573,156,415 | false | {"Kotlin": 19195} | fun main() {
data class Time(
val start: Int,
val end: Int
)
infix fun Time.overlaps(b: Time) = start <= b.start && end >= b.end
infix fun Time.singleOverlap(b: Time) = b.start in start..end || b.end in start..end
fun List<String>.mapToTimes() = this.map { line ->
line.split(',')
.map { range -> range.split("-").map { Integer.valueOf(it) } }
.map { Time(it[0], it[1]) }
}
fun part1(input: List<String>) = input
.mapToTimes()
.map { (a, b) -> a overlaps b || b overlaps a }
.count { it }
fun part2(input: List<String>) = input
.mapToTimes()
.map { (a, b) -> a singleOverlap b || b singleOverlap a }
.count { it }
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | cfd08064654baabea03f8bf31c3133214827289c | 946 | Aoc22 | Apache License 2.0 |
src/main/algorithms/Quicksort.kt | dremme | 162,006,465 | false | {"Kotlin": 24254} | package algorithms
/**
* Sorts the array using quicksort. Elements must be greater than zero.
*/
fun IntArray.quicksort() {
require(all { it > 0 })
quicksort(0, size - 1)
}
/**
* Quicksort algorithm picking the highest element as pivot,
* so elements are only shifted to the right if they are
*/
private fun IntArray.quicksort(from: Int, to: Int) {
if (from < to) {
val pivot = this[to]
var index = from
(from..to).forEach {
if (this[it] < pivot) swap(index++, it)
}
swap(index, to)
quicksort(from, index - 1)
quicksort(index + 1, to)
}
}
private fun IntArray.swap(a: Int, b: Int) {
val temp = this[a]
this[a] = this[b]
this[b] = temp
}
| 0 | Kotlin | 0 | 0 | 1bdd6639502e3a5317a76bb5c0c116f04123f047 | 743 | coding-kotlin | MIT License |
2019/src/main/kotlin/com/github/jrhenderson1988/adventofcode2019/day7/AmplifierController.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.day7
class AmplifierController(private val program: String) {
fun calculateOutputSignal(phaseSequence: List<Int>, initialSignal: Int) =
phaseSequence.fold(initialSignal) { signal, input ->
Amplifier(program, input).execute(signal)
}
fun calculateLargestOutputSignal(phaseSequence: List<Int>, initialSignal: Int) =
generatePermutations(phaseSequence).map { sequence -> calculateOutputSignal(sequence, initialSignal) }.max()
fun calculateMaxThrusterSignalFromFeedbackLoop(phaseSequence: List<Int>, initialSignal: Int) =
generatePermutations(phaseSequence).map { sequence ->
val amplifiers = sequence.map { Amplifier(program, it) }
var signal = 0
while (!amplifiers.last().terminated) {
signal = amplifiers.fold(signal) { input, amplifier ->
amplifier.execute(input)
}
}
amplifiers.last().lastOutput
}.max()
companion object {
fun generatePermutations(items: List<Int>) = generatePermutations(items, items.size)
/**
* Iterative version of Heap's algorithm to generate permutations:
* https://en.wikipedia.org/wiki/Heap%27s_algorithm
*/
private fun generatePermutations(items: List<Int>, n: Int): Set<List<Int>> {
val elements = items.toMutableList()
val result = mutableSetOf<List<Int>>()
val indexes = (0 until n).map { 0 }.toMutableList()
result.add(elements.toList())
var i = 0
while (i < n) {
if (indexes[i] < i) {
val a = if (i % 2 == 0) 0 else indexes[i]
val b = i
val tmp = elements[a]
elements[a] = elements[b]
elements[b] = tmp
result.add(elements.toList())
indexes[i] = indexes[i] + 1
i = 0
} else {
indexes[i] = 0
i++
}
}
return result
}
}
} | 0 | Kotlin | 0 | 0 | 7b56f99deccc3790c6c15a6fe98a57892bff9e51 | 2,200 | advent-of-code | Apache License 2.0 |
src/day11/Day11.kt | kerchen | 573,125,453 | false | {"Kotlin": 137233} | package day11
import readInput
import java.util.regex.Pattern
data class Item(var worryLevel: Long) {
var ownershipHistory = mutableListOf<Int>()
}
class Monkey(startingItems: List<Item>,
monkeyNumber: Int,
val inspectEffectOperation: (Long) -> Long,
val testFactor: Long,
val testFunction: (Long) -> Boolean,
private val testSuccessRecipient: Int,
private val testFailureRecipient: Int) {
var items = mutableListOf<Item>()
init {
for (item in startingItems) {
items.add(item.copy())
items.last().ownershipHistory.add(monkeyNumber)
}
}
fun inspectItem(item: Item, worryReductionFn: (Long) -> Long): Int {
// Apply inspection operation
item.worryLevel = inspectEffectOperation(item.worryLevel)
// Apply boredom effect
item.worryLevel = worryReductionFn(item.worryLevel)
// Test worry level & throw
if (testFunction(item.worryLevel))
return testSuccessRecipient
return testFailureRecipient
}
}
fun createItems(itemsString: String): List<Item> {
val items = mutableListOf<Item>()
val worries = itemsString.split(",")
for (worry in worries) {
items.add(Item(worry.trim().toLong()))
}
return items
}
fun createOperation(opString: String): (Long) -> Long {
val equalSplit = opString.split("=")
val elements = equalSplit[1].trim().split(" ")
check(elements[0].trim() == "old") // Dirty shortcut :}
when(elements[1].trim()) {
"*" -> {
if (elements[2].trim() == "old")
return { v -> v * v }
else
return { v -> v * elements[2].trim().toLong() }
}
"+" -> {
return { v -> v + elements[2].trim().toLong() }
}
else -> throw Exception("Unexpected operator")
}
}
fun createTest(testString: String): Pair<Long, (Long) -> Boolean> {
val pattern = Pattern.compile("""divisible by (\d+)""")
val matcher = pattern.matcher(testString)
matcher.find()
val factor = matcher.group(1).toLong()
return Pair(factor, { v -> (v % factor) == 0.toLong() })
}
fun parseRecipient(recipientString: String): Int {
val pattern = Pattern.compile("""throw to monkey (\d+)""")
val matcher = pattern.matcher(recipientString)
matcher.find()
return matcher.group(1).toInt()
}
fun createMonkey(inputIt: Iterator<String>, monkeyNumber: Int): Monkey {
val itemsLine = inputIt.next().trim()
check(itemsLine.startsWith("Starting items:"))
val itemsString = itemsLine.split(":")[1]
val operationLine = inputIt.next().trim()
check(operationLine.startsWith("Operation:"))
val operationString = operationLine.split(":")[1]
val testLine = inputIt.next().trim()
check(testLine.startsWith("Test:"))
val testString = testLine.split(":")[1]
val successLine = inputIt.next().trim()
check(successLine.startsWith("If true:"))
val successString = successLine.split(":")[1]
val failureLine = inputIt.next().trim()
check(failureLine.startsWith("If false:"))
val failureString = failureLine.split(":")[1]
val (testFactor, testFunction) = createTest(testString)
return Monkey(createItems(itemsString), monkeyNumber, createOperation(operationString), testFactor, testFunction, parseRecipient(successString), parseRecipient(failureString) )
}
fun computeMonkeyBusiness(input: List<String>, roundCount: Int, simpleWorryReduction: Boolean): Long {
val inputIt = input.iterator()
val monkeys = mutableListOf<Monkey>()
var commonDivisor: Long = 1
while(inputIt.hasNext()) {
val recordLine = inputIt.next().trim()
if (recordLine.isEmpty()) continue
check(recordLine.startsWith("Monkey"))
monkeys.add(createMonkey(inputIt, monkeys.size))
commonDivisor *= monkeys.last().testFactor
}
val reductionFn = if (simpleWorryReduction) { worry: Long -> worry / 3 } else { worry: Long -> worry % commonDivisor }
val inspectionCounts = MutableList(monkeys.size) {0}
for (round in IntRange(1,roundCount)) {
val monkeyIterator = monkeys.listIterator()
while (monkeyIterator.hasNext()) {
val index = monkeyIterator.nextIndex()
val monkey = monkeyIterator.next()
inspectionCounts[index] += monkey.items.size
val itemIterator = monkey.items.iterator()
while(itemIterator.hasNext()){
val item = itemIterator.next()
itemIterator.remove()
val toMonkey = monkey.inspectItem(item, reductionFn)
monkeys[toMonkey].items.add(item)
item.ownershipHistory.add(toMonkey)
}
}
}
val sortedCounts = inspectionCounts.sortedDescending()
return sortedCounts[0].toLong() * sortedCounts[1].toLong()
}
fun main() {
fun part1(input: List<String>): Long = computeMonkeyBusiness(input, 20, true)
fun part2(input: List<String>): Long = day11.computeMonkeyBusiness(input, 10000, false)
val testInput = readInput("Day11_test")
check(part1(testInput) == 10605.toLong())
check(part2(testInput) == 2713310158)
val input = readInput("Day11")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | dc15640ff29ec5f9dceb4046adaf860af892c1a9 | 5,353 | AdventOfCode2022 | Apache License 2.0 |
codeforces/round752/c.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package codeforces.round752
const val M = 998244353
private fun solve(): Long {
readLn()
val a = readInts()
val memoNext = IntArray(a.size)
val memoValue = LongArray(a.size)
fun solve(i: Int, next: Int): Long {
if (i == -1) return 0
if (memoNext[i] == next) return memoValue[i]
val countHere = (a[i] + next - 1) / next
val res = (i + 1L) * (countHere - 1) + solve(i - 1, a[i] / countHere)
memoNext[i] = next
memoValue[i] = res
return res
}
return a.indices.sumOf { solve(it - 1, a[it]) % M } % M
}
fun main() = repeat(readInt()) { println(solve()) }
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 760 | competitions | The Unlicense |
kotlin/src/katas/kotlin/leetcode/min_moves_to_obtain_string/MinMoves.kt | dkandalov | 2,517,870 | false | {"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221} | package katas.kotlin.leetcode.min_moves_to_obtain_string
import datsok.shouldEqual
import org.junit.jupiter.api.Test
/**
* https://leetcode.com/discuss/interview-question/398026
*
* You're given a string S consisting of N letters 'a' and/or 'b'.
* In one move, you can swap one letter for the other ('a' for 'b' or 'b' for 'a').
* Write a function that returns the minimum number moves required to obtain a string containing no instances of three identical consecutive letters.
* N is within the range [0..200_000].
*
* Examples
* 1. S = "baaaaa".
* Result is 1, because there is one move to "baabaa".
* 2. S = "baaabbaabbba".
* Result is 2, there four valid strings, e.g. "bbaabbaabbaa".
* 3. S = "bbaabab".
* Result is 0.
*/
class MinMoves {
@Test fun `it works`() {
movesCount("") shouldEqual 0
movesCount("a") shouldEqual 0
movesCount("b") shouldEqual 0
movesCount("aaa") shouldEqual 1
movesCount("baaaaa") shouldEqual 1
movesCount("baaabbaabbba") shouldEqual 2
movesCount("bbaabab") shouldEqual 0
}
private fun movesCount(s: String): Int {
var count = 0
var i = 0
while (i < s.length) {
val window = s.substring(i, minOf(i + 3, s.length))
if (window == "aaa" || window == "bbb") {
i += 3
count++
} else {
i += 1
}
}
return count
}
}
| 7 | Roff | 3 | 5 | 0f169804fae2984b1a78fc25da2d7157a8c7a7be | 1,464 | katas | The Unlicense |
Minimum_Operations_to_Reduce_X_to_Zero_v1.kt | xiekch | 166,329,519 | false | {"C++": 165148, "Java": 103273, "Kotlin": 97031, "Go": 40017, "Python": 22302, "TypeScript": 17514, "Swift": 6748, "Rust": 6579, "JavaScript": 4244, "Makefile": 349} | import java.util.*
import kotlin.collections.HashSet
// Time Limit Exceeded
class Node(val left: Int, val right: Int, val x: Int, val level: Int)
class Solution {
fun minOperations(nums: IntArray, x: Int): Int {
val queue = LinkedList<Node>()
val visited = HashSet<Pair<Int, Int>>()
queue.push(Node(0, nums.size - 1, x, 0))
while (!queue.isEmpty()) {
val node = queue.pollLast()
if (node.x == 0) return node.level
if (node.x < 0 || node.left > node.right) continue
if (!visited.contains(Pair(node.left + 1, node.right))) {
visited.add(Pair(node.left + 1, node.right))
queue.push(Node(node.left + 1, node.right, node.x - nums[node.left], node.level + 1))
}
if (!visited.contains(Pair(node.left, node.right - 1))) {
visited.add(Pair(node.left, node.right - 1))
queue.push(Node(node.left, node.right - 1, node.x - nums[node.right], node.level + 1))
}
}
return -1
}
}
class TestCase(val nums: IntArray, val x: Int)
fun main() {
val solution = Solution()
val testCases = arrayOf(TestCase(intArrayOf(1, 1, 4, 2, 3), 5),
TestCase(intArrayOf(5, 6, 7, 8, 9), 4), TestCase(intArrayOf(3, 2, 20, 1, 1, 3), 10),
TestCase(intArrayOf(5, 2, 3, 1, 1), 5))
for (case in testCases) {
println(solution.minOperations(case.nums, case.x))
}
} | 0 | C++ | 0 | 0 | eb5b6814e8ba0847f0b36aec9ab63bcf1bbbc134 | 1,474 | leetcode | MIT License |
src/main/kotlin/net/voldrich/aoc2022/Day04.kt | MavoCz | 434,703,997 | false | {"Kotlin": 119158} | package net.voldrich.aoc2022
import net.voldrich.BaseDay
// https://adventofcode.com/2022/day/4
fun main() {
Day04().run()
}
class Day04 : BaseDay() {
override fun task1() : Int {
return input.lines().map(::parse).map { (a,b) ->
contains(a, b) || contains(b, a)
}.map { if (it) 1 else 0 }.sum()
}
override fun task2() : Int {
return input.lines().map(::parse).sumOf { (a, b) ->
overlap(a, b)
}
}
// proposed by copilot (part_
private fun overlap(a: IntRange, b: IntRange): Int {
for (i in a) {
if (i in b) {
return 1
}
}
return 0
}
// proposed by copilot
private fun contains(range: IntRange, range2: IntRange): Boolean {
return range.first <= range2.first && range.last >= range2.last
}
private fun parse(line: String): Pair<IntRange, IntRange> {
val (a1, a2, b1, b2) = line.split(",", "-").map { it.toInt() }
return Pair(a1..a2, b1..b2)
}
}
| 0 | Kotlin | 0 | 0 | 0cedad1d393d9040c4cc9b50b120647884ea99d9 | 1,050 | advent-of-code | Apache License 2.0 |
src/main/kotlin/g1601_1700/s1659_maximize_grid_happiness/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1601_1700.s1659_maximize_grid_happiness
// #Hard #Dynamic_Programming #Bit_Manipulation #Bitmask #Memoization
// #2023_06_15_Time_181_ms_(100.00%)_Space_36.9_MB_(100.00%)
class Solution {
private var m = 0
private var n = 0
private lateinit var dp: Array<Array<Array<Array<IntArray>>>>
private val notPlace = 0
private val intro = 1
private val extro = 2
private var mod = 0
fun getMaxGridHappiness(m: Int, n: Int, introvertsCount: Int, extrovertsCount: Int): Int {
this.m = m
this.n = n
val numOfState = Math.pow(3.0, n.toDouble()).toInt()
dp = Array(m) {
Array(n) {
Array(introvertsCount + 1) {
Array(extrovertsCount + 1) { IntArray(numOfState) }
}
}
}
mod = numOfState / 3
return dfs(0, 0, introvertsCount, extrovertsCount, 0)
}
private fun dfs(x: Int, y: Int, ic: Int, ec: Int, state: Int): Int {
if (x == m) {
return 0
} else if (y == n) {
return dfs(x + 1, 0, ic, ec, state)
}
if (dp[x][y][ic][ec][state] != 0) {
return dp[x][y][ic][ec][state]
}
// 1 - not place
var max = dfs(x, y + 1, ic, ec, state % mod * 3)
val up = state / mod
val left = state % 3
// 2 - place intro
if (ic > 0) {
var temp = 120
if (x > 0 && up != notPlace) {
temp -= 30
temp += if (up == intro) -30 else 20
}
if (y > 0 && left != notPlace) {
temp -= 30
temp += if (left == intro) -30 else 20
}
var nextState = state
nextState %= mod
nextState *= 3
nextState += intro
max = Math.max(max, temp + dfs(x, y + 1, ic - 1, ec, nextState))
}
// 3 - place extro
if (ec > 0) {
var temp = 40
if (x > 0 && up != notPlace) {
temp += 20
temp += if (up == intro) -30 else 20
}
if (y > 0 && left != notPlace) {
temp += 20
temp += if (left == intro) -30 else 20
}
var nextState = state
nextState %= mod
nextState *= 3
nextState += extro
max = Math.max(max, temp + dfs(x, y + 1, ic, ec - 1, nextState))
}
dp[x][y][ic][ec][state] = max
return max
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 2,541 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/daythirteen/DayTHirteen.kt | pauliancu97 | 619,525,509 | false | null | package daythirteen
import getLines
private sealed class Token {
object LeftBracket : Token() {
const val CHAR = '['
}
object RightBracket : Token() {
const val CHAR = ']'
}
data class Number(val value: Int) : Token()
object Separator : Token() {
const val CHAR = ','
}
}
private sealed class Packet : Comparable<Packet> {
data class Number(val value: Int) : Packet()
data class PacketList(val list: List<Packet>) : Packet()
override fun compareTo(other: Packet): Int {
return when (getCompareResult(this, other)) {
CompareResult.Less -> -1
CompareResult.Equal -> 0
CompareResult.Greater -> 1
}
}
}
private enum class CompareResult {
Less,
Greater,
Equal
}
private fun getTokenizedString(string: String): List<Token> {
val tokens: MutableList<Token> = mutableListOf()
var currentString = string
while (currentString.isNotEmpty()) {
when (currentString.first()) {
Token.LeftBracket.CHAR -> {
tokens.add(Token.LeftBracket)
currentString = currentString.drop(1)
}
Token.RightBracket.CHAR -> {
tokens.add(Token.RightBracket)
currentString = currentString.drop(1)
}
Token.Separator.CHAR -> {
tokens.add(Token.Separator)
currentString = currentString.drop(1)
}
in '0'..'9' -> {
var index = 0
while (index < currentString.length && currentString[index].isDigit()) {
index++
}
val value = currentString.take(index).toInt()
tokens.add(Token.Number(value))
currentString = currentString.drop(index)
}
}
}
return tokens
}
private fun getParsedPacketElement(tokens: List<Token>): Pair<Packet, List<Token>> =
when (val token = tokens.firstOrNull()) {
is Token.Number -> Packet.Number(token.value) to tokens.drop(2)
Token.LeftBracket -> {
var index = 0
var depth = 0
while (index < tokens.size && (depth != 0 || index == 0)) {
when (tokens[index]) {
Token.LeftBracket -> depth++
Token.RightBracket -> depth--
else -> {}
}
index++
}
val packetListTokens = tokens.take(index)
val remainingTokens = if (index < tokens.size && tokens[index] == Token.Separator) {
tokens.drop(index + 1)
} else {
tokens.drop(index)
}
val packetList = getParsedPacket(packetListTokens)
packetList to remainingTokens
}
else -> error("Empty token string or invalid token")
}
private fun getParsedPacket(tokens: List<Token>): Packet {
var currentTokens = tokens.drop(1).dropLast(1)
val packets: MutableList<Packet> = mutableListOf()
while (currentTokens.isNotEmpty()) {
val (packet, remainingTokens) = getParsedPacketElement(currentTokens)
packets.add(packet)
currentTokens = remainingTokens
}
return Packet.PacketList(packets)
}
private fun String.toPacket(): Packet {
val tokenized = getTokenizedString(this)
return getParsedPacket(tokenized)
}
private fun getCompareResult(first: Int, second: Int): CompareResult =
when {
first < second -> CompareResult.Less
first > second -> CompareResult.Greater
else -> CompareResult.Equal
}
private fun getCompareResult(first: Packet, second: Packet): CompareResult =
when (first) {
is Packet.Number -> when (second) {
is Packet.Number -> getCompareResult(first.value, second.value)
is Packet.PacketList -> {
val firstList = Packet.PacketList(list = listOf(Packet.Number(first.value)))
getCompareResult(firstList, second)
}
}
is Packet.PacketList -> when (second) {
is Packet.Number -> {
val secondList = Packet.PacketList(list = listOf(Packet.Number(second.value)))
getCompareResult(first, secondList)
}
is Packet.PacketList -> {
when {
first.list.isEmpty() && second.list.isEmpty() -> CompareResult.Equal
first.list.isEmpty() -> CompareResult.Less
second.list.isEmpty() -> CompareResult.Greater
else -> {
val firstElement = first.list.first()
val secondElement = second.list.first()
val compareResult = getCompareResult(firstElement, secondElement)
if (compareResult == CompareResult.Equal) {
val remainingFirst = Packet.PacketList(list = first.list.drop(1))
val remainingSecond = Packet.PacketList(list = second.list.drop(1))
getCompareResult(remainingFirst, remainingSecond)
} else {
compareResult
}
}
}
}
}
}
private fun getPacketPairs(path: String): List<Pair<Packet, Packet>> {
val strings = getLines(path)
val numOfPacketPairs = (strings.size + 1) / 3
return (0 until numOfPacketPairs)
.map { index ->
val firstString = strings[3 * index]
val secondString = strings[3 * index + 1]
val firstPacket = firstString.toPacket()
val secondPacket = secondString.toPacket()
firstPacket to secondPacket
}
}
private fun getOrderedPairsIndexSum(packetPairs: List<Pair<Packet, Packet>>): Int =
packetPairs.withIndex()
.filter { (_, packetPair) ->
val (firstPacket, secondPacket) = packetPair
getCompareResult(firstPacket, secondPacket) == CompareResult.Less
}
.sumOf { (index, _) -> index + 1 }
private fun solvePartOne() {
val packetPairs = getPacketPairs("day_13.txt")
val answer = getOrderedPairsIndexSum(packetPairs)
println(answer)
}
private fun solvePartTwo() {
val packetPairs = getPacketPairs("day_13.txt")
val firstDividerPacket = "[[2]]".toPacket()
val secondDividerPacket = "[[6]]".toPacket()
val packets = packetPairs.flatMap { (first, second) -> listOf(first, second) } +
listOf(firstDividerPacket, secondDividerPacket)
val sortedPackets = packets.sorted()
val firstIndex = sortedPackets.indexOf(firstDividerPacket) + 1
val secondIndex = sortedPackets.indexOf(secondDividerPacket) + 1
val answer = firstIndex * secondIndex
println(answer)
}
fun main() {
//solvePartOne()
solvePartTwo()
} | 0 | Kotlin | 0 | 0 | 78af929252f094a34fe7989984a30724fdb81498 | 6,956 | advent-of-code-2022 | MIT License |
src/test/kotlin/Day18.kt | FredrikFolkesson | 320,692,155 | false | null | import Day18.Operator.*
import org.junit.jupiter.api.Test
import java.lang.IllegalArgumentException
import kotlin.test.assertEquals
class Day18 {
@Test
fun `test demo input`() {
println(evaluateExpressionAdditionPrecidence("((2 + 4 * 9) * (6 + 9 * 8 + 6) + 6) + 2 + 4 * 2"))
}
enum class Operator {
Addition, Multiplication;
}
@Test
fun `real data`() {
println(readFileAsLinesUsingUseLines("/Users/fredrikfolkesson/git/advent-of-code/inputs/input-day18.txt").map {
evaluateExpressionAdditionPrecidence(
it
)
}.sumOf { it.first })
}
@Test
fun `test operator`() {
assertEquals(21, operate(Multiplication, 7, 3))
assertEquals(10, operate(Addition, 7, 3))
}
private fun operate(operator: Operator?, paramOne: Long, paramTwo: Long): Long {
return when (operator) {
Addition -> paramOne + paramTwo
Multiplication -> paramOne * paramTwo
else -> throw IllegalArgumentException("No operator!")
}
}
private fun evaluateExpressionLeftToRight(expressionString: String): Pair<Long, Long> {
val spaceRemovedExpressionString = expressionString.replace(" ", "")
return Pair(
spaceRemovedExpressionString.foldIndexed(
Triple<Long, Operator?, Long>(
0,
null,
0
)
) { index, (acc, operator, skips), c ->
if (skips > 0L) {
Triple(acc, operator, skips - 1)
} else {
when (c) {
'+' -> Triple(acc, Addition, 0L)
'*' -> Triple(acc, Multiplication, 0L)
'(' -> {
val (valueOfExpressionInParanthesis, skips) = evaluateExpressionLeftToRight(
spaceRemovedExpressionString.substring(
index + 1
)
)
if (operator == null) Triple(valueOfExpressionInParanthesis, null, skips) else Triple(
operate(
operator,
acc,
valueOfExpressionInParanthesis
), null, skips
)
}
')' -> return Pair(acc, index + 1L)
else -> {
//Handle that the numbers might now be more than one digits since I reuse this one for part two multiplication when I handled the addition
val restOfString = spaceRemovedExpressionString.substring(index)
val newNumber = restOfString.substringBefore("*").substringBefore("+")
val newNumberLong = newNumber.toLong()
if (operator == null) Triple(newNumberLong, null, newNumber.length - 1L) else Triple(
operate(
operator,
acc,
newNumberLong
), null, newNumber.length - 1L
)
}
}
}
}.first, 0L
)
}
private fun evaluateExpressionAdditionPrecidence(expressionString: String): Pair<Long, Long> {
val spaceRemovedExpressionString = expressionString.replace(" ", "")
// First only do the additions
val firstPass =
spaceRemovedExpressionString.foldIndexed(
Quadruple<Long, Operator?, Long, String>(
0,
null,
0,
""
)
) { index, (acc, operator, skips, stringForSecondPass), c ->
if (skips != 0L) {
Quadruple(acc, operator, skips - 1, stringForSecondPass)
} else {
when (c) {
'+' -> Quadruple(acc, Addition, 0L, stringForSecondPass)
// Multiplication we handle on the secondpass, so build up the string for that, which is what we have before, what we have added an the multiplication sign
'*' -> Quadruple(0, null, 0L, stringForSecondPass + acc.toString() + "*")
'(' -> {
val (valueOfExpressionInParanthesis, skips) = evaluateExpressionAdditionPrecidence(
spaceRemovedExpressionString.substring(
index + 1
)
)
if (operator == null) Quadruple(
valueOfExpressionInParanthesis,
null,
skips,
stringForSecondPass
) else Quadruple(
operate(
operator,
acc,
valueOfExpressionInParanthesis
), null, skips, stringForSecondPass
)
}
')' -> return Pair(
evaluateExpressionLeftToRight(stringForSecondPass + acc.toString()).first,
index + 1L
)
else -> if (operator == null) Quadruple(
c.toString().toLong(),
null,
0,
stringForSecondPass
) else Quadruple(
operate(
operator,
acc,
c.toString().toLong()
), null, 0, stringForSecondPass
)
}
}
}
val stringForSecondPas = firstPass.fourth + firstPass.first.toString()
val afterSecondPass = evaluateExpressionLeftToRight(stringForSecondPas)
return Pair(afterSecondPass.first, 0L)
}
}
| 0 | Kotlin | 0 | 0 | 79a67f88e1fcf950e77459a4f3343353cfc1d48a | 6,552 | advent-of-code | MIT License |
plot-base-portable/src/commonMain/kotlin/jetbrains/datalore/plot/base/stat/regression/RegressionUtil.kt | randomnetcat | 476,483,866 | true | {"Kotlin": 5699185, "Python": 781105, "C": 2832, "CSS": 1923, "Shell": 1759, "JavaScript": 1121} | /*
* Copyright (c) 2019. JetBrains s.r.o.
* Use of this source code is governed by the MIT license that can be found in the LICENSE file.
*/
package jetbrains.datalore.plot.base.stat.regression
import jetbrains.datalore.plot.base.stat.math3.Percentile
import jetbrains.datalore.plot.common.data.SeriesUtil
import kotlin.random.Random
internal object RegressionUtil {
// sample m data randomly
fun <T> sampling(data: List<T>, m: Int): ArrayList<T> {
val index = sampleInt(data.size, m)
val result = ArrayList<T>()
for (i in index) {
result.add(data[i])
}
return result
}
// sample m int from 0..n-1
private fun sampleInt(n: Int, m: Int): IntArray {
if (n < m || m < 0) {
error("Sample $m data from $n data is impossible!")
}
val perm = IntArray(n)
for (i in 0 until n) {
perm[i] = i
}
val result = IntArray(m)
for (j in 0 until m) {
val r = j + (Random.nextDouble() * (n - j)).toInt()
result[j] = perm[r]
perm[r] = perm[j]
}
return result
}
fun percentile(data: List<Double>, p: Double): Double {
return Percentile.evaluate(data.toDoubleArray(), p * 100)
}
}
fun allFinite(xs: List<Double?>, ys: List<Double?>): Pair<DoubleArray, DoubleArray> {
val tx = ArrayList<Double>()
val ty = ArrayList<Double>()
for ((x, y) in xs.asSequence().zip(ys.asSequence())) {
if (SeriesUtil.allFinite(x, y)) {
tx.add(x!!)
ty.add(y!!)
}
}
return Pair(tx.toDoubleArray(), ty.toDoubleArray())
}
private fun finitePairs(xs: List<Double?>, ys: List<Double?>): ArrayList<Pair<Double, Double>> {
val res = ArrayList<Pair<Double, Double>>()
for ((x, y) in xs.asSequence().zip(ys.asSequence())) {
if (SeriesUtil.allFinite(x, y)) {
res.add(Pair(x!!, y!!))
}
}
return res
}
private fun averageByX(lst: List<Pair<Double, Double>>): Pair<List<Double>, List<Double>> {
if (lst.isEmpty())
return Pair(ArrayList<Double>(), ArrayList<Double>())
val tx = ArrayList<Double>()
val ty = ArrayList<Double>()
var (prevX, sumY) = lst.first()
var countY = 1
for ((x, y) in lst.asSequence().drop(1)) {
if (x == prevX) {
sumY += y
++countY
} else {
tx.add(prevX)
ty.add(sumY.div(countY))
prevX = x
sumY = y
countY = 1
}
}
tx.add(prevX)
ty.add(sumY.div(countY))
return Pair(tx, ty)
}
fun averageByX(xs: List<Double?>, ys: List<Double?>): Pair<DoubleArray, DoubleArray> {
val tp = finitePairs(xs, ys)
tp.sortBy { it.first }
val res = averageByX(tp)
return Pair(res.first.toDoubleArray(), res.second.toDoubleArray())
}
| 1 | Kotlin | 1 | 0 | fe960f43d39844d04a89bd12490cd2dd4dbeaa51 | 2,893 | lets-plot | MIT License |
q2/question2.kt | engividal | 254,778,920 | false | null | // 2. Check words with jumbled letters :
// Our brain can read texts even if letters are jumbled, like the following sentence: “Yuo
// cna porbalby raed tihs esaliy desptie teh msispeillgns.” Given two strings, write a
// method to decide if one is a partialpermutation of the other. Consider a
// partialpermutation only if:
// The first letter hasn’t changed place
// If word has more than 3 letters, up to 2/3 of the letters have changed place
// Examples:
// you, yuo > true
// probably, porbalby > true
// despite, desptie > true
// moon, nmoo > false
// misspellings, mpeissngslli > false
fun main(args: Array<String>) {
println(partialPermutation("you", "yuo"))
println(partialPermutation("probably", "porbalby"))
println(partialPermutation("despite", "desptie"))
println(partialPermutation("moon", "nmoo"))
println(partialPermutation("misspellings", "mpeissngslli"))
}
fun partialPermutation(source: String, dest: String): Boolean{
// The first letter hasn’t changed place
if(source[0] != dest[0]){
return false
}
// If the size of the arrays are different
if(source.length != dest.length){
return false
}
var jumbled = 0
for ((index, value) in source.withIndex()){
val indexDest = dest.indexOf(value)
if ( indexDest != index ){
jumbled ++
}
// If the character does not exist
if ( indexDest == -1 ){
return false
}
}
// If word has more than 3 letters, up to 2/3 of the letters have changed place
val len = source.length
if (len > 3){
if(jumbled > (len * 2/3)){
return false
}else{
return true
}
} else {
return jumbled > 0
}
}
| 0 | Kotlin | 0 | 0 | 930a76acd5e87c7083785772762be829b92bb917 | 1,795 | code-challenge | MIT License |
src/main/kotlin/com/eric/leetcode/MinimumPathSum.kt | wanglikun7342 | 163,727,208 | false | {"Kotlin": 172132, "Java": 27019} | package com.eric.leetcode
class MinimumPathSum {
fun minPathSum(grid: Array<IntArray>): Int {
val dp = Array(grid.size) { Array(grid[0].size) { 0 } }
for (i in grid.indices) {
for (j in grid[0].indices) {
if (i == 0 && j == 0) {
dp[0][0] = grid[0][0]
} else if (i == 0) {
dp[0][j] = dp[0][j - 1] + grid[i][j]
} else if (j == 0) {
dp[i][0] = dp[i - 1][0] + grid[i][j]
} else {
dp[i][j] = minOf(dp[i - 1][j] + grid[i][j], dp[i][j - 1] + grid[i][j])
}
}
}
return dp[dp.lastIndex][dp[0].lastIndex]
}
}
fun main(args: Array<String>) {
val input = arrayOf(intArrayOf(1, 3, 1), intArrayOf(1, 5, 1), intArrayOf(4, 2, 1))
val minimumPathSum = MinimumPathSum()
println(minimumPathSum.minPathSum(input))
} | 0 | Kotlin | 2 | 8 | d7fb5ff5a0a64d9ce0a5ecaed34c0400e7c2c89c | 932 | Leetcode-Kotlin | Apache License 2.0 |
src/main/kotlin/day4.kt | bfrengley | 318,716,410 | false | null | package aoc2020.day4
import aoc2020.util.asBlocks
import aoc2020.util.loadTextResource
data class Passport(
val byr: String,
val iyr: String,
val eyr: String,
val hgt: String,
val hcl: String,
val ecl: String,
val pid: String,
val cid: String?,
) {
companion object {
// is this too :galaxybrain:
// idk if this duplication is actually worth it but hey, it handles existence checks
private fun from(map: Map<String, String>) = object {
val byr by map
val iyr by map
val eyr by map
val hgt by map
val hcl by map
val ecl by map
val pid by map
val cid = map["cid"]
val data = Passport(byr, iyr, eyr, hgt, hcl, ecl, pid, cid)
}.data
fun tryFrom(map: Map<String, String>) = try {
from(map)
} catch (_: NoSuchElementException) {
null
}
}
fun validate(): Boolean {
try {
val datesValid = this.byr.length == 4 && this.byr.toInt() in 1920..2002 &&
this.iyr.length == 4 && this.iyr.toInt() in 2010..2020 &&
this.eyr.length == 4 && this.eyr.toInt() in 2020..2030
val height = this.hgt.takeWhile { it.isDigit() }.toInt()
val heightType = this.hgt.dropWhile { it.isDigit() }
val heightValid = when (heightType) {
"cm" -> height in 150..193
"in" -> height in 59..76
else -> false
}
val hairValid = this.hcl[0] == '#' &&
this.hcl.substring(1).all { it in '0'..'9' || it in 'a'..'f' }
val eyesValid = this.ecl in setOf("amb", "blu", "brn", "gry", "grn", "hzl", "oth")
val pidValid = this.pid.length == 9 && this.pid.all { it.isDigit() }
return datesValid && heightValid && hairValid && eyesValid && pidValid
} catch (_: NumberFormatException) {
return false
}
}
}
fun main(args: Array<String>) {
val lines = loadTextResource("/day4.txt").lines()
print("Part 1: ")
val passports = loadPassports(lines)
println(passports.size)
print("Part 2: ")
println(passports.filter { it.validate() }.size)
}
fun loadPassports(lines: List<String>) =
lines.asBlocks().mapNotNull { block -> parsePassport(block.flatMap { it.split(' ') }) }
fun parsePassport(fields: List<String>) = Passport.tryFrom(
fields
.map { it.split(':') }
.associate { (k, v) -> Pair(k, v) }
)
| 0 | Kotlin | 0 | 0 | 088628f585dc3315e51e6a671a7e662d4cb81af6 | 2,585 | aoc2020 | ISC License |
kotlin/src/main/kotlin/be/swsb/aoc2023/day10/PipeMap.kt | Sch3lp | 724,797,927 | false | {"Kotlin": 44815, "Rust": 14075} | package be.swsb.aoc2023.day10
import be.swsb.aoc2023.Debugging.debug
import be.swsb.aoc2023.Point
import be.swsb.aoc2023.Point.Companion.at
fun solve1(input: String) = PipeMap.fromString(input).countSegments() / 2
fun solve2(input: String) = PipeMap.fromString(input).enhance().containedPoints().size
data class PipeMap(private val points: Map<Point, TilePoint>) {
private val startingPoint = points.values.first { tilePoint -> tilePoint.tile == Start }
private val maxX = points.keys.maxBy { it.x }.x
private val maxY = points.keys.maxBy { it.y }.y
fun countSegments(): Int = pipelinePoints.size
private val pipelinePoints by lazy {
val segments = mutableSetOf(startingPoint)
var (previousSegment, currentSegment) = startingPoint to findStartPipeOptions(startingPoint).first
while (currentSegment != startingPoint) {
segments.add(currentSegment)
val (prev, cur) = currentSegment.follow(previousSegment)
.let { (prev, nextPoint) -> prev to points.getValue(nextPoint) }
previousSegment = prev
currentSegment = cur
}
segments.map { it.point }.toSet()
}
private fun findStartPipeOptions(startPoint: TilePoint): Pair<TilePoint, TilePoint> {
val (top, left, right, bottom) = startPoint.point.orthogonalNeighbours.map { points.get(it) }
val options = mutableListOf(
top?.keepIfInOrNull(VePipe, SEBend, SWBend),
bottom?.keepIfInOrNull(VePipe, NEBend, NWBend),
left?.keepIfInOrNull(HoPipe, SEBend, NEBend),
right?.keepIfInOrNull(HoPipe, NWBend, SWBend),
).filterNotNull()
require(options.size == 2) { "Start does not have exactly 2 connecting tiles, impossible to have a loop." }
return options.let { (first, second) -> first to second }
.debug { "Found start connectors: ${it.first} and ${it.second}" }
}
private fun TilePoint.keepIfInOrNull(vararg tiles: Tile) = if (tile in tiles) this else null
fun enhance(): PipeMap =
copy(points = points.mapValues { (k, v) ->
if (k in pipelinePoints) v
else TilePoint(k, Ground)
})
fun containedPoints(): Set<Point> =
(-1..maxY + 1).flatMap { y ->
(-1..maxX + 1).map { x -> at(x, y) }.windowed(3).fold(TraceAccumulator()) { acc, points ->
val left = points.getOrNull(0)
val tracePoint = points.getOrNull(1)
val right = points.getOrNull(2)
val (intersections, containedPoints) = acc
debug { "checking for intersection at $tracePoint" }
val newIntersections =
if (left !in pipelinePoints && tracePoint in pipelinePoints && right !in pipelinePoints) intersections + tracePoint else intersections
val newContainedPoints =
if (newIntersections.size % 2 == 1) containedPoints + tracePoint else containedPoints
debug { "intersections up until now: $newIntersections" }
debug { "containedPoints up until now: ${newContainedPoints - pipelinePoints}" }
TraceAccumulator(newIntersections.filterNotNull().toSet(), newContainedPoints.filterNotNull().toSet())
}.containedPoints - pipelinePoints
}.toSet()
private data class TraceAccumulator(
val intersections: Set<Point> = emptySet(),
val containedPoints: Set<Point> = emptySet()
)
companion object {
fun fromString(input: String) = PipeMap(
input.lines().flatMapIndexed { y, line ->
line.mapIndexed { x, c ->
TilePoint(Point(x, y), Tile.of(c))
}
}.associateBy(TilePoint::point)
)
}
}
data class TilePoint(val point: Point, val tile: Tile) {
fun follow(previousSegment: TilePoint): Pair<TilePoint, Point> =
this to tile.follow(point, previousSegment.point)
}
sealed class Tile(val icon: Char) {
fun follow(from: Point, previous: Point): Point = connectors(from).other(previous)
abstract fun connectors(from: Point): Pair<Point, Point>
private fun Pair<Point, Point>.other(point: Point): Point = when (point) {
this.first -> this.second
this.second -> this.first
else -> error("$this does not contain $point, so .other cannot be returned")
}
companion object {
fun of(char: Char) = when (char) {
'.' -> Ground
'|' -> VePipe
'-' -> HoPipe
'L' -> NEBend
'J' -> NWBend
'7' -> SWBend
'F' -> SEBend
'S' -> Start
else -> error("Unknown symbol: $char")
}
}
}
data object Ground : Tile('.') {
override fun connectors(from: Point) = from to from
}
data object VePipe : Tile('|') {
override fun connectors(from: Point) = from.plus(Point.at(0, 1)) to from.plus(Point.at(0, -1))
}
data object HoPipe : Tile('-') {
override fun connectors(from: Point) = from.plus(Point.at(1, 0)) to from.plus(Point.at(-1, 0))
}
data object NEBend : Tile('L') {
override fun connectors(from: Point) = from.plus(Point.at(0, -1)) to from.plus(Point.at(1, 0))
}
data object NWBend : Tile('J') {
override fun connectors(from: Point) = from.plus(Point.at(-1, 0)) to from.plus(Point.at(0, -1))
}
data object SWBend : Tile('7') {
override fun connectors(from: Point) = from.plus(Point.at(-1, 0)) to from.plus(Point.at(0, 1))
}
data object SEBend : Tile('F') {
override fun connectors(from: Point) = from.plus(Point.at(1, 0)) to from.plus(Point.at(0, 1))
}
data object Start : Tile('S') {
override fun connectors(from: Point) = from.plus(Point.at(0, 1)) to from.plus(Point.at(0, -1))
} | 0 | Kotlin | 0 | 1 | dec9331d3c0976b4de09ce16fb8f3462e6f54f6e | 5,808 | Advent-of-Code-2023 | MIT License |
2021/src/day16/day16.kt | scrubskip | 160,313,272 | false | {"Kotlin": 198319, "Python": 114888, "Dart": 86314} | package day16
import java.io.File
fun main() {
val input = File("src/day16", "day16input.txt").readLines().first()
val packet = parsePacket(input)
println(packet.getVersionSum())
println(packet.getValue())
}
fun String.toBinaryString(): String {
return this.toCharArray().joinToString("", "", "") {
it.digitToInt(radix = 16).toString(radix = 2)
.padStart(4, '0')
}
}
fun String.fromBinary(): Int {
return this.toInt(2)
}
fun String.fromBinaryLong(): Long {
return this.toLong(2)
}
fun parsePacket(hexString: String): Packet {
return parsePacketWithChildren(hexString.toBinaryString(), 0).first
}
/**
* Parses a packet from the startIndex
* @return Pair of the packet at the startIndex and the number of characters consumed
*/
fun parsePacketWithChildren(binaryString: String, startIndex: Int): Pair<Packet, Int> {
var index = startIndex
val packet = Packet(
binaryString.substring(index, index + 3).fromBinary(),
binaryString.substring(index + 3, index + 6).fromBinary()
)
index += 6
if (packet.isLiteral()) {
// parse groups
val numberList = mutableListOf<String>()
while (true) {
numberList.add(binaryString.substring(index + 1, index + 5))
if (binaryString[index] == '0') {
break
}
index += 5
}
index += 5
packet.setNumber(numberList.joinToString(separator = "", postfix = "").fromBinaryLong())
} else {
// set the length type id
packet.setLengthTypeId(binaryString.substring(index, index + 1).fromBinary())
index += 1
val length = if (packet.getLengthTypeId() == 0) 15 else 11
val lengthPackets = binaryString.substring(index, index + length).fromBinary()
index += length
val endIndex = if (packet.getLengthTypeId() == 0) index + lengthPackets else lengthPackets
var counter = if (packet.getLengthTypeId() == 0) index else 0
while (counter < endIndex) {
with(parsePacketWithChildren(binaryString, index)) {
packet.addPacket(first)
index = second
counter = if (packet.getLengthTypeId() == 0) index else counter + 1
}
}
}
return Pair(packet, index)
}
class Packet(val versionCode: Int, val typeId: Int) : Collection<Packet> {
private val childPackets = mutableListOf<Packet>()
private var number: Long = 0L
private var lengthTypeId: Int = 0
fun addPacket(packet: Packet) {
childPackets.add(packet)
}
fun isLiteral(): Boolean {
return typeId == 4
}
fun setNumber(newNumber: Long) {
require(isLiteral())
number = newNumber
}
fun getNumber(): Long {
return number
}
fun getValue(): Long {
return when (typeId) {
0 -> sumOf { it.getValue() }
1 -> fold(1) { acc, packet -> acc * packet.getValue() }
2 -> minOf { it.getValue() }
3 -> maxOf { it.getValue() }
4 -> number
5 -> if (get(0).getValue() > get(1).getValue()) 1 else 0
6 -> if (get(0).getValue() < get(1).getValue()) 1 else 0
7 -> if (get(0).getValue() == get(1).getValue()) 1 else 0
else -> throw Exception("Unknown type id $typeId")
}
}
fun setLengthTypeId(value: Int) {
lengthTypeId = value
}
fun getLengthTypeId(): Int {
return lengthTypeId
}
fun getVersionSum(): Int {
return versionCode + childPackets.sumOf { it.getVersionSum() }
}
override val size: Int
get() = childPackets.size
override fun contains(element: Packet): Boolean {
return childPackets.contains(element)
}
override fun containsAll(elements: Collection<Packet>): Boolean {
return childPackets.containsAll(elements)
}
override fun isEmpty(): Boolean {
return childPackets.isEmpty()
}
override fun iterator(): Iterator<Packet> {
return childPackets.iterator()
}
operator fun get(index: Int): Packet {
return childPackets[index]
}
} | 0 | Kotlin | 0 | 0 | a5b7f69b43ad02b9356d19c15ce478866e6c38a1 | 4,207 | adventofcode | Apache License 2.0 |
src/main/kotlin/d5/d5.kt | LaurentJeanpierre1 | 573,454,829 | false | {"Kotlin": 118105} | package d5
import readInput
import java.util.Scanner
import java.util.Stack
fun part1(input: List<String>): String {
val (stacks, lineIte) = readStacks(input)
while (lineIte.hasNext()) {
val scanner = Scanner(lineIte.next())
scanner.next() // move
val qte = scanner.nextInt()
scanner.next() // from
val start = scanner.nextInt() - 1
scanner.next() // to
val end = scanner.nextInt() - 1
repeat (qte) {
stacks[end].push(stacks[start].pop())
}
}
val res = StringBuffer()
for (stack in stacks)
res.append(stack.peek())
return res.toString()
}
private fun readStacks(input: List<String>): Pair<MutableList<Stack<Char>>, Iterator<String>> {
val stacks = mutableListOf<Stack<Char>>()
val lineIte = input.iterator()
do {
val line = lineIte.next()
if (line.isNotBlank()) {
for (varIdx in 1 until line.length step 4) { // ^] [^
while (stacks.size <= varIdx / 4)
stacks.add(Stack())
if (line[varIdx] != ' ')
stacks[varIdx / 4].push(line[varIdx])
}
}
} while (line.isNotBlank())
for (stack in stacks) {
stack.pop() // remove stack index
stack.reverse() // upside down
}
return Pair(stacks, lineIte)
}
fun part2(input: List<String>): String {
val (stacks, lineIte) = readStacks(input)
while (lineIte.hasNext()) {
val scanner = Scanner(lineIte.next())
scanner.next() // move
val qte = scanner.nextInt()
scanner.next() // from
val start = scanner.nextInt() - 1
scanner.next() // to
val end = scanner.nextInt() - 1
val tmp = Stack<Char>()
repeat (qte) {
tmp.push(stacks[start].pop())
}
repeat (qte) {
stacks[end].push(tmp.pop())
}
}
val res = StringBuffer()
for (stack in stacks)
res.append(stack.peek())
return res.toString()
}
fun main() {
//val input = readInput("d5/test")
val input = readInput("d5/input1")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 5cf6b2142df6082ddd7d94f2dbde037f1fe0508f | 2,204 | aoc2022 | Creative Commons Zero v1.0 Universal |
src/chapter5/section3/ex32_UniqueSubstrings.kt | w1374720640 | 265,536,015 | false | {"Kotlin": 1373556} | package chapter5.section3
import chapter3.section5.LinearProbingHashSET
import edu.princeton.cs.algs4.Queue
import java.math.BigInteger
import java.util.*
/**
* 不同的子字符串
* 使用Rabin-Karp算法的思想完成练习5.2.14
*
* 解:5.2.14中使用了一个字符串符号表存储子字符串,这里使用存储子字符串hash值的符号表判断
*/
fun ex32_UniqueSubstrings(string: String, L: Int): Iterable<String> {
require(L > 0 && L <= string.length)
val Q = BigInteger.probablePrime(31, Random()).longValueExact()
val R = 65536
var RM = 1L
repeat(L - 1) {
RM = (RM * R) % Q
}
val set = LinearProbingHashSET<Long>()
val queue = Queue<String>()
var hash = 0L
repeat(L) {
hash = (hash * R + string[it].toLong()) % Q
}
set.add(hash)
queue.enqueue(string.substring(0, L))
for (i in 1 until string.length - L) {
hash = (hash + Q - (RM * string[i - 1].toLong()) % Q) % Q
hash = (hash * R + string[i + L - 1].toLong()) % Q
if (!set.contains(hash)) {
queue.enqueue(string.substring(i, i + L))
set.add(hash)
}
}
return queue
}
fun main() {
val string = "cgcgggcgcg"
val L = 3
println(ex32_UniqueSubstrings(string, L).joinToString())
}
| 0 | Kotlin | 1 | 6 | 879885b82ef51d58efe578c9391f04bc54c2531d | 1,307 | Algorithms-4th-Edition-in-Kotlin | MIT License |
2015/src/main/kotlin/day7_func.kt | madisp | 434,510,913 | false | {"Kotlin": 388138} | import utils.Parser
import utils.Solution
import utils.cut
import utils.mapItems
fun main() {
Day7Func.run()
}
object Day7Func : Solution<List<Day7Func.Opcode>>() {
override val name = "day7"
override val parser = Parser.lines.mapItems(Opcode::parse)
private fun value(name: String, ops: Map<String, Opcode>, cache: Map<String, Int>): Pair<Map<String, Int>, Int> {
if (name.first().isDigit()) {
return cache to name.toInt()
}
val cached = cache[name]
if (cached != null) {
return cache to cached
}
val (newCache, value) = ops[name]!!.get(ops, cache)
return (newCache + (name to value)) to value
}
sealed class Opcode(open val dst: String) {
abstract fun get(ops: Map<String, Opcode>, cache: Map<String, Int>): Pair<Map<String, Int>, Int>
data class Assign(val src: String, override val dst: String) : Opcode(dst) {
override fun get(ops: Map<String, Opcode>, cache: Map<String, Int>): Pair<Map<String, Int>, Int> {
return value(src, ops, cache)
}
}
data class And(val l: String, val r: String, override val dst: String) : Opcode(dst) {
override fun get(ops: Map<String, Opcode>, cache: Map<String, Int>): Pair<Map<String, Int>, Int> {
val (lcache, lval) = value(l, ops, cache)
val (rcache, rval) = value(r, ops, lcache)
return rcache to (lval and rval)
}
}
data class Or(val l: String, val r: String, override val dst: String) : Opcode(dst) {
override fun get(ops: Map<String, Opcode>, cache: Map<String, Int>): Pair<Map<String, Int>, Int> {
val (lcache, lval) = value(l, ops, cache)
val (rcache, rval) = value(r, ops, lcache)
return rcache to (lval or rval)
}
}
data class Not(val src: String, override val dst: String) : Opcode(dst) {
override fun get(ops: Map<String, Opcode>, cache: Map<String, Int>): Pair<Map<String, Int>, Int> {
val (ncache, nval) = value(src, ops, cache)
return ncache to nval.inv()
}
}
data class Lshift(val src: String, val n: Int, override val dst: String) : Opcode(dst) {
override fun get(ops: Map<String, Opcode>, cache: Map<String, Int>): Pair<Map<String, Int>, Int> {
val (ncache, nval) = value(src, ops, cache)
return ncache to (nval shl n)
}
}
data class Rshift(val src: String, val n: Int, override val dst: String) : Opcode(dst) {
override fun get(ops: Map<String, Opcode>, cache: Map<String, Int>): Pair<Map<String, Int>, Int> {
val (ncache, nval) = value(src, ops, cache)
return ncache to (nval ushr n)
}
}
companion object {
fun parse(line: String): Opcode {
val (expr, dst) = line.cut(" -> ")
if (expr.startsWith("NOT")) {
return Not(expr.removePrefix("NOT").trim(), dst)
}
if ("AND" in expr) {
val (l, r) = expr.cut(" AND ")
return And(l, r, dst)
}
if ("OR" in expr) {
val (l, r) = expr.cut(" OR ")
return Or(l, r, dst)
}
if ("LSHIFT" in expr) {
val (l, n) = expr.cut(" LSHIFT ")
return Lshift(l, n.toInt(), dst)
}
if ("RSHIFT" in expr) {
val (l, n) = expr.cut(" RSHIFT ")
return Rshift(l, n.toInt(), dst)
}
return Assign(expr, dst)
}
}
}
override fun part1(input: List<Opcode>): Int {
val ops = input.groupBy { it.dst }.mapValues { it.value.first() }
return value("a", ops, emptyMap()).second
}
override fun part2(input: List<Opcode>): Int {
val ops = input.groupBy { it.dst }.mapValues { it.value.first() }
val a = value("a", ops, emptyMap()).second
return value("a", ops + ("b" to Opcode.Assign(a.toString(), "b")), emptyMap()).second
}
}
| 0 | Kotlin | 0 | 1 | 3f106415eeded3abd0fb60bed64fb77b4ab87d76 | 3,813 | aoc_kotlin | MIT License |
src/day12/Code.kt | fcolasuonno | 162,470,286 | false | null | package day12
import java.io.File
fun main(args: Array<String>) {
val name = if (false) "test.txt" else "input.txt"
val dir = ::main::class.java.`package`.name
val input = File("src/$dir/$name").readLines()
val parsed = parse(input)
println("Part 1 = ${part1(parsed)}")
println("Part 2 = ${part2(parsed)}")
}
interface JSON {
fun flatten(filtered: Boolean): List<JSON> =
listOf(this) + children?.flatMap { it.flatten(filtered) }.orEmpty()
val children: List<JSON>? get() = null
val start: Int
var end: Int
}
data class JSONNumber(val string: List<Char>, override val start: Int = 0, override var end: Int = start) : JSON {
val value: Int
init {
var index = start
while (string[index] in '0'..'9' || string[index] == '-') index++
end = index
value = string.subList(start, end).joinToString(separator = "").toInt()
}
}
data class JSONString(val string: List<Char>, override val start: Int = 0, override var end: Int = start) : JSON {
val value: String
init {
var index = start + 1
while (string[index] != '"') index++
end = index + 1
value = string.subList(start + 1, end - 1).joinToString(separator = "")
}
}
data class JSONArray(val string: List<Char>, override val start: Int = 0, override var end: Int = start) : JSON {
override val children = mutableListOf<JSON>()
init {
var index = start + 1
while (string[index] != ']') {
if (string[index] == ',') index++
children.add(when (string[index]) {
'[' -> JSONArray(string, index)
'{' -> JSONObject(string, index)
'-' -> JSONNumber(string, index)
in ('0'..'9') -> JSONNumber(string, index)
'"' -> JSONString(string, index)
else -> throw IllegalArgumentException()
}.also { index = it.end })
}
end = index + 1
}
}
data class JSONObject(val string: List<Char>, override val start: Int = 0, override var end: Int = start) : JSON {
private val map = mutableMapOf<JSONString, JSON>()
override fun flatten(filtered: Boolean) =
if (filtered && map.values.any { it is JSONString && it.value == "red" }) emptyList() else super.flatten(
filtered
)
override val children get() = map.values.toList()
init {
var index = start + 1
while (string[index] != '}') {
if (string[index] == ',') index++
val key = JSONString(string, index).also { index = it.end }
if (string[index] == ':') index++
val value = when (string[index]) {
'[' -> JSONArray(string, index)
'{' -> JSONObject(string, index)
'-' -> JSONNumber(string, index)
in ('0'..'9') -> JSONNumber(string, index)
'"' -> JSONString(string, index)
else -> throw IllegalArgumentException()
}.also { index = it.end }
map[key] = value
}
end = index + 1
}
}
fun parse(input: List<String>) = input.take(1).map { string ->
if (string[0] == '[') {
JSONArray(string.toList())
} else {
JSONObject(string.toList())
}
}.requireNoNulls()
fun part1(input: List<JSON>): Any? = input.map { it.flatten(false).filterIsInstance<JSONNumber>().sumBy { it.value } }
fun part2(input: List<JSON>): Any? = input.map { it.flatten(true).filterIsInstance<JSONNumber>().sumBy { it.value } }
| 0 | Kotlin | 0 | 0 | 24f54bf7be4b5d2a91a82a6998f633f353b2afb6 | 3,554 | AOC2015 | MIT License |
src/main/kotlin/g2401_2500/s2430_maximum_deletions_on_a_string/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2401_2500.s2430_maximum_deletions_on_a_string
// #Hard #String #Dynamic_Programming #Hash_Function #String_Matching #Rolling_Hash
// #2023_07_05_Time_280_ms_(100.00%)_Space_38.5_MB_(50.00%)
@Suppress("NAME_SHADOWING")
class Solution {
private var s: String? = null
private lateinit var hash: IntArray
private lateinit var pows: IntArray
private var visited: HashMap<Int, Int>? = null
fun deleteString(s: String): Int {
this.s = s
if (isBad) {
return s.length
}
visited = HashMap()
fill()
return helper(0, 1, 0, 1)
}
private fun helper(a: Int, b: Int, id1: Int, id2: Int): Int {
var a = a
var b = b
var id2 = id2
val mask = (id1 shl 12) + id2
var ans = 1
if (visited!!.containsKey(mask)) {
return visited!![mask]!!
}
while (b < s!!.length) {
if ((hash[a + 1] - hash[id1]) * pows[id2] == (hash[b + 1] - hash[id2]) * pows[id1]) {
ans = if (id2 + 1 == s!!.length) {
ans.coerceAtLeast(2)
} else {
ans.coerceAtLeast(1 + helper(id2, id2 + 1, id2, id2 + 1))
}
}
a++
id2++
b += 2
}
visited!![mask] = ans
return ans
}
private fun fill() {
val n = s!!.length
hash = IntArray(n + 1)
pows = IntArray(n)
pows[0] = 1
hash[1] = s!![0].code
for (i in 1 until n) {
pows[i] = pows[i - 1] * 1000000007
val temp = pows[i]
hash[i + 1] = s!![i].code * temp + hash[i]
}
}
private val isBad: Boolean
get() {
var i = 1
while (i < s!!.length) {
if (s!![0] != s!![i++]) {
return false
}
}
return true
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,952 | LeetCode-in-Kotlin | MIT License |
lib_algorithms_sort_kotlin/src/main/java/net/chris/lib/algorithms/sort/kotlin/KTQuickSorter.kt | chrisfang6 | 105,401,243 | false | {"Java": 68669, "Kotlin": 26275, "C++": 12503, "CMake": 2182, "C": 1403} | package net.chris.lib.algorithms.sort.kotlin
/**
* Quick sort.
*
* @param <T>
</T> */
abstract class KTQuickSorter : KTSorter() {
override fun subSort(list: IntArray) {
subQuickSort(list, 0, list.size - 1)
}
private fun subQuickSort(array: IntArray, start: Int, end: Int) {
if (array == null || end - start + 1 < 2) {
return
}
val part = partition(array, start, end)
if (part == start) {
subQuickSort(array, part + 1, end)
} else if (part == end) {
subQuickSort(array, start, part - 1)
} else {
subQuickSort(array, start, part - 1)
subQuickSort(array, part + 1, end)
}
}
private fun partition(array: IntArray, start: Int, end: Int): Int {
val value = array[end]
var index = start - 1
for (i in start until end) {
if (compareTo(array[i], value) < 0) {
index++
if (index != i) {
exchangeElements(array, index, i)
}
}
}
if (index + 1 != end) {
exchangeElements(array, index + 1, end)
}
return index + 1
}
/**
* Exchange the 2 items in the list
*
* @param array
* @param position1
* @param position2
*/
private fun exchangeElements(array: IntArray, position1: Int, position2: Int) {
val temp = array[position1]
array[position1] = array[position2]
array[position2] = temp
doUpdate(array)
}
}
| 0 | Java | 0 | 0 | 1f1c2206d5d9f0a3d6c070a7f6112f60c2714ec0 | 1,578 | sort | Apache License 2.0 |
src/main/kotlin/com/askrepps/advent2021/day05/Day05.kt | askrepps | 726,566,200 | false | {"Kotlin": 302802} | /*
* MIT License
*
* Copyright (c) 2021-2023 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.askrepps.advent.advent2021.day05
import com.askrepps.advent.util.getInputLines
import java.io.File
import kotlin.math.abs
import kotlin.math.max
data class GraphCoordinates(val x: Int, val y: Int)
enum class Orientation { Horizontal, Vertical, Diagonal }
data class VentLine(val start: GraphCoordinates, val end: GraphCoordinates) {
val orientation: Orientation
get() = when {
start.x == end.x -> Orientation.Vertical
start.y == end.y -> Orientation.Horizontal
else -> Orientation.Diagonal
}
val points: List<GraphCoordinates> by lazy { generatePoints() }
private fun generatePoints(): List<GraphCoordinates> {
val xDistance = abs(start.x - end.x)
val yDistance = abs(start.y - end.y)
check (xDistance == 0 || yDistance == 0 || xDistance == yDistance) {
"Vent lines must be horizontal, vertical, or diagonal at 45 degrees"
}
val length = max(xDistance, yDistance) + 1
val deltaX = getSlope(start.x, end.x)
val deltaY = getSlope(start.y, end.y)
return (0 until length).map {
GraphCoordinates(start.x + it*deltaX, start.y + it*deltaY)
}
}
private fun getSlope(startValue: Int, endValue: Int) =
when {
startValue < endValue -> 1
startValue > endValue -> -1
else -> 0
}
}
fun String.toCoordinates() =
split(",").let { (x, y) -> GraphCoordinates(x.toInt(), y.toInt()) }
fun String.toVentLine() =
split(" -> ").let { (start, end) -> VentLine(start.toCoordinates(), end.toCoordinates()) }
fun List<VentLine>.countOverlappingPoints(includeDiagonals: Boolean) =
filter { includeDiagonals || it.orientation != Orientation.Diagonal }
.flatMap { it.points }
.groupBy { it }
.count { (_, overlappingPoints) -> overlappingPoints.size >= 2 }
fun getPart1Answer(ventLines: List<VentLine>) =
ventLines.countOverlappingPoints(includeDiagonals = false)
fun getPart2Answer(ventLines: List<VentLine>) =
ventLines.countOverlappingPoints(includeDiagonals = true)
fun main() {
val ventLines = File("src/main/resources/2021/input-2021-day05.txt")
.getInputLines().map { it.toVentLine() }
println("The answer to part 1 is ${getPart1Answer(ventLines)}")
println("The answer to part 2 is ${getPart2Answer(ventLines)}")
}
| 0 | Kotlin | 0 | 0 | 89de848ddc43c5106dc6b3be290fef5bbaed2e5a | 3,547 | advent-of-code-kotlin | MIT License |
src/day18/Day18.kt | crmitchelmore | 576,065,911 | false | {"Kotlin": 115199} | package day18
import helpers.ReadFile
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
class Day18 {
val rlines = ReadFile.named("src/day18/input.txt")
val tlines = listOf(
"2,2,2",
"1,2,2",
"3,2,2",
"2,1,2",
"2,3,2",
"2,2,1",//
"2,2,3",
"2,2,4",
"2,2,6",
"1,2,5",
"3,2,5",
"2,1,5",
"2,3,5",
)
val blines = listOf(
"1,1,1",
"2,1,1",
)
val lines = rlines.map {
val point = it.split(",").map { it.toInt() }
Triple(point[0], point[1], point[2])
}
var exposedFaces = mutableMapOf<Triple<Int,Int,Int>, MutableSet<String>>()
fun tr(t: Triple<Int,Int, Int>, direction: String, index: Int) : Int {
if (direction == "z") {
when (index) {
1 -> return t.first
2 -> return t.second
3 -> return t.third
}
} else if (direction == "y") {
when (index) {
1 -> return t.first
2 -> return t.third
3 -> return t.second
}
} else {
when (index) {
1 -> return t.third
2 -> return t.second
3 -> return t.first
}
}
throw Exception("Bad")
}
fun sweep(direction: String) : Int {
var mappedLines = mutableMapOf<Int, List<Triple<Int,Int, Int>>>()
lines.forEach { mappedLines[tr(it, direction, 3)] = mappedLines.getOrDefault(tr(it, direction, 3), listOf()) + it }
var numPairedFaces = 0
val keys = mappedLines.keys.sorted()
for (i in 1 until keys.size) {
if (keys[i] - keys[i-1] == 1) {
for (cube1 in mappedLines[keys[i-1]]!!) {
for (cube2 in mappedLines[keys[i]]!!) {
if (tr(cube1, direction, 1) == tr(cube2, direction, 1) && tr(cube1, direction, 2) == tr(cube2, direction, 2)) {
exposedFaces[cube1]!!.remove(if (direction == "z") "Top" else if (direction == "y") "Back" else "Right")
exposedFaces[cube2]!!.remove(if (direction == "z") "Bottom" else if (direction == "y") "Front" else "Left")
numPairedFaces++
}
}
}
}
}
return numPairedFaces
}
fun sharesEdge(cube1: Triple<Int,Int,Int>, cube2: Triple<Int,Int,Int>) : Boolean {
return (( abs(cube1.first - cube2.first) == 1 && cube1.second == cube2.second && cube1.third == cube2.third ) ||
( cube1.first == cube2.first && abs(cube1.second - cube2.second) == 1 && cube1.third == cube2.third ) ||
( cube1.first == cube2.first && cube1.second == cube2.second && abs(cube1.third - cube2.third) == 1 )) ||
(( abs(cube1.first - cube2.first) == 1 && abs(cube1.second - cube2.second) == 1 && cube1.third == cube2.third ) ||
( cube1.first == cube2.first && abs(cube1.second - cube2.second) == 1 && abs(cube1.third - cube2.third) == 1 ) ||
( abs(cube1.first - cube2.first) == 1 && cube1.second == cube2.second && abs(cube1.third - cube2.third) == 1 ) )
}
fun buildSurfaces(surfaceFaces: Set<Triple<Int, Int, Int>>) : Map<Int, List<Triple<Int,Int,Int>>> {
var surfaceIndex = 0
var cubeToSurfaceNum = mutableMapOf<Triple<Int,Int,Int>, Int>()
var surfaceNumToCubs = mutableMapOf<Int, List<Triple<Int,Int,Int>>>()
for (cube in surfaceFaces) {
var foundExistingSurface = false
// Check if this cube shares an edge with any existing surface
for (surface in surfaceNumToCubs.keys) {
for (surfaceCube in surfaceNumToCubs[surface]!!) {
if (sharesEdge(cube, surfaceCube)) {
cubeToSurfaceNum[cube] = surface
surfaceNumToCubs[surface] = surfaceNumToCubs[surface]!! + cube
foundExistingSurface = true
break
}
}
if (foundExistingSurface) {
break
}
}
// If not, create a new surface
if (!foundExistingSurface) {
surfaceIndex++
cubeToSurfaceNum[cube] = surfaceIndex
surfaceNumToCubs[surfaceIndex] = listOf(cube)
}
}
// Merge surfaces
var merged = true
while (merged) {
merged = false
for (surface1 in surfaceNumToCubs.keys) {
for (surface2 in surfaceNumToCubs.keys) {
if (surface1 != surface2) {
for (cube1 in surfaceNumToCubs[surface1]!!) {
for (cube2 in surfaceNumToCubs[surface2]!!) {
if (sharesEdge(cube1, cube2)) {
// Merge surface2 into surface1
for (cube in surfaceNumToCubs[surface2]!!) {
cubeToSurfaceNum[cube] = surface1
}
surfaceNumToCubs[surface1] = surfaceNumToCubs[surface1]!! + surfaceNumToCubs[surface2]!!
surfaceNumToCubs.remove(surface2)
merged = true
break
}
}
if (merged) {
break
}
}
if (merged) {
break
}
}
}
if (merged) {
break
}
}
}
// Now merge in to true surfaces
return surfaceNumToCubs
}
fun fill(lavas: Set<Triple<Int, Int, Int>>, x: Pair<Int, Int>, y: Pair<Int, Int>, z: Pair<Int, Int>) : Set<Triple<Int, Int, Int>> {
var waters = mutableSetOf(Triple(x.first - 1, y.first - 1, z.first - 1))
for (i in 1..4) {
for (i in x.first - 1..x.second + 1) {
for (j in y.first - 1..y.second + 1) {
for (k in z.first - 1..z.second + 1) {
if (lavas.contains(Triple(i, j, k))) {
continue
}
val neigh = listOf(
Triple(i + 1, j, k),
Triple(i - 1, j, k),
Triple(i, j + 1, k),
Triple(i, j - 1, k),
Triple(i, j, k + 1),
Triple(i, j, k - 1)
)
if (neigh.any { waters.contains(it) }) {
waters.add(Triple(i, j, k))
} else {
println("cave")
}
}
}
}
}
return waters
}
var numlavas = 0
fun fild(lavas: Set<Triple<Int, Int, Int>>, x: Pair<Int, Int>, y: Pair<Int, Int>, z: Pair<Int, Int>) : Set<Triple<Int, Int, Int>> {
var waters = mutableSetOf(Triple(x.first - 1, y.first - 1, z.first - 1))
var items = mutableListOf(waters.first())
while (items.size > 0) {
val item = items.removeAt(0)
val neigh = listOf(
Triple(item.first + 1, item.second, item.third),
Triple(item.first - 1, item.second, item.third),
Triple(item.first, item.second + 1, item.third),
Triple(item.first, item.second - 1, item.third),
Triple(item.first, item.second, item.third + 1),
Triple(item.first, item.second, item.third - 1)
)
for (n in neigh) {
if (lavas.contains(n) ) {
numlavas += 1
} else {
if (waters.contains(n) || n.first < x.first - 1 || n.first > x.second + 1 || n.second < y.first - 1 || n.second > y.second + 1 || n.third < z.first - 1 || n.third > z.second + 1) {
continue
}
items.add(n)
waters.add(n)
}
}
}
return waters
}
fun flood(lava: List<Triple<Int, Int, Int>>) : Set<Triple<Int,Int,Int>> {
var minMaxX: Pair<Int, Int> = Pair(Int.MAX_VALUE, Int.MIN_VALUE)
var minMaxY: Pair<Int, Int> = Pair(Int.MAX_VALUE, Int.MIN_VALUE)
var minMaxZ: Pair<Int, Int> = Pair(Int.MAX_VALUE, Int.MIN_VALUE)
for (cube in lava) {
minMaxX = Pair(min(minMaxX.first, cube.first), max(minMaxX.second, cube.first))
minMaxY = Pair(min(minMaxY.first, cube.second), max(minMaxY.second, cube.second))
minMaxZ = Pair(min(minMaxZ.first, cube.third), max(minMaxZ.second, cube.third))
}
// Be cautious about edges
minMaxX = Pair(minMaxX.first, minMaxX.second)
minMaxY = Pair(minMaxY.first, minMaxY.second)
minMaxZ = Pair(minMaxZ.first, minMaxZ.second)
val a = fild(lava.toSet(), minMaxX, minMaxY, minMaxZ)
val b = fill(lava.toSet(), minMaxX, minMaxY, minMaxZ)
print("Lavas $numlavas")
return a
}
fun invertSurface(surface: List<Triple<Int, Int, Int>>): Set<Triple<Int, Int, Int>> {
var minMaxX: Pair<Int, Int> = Pair(Int.MAX_VALUE, Int.MIN_VALUE)
var minMaxY: Pair<Int, Int> = Pair(Int.MAX_VALUE, Int.MIN_VALUE)
var minMaxZ: Pair<Int, Int> = Pair(Int.MAX_VALUE, Int.MIN_VALUE)
for (cube in surface) {
minMaxX = Pair(min(minMaxX.first, cube.first), max(minMaxX.second, cube.first))
minMaxY = Pair(min(minMaxY.first, cube.second), max(minMaxY.second, cube.second))
minMaxZ = Pair(min(minMaxZ.first, cube.third), max(minMaxZ.second, cube.third))
}
// Be cautious about edges
minMaxX = Pair(minMaxX.first, minMaxX.second)
minMaxY = Pair(minMaxY.first, minMaxY.second + 1)
minMaxZ = Pair(minMaxZ.first, minMaxZ.second + 1)
var allCubes = mutableSetOf<Triple<Int, Int, Int>>()
for (x in minMaxX.first until minMaxX.second) {
for (y in minMaxY.first until minMaxY.second) {
for (z in minMaxZ.first until minMaxZ.second) {
allCubes.add(Triple(x, y, z))
}
}
}
allCubes.removeAll(surface.toSet())
return allCubes
}
fun result1() {
for (line in lines) {
exposedFaces[line] = mutableSetOf("Top", "Bottom", "Left", "Right", "Front", "Back")
}
val joinedFaces = sweep("x") + sweep("y") + sweep("z")
val surfaceArea = lines.size * 6 - joinedFaces * 2
println("Surface $surfaceArea")
val water = flood(lines)
var touchingWater = 0
var tw = mutableListOf<Triple<Int, Int, Int>>()
for (cube in lines) {
val neigh = listOf(
Triple(cube.first + 1, cube.second, cube.third),
Triple(cube.first - 1, cube.second, cube.third),
Triple(cube.first, cube.second + 1, cube.third),
Triple(cube.first, cube.second - 1, cube.third),
Triple(cube.first, cube.second, cube.third + 1),
Triple(cube.first, cube.second, cube.third - 1),
)
val t = water.intersect(neigh)
tw.addAll(t)
}
println("tw: $tw")
println("Touching water $touchingWater")
// val surfaceFaces = exposedFaces.filter { it.value.size > 0 }.keys
// val allSurfaces = buildSurfaces(surfaceFaces)
// for (surfaceNum in allSurfaces.keys) {
// val surface = allSurfaces[surfaceNum]!!
// val bubbles = buildSurfaces(invertSurface(surface))
// if (bubbles.size > 1) {
// println("Bubble ${bubbles}")
// }
// }
// print(buildSurfaces(surfaceFaces))
}
}
// 2181 low
// 2512 low | 0 | Kotlin | 0 | 0 | fd644d442b5ff0d2f05fbf6317c61ee9ce7b4470 | 12,410 | adventofcode2022 | MIT License |
src/main/kotlin/tr/emreone/kotlin_utils/extensions/Ranges.kt | EmRe-One | 442,916,831 | false | {"Kotlin": 173543} | package tr.emreone.kotlin_utils.extensions
val IntRange.size get() = (last - first + 1).coerceAtLeast(0)
val LongRange.size get() = (last - first + 1).coerceAtLeast(0)
/**
* Tests whether the two [ClosedRange]s overlap or contain one another.
*/
infix fun <T : Comparable<T>> ClosedRange<T>.overlaps(other: ClosedRange<T>): Boolean {
if (isEmpty() || other.isEmpty()) return false
return !(this.endInclusive < other.start || this.start > other.endInclusive)
}
fun IntRange.combine(other: IntRange): IntRange =
listOf(first, last, other.first, other.last).minMax().let { (f, l) -> f..l }
/**
* Merges non-empty [IntRange]s to a potentially shorter list of not-overlapping IntRanges.
*/
fun Iterable<IntRange>.merge(): List<IntRange> {
val sorted = this.filter { !it.isEmpty() }.sortedBy { it.first }
sorted.isNotEmpty() || return emptyList()
val stack = ArrayDeque<IntRange>()
stack.add(sorted.first())
sorted.drop(1).forEach { current ->
if (current.last <= stack.last().last) {
// ignore as it's completely within
} else if (current.first > stack.last().last + 1) {
// it's completely out and after the last
stack.add(current)
} else {
// they overlap
stack.add(stack.removeLast().first..current.last)
}
}
return stack
}
/**
* Given an [IntRange], subtract all the given [others] and calculate a list of [IntRange]s
* with every possible value not subtracted in the resulting ranges.
*
* @param others the ranges to subtract - they need not be merged before.
*/
fun IntRange.subtract(vararg others: IntRange): List<IntRange> = subtract(others.asIterable())
/**
* Given an [IntRange], subtract all the given [others] and calculate a list of [IntRange]s
* with every possible value not subtracted in the resulting ranges.
*
* @param others the ranges to subtract - they need not be merged before.
*/
fun IntRange.subtract(others: Iterable<IntRange>): List<IntRange> {
val relevant = others.merge().filter { it overlaps this }
// if relevant is empty nothing to remove -> return list
if (relevant.isEmpty()) return listOf(this)
return buildList {
var includeFrom = this@subtract.first()
relevant.forEach { minus ->
if (minus.first() > includeFrom)
add(includeFrom until minus.first.coerceAtMost(this@subtract.last()))
includeFrom = minus.last() + 1
}
if (includeFrom <= this@subtract.last())
add(includeFrom..this@subtract.last())
}
}
/**
* Merges non-empty [LongRange]s to a potentially shorter list of not-overlapping LongRanges.
*/
@JvmName("mergeLongRanges")
fun Iterable<LongRange>.merge(): List<LongRange> {
val sorted = this.filter { !it.isEmpty() }.sortedBy { it.first }
sorted.isNotEmpty() || return emptyList()
val stack = ArrayDeque<LongRange>()
stack.add(sorted.first())
sorted.drop(1).forEach { current ->
if (current.last <= stack.last().last) {
// ignore as it's completely within
} else if (current.first > stack.last().last + 1) {
// it's completely out and after the last
stack.add(current)
} else {
// they overlap
stack.add(stack.removeLast().first..current.last)
}
}
return stack
}
/**
* Given an [LongRange], subtract all the given [others] and calculate a list of [LongRange]s
* with every possible value not subtracted in the resulting ranges.
*
* @param others the ranges to subtract - they need not be merged before.
*/
fun LongRange.subtract(vararg others: LongRange): List<LongRange> = subtract(others.asIterable())
/**
* Given an [LongRange], subtract all the given [others] and calculate a list of [LongRange]s
* with every possible value not subtracted in the resulting ranges.
*
* @param others the ranges to subtract - they need not be merged before.
*/
fun LongRange.subtract(others: Iterable<LongRange>): List<LongRange> {
val relevant = others.merge().filter { it overlaps this }
// if relevant is empty nothing to remove -> remove list
if (relevant.isEmpty()) return listOf(this)
return buildList {
var includeFrom = this@subtract.first()
relevant.forEach { minus ->
if (minus.first() > includeFrom)
add(includeFrom until minus.first().coerceAtMost(this@subtract.last()))
includeFrom = minus.last() + 1
}
if (includeFrom <= this@subtract.last())
add(includeFrom..this@subtract.last())
}
}
| 0 | Kotlin | 0 | 0 | aee38364ca1827666949557acb15ae3ea21881a1 | 4,630 | kotlin-utils | Apache License 2.0 |
src/Day01.kt | JonahBreslow | 578,314,149 | false | {"Kotlin": 6978} | import java.io.File
fun main() {
fun readFile(file_path: String) : List<String> {
val text = File(file_path).readLines()
return text
}
fun create_elves_calories(input: List<String>): List<Int>{
var calories = mutableListOf<Int>()
var counter:Int = 0
for (food in input){
when(food){
"" -> {
calories.add(counter)
counter = 0
}
else -> {
counter += food.toInt()
}
}
}
return calories
}
fun get_max_calories(input: List<Int>, n_elves: Int): Int {
val sorted_elves = input.sortedDescending()
val res = sorted_elves.take(n_elves)
return res.sum()
}
fun part1(input: String): Int {
val text = readFile(input)
val elfList = create_elves_calories(text)
return get_max_calories(elfList, n_elves=1)
}
fun part2(input: String): Int {
val text = readFile(input)
val elfList = create_elves_calories(text)
return get_max_calories(elfList, n_elves=3)
}
// test if implementation meets criteria from the description, like:
check(part1("data/day1_test.txt") == 24000)
println(part1("data/day1.txt"))
println(part2("data/day1.txt"))
}
| 0 | Kotlin | 0 | 1 | c307ff29616f613473768168cc831a7a3fa346c2 | 1,361 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/day20/Day20.kt | TheSench | 572,930,570 | false | {"Kotlin": 128505} | package day20
import runDay
fun main() {
fun part1(input: List<String>) = input.toCoordinates(
decryptionKey = 1,
mixCount = 1,
)
fun part2(input: List<String>) = input.toCoordinates(
decryptionKey = 811589153,
mixCount = 10,
)
(object {}).runDay(
part1 = ::part1,
part1Check = 3L,
part2 = ::part2,
part2Check = 1623178306L,
)
}
fun List<String>.toCoordinates(decryptionKey: Int = 1, mixCount: Int = 1) = this.toLongs()
.map { it * decryptionKey }
.toWrappedList()
.let { list ->
repeat(mixCount) { list.mix() }
list
}
.getPositionsFromOriginalZero(listOf(1000, 2000, 3000))
.sum()
fun List<String>.toLongs() = this.map { it.toLong() }
fun List<Long>.toWrappedList() = WrappedList(this.mapIndexed { index, it -> index to it }.toMutableList())
fun WrappedList.mix() = let { wrappedList ->
(0 until wrappedList.size).forEach { originalIndex ->
val position = wrappedList.getPosition(originalIndex)
wrappedList.move(position)
}
wrappedList
}
fun WrappedList.getPositionsFromOriginalZero(positions: List<Int>) = let { list ->
val originalZero = list.find { it.second == 0L }!!
val newPosition = list.getPosition(originalZero.first)
positions
.map { it + newPosition }
.map { list[it].second }
}
class WrappedList(private val innerList: MutableList<Pair<Int, Long>>) : MutableList<Pair<Int, Long>> by innerList {
private val positions: MutableMap<Int, Int> = List(innerList.size) { index -> index to index }.toMap().toMutableMap()
fun getPosition(originalIndex: Int) = positions[originalIndex]!!
override fun get(index: Int): Pair<Int, Long> = innerList[wrap(index)]
override fun set(index: Int, element: Pair<Int, Long>): Pair<Int, Long> {
return innerList.set(wrap(index), element)
}
fun move(index: Int) {
val element = get(index)
val oldPosition = wrap(index)
val newPosition = wrapMoveTo(index + element.second).adjustForBoundaries()
val rangeToShift = if (oldPosition < newPosition) {
(newPosition downTo oldPosition)
} else {
(newPosition..oldPosition)
}
rangeToShift.forEach { positionToSwap ->
val old = get(oldPosition)
val new = set(positionToSwap, get(oldPosition))
set(oldPosition, new)
positions[old.first] = positionToSwap
positions[new.first] = oldPosition
}
}
private fun wrapMoveTo(index: Long) = (index % (size - 1)).let {
if (it >= 0) it else (size - 1) + it
}
private fun wrap(index: Int) = (index % size).let {
if (it >= 0) it else size + it
}
private fun Long.adjustForBoundaries() = when (this) {
0L -> size - 1
else -> this.toInt()
}
override fun toString() = innerList.map { it.second }.joinToString(", ")
} | 0 | Kotlin | 0 | 0 | c3e421d75bc2cd7a4f55979fdfd317f08f6be4eb | 2,759 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/github/solairerove/algs4/leprosorium/linked_list/IntersectionOfTwoLinkedLists.kt | solairerove | 282,922,172 | false | {"Kotlin": 251919} | package com.github.solairerove.algs4.leprosorium.linked_list
/**
* Given the heads of two singly linked-lists headA and headB,
* return the node at which the two lists intersect.
* If the two linked lists have no intersection at all, return null.
*
* Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3
* Output: Intersected at '8'
*
* Explanation: The intersected node's value is 8 (note that this must not be 0 if the two lists intersect).
* From the head of A, it reads as [4,1,8,4,5].
* From the head of B, it reads as [5,6,1,8,4,5].
* There are 2 nodes before the intersected node in A;
* There are 3 nodes before the intersected node in B.
*
* Note that the intersected node's value is not 1
* because the nodes with value 1 in A and B (2nd node in A and 3rd node in B) are different node references.
* In other words, they point to two different locations in memory,
* while the nodes with value 8 in A and B (3rd node in A and 4th node in B) point to the same location in memory.
*/
// O(2n + 2m) time | O(1) space
fun getIntersectionNode(headA: ListNode?, headB: ListNode?): ListNode? {
var curr1: ListNode? = headA
var curr2: ListNode? = headB
while (curr1 != curr2) {
curr1 = if (curr1 == null) headB else curr1.next
curr2 = if (curr2 == null) headA else curr2.next
}
return curr1
}
// O(n + m) time | O(m) space
fun getIntersectionNodeSet(headA: ListNode?, headB: ListNode?): ListNode? {
val set = mutableSetOf<ListNode>()
var curr: ListNode? = headA
while (curr != null) {
set.add(curr)
curr = curr.next
}
curr = headB
while (curr != null) {
if (set.contains(curr)) return curr
curr = curr.next
}
return null
}
| 1 | Kotlin | 0 | 3 | 64c1acb0c0d54b031e4b2e539b3bc70710137578 | 1,786 | algs4-leprosorium | MIT License |
src/test/kotlin/dev/bogwalk/batch3/Problem33Test.kt | bog-walk | 381,459,475 | false | null | package dev.bogwalk.batch3
import dev.bogwalk.util.tests.Benchmark
import dev.bogwalk.util.tests.compareSpeed
import dev.bogwalk.util.tests.getSpeed
import kotlin.test.*
internal class DigitCancellingFractionsTest {
private val tool = DigitCancellingFractions()
@Test
fun `isReducedEquivalent returns true for valid fractions`() {
val fractions = listOf(16 to 64, 26 to 65, 1249 to 9992, 4999 to 9998)
val k = 1
fractions.forEach { (num, denom) ->
val digits = num.toString().length
assertTrue { tool.isReducedEquivalent(digits, num, denom, k) }
}
}
@Test
fun `isReducedEquivalent returns false for invalid fractions`() {
val fractions = listOf(11 to 19, 47 to 71, 328 to 859, 8777 to 7743)
val k = 1
fractions.forEach { (num, denom) ->
val digits = num.toString().length
assertFalse { tool.isReducedEquivalent(digits, num, denom, k) }
}
}
@Test
fun `isReducedEquivalent correct for all K`() {
val fractions = listOf(16 to 64, 166 to 664, 1666 to 6664)
fractions.forEach { (num, denom) ->
val digits = num.toString().length
for (k in 1..3) {
if (k >= digits) break
assertTrue { tool.isReducedEquivalent(digits, num, denom, k) }
}
}
}
@Test
fun `findNonTrivials correct for K = 1`() {
val expected = listOf(
listOf(16 to 64, 19 to 95, 26 to 65, 49 to 98),
listOf(166 to 664, 199 to 995, 217 to 775, 249 to 996, 266 to 665, 499 to 998),
listOf(
1249 to 9992, 1666 to 6664, 1999 to 9995, 2177 to 7775,
2499 to 9996, 2666 to 6665, 4999 to 9998
)
)
for (n in 2..4) {
assertContentEquals(expected[n - 2], tool.findNonTrivialsBrute(n))
assertContentEquals(expected[n - 2], tool.findNonTrivials(n))
}
}
@Test
fun `findNonTrivials correct for K = 2`() {
val n = 3
val k = 2
val expected = listOf(166 to 664, 199 to 995, 266 to 665, 484 to 847, 499 to 998)
assertContentEquals(expected, tool.findNonTrivialsBrute(n, k))
assertContentEquals(expected, tool.findNonTrivials(n, k))
}
@Test
fun `findNonTrivials speed`() {
val n = 4
val k = 1
// sums of numerators & denominators
val expected = 17255 to 61085
val solutions = mapOf(
"Brute" to tool::findNonTrivialsBrute, "Optimised" to tool::findNonTrivials
)
val speeds = mutableListOf<Pair<String, Benchmark>>()
val results = mutableListOf<List<Pair<Int, Int>>>()
for((name, solution) in solutions) {
getSpeed(solution, n, k).run {
speeds.add(name to second)
results.add(first)
}
}
compareSpeed(speeds)
results.forEach { result ->
val (numerators, denominators) = result.unzip()
assertEquals(expected.first, numerators.sum())
assertEquals(expected.second, denominators.sum())
}
}
@Test
fun `PE problem correct`() {
assertEquals(100, tool.productOfNonTrivials())
}
@Test
fun `getCancelledCombos correct`() {
val nums = listOf("9919", "1233", "1051", "5959")
val toCancel = listOf(
listOf('9', '9'), listOf('1', '2', '3'), listOf('1', '5'), listOf('9')
)
val expected = listOf(setOf(19, 91), setOf(3), setOf(1, 10), setOf(559, 595))
nums.forEachIndexed { i, n ->
assertEquals(expected[i], tool.getCancelledCombos(n, toCancel[i]))
}
}
@Test
fun `HR problem correct for K = 1`() {
val k = 1
val expected = listOf(110 to 322, 77262 to 163_829)
for (n in 2..3) {
assertEquals(expected[n - 2], tool.sumOfNonTrivialsBrute(n, k))
assertEquals(expected[n - 2], tool.sumOfNonTrivialsGCD(n, k))
}
}
@Test
fun `HR problem correct for K = 2`() {
val k = 2
val expected = listOf(7429 to 17305, 3_571_225 to 7_153_900)
for (n in 3..4) {
assertEquals(expected[n - 3], tool.sumOfNonTrivialsBrute(n, k))
assertEquals(expected[n - 3], tool.sumOfNonTrivialsGCD(n, k))
}
}
@Test
fun `HR problem correct for K = 3`() {
val n = 4
val expected = 255_983 to 467_405
assertEquals(expected, tool.sumOfNonTrivialsBrute(n, k=3))
assertEquals(expected, tool.sumOfNonTrivialsGCD(n, k=3))
}
@Test
fun `HR problem speed`() {
val n = 4
val k = 1
val expected = 12_999_936 to 28_131_911
val solutions = mapOf(
"Brute" to tool::sumOfNonTrivialsBrute, "GCD" to tool::sumOfNonTrivialsGCD
)
val speeds = mutableListOf<Pair<String, Benchmark>>()
for ((name, solution) in solutions) {
getSpeed(solution, n, k).run {
speeds.add(name to second)
assertEquals(expected, first, "Incorrect $name -> $first")
}
}
compareSpeed(speeds)
}
} | 0 | Kotlin | 0 | 0 | 62b33367e3d1e15f7ea872d151c3512f8c606ce7 | 5,240 | project-euler-kotlin | MIT License |
src/main/aoc2022/Day23.kt | nibarius | 154,152,607 | false | {"Kotlin": 963896} | package aoc2022
import AMap
import Pos
import size
class Day23(input: List<String>) {
enum class Direction(private val adjacent: Pos) {
North(Pos(0, -1)), South(Pos(0, 1)), West(Pos(-1, 0)), East(Pos(1, 0));
fun neighboursAreAdjacentInThisDirection(from: Pos, to: Pos): Boolean {
return when (this) {
North -> from.y > to.y
South -> from.y < to.y
West -> from.x > to.x
East -> from.x < to.x
}
}
fun moveFrom(from: Pos) = from + adjacent
}
// set of positions for all elves
private val elves = AMap.parse(input, listOf('.')).keys.toMutableSet()
private fun List<Pos>.noneInDirectionFrom(direction: Direction, from: Pos): Boolean {
return none { direction.neighboursAreAdjacentInThisDirection(from, it) }
}
/**
* Simulates and returns the number of turns after there were no movement at all
*/
private fun simulate(maxTurns: Int): Int {
val directions = Direction.entries
repeat(maxTurns) { turn ->
// proposed position to origin position
val proposedPositions = mutableMapOf<Pos, Pos>()
// Propose where to move
elves.forEach { elfPos ->
val neighbours = elfPos.allNeighbours(true).filter { it in elves }
if (neighbours.isNotEmpty()) {
for (dir in 0..3) {
val direction = directions[(dir + turn) % 4]
if (neighbours.noneInDirectionFrom(direction, elfPos)) {
val moveTo = direction.moveFrom(elfPos)
if (proposedPositions.putIfAbsent(moveTo, elfPos) != null) {
// There can be at most two elves moving to the same location. If there is a
// collision, remove the one that wanted to move here
proposedPositions.remove(moveTo)
}
break
}
}
}
}
// Move
proposedPositions.ifEmpty { return turn + 1 }.forEach { (movingTo, movingFrom) ->
elves.remove(movingFrom)
elves.add(movingTo)
}
}
return maxTurns
}
private fun MutableSet<Pos>.boundingBox(): Pair<IntRange, IntRange> {
val x = minByOrNull { it.x }!!.x..maxByOrNull { it.x }!!.x
val y = minByOrNull { it.y }!!.y..maxByOrNull { it.y }!!.y
return x to y
}
private fun Pair<IntRange, IntRange>.area() = first.size() * second.size()
@Suppress("unused") // Useful for testing
private fun MutableSet<Pos>.print() {
val bb = boundingBox()
for (y in bb.second) {
for (x in bb.first) {
val ch = if (Pos(x, y) in this) '#' else '.'
print(ch)
}
println()
}
}
fun solvePart1(): Int {
simulate(10)
return elves.boundingBox().area() - elves.size
}
fun solvePart2(): Int {
return simulate(1000)
}
} | 0 | Kotlin | 0 | 6 | f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22 | 3,226 | aoc | MIT License |
src/main/kotlin/com/briarshore/aoc2022/day10/CathodeRayTubePuzzle.kt | steveswing | 579,243,154 | false | {"Kotlin": 47151} | package com.briarshore.aoc2022.day10
import com.briarshore.aoc2022.day10.Instruction.*
import println
import readInput
import java.util.Optional
enum class Instruction(val cycles: Int) {
NOOP(1), ADDX(2)
}
data class Operation(val instruction: Instruction, val argument: Optional<Int>)
fun String.toInstructions(): Operation {
return if (contains(" ")) {
val (instr: String, len: String) = split(" ")
Operation(valueOf(instr.uppercase()), Optional.ofNullable(len.toInt()))
} else {
Operation(valueOf(this.uppercase()), Optional.empty())
}
}
// 15-11+6-3+5-1-8+13+4-1+5-1+5-1+5-1+5-1-35
// .........##........##...................
// .....................###................
// ..........................#.............
// .......................#................
// .....................###......##........
// .....................#..#...............
//
//
//
//
//
//
//
fun main() {
var x = 1
var currentCycle = 0
var signalStrength = 0
val signalHistory = mutableListOf<Int>()
val crtBuffer = mutableListOf<String>()
var crt = 0
fun tick(operation: Operation) {
val (instruction, v) = operation
(0 until instruction.cycles).map {
currentCycle++
if (currentCycle % 40 == 20) {
signalStrength = x * currentCycle
signalHistory += signalStrength
}
}
v.ifPresent { x += it }
}
fun render(operation: Operation) {
val (instruction, v) = operation
(0 until instruction.cycles).map {
val sprite = x - 1..x + 1
if (crt > 0 && crt % 40 == 0) {
println()
crtBuffer += ""
}
val c = if (crt % 40 in sprite) '#' else '.'
print(c)
crtBuffer[crtBuffer.lastIndex] = crtBuffer[crtBuffer.lastIndex] + c
crt++
}
v.ifPresent { x += it }
}
fun part1(lines: List<String>): Int {
x = 1
currentCycle = 0
signalStrength = 0
signalHistory.clear()
lines.map { it.toInstructions() }.forEach { tick(it) }
return x
}
fun part2(lines: List<String>) {
x = 1
currentCycle = 0
crtBuffer.clear()
crtBuffer += ""
crt = 0
println()
lines.map { it.toInstructions() }.forEach { render(it) }
println()
println()
// crtBuffer.forEach { it.println() }
// ##..##..##..##..##..##..##..##..##..##..
// ###...###...###...###...###...###...###.
// ####....####....####....####....####....
// #####.....#####.....#####.....#####.....
// ######......######......######......####
// #######.......#######.......#######.....
}
val smallSampleInput = listOf(
"noop",
"addx 3",
"addx -5",
)
val part1SmallSample = part1(smallSampleInput)
"part1 $part1SmallSample".println()
check(part1SmallSample == -1)
val sampleInput = readInput("d10p1-sample")
val samplePart1 = part1(sampleInput)
"part1 $samplePart1".println()
check(samplePart1 == 17)
val signalSampleHistoryTotal = signalHistory.sum()
"small sample signalHistoryTotal $signalSampleHistoryTotal".println()
check(signalSampleHistoryTotal == 13140)
val input = readInput("d10-input")
val part1 = part1(input)
"part1 $part1".println()
val signalHistoryTotal = signalHistory.sum()
"signalHistoryTotal $signalHistoryTotal".println()
check(signalHistoryTotal == 13480)
part2(input) // EGJBGCFK
val expected = """
####..##....##.###...##...##..####.#..#.
#....#..#....#.#..#.#..#.#..#.#....#.#..
###..#.......#.###..#....#....###..##...
#....#.##....#.#..#.#.##.#....#....#.#..
#....#..#.#..#.#..#.#..#.#..#.#....#.#..
####..###..##..###...###..##..#....#..#.
""".trimIndent().lines()
check(crtBuffer == expected)
}
| 0 | Kotlin | 0 | 0 | a0d19d38dae3e0a24bb163f5f98a6a31caae6c05 | 4,016 | 2022-AoC-Kotlin | Apache License 2.0 |
src/Day04.kt | Hotkeyyy | 573,026,685 | false | {"Kotlin": 7830} | import java.io.File
fun main() {
fun part1(input: String) {
val pairs = input.split("\n").map {
val parts = it.split(",")
Pair(parts[0].split("-").map { it.toInt() }, parts[1].split("-").map { it.toInt() })
}
val count = pairs.count {
val (a, b) = it
(a[0] <= b[0] && a[1] >= b[1]) || (b[0] <= a[0] && b[1] >= a[1])
}
println(count)
}
fun part2(input: String) {
val pairs = input.split("\n").map {
val parts = it.split(",")
Pair(parts[0].split("-").map { it.toInt() }, parts[1].split("-").map { it.toInt() })
}
val count = pairs.count {
val (a, b) = it
(a[0] <= b[1] && a[1] >= b[0]) || (b[0] <= a[1] && b[1] >= a[0])
}
println(count)
}
val input = File("src/Day04.txt").readText()
part1(input)
part2(input)
} | 0 | Kotlin | 0 | 0 | dfb20f1254127f99bc845e9e13631c53de8784f2 | 916 | advent-of-code-2022 | Apache License 2.0 |
2020/day13/day13.kt | flwyd | 426,866,266 | false | {"Julia": 207516, "Elixir": 120623, "Raku": 119287, "Kotlin": 89230, "Go": 37074, "Shell": 24820, "Makefile": 16393, "sed": 2310, "Jsonnet": 1104, "HTML": 398} | /*
* Copyright 2021 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
package day13
import java.lang.Math.floorMod
import kotlin.time.ExperimentalTime
import kotlin.time.TimeSource
import kotlin.time.measureTimedValue
/* Input: Two lines; the first is a timestamp of arrival, the second is a comma-separated list of
bus periods, with "x" values for buses that can be ignored. */
/* Output: time waiting for the first bust after timestamp, times bus period. */
object Part1 {
fun solve(input: Sequence<String>): String {
val lines = input.toList()
val myTime = lines.first().toInt()
return lines[1].split(",")
.filter { it != "x" }
.map(String::toInt)
.associateWith { it - (myTime % it) }
.minByOrNull { it.value }!!
.let { (k, v) -> k * v }
.toString()
}
}
/* Ignore the first line. Output is the first time where each bus will be (it's position) time units
after that time. I.e. apply the Chinese Remainder Theorem to find a number x where x mod first = 0,
x mod fifth = 4, etc. */
object Part2 {
fun solve(input: String): String {
val pairs = input.split(",")
.mapIndexed(::Pair)
.filter { it.second != "x" }
.map {
it.second.toLong()
.let { base -> (if (it.first == 0) 0L else base - (it.first % base)) to base }
}
.toList()
val product = pairs.map { it.second }.reduce(Long::times)
val sum = pairs.map {
val coeff = bezoutCoefficients(it.second, product / it.second)
it.first * coeff.second * (product / it.second)
}.sum()
return floorMod(sum, product).toString()
// https://en.wikipedia.org/wiki/Chinese_remainder_theorem#Search_by_sieving
// I implemented this quickly while trying to understand explanations of how Bézout's identity
// can be used to compute the number which satisfies the Chinese Remainder Theorem constraints.
// This sieve is exponential in the length of the result, and it didn't print the second line of
// output in ~half an hour
// println("Sieving for Chinese remainder of $pairs")
// var sum = 0L
// for (pair in pairs) {
// while (sum % pair.second != pair.first) {
// sum += pair.second
// }
// println("$sum % ${pair.second} = 0")
// }
// return sum.toString()
}
/* See https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm */
private fun bezoutCoefficients(x: Long, y: Long): Pair<Long, Long> {
var r0 = x
var r1 = y
var s0 = 1L
var s1 = 0L
var t0 = 0L
var t1 = 1L
while (true) {
val q = r0 / r1
val r = r0 % r1
val s = s0 - q * s1
val t = t0 - q * t1
if (r == 0L) {
return s1 to t1
}
r0 = r1
r1 = r
s0 = s1
s1 = s
t0 = t1
t1 = t
}
}
}
@ExperimentalTime
@Suppress("UNUSED_PARAMETER")
fun main(args: Array<String>) {
val lines = generateSequence(::readLine).toList()
print("part1: ")
TimeSource.Monotonic.measureTimedValue { Part1.solve(lines.asSequence()) }.let {
println(it.value)
System.err.println("Completed in ${it.duration}")
}
print("part2: ")
// TimeSource.Monotonic.measureTimedValue { Part2.solve(lines.asSequence()) }.let {
TimeSource.Monotonic.measureTimedValue { Part2.solve(lines[1]) }.let {
println(it.value)
System.err.println("Completed in ${it.duration}")
}
// println()
// println("Extra examples:")
// listOf("67,7,59,61", "67,x,7,59,61", "67,7,x,59,61", "1789,37,47,1889").forEach {
// println(it)
// println(Part2.solve(it))
// }
}
| 0 | Julia | 1 | 5 | f2d6dbb67d41f8f2898dbbc6a98477d05473888f | 3,677 | adventofcode | MIT License |
src/main/kotlin/com/chriswk/aoc/advent2020/Day9.kt | chriswk | 317,863,220 | false | {"Kotlin": 481061} | package com.chriswk.aoc.advent2020
import com.chriswk.aoc.AdventDay
import com.chriswk.aoc.util.report
class Day9: AdventDay(2020, 9) {
companion object {
@JvmStatic
fun main(args: Array<String>) {
val day = Day9()
report {
day.part1()
}
report {
day.part2()
}
}
}
fun availableSums(numbers: List<Long>): Set<Long> {
return numbers.flatMapIndexed { i, x ->
if (i < numbers.size - 1) {
numbers.drop(i).map { x + it }
} else {
listOf(0)
}
}.toSet()
}
fun findFirstNumberWhichIsNotASum(preambleSize: Int, numbers: Sequence<List<Long>>): Long? {
return findWeakness(preambleSize, numbers)?.last()
}
fun findWeakness(preambleSize: Int, numbers: Sequence<List<Long>>): List<Long>? {
return numbers.firstOrNull {
!availableSums(it.take(preambleSize)).contains(it.last())
}
}
fun part1(): Long {
val numberSequence = inputAsLines.asSequence().map { it.toLong() }.windowed(26)
val ans = findFirstNumberWhichIsNotASum(25, numberSequence)
if (ans == null) {
throw IllegalStateException("Could not find a valid number")
} else {
return ans
}
}
fun findContinguousSumForWeakness(target: Long, numbers: List<Long>): List<Long> {
return (3 until numbers.size).asSequence().mapNotNull { numbersToSum ->
numbers.windowed(numbersToSum).firstOrNull { it.sum() == target }
}.first()
}
fun findMinMax(numbers: List<Long>): Pair<Long, Long> {
return numbers.minOrNull()!! to numbers.maxOrNull()!!
}
fun part2(): Long {
val allNumbers = inputAsLines.map { it.toLong() }
val numberSequence = inputAsLines.asSequence().map { it.toLong() }.windowed(26)
val numbers = findWeakness(25, numberSequence)!!
val sumToFind = numbers.last()
val sumFound = findContinguousSumForWeakness(sumToFind, allNumbers)
val (min, max) = findMinMax(sumFound)
return min + max
}
} | 116 | Kotlin | 0 | 0 | 69fa3dfed62d5cb7d961fe16924066cb7f9f5985 | 2,197 | adventofcode | MIT License |
src/Day01.kt | punx120 | 573,421,386 | false | {"Kotlin": 30825} | fun main() {
fun part1(input: List<String>): Int {
var max = 0
var current = 0
for (row: String in input) {
if (row.isEmpty()) {
if (current > max) {
max = current
}
current = 0
} else {
current += row.toInt()
}
}
return max
}
fun part2(input: List<String>): Int {
var current = 0
val top = mutableListOf<Int>()
for (row: String in input) {
if (row.isEmpty()) {
top.add(current)
if (top.size > 3) {
top.sort()
top.removeAt(0)
}
current = 0
} else {
current += row.toInt()
}
}
return top.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
println(part1(testInput))
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | eda0e2d6455dd8daa58ffc7292fc41d7411e1693 | 1,108 | aoc-2022 | Apache License 2.0 |
src/Day09.kt | haitekki | 572,959,197 | false | {"Kotlin": 24688} | import kotlin.math.absoluteValue
fun main() {
fun calculateLocation(hLocation: Pair<Int, Int>, tLocation: Pair<Int, Int>): Pair<Int, Int> {
val relativePosition = Pair(hLocation.first-tLocation.first, hLocation.second-tLocation.second)
return if (relativePosition.first == 0 &&
relativePosition.second > 1) {
// println("-> 0,+1")
Pair(tLocation.first, tLocation.second + 1)
} else if (relativePosition.first == 0 &&
relativePosition.second < -1) {
// println("-> 0,-1")
Pair(tLocation.first, tLocation.second - 1)
} else if (relativePosition.first > 1 &&
relativePosition.second == 0) {
// println("-> +1,0")
Pair(tLocation.first + 1, tLocation.second)
} else if (relativePosition.first < -1 &&
relativePosition.second == 0) {
// println("-> -1,0")
Pair(tLocation.first - 1, tLocation.second)
} else if (relativePosition.first > 0 &&
relativePosition.second > 0 &&
(relativePosition.first * relativePosition.second).absoluteValue > 1) {
// println("-> +1,+1")
Pair(tLocation.first+1, tLocation.second+1)
} else if (relativePosition.first > 0 &&
relativePosition.second < 0 &&
(relativePosition.first * relativePosition.second).absoluteValue > 1) {
// println("-> +1,-1")
Pair(tLocation.first+1, tLocation.second-1)
} else if (relativePosition.first < 0 &&
relativePosition.second > 0 &&
(relativePosition.first * relativePosition.second).absoluteValue > 1) {
// println("-> -1,+1")
Pair(tLocation.first-1, tLocation.second+1)
} else if (relativePosition.first < 0 &&
relativePosition.second < 0 &&
(relativePosition.first * relativePosition.second).absoluteValue > 1) {
// println("-> -1,-1")
Pair(tLocation.first-1, tLocation.second-1)
} else {
// println("-> 0,0")
Pair(tLocation.first, tLocation.second)
}
}
fun moveHead(inst: String, hLocation: Pair<Int, Int>): Pair<Int, Int> {
return when (inst) {
"U" -> Pair(hLocation.first + 1, hLocation.second)
"D" -> Pair(hLocation.first - 1, hLocation.second)
"R" -> Pair(hLocation.first, hLocation.second + 1)
"L" -> Pair(hLocation.first, hLocation.second - 1)
else -> Pair(0,0)
}
}
fun part1(input: String): Int {
var hLocation = Pair(0,0)
var tLocation = Pair(0,0)
val moveHistory = mutableSetOf("${tLocation.first}-${tLocation.second}")
for(instruction in input.lines()) {
val splittedInstr = instruction.split(" ")
for (moveN in 1..splittedInstr[1].toInt()) {
hLocation = moveHead(splittedInstr[0], hLocation)
tLocation = calculateLocation(hLocation, tLocation)
moveHistory.add("${tLocation.first}-${tLocation.second}")
}
}
return moveHistory.size
}
fun part2(input:String): Int {
var hLocation = Pair(0,0)
val tList: MutableList<Pair<Int,Int>> = mutableListOf(Pair(0,0),Pair(0,0),Pair(0,0),Pair(0,0),Pair(0,0),Pair(0,0),Pair(0,0),Pair(0,0),Pair(0,0))
val moveHistory = mutableSetOf("${tList.last().first}-${tList.last().second}")
for(instruction in input.lines()) {
val splittedInstr = instruction.split(" ")
for (moveN in 1..splittedInstr[1].toInt()) {
hLocation = moveHead(splittedInstr[0], hLocation)
for (i in tList.indices) {
tList[i] = when (i) {
0 -> calculateLocation(hLocation, tList[i])
else -> calculateLocation(tList[i-1], tList[i])
}
}
moveHistory.add("${tList[8].first}-${tList[8].second}")
}
}
return moveHistory.size
}
val testInput =
"""
R 5
U 8
L 8
D 3
R 17
D 10
L 25
U 20
""".trimIndent()
println(part1(testInput))
println(part2(testInput))
val input = readInput("Day09")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | b7262133f9115f6456aa77d9c0a1e9d6c891ea0f | 4,505 | aoc2022 | Apache License 2.0 |
src/cn/ancono/math/discrete/Graph.kt | 140378476 | 105,762,795 | false | {"Java": 1912158, "Kotlin": 1243514} | package cn.ancono.math.discrete
typealias Node = Int
typealias Edge = Pair<Node, Node>
//Created by lyc at 2021-03-02
/**
* Describes a general (undirected) graph that has no multiple edges.
* Generally speaking, in mathematics, the graph can be
* represented by a tuple of nodes(vertices) and edges(arcs): `G = (V,E)`, where the set `E`
* contains tuples like `(u,v), u,v in V` which means there is a (undirected) edge from `u` to `v`.
*
* In this interface,
* nodes are represented using consecutive non-negative integers `0,1,...,n-1` for simplicity.
* Edges are represented by pairs of integers.
*/
interface Graph {
/**
* The number of nodes in this graph.
*/
val n: Int
val nodeCount: Int
get() = n
val nodes: Sequence<Node>
get() = (0 until n).asSequence()
val edgeCount: Int
get() {
return (0 until n).sumOf { this.deg(it) } / 2
}
/**
* Returns all the edges in this graph.
*/
val edges: Sequence<Edge>
/**
* Returns the nodes `x` such that there is an edge from `x` to `a`. , that is, the nodes connected to `a`.
*
* @return nodes `{x | (x,a) in E}`
*/
fun nodesIn(a: Node): Sequence<Node>
/**
* Returns the nodes `x` such that there is an edge from `a` to `x`., that is, the nodes connected from `a`.
*
* @return nodes `{x | (a,x) in E}`
*/
fun nodesOut(a: Node): Sequence<Node>
fun degIn(a: Node): Int
fun degOut(a: Node): Int
fun deg(a: Node): Int
fun containsEdge(a: Node, b: Node): Boolean
// /**
// * Returns the node induced subgraph, that is, the subgraph containing
// * all the given nodes, keeping the related edges.
// */
// fun inducedN(nodes : Set<Node>) : Graph
//
// /**
// * Returns the edge induced subgraph, that is, the subgraph containing
// * all the nodes and only the given edges.
// */
// fun inducedE(edges : Set<Edge>) : Graph
// fun removeN(nodes : S)
}
interface DirectedGraph : Graph {
override fun deg(a: Node): Int {
return degIn(a) + degOut(a)
}
}
interface GraphWithData<V, E> : Graph {
fun getNode(a: Node): V
fun getEdge(a: Node, b: Node): E?
}
operator fun <N, E> GraphWithData<N, E>.get(a: Int): N = this.getNode(a)
operator fun <N, E> GraphWithData<N, E>.get(a: Int, b: Int): E? = this.getEdge(a, b)
//TODO implement mutable graphs
interface EdgeMutableGraph : Graph {
fun addEdge()
fun removeEdge()
}
interface EdgeMutableGraphWithData<N, E> : GraphWithData<N, E>
interface MutableGraph {
} | 0 | Java | 0 | 6 | 02c2984c10a95fcf60adcb510b4bf111c3a773bc | 2,612 | Ancono | MIT License |
untitled/src/main/kotlin/Day6.kt | jlacar | 572,845,298 | false | {"Kotlin": 41161} | class Day6(private val fileName: String) : AocSolution {
override val description get() = "Day 6 - Tuning Trouble ($fileName)"
private val input = InputReader(fileName).text
override fun part1() = solve(input, 4)
override fun part2() = solve(input, 14)
}
private fun solve(dataStream: String, packetSize: Int) =
dataStream.windowed(packetSize, 1).indexOfFirst { isMarker(it) } + packetSize
private fun isMarker(packet: String) = packet.toSet().size == packet.length
fun test(packetSize: Int, input: Map<String, Int>) {
input.map { (input, expected) ->
Pair(expected, solve(input, packetSize))
}.map { (expected, actual) ->
if (expected == actual) "Ok: $actual"
else "Fail: expected [$expected] but got [$actual]"
}.forEach(::println)
}
fun main() {
test(4, mapOf(
"bvwbjplbgvbhsrlpgdmjqwftvncz" to 5,
"nppdvjthqldpwncqszvftbrmjlhg" to 6,
"nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg" to 10,
"zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw" to 11,
))
test(14, mapOf(
"mjqjpqmgbljsphdztnvjfqwrcgsmlb" to 19,
"bvwbjplbgvbhsrlpgdmjqwftvncz" to 23,
"nppdvjthqldpwncqszvftbrmjlhg" to 23,
"nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg" to 29,
"zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw" to 26,
))
Day6("Day6.txt") solution {
part1() shouldBe 1093
part2() shouldBe 3534
}
Day6("Day6-alt.txt") solution {
part1() shouldBe 1155
part2() shouldBe 2789
}
// can we do this?
//
// Day6("Day6.txt") shouldHave {
// resultOf("Ok") forIts { testPart1() }
// resultOf("Ok") forIts { testPart2() }
//
// resultOf(1093) forIts { part1() }
// resultOf(3534) forIts { part2() }
// }
} | 0 | Kotlin | 0 | 2 | dbdefda9a354589de31bc27e0690f7c61c1dc7c9 | 1,755 | adventofcode2022-kotlin | The Unlicense |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.