path stringlengths 5 169 | owner stringlengths 2 34 | repo_id int64 1.49M 755M | is_fork bool 2
classes | languages_distribution stringlengths 16 1.68k ⌀ | content stringlengths 446 72k | issues float64 0 1.84k | main_language stringclasses 37
values | forks int64 0 5.77k | stars int64 0 46.8k | commit_sha stringlengths 40 40 | size int64 446 72.6k | name stringlengths 2 64 | license stringclasses 15
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/main/kotlin/com/nibado/projects/advent/y2017/Day25.kt | nielsutrecht | 47,550,570 | false | null | package com.nibado.projects.advent.y2017
import com.nibado.projects.advent.Day
import com.nibado.projects.advent.Direction
import com.nibado.projects.advent.collect.LList
import com.nibado.projects.advent.resourceLines
object Day25 : Day {
private val input = resourceLines(2017, 25).map { it.trim() }.filterNot { it.isEmpty() }
private fun parse(input: List<String>): Turing {
val begin = Regex("Begin in state ([A-Z]).")
val iters = Regex("Perform a diagnostic checksum after ([0-9]+) steps.")
val inState = Regex("In state ([A-Z]):")
val write = Regex("- Write the value ([0-1]).")
val move = Regex("- Move one slot to the (right|left).")
val cont = Regex("- Continue with state ([A-Z]).")
var i = 0
val state = begin.matchEntire(input[i++])!!.groupValues[1]
val iterations = iters.matchEntire(input[i++])!!.groupValues[1].toInt()
val stateMap = mutableMapOf<String, State>()
while (i < input.size) {
val stateVal = inState.matchEntire(input[i++])!!.groupValues[1]
i++
val ins0 = Instructions(
write.matchEntire(input[i++])!!.groupValues[1].toInt(),
if (move.matchEntire(input[i++])!!.groupValues[1] == "right") Direction.EAST else Direction.WEST,
cont.matchEntire(input[i++])!!.groupValues[1]
)
i++
val ins1 = Instructions(
write.matchEntire(input[i++])!!.groupValues[1].toInt(),
if (move.matchEntire(input[i++])!!.groupValues[1] == "right") Direction.EAST else Direction.WEST,
cont.matchEntire(input[i++])!!.groupValues[1]
)
stateMap[stateVal] = State(ins0, ins1)
}
return Turing(state, iterations, stateMap)
}
override fun part1(): String {
val program = parse(input)
program.run()
return program.values().count { it == 1 }.toString()
}
override fun part2() = "Done!"
class Turing(private var state: String, private var iterations: Int, private var stateMap: Map<String, State>) {
private var tape = LList(null, null, 0)
fun values() = tape.first().values()
fun run() = repeat(iterations, { tick() })
private fun tick() {
val state = stateMap[state]!!
val ins = if (tape.value() == 0) state.ins0 else state.ins1
tape.value(ins.write)
this.state = ins.next
when (ins.move) {
Direction.EAST -> {
if (!tape.hasNext()) {
tape.addNext(0)
}
tape = tape.next()
}
Direction.WEST -> {
if (!tape.hasPrev()) {
tape.addPrev(0)
}
tape = tape.prev()
}
}
}
}
data class State(val ins0: Instructions, val ins1: Instructions)
data class Instructions(val write: Int, val move: Direction, val next: String)
}
| 1 | Kotlin | 0 | 15 | b4221cdd75e07b2860abf6cdc27c165b979aa1c7 | 3,146 | adventofcode | MIT License |
src/leetcode/aprilChallenge2020/weekone/MaxSubArray.kt | adnaan1703 | 268,060,522 | false | null | package leetcode.aprilChallenge2020.weekone
import kotlin.math.max
fun main() {
println(maxSubArray(intArrayOf(-2, 1, -3, 4, -1, 2, 1, -5, 4)))
println(maxSubArray(intArrayOf(-2, -1, -3, -4, -1, -2, -1, -5, -4)))
println(maxSubArray(intArrayOf(1, 2, 3, 4, 5)))
println(maxSubArray(intArrayOf(-11)))
println(maxSubArrayRecursion(intArrayOf(-2, 1, -3, 4, -1, 2, 1, -5, 4)))
println(maxSubArrayRecursion(intArrayOf(-2, -1, -3, -4, -1, -2, -1, -5, -4)))
println(maxSubArrayRecursion(intArrayOf(1, 2, 3, 4, 5)))
println(maxSubArrayRecursion(intArrayOf(-1)))
}
fun maxSubArray(nums: IntArray): Int {
var ans = Int.MIN_VALUE
var sum = 0
var i = 0
var j = 0
while (i < nums.size && j < nums.size) {
sum += nums[j]
ans = max(ans, sum)
++j
if (sum <= 0) {
i = j
sum = 0
}
}
return ans
}
/*
* =============================
* Just for education purposes.
* Heuristic: Divide & Conquer
* =============================
*
* Recursions are always slow.
* Should not be used when data set can be large.
*/
fun maxSubArrayRecursion(nums: IntArray): Int {
return getMaxSubArrayRecursion(nums, 0, nums.size - 1)
}
fun getMaxSubArrayRecursion(nums: IntArray, left: Int, right: Int): Int {
if (left == right)
return nums[left]
val mid: Int = (left + right) / 2
return maxTrips(
getMaxSubArrayRecursion(nums, left, mid),
getMaxSubArrayRecursion(nums, mid + 1, right),
findPivotPointSum(nums, left, mid, right)
)
}
fun maxTrips(a: Int, b: Int, c: Int): Int {
return max(max(a, b), c)
}
fun findPivotPointSum(nums: IntArray, left: Int, mid: Int, right: Int): Int {
var sum = 0
var i = mid
var leftSum: Int = Int.MIN_VALUE
while (i >= left) {
sum += nums[i]
leftSum = max(leftSum, sum)
i--
}
sum = 0
i = mid + 1
var rightSum: Int = Int.MIN_VALUE
while (i <= right) {
sum += nums[i]
rightSum = max(rightSum, sum)
i++
}
return leftSum + rightSum
} | 0 | Kotlin | 0 | 0 | e81915db469551342e78e4b3f431859157471229 | 2,115 | KotlinCodes | The Unlicense |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MatrixReshape.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.LinkedList
import java.util.Queue
/**
* 566. Reshape the Matrix
* @see <a href="https://leetcode.com/problems/reshape-the-matrix/">Source</a>
*/
fun interface MatrixReshape {
operator fun invoke(mat: Array<IntArray>, r: Int, c: Int): Array<IntArray>
}
sealed class MatrixReshapeStrategy {
/**
* Approach 1: Using Queue
* Time complexity : O(m * n).
* Space complexity : O(m * n).
*/
class UsingQueue : MatrixReshape {
override operator fun invoke(mat: Array<IntArray>, r: Int, c: Int): Array<IntArray> {
val res = Array(r) { IntArray(c) }
if (mat.isEmpty() || r * c != mat.size * mat[0].size
) {
return mat
}
val queue: Queue<Int> = LinkedList()
for (i in mat.indices) {
for (j in 0 until mat[0].size) {
queue.add(mat[i][j])
}
}
for (i in 0 until r) {
for (j in 0 until c) {
res[i][j] = queue.remove()
}
}
return res
}
}
/**
* Approach 2: Without Using Extra Space
* Time complexity : O(m * n).
* Space complexity : O(m * n).
*/
class WithoutUsingExtraSpace : MatrixReshape {
override operator fun invoke(mat: Array<IntArray>, r: Int, c: Int): Array<IntArray> {
val res = Array(r) { IntArray(c) }
if (mat.isEmpty() || r * c != mat.size * mat[0].size) {
return mat
}
var rows = 0
var cols = 0
for (i in mat.indices) {
for (j in 0 until mat[0].size) {
res[rows][cols] = mat[i][j]
cols++
if (cols == c) {
rows++
cols = 0
}
}
}
return res
}
}
/**
* Approach 3: Using division and modulus
* Time complexity : O(m * n).
* Space complexity : O(m * n).
*/
class UsingDivision : MatrixReshape {
override operator fun invoke(mat: Array<IntArray>, r: Int, c: Int): Array<IntArray> {
val res = Array(r) { IntArray(c) }
if (mat.isEmpty() || r * c != mat.size * mat[0].size) {
return mat
}
var count = 0
for (i in mat.indices) {
for (j in 0 until mat[0].size) {
res[count / c][count % c] = mat[i][j]
count++
}
}
return res
}
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 3,314 | kotlab | Apache License 2.0 |
src/main/kotlin/me/circuitrcay/euler/challenges/twentySixToFifty/Problem43.kt | adamint | 134,989,381 | false | null | package me.circuitrcay.euler.challenges.twentySixToFifty
import me.circuitrcay.euler.Problem
class Problem43 : Problem<String>() {
override fun calculate(): Any {
val nums = mutableListOf<Long>()
// d1 can be any number
// d4 can be 0, 2, 4, 6, or 8
// d6 can be either 0 or 5
// it must be a pandigital number, so continue if num is not unique inside the loop
// these insights bring solve time down from 15 minutes (brute force) to 300 milliseconds
for (one in 0..9 step 1) {
for (two in 0..9 step 1) {
if (two.isNotUnique(one)) continue
for (three in 0..9 step 1) {
if (three.isNotUnique(one, two)) continue
for (four in 0..8 step 2) {
if (four.isNotUnique(one, two, three)) continue
if (toInt(two, three, four) % 2 == 0) {
for (five in 0..9 step 1) {
if (five.isNotUnique(one, two, three, four)) continue
if (toInt(three, four, five) % 3 == 0) {
for (six in 0..5 step 5) {
if (six.isNotUnique(one, two, three, four, five)) continue
if (toInt(four, five, six) % 5 == 0) {
for (seven in 0..9 step 1) {
if (seven.isNotUnique(one, two, three, four, five, six)) continue
if (toInt(five, six, seven) % 7 == 0) {
for (eight in 0..9 step 1) {
if (eight.isNotUnique(one, two, three, four, five, six, seven)) continue
if (toInt(six, seven, eight) % 11 == 0) {
for (nine in 0..9 step 1) {
if (nine.isNotUnique(one, two, three, four, five, six, seven, eight)) continue
if (toInt(seven, eight, nine) % 13 == 0) {
for (ten in 0..9 step 1) {
if (ten.isNotUnique(one, two, three, four, five, six, seven, eight, nine)) continue
if (toInt(eight, nine, ten) % 17 == 0) {
nums.add(toLong(one, two, three, four, five, six, seven, eight, nine, ten))
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
return nums.sum()
}
private fun Int.isNotUnique(vararg others: Int) = others.contains(this)
private fun toInt(vararg ints: Int) = ints.joinToString("") { it.toString() }.toInt()
private fun toLong(vararg longs: Int) = longs.joinToString("") { it.toString() }.toLong()
} | 0 | Kotlin | 0 | 0 | cebe96422207000718dbee46dce92fb332118665 | 3,823 | project-euler-kotlin | Apache License 2.0 |
src/main/kotlin/day02/Day02.kt | daniilsjb | 434,765,082 | false | {"Kotlin": 77544} | package day02
import java.io.File
fun main() {
val data = parse("src/main/kotlin/day02/Day02.txt")
val answer1 = part1(data)
val answer2 = part2(data)
println("🎄 Day 02 🎄")
println()
println("[Part 1]")
println("Answer: $answer1")
println()
println("[Part 2]")
println("Answer: $answer2")
}
private enum class Action {
Up, Down, Forward,
}
private data class Command(
val action: Action,
val number: Int,
)
private fun parse(path: String): List<Command> =
File(path)
.readLines()
.map(String::toCommand)
private fun String.toCommand(): Command {
val (actionPart, numberPart) = this.split(" ")
val action = when (actionPart) {
"up" -> Action.Up
"down" -> Action.Down
"forward" -> Action.Forward
else -> error("Invalid action")
}
val number = numberPart.toInt()
return Command(action, number)
}
private fun part1(commands: List<Command>): Int {
var (horizontal, depth) = arrayOf(0, 0)
for ((action, number) in commands) {
when (action) {
Action.Up -> depth -= number
Action.Down -> depth += number
Action.Forward -> horizontal += number
}
}
return horizontal * depth
}
private fun part2(commands: List<Command>): Int {
var (horizontal, depth, aim) = arrayOf(0, 0, 0)
for ((action, number) in commands) {
when (action) {
Action.Up -> aim -= number
Action.Down -> aim += number
Action.Forward -> {
horizontal += number
depth += aim * number
}
}
}
return horizontal * depth
}
| 0 | Kotlin | 0 | 1 | bcdd709899fd04ec09f5c96c4b9b197364758aea | 1,695 | advent-of-code-2021 | MIT License |
app/src/main/kotlin/com/resurtm/aoc2023/day17/Solution.kt | resurtm | 726,078,755 | false | {"Kotlin": 119665} | package com.resurtm.aoc2023.day17
import java.util.PriorityQueue
import kotlin.math.min
import kotlin.system.measureTimeMillis
fun launchDay17(testCase: String) {
val grid = readInputGrid(testCase)
val iters = 10
var part1 = 0
val part1msec = measureTimeMillis {
repeat(iters) {
part1 = traverse(grid)
}
}
println("Day 17, part 1: ${part1}, ${part1msec / iters}")
var part2 = 0
val part2msec = measureTimeMillis {
repeat(iters) {
part2 = traverse(grid, minSize = 4, maxSize = 10)
}
}
println("Day 17, part 2: ${part2}, ${part2msec / iters}")
}
private fun traverse(gr: Grid, beginInp: Pos? = null, endInp: Pos? = null, minSize: Int = 0, maxSize: Int = 4): Int {
val begin: Pos = beginInp ?: Pos()
val end: Pos = endInp ?: Pos(gr.size - 1, gr[0].size - 1)
val nodes = mutableMapOf<Node, Int>()
for (row in gr.indices) {
for (col in gr[0].indices) {
val pos = Pos(row, col)
for (idx in 0..maxSize) {
nodes[Node(pos, idx, Dir.TOP)] = Int.MAX_VALUE
nodes[Node(pos, idx, Dir.DOWN)] = Int.MAX_VALUE
nodes[Node(pos, idx, Dir.LEFT)] = Int.MAX_VALUE
nodes[Node(pos, idx, Dir.RIGHT)] = Int.MAX_VALUE
}
}
}
nodes[Node(begin.copy(), 0, Dir.RIGHT)] = 0
nodes[Node(begin.copy(), 0, Dir.DOWN)] = 0
val queue = PriorityQueue<ComparableNode>()
queue.add(ComparableNode(0, Node(begin.copy(), 0, Dir.RIGHT)))
queue.add(ComparableNode(0, Node(begin.copy(), 0, Dir.DOWN)))
val visited = mutableSetOf<Node>()
while (queue.isNotEmpty()) {
val currRaw = queue.poll() ?: continue
val curr = currRaw.node
if (curr in visited) continue
visited.add(curr)
for (nextDir in getNextDirs(curr.dir, curr.steps, minSize, maxSize)) {
val nextPos = getNextPos(curr, nextDir.first, gr) ?: continue
val other = Node(nextPos, nextDir.second, nextDir.first)
if (visited.contains(other)) continue
val distCurr = nodes[curr] ?: throw Exception("Invalid state, node cannot be null")
val distOther = nodes[other] ?: throw Exception("Invalid state, node cannot be null")
val newVal = min(distCurr + gr[nextPos.row][nextPos.col], distOther)
nodes[other] = newVal
queue.add(ComparableNode(newVal, other))
}
}
var res = Int.MAX_VALUE
for (idx in minSize..maxSize) {
res = min(res, nodes[Node(end, idx, Dir.TOP)] ?: Int.MAX_VALUE)
res = min(res, nodes[Node(end, idx, Dir.DOWN)] ?: Int.MAX_VALUE)
res = min(res, nodes[Node(end, idx, Dir.LEFT)] ?: Int.MAX_VALUE)
res = min(res, nodes[Node(end, idx, Dir.RIGHT)] ?: Int.MAX_VALUE)
}
return res
}
private fun getNextPos(node: Node, dir: Dir, gr: Grid): Pos? {
val pos = when (dir) {
Dir.TOP -> node.pos.copy(row = node.pos.row - 1)
Dir.DOWN -> node.pos.copy(row = node.pos.row + 1)
Dir.LEFT -> node.pos.copy(col = node.pos.col - 1)
Dir.RIGHT -> node.pos.copy(col = node.pos.col + 1)
}
val good = pos.row >= 0 && pos.col >= 0 && pos.row <= gr.size - 1 && pos.col <= gr[0].size - 1
return if (good) pos else null
}
private fun getNextDirs(dir: Dir, steps: Int, min: Int, max: Int): Array<Pair<Dir, Int>> = when (dir) {
Dir.TOP -> {
if (steps >= max) arrayOf(Pair(Dir.LEFT, 1), Pair(Dir.RIGHT, 1))
else if (steps < min) arrayOf(Pair(Dir.TOP, steps + 1))
else arrayOf(Pair(Dir.LEFT, 1), Pair(Dir.TOP, steps + 1), Pair(Dir.RIGHT, 1))
}
Dir.DOWN -> {
if (steps >= max) arrayOf(Pair(Dir.LEFT, 1), Pair(Dir.RIGHT, 1))
else if (steps < min) arrayOf(Pair(Dir.DOWN, steps + 1))
else arrayOf(Pair(Dir.LEFT, 1), Pair(Dir.DOWN, steps + 1), Pair(Dir.RIGHT, 1))
}
Dir.LEFT -> {
if (steps >= max) arrayOf(Pair(Dir.TOP, 1), Pair(Dir.DOWN, 1))
else if (steps < min) arrayOf(Pair(Dir.LEFT, steps + 1))
else arrayOf(Pair(Dir.TOP, 1), Pair(Dir.LEFT, steps + 1), Pair(Dir.DOWN, 1))
}
Dir.RIGHT -> {
if (steps >= max) arrayOf(Pair(Dir.TOP, 1), Pair(Dir.DOWN, 1))
else if (steps < min) arrayOf(Pair(Dir.RIGHT, steps + 1))
else arrayOf(Pair(Dir.TOP, 1), Pair(Dir.RIGHT, steps + 1), Pair(Dir.DOWN, 1))
}
}
private fun readInputGrid(testCase: String): Grid {
val reader =
object {}.javaClass.getResourceAsStream(testCase)?.bufferedReader()
?: throw Exception("Invalid state, cannot read an input")
val input = mutableListOf<List<Int>>()
while (true) {
val rawLine = reader.readLine() ?: break
input.add(rawLine.trim().map { "$it".toInt() })
}
return input
}
private typealias Grid = List<List<Int>>
private data class Pos(val row: Int = 0, val col: Int = 0)
private data class Node(val pos: Pos, val steps: Int, val dir: Dir)
private data class ComparableNode(val priority: Int, val node: Node) : Comparable<ComparableNode> {
override fun compareTo(other: ComparableNode) =
if (this.priority > other.priority) 1
else if (this.priority < other.priority) -1
else 0
}
private enum class Dir { TOP, DOWN, LEFT, RIGHT }
| 0 | Kotlin | 0 | 0 | fb8da6c246b0e2ffadb046401502f945a82cfed9 | 5,323 | advent-of-code-2023 | MIT License |
kotlin/17.kt | NeonMika | 433,743,141 | false | {"Kotlin": 68645} | import kotlin.math.max
import kotlin.math.min
import kotlin.math.sign
class Day17 : Day<Day17.Target>("17") {
data class Target(val x: IntRange, val y: IntRange)
data class Projectile(val xVel: Int, val yVel: Int, val x: Int = 0, val y: Int = 0) {
fun step() = Projectile(
x + xVel,
y + yVel,
(if (xVel == 0) 0 else xVel - sign(xVel.toDouble())).toInt(),
yVel - 1
)
fun hits(target: Target) = x in target.x && y in target.y
}
override fun dataStar1(lines: List<String>): Target {
val pattern = """target area: x=(-?\d+)\.\.(-?\d+), y=(-?\d+)\.\.(-?\d+)"""
val (x1, x2, y1, y2) = pattern.toRegex().matchEntire(lines[0])!!.groupValues.drop(1).map { it.toInt() }
return Target(min(x1, x2)..max(x1, x2), min(y1, y2)..max(y1, y2))
}
private fun hitlists(data: Target) = (0..data.x.last).asSequence().flatMap { xVel ->
(min(0, data.y.minOrNull()!!)..1000).asSequence().map { yVel ->
sequence {
var cur = Projectile(xVel, yVel)
yield(cur)
while (cur.x < data.x.last && cur.y > data.y.minOrNull()!!) {
cur = cur.step()
yield(cur)
}
}
}
}.filter { list -> list.any { it.hits(data) } }
override fun star1(data: Target): Any = hitlists(data).maxOf { list -> list.maxOf { it.y } }
override fun star2(data: Target) = hitlists(data).count()
}
fun main() {
Day17()()
} | 0 | Kotlin | 0 | 0 | c625d684147395fc2b347f5bc82476668da98b31 | 1,540 | advent-of-code-2021 | MIT License |
src/main/kotlin/com/github/dangerground/aoc2020/Day2.kt | dangerground | 317,439,198 | false | null | package com.github.dangerground.aoc2020
import com.github.dangerground.aoc2020.util.DayInput
class Day2 {
fun isPasswordMatchingByCount(pwAndPolicy: PasswordAndPolicy): Boolean {
val count = getPasswordLength(pwAndPolicy)
return count >= pwAndPolicy.num1
&& count <= pwAndPolicy.num2
}
private fun getPasswordLength(pwAndPolicy: PasswordAndPolicy) =
pwAndPolicy.password.count { a -> a.toString() == pwAndPolicy.policy }
fun isMatchingByCount(line: String) =
isPasswordMatchingByCount(PasswordAndPolicy(line))
fun isPasswordMatchingByPosition(pwAndPolicy: PasswordAndPolicy): Boolean {
var matched = false
var lastPos = -1
do {
lastPos = pwAndPolicy.password.indexOf(pwAndPolicy.policy, lastPos + 1)
if (lastPos == pwAndPolicy.num1 || lastPos == pwAndPolicy.num2) {
if (matched) {
return false
} else {
matched = true
}
}
} while (lastPos != -1)
return matched
}
fun isMatchingByPosition(line: String) =
isPasswordMatchingByPosition(PasswordAndPolicy(line))
}
class PasswordAndPolicy(line: String) {
private val inputSplitter = Regex("^(\\d+)-(\\d+) ([a-z]):( [a-z]+)$")
val password: String
val num1: Int
val num2: Int
val policy: String
init {
val result = inputSplitter.matchEntire(line) ?: throw Exception("Invalid input")
num1 = result.groupValues[1].toInt()
num2 = result.groupValues[2].toInt()
policy = result.groupValues[3]
password = result.groupValues[4]
}
}
fun main() {
val input = DayInput.asStringList(2)
val day2 = Day2()
// part 1
val part1 = input.count { day2.isMatchingByCount(it) }
println("result part 1: $part1")
// part2
val part2 = input.count { day2.isMatchingByPosition(it) }
println("result part 2: $part2")
} | 0 | Kotlin | 0 | 0 | c3667a2a8126d903d09176848b0e1d511d90fa79 | 2,001 | adventofcode-2020 | MIT License |
src/processor/Main.kt | JIghtuse | 262,494,294 | false | null | package processor
fun toIntList(s: String): List<Int> {
return s.split(" ").filter { it.isNotEmpty() }.map { it.toInt() }
}
fun toDoubleList(s: String): List<Double> {
return s.split(" ").filter { it.isNotEmpty() }.map { it.toDouble() }
}
class Matrix(val items: Array<List<Double>>) {
val rows: Int = items.size
val columns: Int = if (items.isEmpty()) 0 else items[0].size
operator fun plus(other: Matrix): Matrix {
if (rows != other.rows) throw Exception("Could not sum matrix of different dimensions (rows)")
if (columns != other.columns) throw Exception("Could not sum matrix of different dimensions (columns)")
return Matrix(Array(rows) { items[it].zip(other.items[it]) { x, y -> x + y } })
}
operator fun times(scalar: Int): Matrix {
return Matrix(Array(rows) { i -> List(columns) { j -> items[i][j] * scalar } })
}
operator fun times(other: Matrix): Matrix {
if (columns != other.rows) throw Exception("Invalid matrix dimensions")
return Matrix(Array(rows) { i -> List(other.columns) { j -> dotProduct(other.items, i, j) } })
}
private fun dotProduct(otherItems: Array<List<Double>>, thisRow: Int, otherColumn: Int): Double {
var p = 0.0
for (k in 0 until columns) {
p += items[thisRow][k] * otherItems[k][otherColumn]
}
return p
}
override fun toString(): String {
return items.joinToString("\n") { it.joinToString(" ") }
}
companion object {
fun readFromStdin(name: String): Matrix {
print("Enter size of $name matrix: ")
val (rows, columns) = toIntList(readLine()!!)
println("Enter $name matrix:")
return Matrix(Array(rows) { toDoubleList(readLine()!!) })
}
}
}
fun main() {
val actions = arrayListOf(
"Exit",
"Add matrices",
"Multiply matrix to a constant",
"Multiply matrices")
val fs = arrayListOf(
fun() {
val a = Matrix.readFromStdin("first")
val b = Matrix.readFromStdin("second")
println("The sum result is: ")
println(a + b)
},
fun() {
val a = Matrix.readFromStdin("a")
print("Enter a constant: ")
val c = readLine()!!.toInt()
println("The multiplication result is: ")
println(a * c)
},
fun() {
val a = Matrix.readFromStdin("first")
val b = Matrix.readFromStdin("second")
println("The multiplication result is: ")
println(a * b)
}
)
fun printActions() {
for (i in 1..actions.lastIndex) {
println("$i. ${actions[i]}")
}
println("0. ${actions[0]}")
}
runLoop@ while (true) {
printActions()
val action = readLine()!!.toInt()
try {
when (action) {
in 1..3 -> fs[action - 1]()
0 -> break@runLoop
else -> throw Exception("Unknown action $action")
}
} catch (e: java.lang.Exception) {
println("Error: ${e.message}")
}
}
}
| 0 | Kotlin | 0 | 0 | 15f4e0d745a3e6814f783bf215786366d9dfeb9e | 3,293 | numeric-matrix-processor | MIT License |
src/main/kotlin/days/Day19.kt | andilau | 433,504,283 | false | {"Kotlin": 137815} | package days
import kotlin.math.absoluteValue
@AdventOfCodePuzzle(
name = "Beacon Scanner",
url = "https://adventofcode.com/2021/day/19",
date = Date(day = 19, year = 2021)
)
class Day19(val input: String) : Puzzle {
private val scanners = input.parse()
private val alignedScanner: List<Scanner> by lazy { scanners.align() }
override fun partOne() =
alignedScanner.flatMap { it.beacons }.toSet().size
override fun partTwo() =
alignedScanner.flatMap { i ->
alignedScanner.map { j -> i to j }
}
.filterNot { (i, j) -> i == j }
.maxOf { (i, j) -> i.offset.manhattanDistance(j.offset) }
private fun String.parse() = this
.split("\n\n")
.map { section ->
val lines = section.lines()
val id = lines.first().substringAfter("--- scanner ").substringBefore(" ---").toInt()
val beacons = lines.drop(1)
.filter(String::isNotEmpty)
.map { line -> Beacon.from(line) }
.toSet()
Scanner(id, beacons)
}
private fun List<Scanner>.align() = buildList<Scanner> {
val unaligned = this@align.toMutableList()
add(unaligned.removeFirst())
loop@ while (unaligned.isNotEmpty()) {
for (next in unaligned)
for (aligned in this) {
val match = aligned.match(next)
if (match != null) {
add(match)
unaligned.remove(next)
continue@loop
}
}
error("No match found")
}
}
data class Scanner(val id: Int, val beacons: Set<Beacon>, val offset: Beacon = Beacon(0, 0, 0)) {
override fun toString(): String {
return "Scanner #$id beacons=${beacons.size} offset=$offset"
}
fun rotate() = sequence {
yield(beacons)
// @formatter:off
listOf(
"X", "Y", "Z", "XX", "XY", "XZ", "YX", "YY", "ZY", "ZZ",
"XXX", "XXY", "XXZ", "XYX", "XYY", "XZZ", "YXX", "YYY", "ZZZ",
"XXXY", "XXYX", "XYXX", "XYYY"
)
.forEach { dimensions ->
yield(
dimensions.fold(beacons) { p, c ->
when (c) {
'X' -> p.map { it.rotateX() }.toSet()
'Y' -> p.map { it.rotateY() }.toSet()
'Z' -> p.map { it.rotateZ() }.toSet()
else -> error("")
}
})
}
}
fun match(other: Scanner): Scanner? {
for (beacon in beacons) {
for (rotatedBeacons in other.rotate()) {
for (rotatedBeacon in rotatedBeacons) {
val offset = beacon - rotatedBeacon
val shiftedBeacons = rotatedBeacons.map { it + offset }.toSet()
if ((beacons intersect shiftedBeacons).count() >= 12) {
// println("Scanner $id matches scanner ${other.id}")
// println("vector = $offset")
return other.copy(beacons = shiftedBeacons, offset = offset)
}
}
}
}
return null
}
}
data class Beacon(val x: Int, val y: Int, val z: Int) {
fun rotateX() = Beacon(x, -z, y)
fun rotateY() = Beacon(z, y, -x)
fun rotateZ() = Beacon(y, -x, z)
fun manhattanDistance(other: Beacon) =
(x - other.x).absoluteValue + (y - other.y).absoluteValue + (z - other.z).absoluteValue
operator fun plus(other: Beacon) =
Beacon(x + other.x, y + other.y, z + other.z)
operator fun minus(other: Beacon) =
Beacon(x - other.x, y - other.y, z - other.z)
companion object {
fun from(line: String) = line.split(',')
.map(String::toInt)
.let { (x, y, z) -> Beacon(x, y, z) }
}
}
} | 0 | Kotlin | 0 | 0 | b3f06a73e7d9d207ee3051879b83e92b049a0304 | 4,253 | advent-of-code-2021 | Creative Commons Zero v1.0 Universal |
src/main/kotlin/dev/shtanko/algorithms/leetcode/RotateFunction.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import kotlin.math.max
/**
* 396. Rotate Function
* @see <a href="https://leetcode.com/problems/rotate-function/">Source</a>
*/
fun interface RotateFunction {
fun maxRotateFunction(nums: IntArray): Int
}
class RotateFunctionDP : RotateFunction {
override fun maxRotateFunction(nums: IntArray): Int {
val len: Int = nums.size
if (len == 0 || len == 1) return 0
var sum = 0
var dp0 = 0
var max = Int.MIN_VALUE
val dp = IntArray(len + 1)
for (i in 0 until len) {
sum += nums[i]
dp0 += i * nums[i]
}
dp[0] = dp0
for (i in 1..len) {
dp[i] = dp[i - 1] + sum - len * nums[len - i]
max = max(dp[i], max)
}
return max
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,416 | kotlab | Apache License 2.0 |
src/main/kotlin/days/Day5.kt | mir47 | 433,536,325 | false | {"Kotlin": 31075} | package days
import kotlin.math.absoluteValue
class Day5 : Day(5) {
override fun partOne(): Int {
var size = 0
val coords = inputList
.map { it.replace(" -> ", ",") }
.map { it.split(",") }
.map {
val x1 = it[0].toInt()
val y1 = it[1].toInt()
val x2 = it[2].toInt()
val y2 = it[3].toInt()
val maxof = maxOf(x1, y1, x2, y2)
if (maxof + 1 > size) size = maxof + 1
Pair(Pair(x1, y1), Pair(x2, y2))
}
var array = Array(size) { Array(size) { 0 } }
var max = 0
coords.forEach {
if (it.first.second == it.second.second) {
if (it.first.first > it.second.first) {
for (i in (it.second.first) .. (it.first.first)) {
array[it.first.second][i]++
if (array[it.first.second][i] > max) max = array[it.first.second][i]
}
} else {
for (i in (it.first.first) .. (it.second.first)) {
array[it.first.second][i]++
if (array[it.first.second][i] > max) max = array[it.first.second][i]
}
}
} else if (it.first.first == it.second.first) {
if (it.first.second > it.second.second) {
for (j in (it.second.second) .. (it.first.second)) {
array[j][it.first.first]++
if (array[j][it.first.first] > max) max = array[j][it.first.first]
}
} else {
for (j in (it.first.second) .. (it.second.second)) {
array[j][it.first.first]++
if (array[j][it.first.first] > max) max = array[j][it.first.first]
}
}
}
}
var count = 0
array.forEach { ar -> count += ar.count { it >= 2 } }
return count
}
override fun partTwo(): Int {
var size = 0
val coords = inputList
.map { it.replace(" -> ", ",") }
.map { it.split(",") }
.map {
val x1 = it[0].toInt()
val y1 = it[1].toInt()
val x2 = it[2].toInt()
val y2 = it[3].toInt()
val maxof = maxOf(x1, y1, x2, y2)
if (maxof + 1 > size) size = maxof + 1
Pair(Pair(x1, y1), Pair(x2, y2))
}
var array = Array(size) { Array(size) { 0 } }
var max = 0
coords.forEach {
if (it.first.second == it.second.second) {
if (it.first.first > it.second.first) {
for (i in (it.second.first) .. (it.first.first)) {
array[it.first.second][i]++
if (array[it.first.second][i] > max) max = array[it.first.second][i]
}
} else {
for (i in (it.first.first) .. (it.second.first)) {
array[it.first.second][i]++
if (array[it.first.second][i] > max) max = array[it.first.second][i]
}
}
} else if (it.first.first == it.second.first) {
if (it.first.second > it.second.second) {
for (j in (it.second.second) .. (it.first.second)) {
array[j][it.first.first]++
if (array[j][it.first.first] > max) max = array[j][it.first.first]
}
} else {
for (j in (it.first.second) .. (it.second.second)) {
array[j][it.first.first]++
if (array[j][it.first.first] > max) max = array[j][it.first.first]
}
}
} else {
var startX = 0
var startY = 0
var length = (it.first.first - it.second.first).absoluteValue
var dY = 0
if (it.first.first > it.second.first) {
startX = it.second.first
startY = it.second.second
dY = if (it.first.second > it.second.second) 1 else -1
} else {
startX = it.first.first
startY = it.first.second
dY = if (it.first.second > it.second.second) -1 else 1
}
var yInc = startY
for (j in startX..(startX + length)) {
array[yInc][j]++
yInc += dY
}
}
}
var count = 0
array.forEach { ar -> count += ar.count { it >= 2 } }
return count
}
} | 0 | Kotlin | 0 | 0 | 686fa5388d712bfdf3c2cc9dd4bab063bac632ce | 4,891 | aoc-2021 | Creative Commons Zero v1.0 Universal |
src/leetcode_study_badge/data_structure/Day1.kt | faniabdullah | 382,893,751 | false | null | package leetcode_study_badge.data_structure
import java.util.*
class Day1 {
fun singleNumber(nums: IntArray): Int {
/*
https://leetcode.com/problems/single-number/
TC: O(N)
SC: O(1)
// XOR of A XOR A = 0, so all duplicates will cancel each other,
// leaving the non duplicate
*/
var singleNumber = 0
nums.forEach {
singleNumber = singleNumber.xor(it)
}
return singleNumber
}
fun majorityElement(nums: IntArray): Int {
nums.sort()
return nums[nums.size / 2]
}
/*
// https://leetcode.com/problems/3sum/
Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]
-4 -1 -1 0 1 2
*/
fun threeSum(nums: IntArray): List<List<Int>> {
var res = HashSet<List<Int>>()
nums.sort()
for (i in 0 until nums.lastIndex-1){
var j = i+1
var k = nums.lastIndex
var tmp = - nums[i]
while (j < k){
var sum = nums[j] + nums[k]
when {
sum == tmp -> {
res.add(listOf(nums[i],nums[j],nums[k]))
j++
k--
}
sum < tmp ->{
j++
}
else ->{
k--
}
}
}
}
return res.toList()
}
}
fun main() {
println(Day1().singleNumber(intArrayOf(2, 2, 13, 5, 7, 8, 8, 7, 13)))
println(Day1().threeSum(intArrayOf(-2,0,1,1,2)))
} | 0 | Kotlin | 0 | 6 | ecf14fe132824e944818fda1123f1c7796c30532 | 1,684 | dsa-kotlin | MIT License |
src/Day05.kt | RaspiKonk | 572,875,045 | false | {"Kotlin": 17390} | import java.lang.Integer.max
/**
* Day 5: Pakete mit dem Kran umschichten
*
* Part 1: Wie sind die Buchstaben der obersten Paketreihe nach dem Umschichten? Kran kann nur 1 Kiste aufnehmen.
* Part 2: Kran kann auch mhrere Kisten aufnehmen.
*/
fun main()
{
val start = System.currentTimeMillis()
val DAY: String = "05"
println("Advent of Code 2022 - Day $DAY")
//
// fun padRight(s: String?, n: Int): String
// {
// return "%-${n}s".format(s)
// }
// Solve part 1.
// - find number of stacks
// - make array with this size
// - chunk line and add pakets to array
// move stuff
fun part1(input: List<String>): String {
// var numberOfStacks: Int = 0
// var maxLineLength = 0
// // find how many stacks we have
// stacksearch@ for (line in input) {
// if (!line.contains("[") && !line.isEmpty() && !line.contains("move")) {
// maxLineLength = max(maxLineLength, line.length)
// // we hve the line with the stacks:
// // 1 2 3
// var myLine = line.trim()
// var stacks = myLine.split(" ")
// var biggestNumberAsString: String = stacks[stacks.size - 1].trim()
// numberOfStacks = biggestNumberAsString.toInt()
// break@stacksearch
// }
//
// }
// println("Number of stacks: " + numberOfStacks + " longest line: $maxLineLength")
//
//
// val listOfPositions: MutableList<String> = ArrayList()
// for (i in 1..numberOfStacks)
// {
// listOfPositions.add("") // create empty strings
// }
// println(listOfPositions)
//
// parseParcels@for((lineNumber, line) in input.withIndex())
// {
// var myLine:String = if(line.length == maxLineLength) line else padRight(line, maxLineLength+1) // falls die Zeile kürzer ist als die Zeile mit den Zahlen
// if(!myLine.contains("["))
// {
// break
// }
// var chunkedLine = myLine.chunked(numberOfStacks+1)
// println(chunkedLine) // [ , [D] , ]
// for((i, chunk) in chunkedLine.withIndex())
// {
// var myChunk: String = chunk.trim()
// myChunk = myChunk.replace("[", "")
// myChunk = myChunk.replace("]", "")
// if(myChunk.length != 0)
// {
// listOfPositions[i] += myChunk
// }
// println(chunk)
// }
// //stackArray.indices
// }
// println("listOfPositions: " + listOfPositions) // [NZ, DCM, P]
//
// // now reverse the order in each stack so that the top most crate is at the end of the string
// for((i, entry) in listOfPositions.withIndex())
// {
// listOfPositions[i] = listOfPositions[i].reversed()
// }
// println("listOfPositions: " + listOfPositions) // [ZN, MCD, P]
// FUCK IT
val listOfPositions: MutableList<String> = ArrayList()
listOfPositions.clear()
listOfPositions.add("BLDTWCFM")
listOfPositions.add("NBL")
listOfPositions.add("JCHTLV")
listOfPositions.add("SPJW")
listOfPositions.add("ZSCFTLR")
listOfPositions.add("WDGBHNZ")
listOfPositions.add("FMSPVGCN")
listOfPositions.add("WQRJFVCZ")
listOfPositions.add("RPMLH")
// FINALLY: move the crates
for (line in input)
{
if(!line.contains("move"))
{
continue
}
//println(line) // move 1 from 2 to 1
var howMany: Int = 0
var from: Int = 0
var to: Int = 0
var commandInPieces = line.trim().split(" ") // [move, 1, from, 1, to, 2]
//println(commandInPieces)
howMany = commandInPieces[1].toInt()
from = commandInPieces[3].toInt() - 1
to = commandInPieces[5].toInt() - 1
listOfPositions[to] += listOfPositions[from].takeLast(howMany) // Part 1: .reversed() hinzufügen
listOfPositions[from] = listOfPositions[from].dropLast(howMany)
}
// combine answer string
var theAnswer: String = ""
for(entry in listOfPositions)
{
theAnswer += entry.last()
}
return theAnswer
}
// Solve part 2.
fun part2(input: List<String>): Int
{
for(line in input)
{
//println(line)
// siehe oben - einfach das .reversed weglassen
}
return input.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day${DAY}_test")
val input = readInput("Day${DAY}")
// Part 1
//check(part1(testInput) == "CMZ")
println("Part 1: ${part1(input)}") // TGWSMRBPN
// Part 2
//check(part2(testInput) == 24000)
//println("Part 2: ${part2(input)}") // TZLTLWRNF
val elapsedTime = System.currentTimeMillis() - start
println("Elapsed time: $elapsedTime ms")
} | 0 | Kotlin | 0 | 1 | 7d47bea3a5e8be91abfe5a1f750838f2205a5e18 | 4,332 | AoC_Kotlin_2022 | Apache License 2.0 |
src/main/kotlin/File07.kt | andrewrlee | 319,095,151 | false | null | import java.io.File
import java.nio.charset.StandardCharsets.UTF_8
private class Challenge07 {
data class Bag(val description: String, val quantity: Int, val children: List<Bag> = emptyList()) {
constructor(args: List<String>) : this(args[2], args[1].toInt())
companion object {
val fullLineRegex = "^(.*?) bags contain (.*?).$".toRegex()
val contentRegex = "^(\\d)+ (.*) bag[s]*$".toRegex()
fun extract(regex: Regex, value: String) = regex.find(value)?.groupValues
fun extractContents(line: String) =
line.split(',').mapNotNull { extract(contentRegex, it.trim())?.let(::Bag) }
fun create(line: String) = extract(fullLineRegex, line)!!.let { Bag(it[1], 1, extractContents(it[2])) }
}
}
val bags = File("src/main/resources/07-input.txt").readLines(UTF_8).map(Bag::create)
val containingBags: Map<String, List<String>> = bags
.flatMap { bag -> bag.children.map { Pair(it.description, bag.description) } }
.groupBy { it.first }
.mapValues { it.value.map { it.second } }
fun findContainingBags(bagName: String, seen: Set<String> = emptySet()): Set<String> {
val containers = containingBags[bagName] ?: return seen
return containers.flatMap { findContainingBags(it, seen + containers) }.toSet()
}
fun findAnswer1v1() = findContainingBags("shiny gold").count()
val containedBags = bags.groupBy { it.description }.mapValues { it.value[0] }
fun countContainedBags(bagName: String): Int =
1 + containedBags[bagName]!!.children.map { it.quantity * countContainedBags(it.description) }.sum()
fun findAnswer2v1() = countContainedBags("shiny gold") - 1 // don't count the shiny gold bag!
fun solve() {
println(findAnswer1v1())
println(findAnswer2v1())
}
}
fun main() = Challenge07().solve() | 0 | Kotlin | 0 | 0 | a9c21a6563f42af7fada3dd2e93bf75a6d7d714c | 1,903 | adventOfCode2020 | MIT License |
Kotlin/src/NextPermutation.kt | TonnyL | 106,459,115 | false | null | /**
* Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
*
* If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
*
* The replacement must be in-place, do not allocate extra memory.
*
* Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
* 1,2,3 → 1,3,2
* 3,2,1 → 1,2,3
* 1,1,5 → 1,5,1
*
* Accepted.
*/
class NextPermutation {
fun nextPermutation(nums: IntArray) {
var i = nums.size - 2
while (i >= 0 && nums[i] >= nums[i + 1]) {
i--
}
if (i >= 0) {
var j = nums.size - 1
while (nums[j] <= nums[i]) {
j--
}
swap(nums, i, j)
}
reverse(nums, i + 1, nums.size - 1)
}
private fun swap(nums: IntArray, i: Int, j: Int) {
val tmp = nums[i]
nums[i] = nums[j]
nums[j] = tmp
}
private fun reverse(nums: IntArray, i: Int, j: Int) {
var tmpI = i
var tmpJ = j
while (tmpI < tmpJ) {
swap(nums, tmpI++, tmpJ--)
}
}
}
| 1 | Swift | 22 | 189 | 39f85cdedaaf5b85f7ce842ecef975301fc974cf | 1,241 | Windary | MIT License |
src/tsp/Distance.kt | dbcorish | 394,464,582 | false | {"Kotlin": 19701} | package tsp
import kotlin.math.sqrt
/**
* Handles all distance calculations
*/
object Distance {
/**
* Calculates total distance of journey
*/
fun total(tempSolutionAr: IntArray)
: Double {
var totalDistance = 0.0
for (i in 0 until numberOfCities - 1) {
city1 = tempSolutionAr[i]
city2 = tempSolutionAr[i + 1]
val distanceBetweenCities = Distance.betweenCities(city1, city2)
totalDistance += distanceBetweenCities
}
return totalDistance
}
/**
* Calculates distance between two cities, based on Haversine formula
*/
fun betweenCities(city1: Int, city2: Int)
: Double {
val earthRadius = 6371.0
val lat1 = Math.toRadians(xCoordinatesAr[city1])
val lon1 = Math.toRadians(yCoordinatesAr[city1])
val lat2 = Math.toRadians(xCoordinatesAr[city2])
val lon2 = Math.toRadians(yCoordinatesAr[city2])
val latDistance = lat2 - lat1
val lonDistance = lon2 - lon1
val x =
(StrictMath.pow(StrictMath.sin(latDistance / 2.0), 2.0) +
(StrictMath.cos(lat1) *
StrictMath.cos(lat2) *
StrictMath.pow(StrictMath.sin(lonDistance / 2.0), 2.0)))
val y = StrictMath.asin(sqrt(x)) * 2.0
return y * earthRadius
}
/**
* Checks that cities and their neighbours' distances are over the minimum distance
*/
fun checkOverMin(tempAr: IntArray, cityToCheck: Int): Boolean {
// Handles edge cases of 0 and 1000
return when (cityToCheck) {
0 -> minDistanceBetweenCities < Distance.betweenCities(
tempAr[cityToCheck],
tempAr[cityToCheck + 1]
)
numberOfCities-1 -> minDistanceBetweenCities < Distance.betweenCities(
tempAr[cityToCheck],
tempAr[cityToCheck - 1]
)
else -> (minDistanceBetweenCities < Distance.betweenCities(tempAr[cityToCheck], tempAr[cityToCheck - 1])
&&
minDistanceBetweenCities < Distance.betweenCities(tempAr[cityToCheck], tempAr[cityToCheck + 1])
)
}
}
} | 0 | Kotlin | 0 | 0 | c0e6f74f431dcc37890ab07835bd7e9979296beb | 2,351 | kotlin-tsp-solver | MIT License |
src/Day07_part1.kt | lowielow | 578,058,273 | false | {"Kotlin": 29322} | fun main() {
fun part1(input: List<String>): Int {
val dir = mutableListOf<String>()
val list = mutableListOf<MutableList<String>>()
var rawList = mutableListOf<String>()
val dirRegex = Regex("\\$ cd ([a-z]+|/)")
val listRegex = Regex("^([a-z]*\\d*) ([a-z][.a-z]*)$")
var totalSum = 0
var count = 0
for (str in input) {
if (dirRegex.matches(str)) {
if (rawList.isNotEmpty()) {
list.add(rawList)
rawList = mutableListOf()
}
val dirMatch = dirRegex.find(str)!!
dir.add(dirMatch.groupValues[1])
} else if (listRegex.matches(str)) {
val listMatch = listRegex.find(str)!!
rawList.add(listMatch.groupValues[1])
rawList.add(listMatch.groupValues[2])
}
}
list.add(rawList)
for (i in list.indices) {
for (j in list[i].indices) {
if (list[i][j] == "dir") {
count++
}
}
}
while (true) {
for (i in list.size - 1 downTo 0) {
loop@for (j in list[i].indices step 2) {
if (list[i][j] == "dir") {
var newValue = 0
var k = 0
for (x in dir.indices) {
if (x > i && list[i][j + 1] == dir[x]) {
k = x
break
}
}
for (l in list[k].indices step 2) {
if (list[k][l].toIntOrNull() != null) {
newValue += list[k][l].toInt()
}
}
list[i][j] = newValue.toString()
count--
}
}
}
if (count == 0) {
break
}
}
for (i in list.indices) {
var currSum = 0
for (j in list[i].indices step 2) {
currSum += list[i][j].toInt()
}
if (currSum <= 100000) {
totalSum += currSum
}
}
return totalSum
}
val input = readInput("Day07")
part1(input).println()
} | 0 | Kotlin | 0 | 0 | acc270cd70a8b7f55dba07bf83d3a7e72256a63f | 2,460 | aoc2022 | Apache License 2.0 |
src/aoc2022/Day04.kt | RobertMaged | 573,140,924 | false | {"Kotlin": 225650} | package aoc2022
fun main() {
fun String.splitElves() = this.split(',').map { elf ->
val (startSection, endSection) = elf.split('-').map { it.toInt() }
startSection..endSection
}
fun part1(input: List<String>): Int = input.count { assignmentPair ->
val (firstElf, secondElf) = assignmentPair.splitElves()
return@count when ((firstElf intersect secondElf).size) {
firstElf.count(), secondElf.count() -> true
else -> false
}
}
fun part2(input: List<String>): Int = input.count { line ->
val (firstElf, secondElf) = line.splitElves()
return@count (firstElf intersect secondElf).any()
}
val testInput = readInput("Day04_test")
check(part1(testInput).also(::println) == 2)
check(part2(testInput).also(::println) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
// part one alternative
// firstElf.first <= secondElf.first && firstElf.last >= secondElf.last -> count++
// secondElf.first <= firstElf.first && secondElf.last >= firstElf.last -> count++ | 0 | Kotlin | 0 | 0 | e2e012d6760a37cb90d2435e8059789941e038a5 | 1,132 | Kotlin-AOC-2023 | Apache License 2.0 |
src/Day03.kt | alexladeira | 573,196,827 | false | {"Kotlin": 3920} | fun main() {
val sum = part2()
print(sum)
}
private fun part2() = readInput("Day03").chunked(3).fold(0) { acc, strings ->
val lowerCaseRange = CharProgression.fromClosedRange('a', 'z', 1)
strings[0].find { c -> strings[1].contains(c) && strings[2].contains(c) }.let { c ->
if (lowerCaseRange.contains(c)) {
acc + c!!.code - 96
} else {
acc + c!!.code - 38
}
}
}
private fun part1() = readInput("Day03").fold(0) { acc, s ->
val str0 = s.substring(0, s.length / 2)
val str1 = s.substring(s.length / 2)
val lowerCaseRange = CharProgression.fromClosedRange('a', 'z', 1)
str0.find { c -> str1.contains(c) }.let { c ->
if (lowerCaseRange.contains(c)) {
acc + c!!.code - 96
} else {
acc + c!!.code - 38
}
}
} | 0 | Kotlin | 0 | 0 | facafc2d92de2ad2b6264610be4159c8135babcb | 839 | aoc-2022-in-kotlin | Apache License 2.0 |
aoc_2023/src/main/kotlin/problems/day24/HailSimulator.kt | Cavitedev | 725,682,393 | false | {"Kotlin": 228779} | package problems.day24
import com.microsoft.z3.Context
import com.microsoft.z3.Status
import java.math.BigDecimal
import java.math.MathContext
class HailSimulator(lines: List<String>) {
val hailstones = lines.map { line ->
val (cord, mov) = line.split("@").map {
val splits = it.split(",").map { splittedCoord ->
splittedCoord.trim().toBigDecimal(MathContext(20))
}
HailCoordinate(splits[0], splits[1], splits[2])
}
Hailstone(cord, mov)
}
fun intersectionsXY(): List<HailCoordinate> {
val returnIntersections = mutableListOf<HailCoordinate>()
for (i in 0..<this.hailstones.size) {
for (j in i + 1..<this.hailstones.size) {
val intersection = this.hailstones[i].intersectionXY(this.hailstones[j]) ?: continue
returnIntersections.add(intersection)
}
}
return returnIntersections
}
fun intersectionsIn2DArea(min: BigDecimal, max: BigDecimal): List<HailCoordinate> {
return intersectionsXY().filter {
it.x >= min && it.x <= max &&
it.y >= min && it.y <= max
}
}
fun combinations(): List<Pair<Hailstone, Hailstone>> {
val combinations = mutableListOf<Pair<Hailstone, Hailstone>>()
for (i in 0..<this.hailstones.size) {
for (j in i + 1..<this.hailstones.size) {
combinations.add(Pair(hailstones[i], hailstones[j]))
}
}
return combinations
}
fun relativePositions(): List<Int> {
return combinations().map { it.first.relativePosition(it.second) }
}
fun firstPlane(): HailPlane {
for (i in 0..<this.hailstones.size) {
for (j in i + 1..<this.hailstones.size) {
val plane = this.hailstones[i].planeParalelLines(this.hailstones[j]) ?: continue
return plane
}
}
throw Exception("Unreachable")
}
fun rockThrown(): Hailstone {
val plane = firstPlane()
val usedHailstones = mutableListOf<Hailstone>()
val intersections = mutableListOf<HailCoordinate>()
for (hailstone in hailstones) {
try {
val planes = hailstone.toPlanes()
val intersection = plane.intersection(planes[0], planes[1])
intersections.add(intersection)
usedHailstones.add(hailstone)
} catch (e: ArithmeticException) {
}
if (intersections.size >= 2) break
}
// val planesHailStones = this.hailstones.take(2).map { it.toPlanes() }
// val intersections = planesHailStones.map { plane.intersection(it[0], it[1]) }
val timeIntersection1 = (intersections[0].x - usedHailstones[0].pos.x) / usedHailstones[0].vel.x
val timeIntersection2 = (intersections[1].x - usedHailstones[1].pos.x) / usedHailstones[1].vel.x
return rockFromTimesAndIntersections(listOf(timeIntersection1, timeIntersection2), intersections)
}
private fun rockFromTimesAndIntersections(
usedTimes: List<BigDecimal>,
intersections: List<HailCoordinate>,
): Hailstone {
val timeIntersection1 = usedTimes[0]
val timeIntersection2 = usedTimes[1]
if (timeIntersection1 < timeIntersection2) {
return rockFromIntersectionsAndTime(intersections[0], intersections[1], timeIntersection1)
} else {
return rockFromIntersectionsAndTime(intersections[1], intersections[0], timeIntersection1)
}
}
private fun rockFromIntersectionsAndTime(
firstIntersection: HailCoordinate,
secondIntersection: HailCoordinate,
timeIntersection1: BigDecimal
): Hailstone {
val speed = secondIntersection.subtract(firstIntersection)
val startPos = secondIntersection.subtract(speed.multiply(timeIntersection1))
return Hailstone(startPos, speed)
}
fun rockThrownBruteForcing(): Hailstone? {
for (x in -400..400) {
for (y in -400..400) {
for (z in -400..400) {
val adjustedSpeed = HailCoordinate(x.toBigDecimal(), y.toBigDecimal(), z.toBigDecimal())
val adjustedHailstones = hailstones.map {
Hailstone(it.pos, it.vel.subtract(adjustedSpeed))
}
val refHailstone = adjustedHailstones.first()
var intersect = refHailstone.intersectionXYZ(adjustedHailstones[1])
var index = 2
while (intersect != null) {
if (index >= adjustedHailstones.size) {
val timeIntersection1 =
(intersect.x - adjustedHailstones[0].pos.x) / adjustedHailstones[0].vel.x
val timeIntersection2 =
(intersect.x - adjustedHailstones[1].pos.x) / adjustedHailstones[1].vel.x
val timeIntersections = listOf(timeIntersection1, timeIntersection2)
val intersections = this.hailstones.take(2).mapIndexed { index, hailstone ->
hailstone.pos.add(hailstone.vel.multiply(timeIntersections[index]))
}
print("SOL")
val orderedIntersections = timeIntersections.zip(intersections).sortedBy { it.first }
val vel =
(orderedIntersections[1].second.subtract(orderedIntersections[0].second)).divide(
orderedIntersections[1].first - orderedIntersections[0].first
)
val position =
orderedIntersections[0].second.subtract(vel.multiply(orderedIntersections[0].first))
return Hailstone(position, vel)
// solution
}
val nextHailstone = adjustedHailstones[index]
val newIntersect = refHailstone.intersectionXYZ(nextHailstone)
if (newIntersect != intersect) break
index++
}
}
}
}
return null
}
fun resolveEquations(): Hailstone? {
val ctx = Context()
val t1 = ctx.mkRealConst("t1")
val t2 = ctx.mkRealConst("t2")
val t3 = ctx.mkRealConst("t3")
val x = ctx.mkRealConst("x")
val vx = ctx.mkRealConst("vx")
val y = ctx.mkRealConst("y")
val vy = ctx.mkRealConst("vy")
val z = ctx.mkRealConst("z")
val vz = ctx.mkRealConst("vz")
val hailstone1 = this.hailstones[0]
val hailstone2 = this.hailstones[1]
val hailstone3 = this.hailstones[2]
val el1_x = ctx.mkReal(hailstone1.pos.x.toPlainString())
val el1_vx = ctx.mkReal(hailstone1.vel.x.toPlainString())
val el2_x = ctx.mkReal(hailstone2.pos.x.toPlainString())
val el2_vx = ctx.mkReal(hailstone2.vel.x.toPlainString())
val el3_x = ctx.mkReal(hailstone3.pos.x.toPlainString())
val el3_vx = ctx.mkReal(hailstone3.vel.x.toPlainString())
val el1_y = ctx.mkReal(hailstone1.pos.y.toPlainString())
val el1_vy = ctx.mkReal(hailstone1.vel.y.toPlainString())
val el2_y = ctx.mkReal(hailstone2.pos.y.toPlainString())
val el2_vy = ctx.mkReal(hailstone2.vel.y.toPlainString())
val el3_y = ctx.mkReal(hailstone3.pos.y.toPlainString())
val el3_vy = ctx.mkReal(hailstone3.vel.y.toPlainString())
val el1_z = ctx.mkReal(hailstone1.pos.z.toPlainString())
val el1_vz = ctx.mkReal(hailstone1.vel.z.toPlainString())
val el2_z = ctx.mkReal(hailstone2.pos.z.toPlainString())
val el2_vz = ctx.mkReal(hailstone2.vel.z.toPlainString())
val el3_z = ctx.mkReal(hailstone3.pos.z.toPlainString())
val el3_vz = ctx.mkReal(hailstone3.vel.z.toPlainString())
val eq1 = ctx.mkEq(
ctx.mkSub(el1_x, ctx.mkMul(el1_vx, t1)),
ctx.mkAdd(x, ctx.mkMul(vx, t1))
)
val eq2 = ctx.mkEq(
ctx.mkSub(el2_x, ctx.mkMul(el2_vx, t2)),
ctx.mkAdd(x, ctx.mkMul(vx, t2))
)
val eq3 = ctx.mkEq(
ctx.mkSub(el3_x, ctx.mkMul(el3_vx, t3)),
ctx.mkAdd(x, ctx.mkMul(vx, t3))
)
val eq4 = ctx.mkEq(
ctx.mkSub(el1_y, ctx.mkMul(el1_vy, t1)),
ctx.mkAdd(y, ctx.mkMul(vy, t1))
)
val eq5 = ctx.mkEq(
ctx.mkSub(el2_y, ctx.mkMul(el2_vy, t2)),
ctx.mkAdd(y, ctx.mkMul(vy, t2))
)
val eq6 = ctx.mkEq(
ctx.mkSub(el3_y, ctx.mkMul(el3_vy, t3)),
ctx.mkAdd(y, ctx.mkMul(vy, t3))
)
val eq7 = ctx.mkEq(
ctx.mkSub(el1_z, ctx.mkMul(el1_vz, t1)),
ctx.mkAdd(z, ctx.mkMul(vz, t1))
)
val eq8 = ctx.mkEq(
ctx.mkSub(el2_z, ctx.mkMul(el2_vz, t2)),
ctx.mkAdd(z, ctx.mkMul(vz, t2))
)
val eq9 = ctx.mkEq(
ctx.mkSub(el3_z, ctx.mkMul(el3_vz, t3)),
ctx.mkAdd(z, ctx.mkMul(vz, t3))
)
val solver = ctx.mkSolver()
// Add equations to the solver
solver.add(eq1)
solver.add(eq2)
solver.add(eq3)
solver.add(eq4)
solver.add(eq5)
solver.add(eq6)
solver.add(eq7)
solver.add(eq8)
solver.add(eq9)
val result = solver.check()
if (result == Status.SATISFIABLE) {
// Get the model
val model = solver.model
// Get parameter values from the model
val xValue = model.eval(x, false).toString()
val yValue = model.eval(y, false).toString()
val zValue = model.eval(z, false).toString()
val vxValue = model.eval(vx, false).toString()
val vyValue = model.eval(vy, false).toString()
val vzValue = model.eval(vz, false).toString()
// Print parameter values
// println("x = $xValue")
// println("y = $yValue")
// println("z = $zValue")
// println("vx = $vxValue")
// println("vy = $vyValue")
// println("vz = $vzValue")
return Hailstone(
HailCoordinate(BigDecimal(xValue), BigDecimal(yValue), BigDecimal(zValue)),
HailCoordinate(BigDecimal(vxValue), BigDecimal(vyValue), BigDecimal(vzValue))
)
} else {
println("No solution found.")
return null
}
}
} | 0 | Kotlin | 0 | 1 | aa7af2d5aa0eb30df4563c513956ed41f18791d5 | 10,845 | advent-of-code-2023 | MIT License |
app/src/main/java/com/fq/algorithm/Graph.kt | lodqc | 682,931,448 | false | null | package com.fq.algorithm
import java.util.LinkedList
import java.util.PriorityQueue
import java.util.Queue
class Graph {
var nodes: HashMap<Int, Node> = HashMap()
var edges: HashSet<Edge> = HashSet()
}
class Node(var value: Int) {
var `in` = 0
var out = 0
var nexts: ArrayList<Node> = ArrayList()
var edges: ArrayList<Edge> = ArrayList()
}
class Edge(var weight: Int, var from: Node, var to: Node)
object GraphUtils {
fun createGraph(matrix: Array<IntArray>): Graph {
val graph = Graph()
for (i in matrix.indices) {
val from = matrix[i][0]
val to = matrix[i][1]
val weight = matrix[i][2]
if (!graph.nodes.containsKey(from)) {
graph.nodes[from] = Node(from)
}
if (!graph.nodes.containsKey(to)) {
graph.nodes[to] = Node(to)
}
val fromNode = graph.nodes[from]!!
val toNode = graph.nodes[to]!!
val edge = Edge(weight, fromNode, toNode)
fromNode.nexts.add(toNode)
fromNode.out++
toNode.`in`++
fromNode.edges.add(edge)
graph.edges.add(edge)
}
return graph
}
}
fun sortedTopology(graph: Graph): List<Node> {
//key:某一个node
//value:剩余的入度
val inMap = java.util.HashMap<Node, Int>()
//入度为0的点,才能进这个队列
val zeroInQueue: Queue<Node> = LinkedList()
for (node in graph.nodes.values) {
inMap[node] = node.`in`
if (node.`in` == 0) {
zeroInQueue.add(node)
}
}
//拓扑排序的结果,依次加入resu1t
val result: MutableList<Node> = java.util.ArrayList()
while (!zeroInQueue.isEmpty()) {
val cur = zeroInQueue.poll()!!
result.add(cur)
for (next in cur.nexts) {
inMap[next] = inMap[next]!! - 1
if (inMap[next] == 0) {
zeroInQueue.add(next)
}
}
}
return result
}
fun primMST(graph: Graph): Set<Edge>{
//解锁的边进入小根堆
val priorityQueue = PriorityQueue(EdgeComparator())
val set = java.util.HashSet<Node>()
val result: MutableSet<Edge> = java.util.HashSet() //依次挑选的的边在result里
for (node in graph.nodes.values) { //随便挑了一个点
//node是开始点
if (!set.contains(node)) {
set.add(node)
//由一个点,解锁所有相连的边
priorityQueue.addAll(node.edges)
while (!priorityQueue.isEmpty()) {
val edge = priorityQueue.poll()!! //弹出解锁的边中,最小的边
val toNode = edge.to //可能的一个新的点
if (!set.contains(toNode)) { //不含有的时候,就是新的点
set.add(toNode)
result.add(edge)
for (nextEdge in toNode.edges) {
priorityQueue.add(nextEdge)
//break;
}
}
}
}
}
return result
}
fun dijkstra1(head: Node): java.util.HashMap<Node, Int> {
//从head出发到所有点的最小距离
//key:从head出发到达key
//value:从head出发到达key的最小距离
//如果在表中,没有T的记录,含义是从head出发到T这个点的距离为正无穷
val distanceMap = java.util.HashMap<Node, Int>()
distanceMap[head] = 0
//已经求过距离的节点,存在selectedNodes中,以后再也不碰
val selectedNodes = java.util.HashSet<Node>()
var minNode = getMinDistanceAndUnselectedNode(distanceMap, selectedNodes)
while (minNode != null) {
val distance = distanceMap[minNode]!!
for (edge in minNode.edges) {
val toNode = edge.to
if (!distanceMap.containsKey(toNode)) {
distanceMap[toNode] = distance + edge.weight
}
distanceMap[edge.to] = Math.min(
distanceMap[toNode]!!,
distance + edge.weight
)
}
selectedNodes.add(minNode)
minNode = getMinDistanceAndUnselectedNode(distanceMap, selectedNodes)
}
return distanceMap
}
fun getMinDistanceAndUnselectedNode(
distanceMap: java.util.HashMap<Node, Int>,
touchedNodes: java.util.HashSet<Node>
): Node? {
var minNode: Node? = null
var minDistance = Int.MAX_VALUE
for ((node, distance) in distanceMap) {
if (!touchedNodes.contains(node) && distance < minDistance) {
minNode = node
minDistance = distance
}
}
return minNode
}
//从head出发,所有head能到达的节点,生成到达每个节点的最小路径记录并返回
fun dijkstra2(head: Node?, size: Int): java.util.HashMap<Node, Int> {
val nodeHeap = NodeHeap(size)
nodeHeap.addorUpdateOrIgnore(head, 0)
val result = java.util.HashMap<Node, Int>()
while (!nodeHeap.isEmpty) {
val record = nodeHeap.pop()
val cur = record.node
val distance = record.distance
for (edge in cur.edges) {
nodeHeap.addorUpdateOrIgnore(edge.to, edge.weight + distance)
}
result[cur] = distance
}
return result
}
fun main(args: Array<String>) {
val graph =
GraphUtils.createGraph(arrayOf(intArrayOf(0, 1, 5), intArrayOf(1, 2, 3), intArrayOf(0, 2, 7)))
print(graph)
} | 0 | Kotlin | 0 | 0 | bb50160451db7ca86eabe51478afa3e1f5c95e9b | 5,474 | algorithm | Apache License 2.0 |
stepik/sportprogramming/RecursiveComivoigerSolution.kt | grine4ka | 183,575,046 | false | {"Kotlin": 98723, "Java": 28857, "C++": 4529} | package stepik.sportprogramming
private var a: Array<IntArray> = emptyArray()
private var ans: Int = Int.MAX_VALUE
private var ansPerm: String = ""
private var p: IntArray = intArrayOf()
private var used: BooleanArray = booleanArrayOf()
private var n: Int = 0
fun main() {
n = readInt()
a = Array(n) {
readInts()
}
p = IntArray(n) { 0 }
used = BooleanArray(n) { false }
p[0] = 0
recNew(1, 0)
println("The shortest path is $ansPerm with value $ans")
}
private fun recNew(idx: Int, len: Int) {
if (len >= ans) {
return
}
if (idx == n) {
val length = len + a[p[idx - 1]][0]
if (length < ans) {
ansPerm = p.joinToString(prefix = "{", postfix = "}")
ans = length
}
return
}
for (i in 1 until n) {
if (used[i]) continue
p[idx] = i
used[i] = true
recNew(idx + 1, len + a[p[idx - 1]][i])
used[i] = false
}
}
private fun readInt() = readLine()!!.toInt()
private fun readInts() = readLine()!!.split(" ").map(String::toInt).toIntArray()
| 0 | Kotlin | 0 | 0 | c967e89058772ee2322cb05fb0d892bd39047f47 | 1,099 | samokatas | MIT License |
app/src/main/java/com/example/algoview/ui/algoview/Graph.kt | youness-1 | 544,147,511 | false | {"Kotlin": 28008} | package com.example.algoview.ui.algoview
import java.util.*
import kotlin.math.abs
import kotlin.math.sqrt
class Edge(var destination: Vertex, var weight: Double)
class Vertex(
var id: Int,
var i: Int, var j: Int
) : Comparable<Vertex> {
var parent: Vertex? = null
var distance = Double.POSITIVE_INFINITY
var edges: LinkedList<Edge> = LinkedList<Edge>()
var discovered = false
var heuristic = 0.0
var f = Double.POSITIVE_INFINITY
override operator fun compareTo(other: Vertex): Int {
return distance.compareTo(other.distance)
}
}
class Graph(heuristicType: Heuristic) {
private var heuristicType: Heuristic
private var vertex = ArrayList<Vertex>()
init {
this.heuristicType=heuristicType
}
fun addVertex(id: Int, i: Int, j: Int) {
val v1 = Vertex(id, i, j)
vertex.add(v1)
}
fun addEdge(source: Vertex, destination: Vertex?, weight: Double) {
source.edges.add(Edge(destination!!, weight))
}
fun getVertex(i: Int, j: Int): Vertex? {
for (c in vertex.indices) if (vertex[c].i == i && vertex[c].j == j) return vertex[c]
return null
}
fun heuristic(v: Vertex, destination: Vertex) {
if (heuristicType == Heuristic.EUCLIDEAN){
v.heuristic = sqrt(((v.i - destination.i) * (v.i - destination.i) + (v.j - destination.j) * (v.j - destination.j)).toDouble())
}
else{
v.heuristic = abs(destination.i.toDouble() - v.i.toDouble()) + abs(destination.j.toDouble() - v.j.toDouble())
}
}
}
enum class Algorithm(val type: Int) {
DIJKSTRA(1),
ASTAR(2)
}
enum class Heuristic {
MANHATTAN,
EUCLIDEAN
} | 0 | Kotlin | 0 | 0 | f420e99ebe2636f4152392784eb7caf1ede23434 | 1,704 | AlgoView | Creative Commons Zero v1.0 Universal |
src/Day01.kt | Qdelix | 574,590,362 | false | null | fun main() {
fun part1(input: List<String>): Int {
var highestSum = 0
var actualSum = 0
input.forEach { inputLine ->
if (inputLine.isNotEmpty()) {
actualSum += inputLine.toInt()
} else {
if (actualSum > highestSum) {
highestSum = actualSum
}
actualSum = 0
}
}
return highestSum
}
fun part2(input: List<String>): Int {
var firstSum = 0
var secondSum = 0
var thirdSum = 0
var actualSum = 0
input.forEach { inputLine ->
if (inputLine.isNotEmpty()) {
actualSum += inputLine.toInt()
} else {
if (actualSum > firstSum) {
thirdSum = secondSum
secondSum = firstSum
firstSum = actualSum
} else if (actualSum > secondSum) {
thirdSum = secondSum
secondSum = actualSum
} else if (actualSum > thirdSum) {
thirdSum = actualSum
}
actualSum = 0
}
}
return firstSum + secondSum + thirdSum
}
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 8e5c599d5071d9363c8f33b800b008875eb0b5f5 | 1,351 | aoc22 | Apache License 2.0 |
plugin/src/main/kotlin/com/jraska/module/graph/GraphvizWriter.kt | dafi | 230,582,038 | true | {"Kotlin": 20110} | package com.jraska.module.graph
object GraphvizWriter {
fun toGraphviz(dependencyGraph: DependencyGraph, groups: Set<String> = emptySet()): String {
val longestPathConnections = dependencyGraph.longestPath()
.nodeNames.zipWithNext()
.toSet()
val stringBuilder = StringBuilder()
stringBuilder.append("digraph G {\n")
if(groups.isNotEmpty()) {
stringBuilder.append("ranksep = 1.5\n")
}
groups.forEach {
stringBuilder.append(generateGroup(dependencyGraph, it))
}
dependencyGraph.nodes().flatMap { node -> node.dependsOn.map { node.key to it.key } }
.forEach { connection ->
stringBuilder.append("\"${connection.first}\"")
.append(" -> ")
.append("\"${connection.second}\"")
if (longestPathConnections.contains(connection)) {
stringBuilder.append(" [color=red style=bold]")
}
stringBuilder.append("\n")
}
stringBuilder.append("}")
return stringBuilder.toString()
}
private fun generateGroup(dependencyGraph: DependencyGraph, groupName: String): String {
val builder = StringBuilder()
.append("subgraph cluster_").append(groupName.replace(":", "")).appendln("{")
.appendln("style = filled;")
.appendln("color = lightgrey;")
.appendln("node[style = filled, color = white];")
.append("label = \"").append(groupName).appendln("\"")
dependencyGraph.nodes().filter { it.key.startsWith(groupName) }.forEach {
builder.append("\"").append(it.key).appendln("\"")
}
return builder.appendln("}")
.appendln()
.toString()
}
}
| 0 | Kotlin | 0 | 0 | eee1159f56e7f8389f411b415b3a390c341e9dec | 1,631 | modules-graph-assert | Apache License 2.0 |
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[18]四数之和.kt | maoqitian | 175,940,000 | false | {"Kotlin": 354268, "Java": 297740, "C++": 634} | import java.util.*
import kotlin.collections.ArrayList
//给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c +
// d 的值与 target 相等?找出所有满足条件且不重复的四元组。
//
// 注意:答案中不可以包含重复的四元组。
//
//
//
// 示例 1:
//
//
//输入:nums = [1,0,-1,0,-2,2], target = 0
//输出:[[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
//
//
// 示例 2:
//
//
//输入:nums = [], target = 0
//输出:[]
//
//
//
//
// 提示:
//
//
// 0 <= nums.length <= 200
// -109 <= nums[i] <= 109
// -109 <= target <= 109
//
// Related Topics 数组 哈希表 双指针
// 👍 857 👎 0
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
fun fourSum(nums: IntArray, target: Int): List<List<Int>> {
//双指针 时间复杂度 O(n^3)
val res: MutableList<List<Int>> = ArrayList()
val length: Int = nums.size
//排序好数组
Arrays.sort(nums)
if (length == 0) return res
for (a in 0 until length - 3) { //开头指针
//相等跳过当前数
if (a > 0 && nums[a] == nums[a - 1]) continue
for (d in length - 1 downTo a + 2 + 1) { //末尾指针
//相等跳过当前数
if (d < length - 1 && nums[d] == nums[d + 1]) continue
//确定另外两数index
var b = a + 1
var c = d - 1
//当前和最小值
val min = nums[a] + nums[d] + nums[b] + nums[b + 1]
if (min > target) continue
//当前和最大值
val max = nums[a] + nums[d] + nums[c - 1] + nums[c]
//不在当前范围
if (max < target) break
while (c > b) {
//继续以 c b 为指针寻找
val sum = nums[a] + nums[b] + nums[c] + nums[d]
when {
sum > target -> c--
sum < target -> b++
else -> {
res.add(listOf(nums[a], nums[b], nums[c], nums[d]))
while (c > b && nums[b] == nums[b + 1]) b++
while (c > b && nums[c] == nums[c - 1]) c--
b++
c--
}
}
}
}
}
return res
}
}
//leetcode submit region end(Prohibit modification and deletion)
| 0 | Kotlin | 0 | 1 | 8a85996352a88bb9a8a6a2712dce3eac2e1c3463 | 2,654 | MyLeetCode | Apache License 2.0 |
src/main/kotlin/io/github/alexandrepiveteau/datalog/core/interpreter/database/RulesDatabase.kt | alexandrepiveteau | 607,114,441 | false | null | package io.github.alexandrepiveteau.datalog.core.interpreter.database
import io.github.alexandrepiveteau.datalog.core.rule.CombinationRule
import io.github.alexandrepiveteau.datalog.core.rule.Rule
/**
* An intentional database, with predicate derivation rules. Each set of rules is associated with a
* predicate and an arity. The same predicate can be associated with a different set of rules and
* may have different arity.
*/
internal interface RulesDatabase<out T> {
/** Returns an [Iterator] with all keys in the [RulesDatabase]. */
operator fun iterator(): Iterator<PredicateWithArity>
/** Returns the [Set] of [CombinationRule]s for the given [PredicateWithArity]. */
operator fun get(key: PredicateWithArity): Set<Rule<T>>
/**
* Returns a new [RulesDatabase] with the same contents as this [RulesDatabase] for the given keys
* only.
*/
fun filter(keys: Collection<PredicateWithArity>): RulesDatabase<T>
/**
* Returns `true` if the [RulesDatabase] contains the given [PredicateWithArity], or `false`
* otherwise.
*/
operator fun contains(key: PredicateWithArity): Boolean
}
internal data class MapRulesDatabase<out T>(
private val map: Map<PredicateWithArity, Set<Rule<T>>>,
) : RulesDatabase<T> {
override fun iterator(): Iterator<PredicateWithArity> = map.keys.iterator()
override fun get(key: PredicateWithArity): Set<Rule<T>> = map[key] ?: emptySet()
override fun filter(
keys: Collection<PredicateWithArity>,
): RulesDatabase<T> = MapRulesDatabase(map.filterKeys { it in keys })
override fun contains(key: PredicateWithArity): Boolean = map.containsKey(key)
}
| 3 | Kotlin | 0 | 2 | 68f3e2d43c866d2057a0231188175c31b2f26940 | 1,640 | epfl-datalog-kotlin | MIT License |
aoc2020kot/src/main/kotlin/main.kt | fasiha | 365,094,027 | false | null | import kotlin.math.PI
import kotlin.math.cos
import kotlin.math.roundToInt
import kotlin.math.sin
// From https://stackoverflow.com/a/53018129
fun getResourceAsText(path: String): String {
return object {}.javaClass.getResource(path)?.readText() ?: throw Exception("Unable to read file")
}
fun getResourceAsBytes(path: String): ByteArray {
return object {}.javaClass.getResource(path)?.readBytes() ?: throw Exception("Unable to read file")
}
fun getResourceAsInts(path: String): Sequence<Int> {
return getResourceAsText(path).trim().lineSequence().map { it.toInt() }
}
fun getResourceAsLongs(path: String): Sequence<Long> {
return getResourceAsText(path).trim().lineSequence().map { it.toLong() }
}
fun problem1a(expenses: Sequence<Long> = getResourceAsLongs("1.txt"), targetSum: Long = 2020): Pair<Long, List<Long>>? {
val seen: MutableSet<Long> = mutableSetOf()
for (x in expenses) {
if (seen.contains(targetSum - x)) {
return Pair((targetSum - x) * x, listOf(targetSum - x, x))
}
seen += x
}
return null
}
fun problem1b(): Pair<Int, List<Int>>? {
val targetSum = 2020
val expenses = getResourceAsInts("1.txt")
val seen: MutableSet<Int> = mutableSetOf()
for (x in expenses) {
for (y in seen) {
if (seen.contains(targetSum - (x + y))) {
return Pair(x * y * (targetSum - (x + y)), listOf(x, y, targetSum - (x + y)))
}
}
seen += x
}
return null
}
fun problem2a(a: Boolean): Int {
val re = "([0-9]+)-([0-9]+) (.): (.+)".toRegex()
fun isValid(lo: Int, hi: Int, ch: String, pw: String): Boolean {
val count = ch.toRegex().findAll(pw).count()
return count in lo..hi
}
fun isValidB(i: Int, j: Int, ch: String, pw: String): Boolean {
return (pw[i - 1] == ch[0]).xor(pw[j - 1] == ch[0])
}
val valid = if (a) ::isValid else ::isValidB
val contents = getResourceAsText("2.txt")
return contents.trim().lineSequence().mapNotNull { re.find(it)?.destructured }
.filter { (lo, hi, ch, pw) -> valid(lo.toInt(), hi.toInt(), ch, pw) }.count()
}
fun problem3a(right: Int, down: Int): Int {
val map = getResourceAsText("3.txt").trim().lines()
val width = map[0].length
val tree = '#'
var nTrees = 0
var row = 0
var col = 0
while (row < map.size) {
nTrees += if (map[row][col % width] == tree) 1 else 0
row += down
col += right
}
return nTrees
}
fun problem3b(): Long {
return listOf(
problem3a(1, 1),
problem3a(3, 1),
problem3a(5, 1),
problem3a(7, 1),
problem3a(1, 2)
).fold(1L) { acc, i -> acc * i }
}
fun problem4a(): Int {
val contents = getResourceAsText("4.txt").trim().splitToSequence("\n\n")
val listOfKeys = contents.map {
it
.split("\\s".toRegex())
.map { kv -> kv.splitToSequence(':').first() }
.toSet()
}
return listOfKeys.count { it.containsAll(listOf("byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid")) }
}
fun <T> listToPair(l: List<T>): Pair<T, T> {
return Pair(l[0], l[1])
}
fun problem4b(): Int {
val requiredFields = listOf("byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid")
val okEyeColors = setOf("amb", "blu", "brn", "gry", "grn", "hzl", "oth")
val contents = getResourceAsText("4.txt").trim().splitToSequence("\n\n")
val passports = contents.map {
it
.split("\\s".toRegex())
.associate { kv -> listToPair(kv.split(":")) }
}
val validPassports = passports.filter { requiredFields.all { k -> it.containsKey(k) } }
fun isValid(m: Map<String, String>): Boolean {
val hgt = m["hgt"]!!
val hgtOk = (hgt.endsWith("cm") && hgt.dropLast(2).toInt() in 150..193) ||
(hgt.endsWith("in") && hgt.dropLast(2).toInt() in 59..76)
return hgtOk &&
(m["byr"]?.toInt() in 1920..2002) &&
(m["iyr"]?.toInt() in 2010..2020) &&
(m["eyr"]?.toInt() in 2020..2030) &&
(m["hcl"]!!.contains("^#[a-f0-9]{6}$".toRegex())) &&
(okEyeColors.contains(m["ecl"]!!)) &&
(m["pid"]!!.contains("^[0-9]{9}$".toRegex()))
}
return validPassports.count(::isValid)
}
fun strToBinary(s: String, zeroChar: Char): Int {
return s.toCharArray().fold(0) { acc, i -> (acc shl 1) + if (i == zeroChar) 0 else 1 }
// Does toCharArray *create* a new array? Or is it a view?
// Because, an alternative: `chars` returns IntSequence, so
// return s.chars().map{if (it == zeroChar.toInt()) 0 else 1}.reduce{ acc, i -> (acc shl 1) + i }.asInt
}
fun problem5a(): Int {
val lines = getResourceAsText("5.txt").trim().lineSequence()
return lines.maxOfOrNull { strToBinary(it.take(7), 'F') * 8 + strToBinary(it.takeLast(3), 'L') }!!
}
fun problem5b(): Int {
val lines = getResourceAsText("5.txt").trim().lineSequence()
val sorted = lines.map { strToBinary(it.take(7), 'F') * 8 + strToBinary(it.takeLast(3), 'L') }.sorted()
for ((curr, next) in sorted.zipWithNext()) {
if (curr + 1 != next) return curr + 1
}
return -1
}
fun problem6a(): Int {
val groups = getResourceAsText("6.txt").trim().splitToSequence("\n\n")
return groups.sumOf { it.replace("\n", "").toSet().size }
}
fun problem6b(): Int {
val groups = getResourceAsText("6.txt").trim().splitToSequence("\n\n")
return groups.sumOf {
it.splitToSequence("\n")
.map { person -> person.toSet() }
.reduce { acc, i -> acc intersect i }
.size
}
}
fun problem7a(): Int {
fun outerToInner(rule: String): Sequence<Pair<String, String>> {
val split = rule.split(" bags contain")
val parent = split[0] // don't need null check?
return "[0-9]+ ([a-z ]+?) bag".toRegex().findAll(split[1]).map { Pair(parent, it.destructured.component1()) }
}
val innerToOuters =
getResourceAsText("7.txt").trim().lineSequence().flatMap(::outerToInner).groupBy({ it.second }, { it.first })
val ancestors: MutableSet<String> = mutableSetOf()
fun recur(inner: String) {
val outers = innerToOuters[inner].orEmpty()
ancestors += outers
outers.forEach(::recur)
}
recur("shiny gold")
return ancestors.size
}
data class BagContent(val num: Int, val color: String)
fun problem7b(): Int {
fun outerToInners(rule: String): Pair<String, List<BagContent>> {
val split = rule.split(" bags contain")
assert(split.size >= 2) { "two sides to the rule expected" }
val parent = split[0] // don't need null check? Guess not. Either this will throw or the assert above
return Pair(
parent,
"([0-9]+) ([a-z ]+?) bag"
.toRegex()
.findAll(split[1])
.map { BagContent(it.destructured.component1().toInt(), it.destructured.component2()) }
.toList()
)
}
val outerToInners =
getResourceAsText("7.txt").trim().lineSequence().associate(::outerToInners)
fun recur(outer: String): Int {
val inners = outerToInners[outer].orEmpty()
return inners.sumOf { it.num + it.num * recur(it.color) }
}
return recur("shiny gold")
}
enum class Op { Acc, Jmp, Nop }
data class OpCode(val op: Op, val arg: Int)
fun loadProgram8(): List<OpCode> {
return getResourceAsText("8.txt").trim().lines().map {
val (op, arg) = it.split(" ")
OpCode(
when (op) {
"nop" -> Op.Nop
"acc" -> Op.Acc
"jmp" -> Op.Jmp
else -> throw Error("unknown")
},
arg.toInt()
)
}
}
enum class FinalState { Terminated, InfiniteLoop }
fun problem8a(program: List<OpCode> = loadProgram8()): Pair<FinalState, Int> {
val linesVisited = mutableSetOf<Int>()
var programCounter = 0
var acc = 0
while (programCounter < program.size) {
if (linesVisited.contains(programCounter)) return Pair(FinalState.InfiniteLoop, acc)
else linesVisited.add(programCounter)
val (op, arg) = program[programCounter]
when (op) {
Op.Acc -> {
acc += arg
programCounter++
}
Op.Jmp -> programCounter += arg
Op.Nop -> programCounter++
}
}
return Pair(FinalState.Terminated, acc)
}
fun problem8b(): Int {
val program = loadProgram8()
for ((idx, op) in program.withIndex()) {
if (op.op == Op.Nop || op.op == Op.Jmp) {
val newProgram = program.toMutableList()
newProgram[idx] = OpCode(if (op.op == Op.Nop) Op.Jmp else Op.Nop, op.arg)
val (newState, newAcc) = problem8a(newProgram)
if (newState == FinalState.Terminated) return newAcc
}
}
throw Error("no solution found")
}
// Kotlin Sad 1: no nested destructure
// 2: windowed returns a List of Lists? No Sequence? Is that inefficient?
// Question: is List.asSequence() expensive?
// Definitely annoying: `if(x != null) return x.max()` doesn't work: Kotlin doesn't know x is non-null there. Similarly `if(m.containsKey(idx)) return m[idx]!!`
// ^^ But --- wait https://kotlinlang.org/docs/basic-syntax.html#nullable-values-and-null-checks `x and y are automatically cast to non-nullable after null check`
// subList does bound-checking. I miss python lst[5:1000000] would just work
// Why does "asd".toCharArray().mapNotNull not exist?
fun problem9a(numbers: Sequence<Long> = getResourceAsLongs("9.txt")): Long {
val preamble = 25
return numbers
.windowed(1 + preamble)
.first { problem1a(it.dropLast(1).asSequence(), it.last()) == null }
.last()
}
fun problem9b(): Long {
val numbers = getResourceAsLongs("9.txt").toList()
val target = problem9a(numbers.asSequence()) // is this stupid, going from seq -> list -> seq?
for (win in 2..numbers.size) {
val solution = numbers.windowed(win).firstOrNull { it.sum() == target }
if (solution != null) return solution.maxOrNull()!! + solution.minOrNull()!!
}
error("unable to find solution")
}
fun problem10a(): Int {
return getResourceAsInts("10.txt")
.sorted()
.zipWithNext { a, b -> b - a }
.groupingBy { it }
.eachCount()
.values
.fold(1) { acc, it -> acc * (it + 1) }
}
fun problem10b(): Long {
val list0 = listOf(0) + getResourceAsInts("10.txt").sorted()
val list = list0 + (list0.last() + 3)
val m = mutableMapOf<Int, Long>()
fun recur(idx: Int = 0): Long {
if (idx + 1 == list.size) return 1
if (m.containsKey(idx)) return m[idx]!!
val cur = list[idx]
val next = list.drop(idx + 1).takeWhile { it <= cur + 3 }.size // drop & takeWhile since subList checks bounds
val numDescendants = (idx + 1..idx + next).sumOf(::recur)
m += idx to numDescendants
return numDescendants
}
return recur()
}
data class DoubleBuffer(
val get: (Int, Int) -> Byte,
val set: (Int, Int, Byte) -> Unit,
val flip: () -> Unit,
val getBuffer: () -> ByteArray,
val getLineOfSight: (Int, Int, (Byte) -> Boolean) -> List<Byte>,
val height: Int,
val width: Int,
)
fun prepareBytes(aBuffer: ByteArray): DoubleBuffer {
// FIXME: BOM 0xEF,0xBB,0xBF https://en.wikipedia.org/wiki/Byte_order_mark
val newline = aBuffer.indexOf('\n'.toByte())
assert(newline > 0) { "file must contain newlines" }
val (width, padding) = when (aBuffer[newline - 1]) {
'\r'.toByte() -> Pair(newline - 1, 2)
else -> Pair(newline, 1)
}
val lastIdx = aBuffer.indexOfLast { !(it == '\n'.toByte() || it == '\r'.toByte()) } + 1
val height = (lastIdx + padding) / (width + padding)
val bBuffer = aBuffer.copyOf()
var readBufferA = true // which buffer, a or b, is the read-ready copy? The other will be written to until flip()ed
val rowColToIndex = { row: Int, col: Int -> row * (width + padding) + col }
val get = { row: Int, col: Int -> (if (readBufferA) aBuffer else bBuffer)[rowColToIndex(row, col)] }
val set = { row: Int, col: Int, new: Byte ->
(if (readBufferA) bBuffer else aBuffer)[rowColToIndex(row, col)] = new
}
val flip = { readBufferA = !readBufferA }
val getBuffer = { if (readBufferA) aBuffer else bBuffer }
val getLineOfSight = { row: Int, col: Int, f: (Byte) -> Boolean ->
val inBounds = { r: Int, c: Int -> r >= 0 && c >= 0 && r < height && c < width }
val buf = if (readBufferA) aBuffer else bBuffer
val ret = mutableListOf<Byte>()
for (dr in -1..1) {
for (dc in -1..1) {
if (dc == 0 && dr == 0) continue
var r = row + dr
var c = col + dc
while (inBounds(r, c)) {
val char = buf[rowColToIndex(r, c)]
if (f(char)) {
ret += char
break
}
c += dc
r += dr
}
}
}
ret
}
return DoubleBuffer(get, set, flip, getBuffer, getLineOfSight, height, width)
}
fun problem11(partA: Boolean): Int {
val buffer = prepareBytes(getResourceAsBytes("11.txt"))
val occupiedThreshold = if (partA) 4 else 5
val predicate = if (partA) ({ true }) else ({ b: Byte -> b != '.'.toByte() })
while (true) {
var changed = false
for (row in 0 until buffer.height) {
for (col in 0 until buffer.width) {
val seat = buffer.get(row, col)
if (seat != '.'.toByte()) {
val ring = buffer.getLineOfSight(row, col, predicate)
val occupied = ring.count { it == '#'.toByte() }
if (seat == 'L'.toByte() && occupied == 0) {
buffer.set(row, col, '#'.toByte())
changed = true
} else if (seat == '#'.toByte() && occupied >= occupiedThreshold) {
buffer.set(row, col, 'L'.toByte())
changed = true
} else {
buffer.set(row, col, seat)
}
}
}
}
buffer.flip() // all done reading from one buffer and writing to the other: flip which one is readable
if (!changed) break
}
return buffer.getBuffer().count { it == '#'.toByte() }
}
fun bytesToLinesSequence(bytes: ByteArray): Sequence<ByteArray> {
return sequence {
val lineFeed = '\n'.toByte()
val carriageReturn = '\r'.toByte()
var newlineSize = 1 // unix
var slice = bytes.sliceArray(bytes.indices)
val searchIdx = slice.indexOf(lineFeed)
if (searchIdx < 0) {
yield(slice)
} else {
if (searchIdx > 0 && slice[searchIdx - 1] == carriageReturn) newlineSize = 2 // Windows
yield(slice.sliceArray(0..searchIdx - newlineSize))
slice = slice.sliceArray(searchIdx + 1 until slice.size)
while (slice.isNotEmpty()) {
val searchIdx = slice.indexOf(lineFeed)
if (searchIdx < 0) {
yield(slice)
break
}
yield(slice.sliceArray(0..searchIdx - newlineSize))
slice = slice.sliceArray(searchIdx + 1 until slice.size)
}
}
}
}
fun prob12(): Int {
val faceToDelta = mapOf('N' to Pair(0, 1), 'S' to Pair(0, -1), 'E' to Pair(1, 0), 'W' to Pair(-1, 0))
val faces = listOf('N', 'E', 'S', 'W')
var x = 0
var y = 0
var faceIdx = faces.indexOf('E')
for (line in bytesToLinesSequence(getResourceAsBytes("12.txt"))) {
val instruction = line[0].toChar()
val arg = String(line.sliceArray(1 until line.size), Charsets.US_ASCII).toInt()
when (instruction) {
'N' -> y += arg
'S' -> y -= arg
'W' -> x -= arg
'E' -> x += arg
'L' -> faceIdx = (4 + faceIdx - arg / 90) % 4
'R' -> faceIdx = (4 + faceIdx + arg / 90) % 4
'F' -> {
val (dx, dy) = faceToDelta[faces[faceIdx]]!!
x += dx * arg
y += dy * arg
}
}
}
return kotlin.math.abs(x) + kotlin.math.abs(y)
}
// See https://mathworld.wolfram.com/RotationMatrix.html
fun rotate(x: Int, y: Int, deg: Int): Pair<Int, Int> {
val t = PI / 180.0 * deg;
val cosT = cos(t)
val sinT = sin(t)
return Pair((cosT * x - sinT * y).roundToInt(), (sinT * x + cosT * y).roundToInt())
}
fun prob12b(): Int {
var x = 0
var y = 0
var dx = 10 // waypoint
var dy = 1 // waypoint
for (line in bytesToLinesSequence(getResourceAsBytes("12.txt"))) {
val instruction = line[0].toChar()
val arg = String(line.sliceArray(1 until line.size), Charsets.US_ASCII).toInt()
when (instruction) {
'N' -> dy += arg
'S' -> dy -= arg
'W' -> dx -= arg
'E' -> dx += arg
'L', 'R' -> {
val (x1, y1) = rotate(dx, dy, if (instruction == 'L') arg else -arg) // L: clockwise
dx = x1
dy = y1
}
'F' -> {
x += dx * arg
y += dy * arg
}
}
}
return kotlin.math.abs(x) + kotlin.math.abs(y)
}
fun prob13(): Int {
val lines = getResourceAsText("13.txt").lines()
val earliest = lines[0].toInt()
val busses = lines[1].split(',').filter { it != "x" }.map { it.toInt() }
// Can we write the following loop using sequences?
// `generateSequence(earliest) {it+1 }.first{ time -> busses.any { bus -> (time % bus) == 0 }}!!` but without
// having to redo the last mod checks?
var t = earliest
while (true) {
val bus = busses.find { t % it == 0 }
if (bus != null) {
return bus * (t - earliest)
}
t++
}
}
// Find x such that `x % a.component2() == a.component1()` AND `x % b.component2() == b.component1()`
// That is, the first element of each pair is congruent to x modulo the second element of the pair
// Step one of the sieve algorithm per https://en.wikipedia.org/wiki/Chinese_remainder_theorem#Computation,i
fun chineseRemainderTheoremPair(a: Pair<Long, Long>, b: Pair<Long, Long>): Long {
var congruence: Long = a.component1()
val mod = a.component2()
val secondCongruence = b.component1()
val secondMod = b.component2()
assert(congruence > 0 && mod > 0 && secondCongruence > 0 && secondMod > 0) { "positive only" }
while (true) {
if ((congruence % secondMod) == secondCongruence) return congruence
congruence += mod
}
}
fun prob13b(): Long {
val list = getResourceAsText("13.txt").lines()[1].split(',')
val equivalences = list
.mapIndexedNotNull { i, stringModulo ->
when (stringModulo) {
"x" -> null
else -> {
val mod = stringModulo.toLong()
val push = (list.size / mod + 1) * mod
// push the modulo to be greater than the biggest index i
// without this, we might end up with `mod - i % mod` being negative when index is big enough
Pair((push - i.toLong()) % mod, mod)
}
}
}
.sortedByDescending { (_, n) -> n }
// x = equivalences[0][0] % equivalences[0][1] = equivalences[1][0] % equivalences[1][1] = ...
// In other words, the first element is congruent with x modulo the second element.
// In the language of https://en.wikipedia.org/wiki/Chinese_remainder_theorem#Computation,
// equivalences[i] = Pair(a_i, n_i)
val sol = equivalences.reduce { acc, pair ->
val newCongruent = chineseRemainderTheoremPair(acc, pair)
Pair(newCongruent, acc.component2() * pair.component2())
}
return sol.component1()
}
fun prob14(): Long {
// Pair(OrMask (1s), AndMask (0s))
// OrMask's binary representation has 1s wherever the bitmask has a '1' character and 0s otherwise
// AndMask in binary has 0s wherever the bitmask is '0' but 1s otherwise
// This way, `foo OR OrMask AND AndMask` will apply the overall mask.
fun stringToMasks(s: String): Pair<Long, Long> {
return s.toCharArray().foldIndexed(Pair(0L, 0L)) { idx, (orMask, andMask), x ->
val bit = 1L shl (s.length - idx - 1)
Pair(orMask + if (x == '1') bit else 0, andMask + if (x == '0') 0 else bit)
}
}
val mem = mutableMapOf<Int, Long>()
var mask = Pair(0L, 0L)
for (line in getResourceAsText("14.txt").trim().lineSequence()) {
if (line.startsWith("ma")) {
mask = stringToMasks(line.drop(7))
} else {
val group = "mem\\[(?<idx>[0-9]+)\\] = (?<value>.*)".toRegex().find(line)!!.groupValues
val idx = group[1].toInt()
val value = group[2].toLong()
mem[idx] = (value or mask.component1()) and mask.component2()
}
}
return mem.values.sum()
}
/**
* Given a list of numbers representing how many options each dimension has,
* generates a sequence whose each step is a list of numbers representing
* the chosen index for each dimension.
*
* If you're choosing between 4 shirts, 5 pants, and 3 pairs of shoes,
* `cartesianProduct(listOf(4, 5, 3))` will start at `(0, 0, 0)` and end at
* `(3, 4, 2)` and will enumerate each option.
*
* from https://github.com/fasiha/cartesian-product-generator/issues/3
*/
fun cartesianProduct(lengthArr: List<Int>): Sequence<List<Int>> {
val idx = lengthArr.map { 0 }.toMutableList()
var carry = 0
return sequence<List<Int>> {
while (carry == 0) {
yield(idx)
carry = 1
for (i in idx.indices) {
idx[i] += carry
if (idx[i] >= lengthArr[i]) {
idx[i] = 0
carry = 1
} else {
carry = 0
break
}
}
}
}
}
fun prob14b(): Long {
// We now have three things to generate from each mask string:
// - an OrMask whose binary has 1s where the input char is 1
// - an AndMask whose binary has 0s when the input char is X, since we want to zero out the floats
// - a floats list consisting of 2**index for each index whose character was X
fun stringToMasks(s: String): Triple<Long, Long, List<Long>> {
return s.toCharArray().foldIndexed(Triple(0L, 0L, listOf())) { idx, (orMask, andMask, floats), x ->
val bit = 1L shl (s.length - idx - 1)
Triple(
orMask + if (x == '1') bit else 0,
andMask + if (x == 'X') 0 else bit,
if (x == 'X') floats + bit else floats
)
}
}
val mem = mutableMapOf<Long, Long>()
var mask = Triple(0L, 0L, listOf<Long>())
for (line in getResourceAsText("14.txt").trim().lineSequence()) {
if (line.startsWith("ma")) {
mask = stringToMasks(line.drop(7))
} else {
val (orMask, andMask, floatMask) = mask
val group = "mem\\[(?<idx>[0-9]+)\\] = (?<value>.*)".toRegex().find(line)!!.groupValues
val value = group[2].toLong()
val idx = group[1].toLong()
val newIdx = (idx or orMask) and andMask
for (float in cartesianProduct(floatMask.map { 2 })) {
// each element of float will be 0 or 1, whether to turn the floating bit on or off
val floatIdx = newIdx + float.zip(floatMask).sumOf { (use, bit) -> use * bit }
// we're using multiplication as a shortcut to `if(use>0) bit else 0`
mem[floatIdx] = value
}
}
}
return mem.values.sum()
}
fun prob15(partA: Boolean): Int {
val input = listOf(0, 5, 4, 1, 10, 14, 7)
val spoken = input.withIndex().associate { it.value to listOf(it.index + 1) }.toMutableMap()
var lastSpoken = input.last()
for (turn in input.size + 1..(if (partA) 2020 else 30_000_000)) {
val prev = spoken[lastSpoken]!!
lastSpoken = if (prev.size == 1) {
0
} else {
// prev is list of 2
prev[1] - prev[0]
}
if (!spoken.containsKey(lastSpoken)) {
spoken[lastSpoken] = listOf(turn)
} else {
val newPrevious = spoken[lastSpoken]!!
spoken[lastSpoken] = listOf(newPrevious.last(), turn)
}
}
return lastSpoken
}
fun main(args: Array<String>) {
println("Problem 1a: ${problem1a()}")
println("Problem 1b: ${problem1b()}")
println("Problem 2a: ${problem2a(true)}")
println("Problem 2b: ${problem2a(!true)}")
println("Problem 3a: ${problem3a(3, 1)}")
println("Problem 3b: ${problem3b()}")
println("Problem 4a: ${problem4a()}")
println("Problem 4b: ${problem4b()}")
println("Problem 5a: ${problem5a()}")
println("Problem 5b: ${problem5b()}")
println("Problem 6a: ${problem6a()}")
println("Problem 6b: ${problem6b()}")
println("Problem 7a: ${problem7a()}")
println("Problem 7b: ${problem7b()}")
println("Problem 8a: ${problem8a()}")
println("Problem 8b: ${problem8b()}")
println("Problem 9a: ${problem9a()}")
println("Problem 9b: ${problem9b()}")
println("Problem 10a: ${problem10a()}")
println("Problem 10b: ${problem10b()}")
// println("Problem 11a: ${problem11(true)}")
// println("Problem 11b: ${problem11(false)}")
println("Problem 12: ${prob12()}")
println("Problem 12b: ${prob12b()}")
println("Problem 13: ${prob13()}")
println("Problem 13b: ${prob13b()}")
println("Problem 14: ${prob14()}")
println("Problem 14b: ${prob14b()}")
println("Problem 15: ${prob15(true)}")
// println("Problem 15b: ${prob15(false)}")
} | 0 | Kotlin | 0 | 0 | 59edfcbdf03ebff3250b9c4d535d1e80e5ba5398 | 26,226 | advent-of-code-2020 | The Unlicense |
code/day_05/src/jvm8Main/kotlin/task2.kt | dhakehurst | 725,945,024 | false | {"Kotlin": 105846} | package day_05
fun task2(lines: List<String>) = task2_3(lines)
// just iterate for a long time ;-)
fun task2_1(lines: List<String>):Long {
val seeds = lines[0].substringAfter(":").split(" ").mapNotNull { it.trim().toLongOrNull() }
val seeds2 = mutableListOf<LongRange>()
var i = 0
while(i < seeds.size) {
seeds2.add(LongRange(seeds[i], seeds[i]+seeds[i+1]-1))
i += 2
}
val mappers = mutableListOf<Mapper>()
for (line in lines.drop(1)) {
when {
line.trim().isBlank() -> Unit
line.contains(":") -> mappers.add(Mapper(line.substringBefore(":")))
else -> {
val nums = line.split(" ").mapNotNull { it.trim().toLongOrNull() }
mappers.last().ranges.add(RangeMap(nums[0], nums[1], nums[2]))
}
}
}
println("Total SeedRanges: ${seeds2.size}")
val locations = seeds2.mapIndexed { idx, sr ->
println("seedRange: $idx - $sr")
sr.minOf {
mappers.fold(it) { acc, mpr ->
mpr.map(acc)
}
}
}
println("Min: ${locations.min()}")
return locations.min()
}
// try to work backwards.....does not work! - am missing something
fun task2_2(lines: List<String>) :Long {
val seeds = lines[0].substringAfter(":").split(" ").mapNotNull { it.trim().toLongOrNull() }
val seeds2 = mutableListOf<Range>()
var i = 0
while(i < seeds.size) {
seeds2.add(Range(seeds[i], seeds[i+1]))
i += 2
}
val mappers = mutableListOf<Mapper>()
for (line in lines.drop(1)) {
when {
line.trim().isBlank() -> Unit
line.contains(":") -> mappers.add(Mapper(line.substringBefore(":")))
else -> {
val nums = line.split(" ").mapNotNull { it.trim().toLongOrNull() }
mappers.last().ranges.add(RangeMap(nums[0], nums[1], nums[2]))
}
}
}
var md = mappers.last().srcForMinDstMax
for(mpr in mappers.reversed().drop(1)) {
mpr.filterToRangesWithDstLessThan(md)
md = mpr.filteredSrcForMinDstMax
}
val minSeedsMaxToSearch = mappers.first().filteredSrcForMinDstMax
println("Total SeedRanges: ${seeds2.size}")
val locations = seeds2.mapIndexedNotNull { idx, sr ->
println("seedRange: $idx - $sr")
if (sr.max < minSeedsMaxToSearch) {
println("mapping")
sr.limitTo(minSeedsMaxToSearch)
sr.minOf {
mappers.fold(it) { acc, mpr ->
mpr.map(acc)
}
}
} else {
println("ignored")
null
}
}
println("Min: ${locations.min()}")
return locations.min()
}
// use range intersections.
fun task2_3(lines: List<String>):Long {
val seeds = lines[0].substringAfter(":").split(" ").mapNotNull { it.trim().toLongOrNull() }
val seeds2 = mutableListOf<LongRange>()
var i = 0
while(i < seeds.size) {
seeds2.add(LongRange(seeds[i], seeds[i]+seeds[i+1]-1))
i += 2
}
val mappers = mutableListOf<Mapper>()
for (line in lines.drop(1)) {
when {
line.trim().isBlank() -> Unit
line.contains(":") -> mappers.add(Mapper(line.substringBefore(":")))
else -> {
val nums = line.split(" ").mapNotNull { it.trim().toLongOrNull() }
mappers.last().ranges.add(RangeMap(nums[0], nums[1], nums[2]))
}
}
}
val locRanges = mappers.fold(seeds2 as List<LongRange>) { acc, mpr ->
mpr.mapRanges(acc)
}
println("Min: ${locRanges.minOf { it.first }}")
return locRanges.minOf { it.first }
} | 0 | Kotlin | 0 | 0 | be416bd89ac375d49649e7fce68c074f8c4e912e | 3,722 | advent-of-code | Apache License 2.0 |
src/main/kotlin/com/hopkins/aoc/day18/main.kt | edenrox | 726,934,488 | false | {"Kotlin": 88215} | package com.hopkins.aoc.day18
import com.hopkins.aoc.day17.Point
import java.io.File
const val debug = true
const val part = 2
/** Advent of Code 2023: Day 18 */
fun main() {
// Step 1: Read the file input
val lines: List<String> = File("input/input18.txt").readLines()
if (debug) {
println("Step 1: Read file")
println("=======")
println(" num lines: ${lines.size}")
}
// Step 2: Build the map
val map = mutableMapOf<Point, Point>()
val start = Point.of(100, 100)
map[start] = Point.ORIGIN
var current = start
var areaAlongPath = 0L
val foundCorners = mutableSetOf<Point>(start)
val lineCounts = mutableMapOf<Int, Int>()
lines.forEach { line ->
// Parse the line
val (dirStr, countStr, colorPart) = line.split(" ")
val color = colorPart.substring(2, colorPart.indexOf(")"))
val direction =
if (part == 1) {
directionLookup1[dirStr]!!
} else {
directionLookup2[color.last()]!!
}
val count =
if (part == 1) {
countStr.toInt()
} else {
color.substring(0, 5).toInt(radix = 16)
}
areaAlongPath += count
if (direction == directionUp) {
}
}
print("Area Along Path=$areaAlongPath")
if (true) {
return
}
val left = map.keys.minOf { it.x }
val right = map.keys.maxOf { it.x }
val top = map.keys.minOf { it.y }
val bottom = map.keys.maxOf { it.y }
val width = right - left + 1
val height = bottom - top + 1
if (debug) {
println()
println("Step 2: Build the map")
println("=======")
println(" width: $width")
println(" height: $height")
if (width < 11) {
for (y in top..bottom) {
print(" ")
for (x in left..right) {
val point = Point.of(x, y)
val direction = map[point]
print(
when (direction) {
directionUp, directionDown -> "|"
directionLeft, directionRight -> "-"
Point.ORIGIN -> "+"
else -> "."
}
)
}
println()
}
}
}
// Step 3: Count the area inside the map
val corners = map.filter {(key, value) -> value == Point.ORIGIN }
println("Num corners: ${corners.size}")
val cornersByRow = corners.map { it.key.y to it.key.x }.groupBy({ it.first }, {it.second })
val importantCorners = mutableSetOf<Point>()
for (row in cornersByRow.keys) {
val cornersInRow = cornersByRow[row]!!.sorted()
println("row=$row corners=$cornersInRow")
require(cornersInRow.size % 2 == 0)
for (index in 0 until cornersInRow.size / 2) {
val first = cornersInRow[index * 2]
val c1 = Point.of(first, row)
val second = cornersInRow[index * 2 + 1]
val c2 = Point.of(second, row)
val t1 = map[c1.add(directionUp)] == null
val t2 = map[c2.add(directionUp)] == null
if (t1 != t2) {
importantCorners.add(if (index % 2 == 0) c2 else c1)
}
}
}
val importantCornersByRow = importantCorners.map { it.y to it.x }.groupBy({ it.first }, {it.second })
println("Num important corners: ${importantCorners}")
val verticalByRow = map
.filter { it.value == directionUp || it.value == directionDown }
.entries
.groupBy( {it.key.y}, {it.key.x})
var areaInPath = 0L
for (row in verticalByRow.keys) {
val rowValues = (verticalByRow[row]!! + (importantCornersByRow[row] ?: emptyList())).sorted()
if (rowValues.size % 2 != 0) {
println("row=$row values=$rowValues")
println("Hi")
}
for (index in 0 until rowValues.size / 2) {
val first = rowValues[index * 2]
val second = rowValues[index * 2 + 1]
areaInPath += (second - first - 1)
}
}
var area = areaAlongPath - 1 + areaInPath
println("Total area inside: $area") // 49061
}
val directionUp = Point.of(0, -1)
val directionDown = Point.of(0, 1)
val directionLeft = Point.of(-1, 0)
val directionRight = Point.of(1, 0)
val directions = listOf(directionUp, directionDown, directionLeft, directionRight)
val directionLookup1 = mapOf(
"L" to directionLeft,
"U" to directionUp,
"R" to directionRight,
"D" to directionDown
)
val directionLookup2 = mapOf(
'0' to directionRight,
'1' to directionDown,
'2' to directionLeft,
'3' to directionUp
) | 0 | Kotlin | 0 | 0 | 45dce3d76bf3bf140d7336c4767e74971e827c35 | 4,824 | aoc2023 | MIT License |
src/main/kotlin/LangDecoder.kt | nmicra | 262,980,033 | false | null | /**
* Given map is how to encode any character in alphabet.
* Write a decode function, that will return all possible variant that can be encoded for a given string
* Example: for a given string "12", possible values [ab,l]
* for "1213" --> [abac, abm, auc, lac, lm]
*/
val map = mapOf(
"a" to "1", "b" to "2", "c" to "3", "d" to "4", "e" to "5",
"f" to "6", "g" to "7", "h" to "8", "i" to "9", "j" to "10",
"k" to "11", "l" to "12", "m" to "13", "n" to "14", "o" to "15",
"p" to "16", "q" to "17", "r" to "18", "s" to "19", "t" to "20",
"u" to "21", "v" to "22", "w" to "23", "x" to "24", "y" to "25", "z" to "26"
)
fun main() {
println(decode("1213"))
}
val reversedMap = map.entries.associateBy({ it.value }) { it.key }
val abcMaxLength = map["z"]?.length ?: error("Assumption that z is the last character of the alphabet")
fun splitString(str : String,n : Int) : Pair<String,String> = Pair(str.toCharArray().dropLast(str.length-n).joinToString(""),
str.toCharArray().drop(n).joinToString(""))
tailrec fun decode(str: String) : Set<String> {
fun aggregate(splitedPair : Pair<String,String>) : Set<String> {
val set = (1..splitedPair.first.length)
.map { splitString(splitedPair.first,it) }
.map { reversedMap[it.first].orEmpty() + reversedMap[it.second].orEmpty() }
.toSet()
val set2 = decode(splitedPair.second)
return set.map {el1 -> set2.map { el1 +it }.toSet() }.flatten().toSet()
}
return when {
str.length <= abcMaxLength -> (1..str.length)
.map { splitString(str,it) }
.map { reversedMap[it.first].orEmpty() + reversedMap[it.second].orEmpty() }
.toSet()
else -> (1..abcMaxLength).asSequence()
.map { splitString(str, it) }
.map { aggregate(it) }
.toSet().flatten().toSet()
}
} | 0 | Kotlin | 0 | 0 | 4bf80f01af6c4a08221131878b7d53e2826db241 | 1,984 | kotlin_practice | Apache License 2.0 |
src/aoc2021/Day02.kt | dayanruben | 433,250,590 | false | {"Kotlin": 79134} | package aoc2021
import readInput
fun main() {
val (year, day) = "2021" to "Day02"
data class State(
private val hasAim: Boolean = false,
var horizontal: Int = 0,
var depth: Int = 0,
var aim: Int = 0
) {
fun move(direction: String, x: Int) = if (hasAim) {
when (direction) {
"down" -> aim += x
"up" -> aim -= x
"forward" -> {
horizontal += x
depth += aim * x
}
else -> {}
}
} else {
when (direction) {
"forward" -> horizontal += x
"down" -> depth += x
"up" -> depth -= x
else -> {}
}
}
}
fun calculate(input: List<String>, hasAim: Boolean): Int {
val state = State(hasAim)
input.forEach {
val (direction, value) = it.split(" ")
val x = value.toInt()
state.move(direction, x)
}
return state.horizontal * state.depth
}
fun part1(input: List<String>) = calculate(input, hasAim = false)
fun part2(input: List<String>) = calculate(input, hasAim = true)
val testInput = readInput(name = "${day}_test", year = year)
val input = readInput(name = day, year = year)
check(part1(testInput) == 150)
println(part1(input))
check(part2(testInput) == 900)
println(part2(input))
} | 1 | Kotlin | 2 | 30 | df1f04b90e81fbb9078a30f528d52295689f7de7 | 1,485 | aoc-kotlin | Apache License 2.0 |
src/main/kotlin/Day11.kt | SimonMarquis | 434,880,335 | false | {"Kotlin": 38178} | import Neighborhood.Moore
class Day11(val raw: List<String>) {
private val cavern: Cavern get() = raw.toCavern()
fun part1(): Int = with(cavern) {
(1..100).sumOf { step() }
}
fun part2(): Int = with(cavern) {
generateSequence(1) {
it.inc()
}.first {
step() == octopuses.size
}
}
class Cavern(val map: Array<Array<Octopus>>) {
val octopuses = map.flatten()
fun step(): Int {
octopuses.forEach { it.energy++ }
while (true) {
val flashed = octopuses.filter {
it.energy > 9 && !it.flashed
}.onEach { it.flash() }
if (flashed.isEmpty()) break
}
return octopuses.filter {
it.flashed
}.onEach {
it.energy = 0; it.flashed = false
}.size
}
private fun Octopus.flash() = map.neighboursOf(Moore, x, y).forEach { it.energy++ }.also { flashed = true }
override fun toString() = map.joinToString("\n") { line -> line.joinToString("") { it.energy.toString() } }
}
private fun List<String>.toCavern() = Cavern(mapIndexed { y, it -> it.toOctopuses(y) }.toTypedArray())
data class Octopus(val x: Int, val y: Int, var energy: Int, var flashed: Boolean = false)
private fun String.toOctopuses(y: Int) = mapIndexed { x, it -> it.toOctopus(x, y) }.toTypedArray()
private fun Char.toOctopus(x: Int, y: Int) = Octopus(x, y, digitToInt())
} | 0 | Kotlin | 0 | 0 | 8fd1d7aa27f92ba352e057721af8bbb58b8a40ea | 1,542 | advent-of-code-2021 | Apache License 2.0 |
src/Day08.kt | benwicks | 572,726,620 | false | {"Kotlin": 29712} | fun main() {
fun constructTreeGrid(input: List<String>) = arrayOf<IntArray>(
*input.map { it.map { char -> char.code - 48 }.toIntArray() }.toTypedArray()
)
fun isVisibleFromLeft(treeGrid: Array<IntArray>, x: Int, y: Int): Boolean {
val interiorTreeHeight = treeGrid[y][x]
val rowOverToTree = treeGrid[y].take(x)
return rowOverToTree.all { it < interiorTreeHeight }
}
fun isVisibleFromRight(treeGrid: Array<IntArray>, x: Int, y: Int): Boolean {
val row = treeGrid[y]
val interiorTreeHeight = row[x]
val rowOverToTree = row.takeLast(row.size - x - 1) // .reversed()
return rowOverToTree.all { it < interiorTreeHeight }
}
fun isVisibleFromTop(treeGrid: Array<IntArray>, x: Int, y: Int): Boolean {
val interiorTreeHeight = treeGrid[y][x]
val columnDownToTree = treeGrid.map { it[x] }.take(y)
return columnDownToTree.all { it < interiorTreeHeight }
}
fun isVisibleFromBottom(treeGrid: Array<IntArray>, x: Int, y: Int): Boolean {
val interiorTreeHeight = treeGrid[y][x]
val columnSize = treeGrid.size
val columnUpToTree = treeGrid.map { it[x] }.takeLast(columnSize - y - 1) // .reversed()
return columnUpToTree.all { it < interiorTreeHeight }
}
fun part1(input: List<String>): Int {
val width = input.first().length
val height = input.size
val perimeterTreesVisible = width*2 + height*2 - 4
// how many trees are visible from outside the grid?
var interiorTreesVisible = 0
val treeGrid = constructTreeGrid(input)
// iterate over interior trees
for (y in 1..width - 2) {
for (x in 1..height - 2) {
if (isVisibleFromLeft(treeGrid, x, y)) {
interiorTreesVisible++
} else if (isVisibleFromRight(treeGrid, x, y)) {
interiorTreesVisible++
} else if (isVisibleFromTop(treeGrid, x, y)) {
interiorTreesVisible++
} else if (isVisibleFromBottom(treeGrid, x, y)) {
interiorTreesVisible++
}
}
}
return perimeterTreesVisible + interiorTreesVisible
}
fun calculateScenicScore(treeGrid: Array<IntArray>, x: Int, y: Int): Int {
val row = treeGrid[y]
val columnSize = treeGrid.size
val treeHeight = row[x]
val rowLeftOfTree = row.take(x).reversed()
val rowRightOfTree = row.takeLast(row.size - x - 1)
val columnAboveTree = treeGrid.map { it[x] }.take(y).reversed()
val columnBelowTree = treeGrid.map { it[x] }.takeLast(columnSize - y - 1)
val indexOfFirstTreeVisibleLeft = rowLeftOfTree.indexOfFirst { it >= treeHeight }
val numTreesVisibleLeft = if (indexOfFirstTreeVisibleLeft == -1) { rowLeftOfTree.size } else { indexOfFirstTreeVisibleLeft + 1 }
val indexOfFirstTreeVisibleRight = rowRightOfTree.indexOfFirst { it >= treeHeight }
val numTreesVisibleRight = if (indexOfFirstTreeVisibleRight == -1) { rowRightOfTree.size } else { indexOfFirstTreeVisibleRight + 1 }
val indexOfFirstTreeVisibleUp = columnAboveTree.indexOfFirst { it >= treeHeight }
val numTreesVisibleUp = if (indexOfFirstTreeVisibleUp == -1) { columnAboveTree.size } else { indexOfFirstTreeVisibleUp + 1 }
val indexOfFirstTreeVisibleDown = columnBelowTree.indexOfFirst { it >= treeHeight }
val numTreesVisibleDown = if (indexOfFirstTreeVisibleDown == -1) { columnBelowTree.size } else { indexOfFirstTreeVisibleDown + 1 }
return numTreesVisibleLeft * numTreesVisibleRight * numTreesVisibleUp * numTreesVisibleDown
}
fun part2(input: List<String>): Int {
// find the highest possible scenic score
val width = input.first().length
val height = input.size
var maxScenicScore = 0
val treeGrid = constructTreeGrid(input)
for (y in 1..width - 2) {
for (x in 1..height - 2) {
val scenicScore = calculateScenicScore(treeGrid, x, y)
if (scenicScore > maxScenicScore) {
maxScenicScore = scenicScore
}
}
}
return maxScenicScore
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08_test")
check(part1(testInput) == 21)
check(part2(testInput) == 8)
val input = readInput("Day08")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | fbec04e056bc0933a906fd1383c191051a17c17b | 4,592 | aoc-2022-kotlin | Apache License 2.0 |
src/aoc2021/day02/Code.kt | ldickmanns | 572,675,185 | false | {"Kotlin": 48227} | package aoc2021.day02
import readInput
fun main() {
val input = readInput("aoc2021/day02/input")
println(part1(input))
println(part2(input))
}
fun part1(input: List<String>): Int {
var horizontalPosition = 0
var depth = 0
input.forEach { line: String ->
when {
"forward" in line -> horizontalPosition += line.removePrefix("forward ").toInt()
"down" in line -> depth += line.removePrefix("down ").toInt()
"up" in line -> depth -= line.removePrefix("up ").toInt()
else -> error("Invalid Input")
}
}
println("Depth $depth")
println("Horizontal position $horizontalPosition")
return depth * horizontalPosition
}
fun part2(input: List<String>): Int {
var horizontalPosition = 0
var depth = 0
var aim = 0
input.forEach { line: String ->
when {
"forward" in line -> {
val asInt = line.removePrefix("forward ").toInt()
horizontalPosition += asInt
depth += aim * asInt
}
"down" in line -> aim += line.removePrefix("down ").toInt()
"up" in line -> aim -= line.removePrefix("up ").toInt()
else -> error("Invalid Input")
}
}
println("Depth $depth")
println("Horizontal position $horizontalPosition")
return depth * horizontalPosition
}
| 0 | Kotlin | 0 | 0 | 2654ca36ee6e5442a4235868db8174a2b0ac2523 | 1,389 | aoc-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/g1201_1300/s1263_minimum_moves_to_move_a_box_to_their_target_location/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1201_1300.s1263_minimum_moves_to_move_a_box_to_their_target_location
// #Hard #Array #Breadth_First_Search #Matrix #Heap_Priority_Queue
// #2023_06_08_Time_183_ms_(100.00%)_Space_36.4_MB_(100.00%)
import java.util.LinkedList
import java.util.Queue
class Solution {
private var n = 0
private var m = 0
private lateinit var grid: Array<CharArray>
private val dirs = arrayOf(intArrayOf(1, 0), intArrayOf(0, 1), intArrayOf(-1, 0), intArrayOf(0, -1))
fun minPushBox(grid: Array<CharArray>): Int {
n = grid.size
m = grid[0].size
this.grid = grid
val box = IntArray(2)
val target = IntArray(2)
val player = IntArray(2)
findLocations(box, target, player)
val q: Queue<IntArray> = LinkedList()
q.offer(intArrayOf(box[0], box[1], player[0], player[1]))
// for 4 directions
val visited = Array(n) { Array(m) { BooleanArray(4) } }
var steps = 0
while (q.isNotEmpty()) {
var size = q.size
while (size-- > 0) {
val cur = q.poll()
if (cur != null && cur[0] == target[0] && cur[1] == target[1]) {
return steps
}
for (i in 0..3) {
if (cur != null) {
val newPlayerLoc = intArrayOf(cur[0] + dirs[i][0], cur[1] + dirs[i][1])
val newBoxLoc = intArrayOf(cur[0] - dirs[i][0], cur[1] - dirs[i][1])
if (visited[cur[0]][cur[1]][i] ||
isOutOfBounds(newPlayerLoc, newBoxLoc) ||
!isReachable(newPlayerLoc, cur)
) {
continue
}
visited[cur[0]][cur[1]][i] = true
q.offer(intArrayOf(newBoxLoc[0], newBoxLoc[1], cur[0], cur[1]))
}
}
}
steps++
}
return -1
}
private fun isReachable(targetPlayerLoc: IntArray, cur: IntArray): Boolean {
val visited = Array(n) { BooleanArray(m) }
visited[cur[0]][cur[1]] = true
visited[cur[2]][cur[3]] = true
val q: Queue<IntArray> = LinkedList()
q.offer(intArrayOf(cur[2], cur[3]))
while (q.isNotEmpty()) {
val playerLoc = q.poll()
if (playerLoc[0] == targetPlayerLoc[0] && playerLoc[1] == targetPlayerLoc[1]) {
return true
}
for (d in dirs) {
val x = playerLoc[0] + d[0]
val y = playerLoc[1] + d[1]
if (isOutOfBounds(x, y) || visited[x][y]) {
continue
}
visited[x][y] = true
q.offer(intArrayOf(x, y))
}
}
return false
}
private fun isOutOfBounds(player: IntArray, box: IntArray): Boolean {
return isOutOfBounds(player[0], player[1]) || isOutOfBounds(box[0], box[1])
}
private fun isOutOfBounds(x: Int, y: Int): Boolean {
return x < 0 || y < 0 || x == n || y == m || grid[x][y] == '#'
}
private fun findLocations(box: IntArray, target: IntArray, player: IntArray) {
var p = false
var t = false
var b = false
for (i in 0 until n) {
for (j in 0 until m) {
if (grid[i][j] == 'S') {
player[0] = i
player[1] = j
p = true
} else if (grid[i][j] == 'T') {
target[0] = i
target[1] = j
t = true
} else if (grid[i][j] == 'B') {
box[0] = i
box[1] = j
b = true
}
if (p && b && t) {
// found all
return
}
}
}
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 3,981 | LeetCode-in-Kotlin | MIT License |
src/main/java/sudoku/Sudoku.kt | ununhexium | 125,272,921 | false | null | package sudoku
data class Grid(val given: List<List<Int>>)
data class Guess(val position: Pair<Int,Int>, val number:Int)
data class Proposal(val original:Sudoku, val proposition: List<Guess>)
fun main(args: Array<String>) {
// val grid1 = parse()
}
typealias Sudoku = List<List<Int>>
fun parse(text: List<String>): Sudoku {
val parsed = text.map {
it.trim()
}.filter {
it.isNotEmpty()
}.map {
it.filter {
it in ('0'..'9')
}.map {
it.toInt() - '0'.toInt()
}
}
if (parsed.size != 9) {
throw IllegalArgumentException("The grid is not 9 lines long")
}
if (parsed.map { it.size }.any { it != 9 }) {
throw IllegalArgumentException("All lines must be 9 numbers long")
}
return parsed
}
/**
* Lists all the values contained in the given rectangle, bounds inclusive.
*/
fun listValues(
sudoku: Sudoku,
startRow: Int,
startColumn: Int,
endRow: Int,
endColumn: Int
): List<Int> {
return (startRow..endRow).flatMap { row ->
(startColumn..endColumn).map { col ->
sudoku[row][col]
}
}.filter { it != 0 }
}
fun listExistingValuesInSquare(
sudoku: Sudoku,
row: Int,
column: Int
): List<Int> {
val sRow = row / 3
val sCol = column / 3
return listValues(
sudoku,
sRow * 3,
sCol * 3,
(sRow + 1) * 3 - 1,
(sCol + 1) * 3 - 1
)
}
fun listExistingValuesInRow(sudoku: Sudoku, row: Int) =
listValues(sudoku, row, 0, row, 8)
fun listExistingValuesInColumn(sudoku: Sudoku, column: Int) =
listValues(sudoku, 0, column, 8, column)
fun options(sudoku: Sudoku, row: Int, column: Int): List<Int> {
val rowValues = listExistingValuesInRow(sudoku, row)
val columnValues = listExistingValuesInColumn(sudoku, column)
val squareValues = listExistingValuesInSquare(sudoku, row, column)
return (1..9).filter {
it !in rowValues && it !in columnValues && it !in squareValues
}
}
fun reject(origin: Sudoku, proposal: Sudoku, row: Int, col: Int): Boolean {
val opt = options(origin, row, col)
return proposal[row][col] !in opt
}
fun accept(proposal: Sudoku) =
proposal.flatMap {
it.map {
it
}
}.any {
it == 0
}.not()
fun first(original: Sudoku) = original
fun next(proposal: Sudoku, row: Int, col: Int): Sudoku {
val current = proposal[row][col]
val currentPosition = row to col
val nextPosition = when (current) {
9 -> next(row, col)
else -> {
currentPosition
}
}
val nextNumber = when (current) {
9 -> 1
else -> current + 1
}
// TODO: change
return proposal
}
fun next(row: Int, col: Int) =
when (col) {
9 -> row + 1 to 1
else -> row to col + 1
}
| 0 | Kotlin | 0 | 0 | 11aca6b37e06fe1e8ad31467703dacf857332825 | 2,700 | samples | The Unlicense |
src/tommyred/days/Day2.kt | TommyRed | 113,504,972 | false | null | package cz.tommyred.days
/**
* Created by Rechtig on 06.12.2017.
*/
val sample = "5 1 9 5\n7 5 3\n2 4 6 8"
val hardInput = "4347 3350 196 162 233 4932 4419 3485 4509 4287 4433 4033 207 3682 2193 4223\n648 94 778 957 1634 2885 1964 2929 2754 89 972 112 80 2819 543 2820\n400 133 1010 918 1154 1008 126 150 1118 117 148 463 141 940 1101 89\n596 527 224 382 511 565 284 121 643 139 625 335 657 134 125 152\n2069 1183 233 213 2192 193 2222 2130 2073 2262 1969 2159 2149 410 181 1924\n1610 128 1021 511 740 1384 459 224 183 266 152 1845 1423 230 1500 1381\n5454 3936 250 5125 244 720 5059 202 4877 5186 313 6125 172 727 1982 748\n3390 3440 220 228 195 4525 1759 1865 1483 5174 4897 4511 5663 4976 3850 199\n130 1733 238 1123 231 1347 241 291 1389 1392 269 1687 1359 1694 1629 1750\n1590 1394 101 434 1196 623 1033 78 890 1413 74 1274 1512 1043 1103 84\n203 236 3001 1664 195 4616 2466 4875 986 1681 152 3788 541 4447 4063 5366\n216 4134 255 235 1894 5454 1529 4735 4962 220 2011 2475 185 5060 4676 4089\n224 253 19 546 1134 3666 3532 207 210 3947 2290 3573 3808 1494 4308 4372\n134 130 2236 118 142 2350 3007 2495 2813 2833 2576 2704 169 2666 2267 850\n401 151 309 961 124 1027 1084 389 1150 166 1057 137 932 669 590 188\n784 232 363 316 336 666 711 430 192 867 628 57 222 575 622 234"
val xsample = "5 9 2 8\n9 4 7 3\n3 8 6 5"
fun main(args: Array<String>) {
println(solve2(parseInput(xsample)))
}
fun solve(list: List<List<Int>>): Int = list.map { it.max()!! - it.min()!! }.reduce { a, b -> a + b }
fun solve2(list: List<List<Int>>): Int = list.map { getFirstDivisor(it) }.reduce { a, b -> run { println("a $a b $b"); a + b } }
fun getFirstDivisor(list: List<Int>): Int {
return 1
}
fun parseInput(input: String): List<List<Int>> = input.split("\n").map { it.split(" ").map { it.toInt() } }
| 0 | Kotlin | 0 | 0 | 2c8b7c58cad55f29c54f89ddb6e0636cc1030fad | 1,811 | AoC2017 | MIT License |
src/main/kotlin/com/hj/leetcode/kotlin/problem1372/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem1372
import com.hj.leetcode.kotlin.common.model.TreeNode
/**
* LeetCode page: [1372. Longest ZigZag Path in a Binary Tree](https://leetcode.com/problems/longest-zigzag-path-in-a-binary-tree/);
*/
class Solution {
/* Complexity:
* Time O(N) and Space O(H) where N and H are the number of nodes and height of root
*/
fun longestZigZag(root: TreeNode?): Int {
var longestZigZag = 0
dfs(root) { maxLengthToNode ->
if (longestZigZag < maxLengthToNode) longestZigZag = maxLengthToNode
}
return longestZigZag
}
/**
* Perform a DFS and calls [onEachNode] passing the length of longest zigzag path to the node as an argument.
* [zigzagLengthLeft] and [zigzagLengthRight] are the length of longest zigzag paths incident to the node through
* a left edge and right edge respectively.
*/
private fun dfs(
root: TreeNode?,
zigzagLengthLeft: Int = 0,
zigzagLengthRight: Int = 0,
onEachNode: (maxLengthToNode: Int) -> Unit
) {
if (root == null) return
onEachNode(maxOf(zigzagLengthLeft, zigzagLengthRight))
dfs(root.left, 1 + zigzagLengthRight, 0, onEachNode)
dfs(root.right, 0, 1 + zigzagLengthLeft, onEachNode)
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 1,310 | hj-leetcode-kotlin | Apache License 2.0 |
src/main/kotlin/structures/GraphWithWeights.kt | DmitryTsyvtsyn | 418,166,620 | false | {"Kotlin": 223256} | package structures
/**
*
* data structure: directed graph with weights
*
* description: made up of vertices connected by edges that have direction and weight
*
*/
class GraphWithWeights<T> {
private val data = linkedMapOf<Vertex<T>, MutableList<VertexConnection<T>>>()
/**
* adds a new vertex with a value [value]
*/
fun addVertex(value: T) = data.putIfAbsent(Vertex(value), mutableListOf())
/**
* removes a vertex by value [value] from a graph
*/
fun removeVertex(value: T) {
val removingVertex = Vertex(value)
data.values.forEach { list ->
list.removeIf { it.vertex == removingVertex }
}
data.remove(removingVertex)
}
/**
* adds an edge between two vertices, that have values [value1], [value2]
*/
fun addEdge(value1: T, value2: T, cost: Int) {
val vertex1 = Vertex(value1)
val vertex2 = Vertex(value2)
data[vertex1]?.add(VertexConnection(vertex2, cost))
}
/**
* removes an edge between two vertices, that have values [value1], [value2]
*/
fun removeEdge(value1: T, value2: T) {
val vertex1 = Vertex(value1)
val vertex2 = Vertex(value2)
data[vertex1]?.removeIf { it.vertex == vertex2 }
}
/**
* returns the associated vertices and their weights with the given vertex value [value]
*/
fun connectedVertexesWithWeights(value: T) = data[Vertex(value)] ?: listOf()
/**
* implementation of Dijkstra's algorithm, returns pairs of a vertex and the minimum weight needed to get to that vertex (the starting vertex is the first added)
*/
fun dijkstraAlgorithm(): Map<Vertex<T>, Int> {
val unvisitedVertexes = linkedMapOf<Vertex<T>, Int>()
data.keys.forEach { vertex ->
unvisitedVertexes[vertex] = Int.MAX_VALUE
}
val visitedVertexes = linkedMapOf<Vertex<T>, Int>()
var minimumCost = 0
var currentVertex = unvisitedVertexes.keys.firstOrNull() ?: return visitedVertexes
while(unvisitedVertexes.isNotEmpty()) {
val neighbourVertexConnections = data[currentVertex] ?: emptyList()
for (neighbourVertexConnection in neighbourVertexConnections) {
val neighbourVertex = neighbourVertexConnection.vertex
if (!unvisitedVertexes.contains(neighbourVertex)) continue
val newCost = minimumCost + neighbourVertexConnection.cost
val neighbourVertexCost = unvisitedVertexes[neighbourVertex] ?: Int.MAX_VALUE
if (neighbourVertexCost > newCost) {
unvisitedVertexes[neighbourVertex] = newCost
}
}
visitedVertexes[currentVertex] = minimumCost
unvisitedVertexes.remove(currentVertex)
val nextUnvisitedEntry = unvisitedVertexes.entries
.filter { it.value != Int.MAX_VALUE }
.minByOrNull { it.value } ?: return visitedVertexes
currentVertex = nextUnvisitedEntry.key
minimumCost = nextUnvisitedEntry.value
}
return visitedVertexes
}
}
/**
* helper class for defining graph weights
*/
data class VertexConnection<T>(val vertex: Vertex<T>, val cost: Int) | 0 | Kotlin | 135 | 767 | 7ec0bf4f7b3767e10b9863499be3b622a8f47a5f | 3,289 | Kotlin-Algorithms-and-Design-Patterns | MIT License |
src/main/kotlin/com/jaspervanmerle/aoc2021/day/Day18.kt | jmerle | 434,010,865 | false | {"Kotlin": 60581} | package com.jaspervanmerle.aoc2021.day
class Day18 : Day("4124", "4673") {
private data class Element(var value: Int, var depth: Int)
override fun solvePartOne(): Any {
val numbers = input.lines().map { parseLine(it) }
var result = numbers[0]
for (number in numbers.drop(1)) {
result = add(result, number)
}
return magnitude(result)
}
override fun solvePartTwo(): Any {
val numbers = input.lines().map { parseLine(it) }
return numbers.indices
.flatMap { i -> numbers.indices.filter { it != i }.map { i to it } }
.maxOf { magnitude(add(numbers[it.first], numbers[it.second])) }
}
private fun parseLine(line: String): MutableList<Element> {
val elements = mutableListOf<Element>()
var currentDepth = 0
for (ch in line) {
when (ch) {
'[' -> currentDepth++
']' -> currentDepth--
',' -> continue
else -> elements.add(Element(ch.digitToInt(), currentDepth))
}
}
return elements
}
private fun add(lhs: List<Element>, rhs: List<Element>): MutableList<Element> {
val newElements = (lhs + rhs)
.map { it.copy(depth = it.depth + 1) }
.toMutableList()
while (true) {
if (explode(newElements)) {
continue
}
if (split(newElements)) {
continue
}
break
}
return newElements
}
private fun explode(elements: MutableList<Element>): Boolean {
for (i in 0 until elements.size - 1) {
val element = elements[i]
val nextElement = elements[i + 1]
if (element.depth <= 4 || element.depth != nextElement.depth) {
continue
}
if (i != 0) {
elements[i - 1].value += element.value
}
if (i + 2 < elements.size) {
elements[i + 2].value += nextElement.value
}
nextElement.value = 0
nextElement.depth--
elements.removeAt(i)
return true
}
return false
}
private fun split(elements: MutableList<Element>): Boolean {
for (i in elements.indices) {
val element = elements[i]
if (element.value <= 9) {
continue
}
val leftValue = element.value / 2
val rightValue = if (element.value % 2 == 0) leftValue else leftValue + 1
element.value = leftValue
element.depth++
elements.add(i + 1, Element(rightValue, element.depth))
return true
}
return false
}
private fun magnitude(elements: MutableList<Element>): Int {
while (elements.size > 1) {
for (i in 0 until elements.size - 1) {
val element = elements[i]
val nextElement = elements[i + 1]
if (element.depth != nextElement.depth) {
continue
}
element.value = 3 * element.value + 2 * nextElement.value
element.depth--
elements.removeAt(i + 1)
break
}
}
return elements[0].value
}
}
| 0 | Kotlin | 0 | 0 | dcac2ac9121f9bfacf07b160e8bd03a7c6732e4e | 3,405 | advent-of-code-2021 | MIT License |
src/main/kotlin/co/csadev/advent2020/Day03.kt | gtcompscientist | 577,439,489 | false | {"Kotlin": 252918} | /**
* Copyright (c) 2021 by <NAME>
* Advent of Code 2020, Day 3
* Problem Description: http://adventofcode.com/2020/day/3
*/
package co.csadev.advent2020
class Day03(private val input: List<String>) {
private val width = input.first().length
fun solvePart1(): Int = checkTrees(3 to 1)
fun solvePart2(): Long = listOf(1 to 1, 3 to 1, 5 to 1, 7 to 1, 1 to 2).fold(1L) { acc, i ->
acc * checkTrees(i)
}
private fun checkTrees(slope: Pair<Int, Int>): Int {
var trees = 0
var location = 0 to 0
while (location.second < input.size) {
trees += if (input[location.second][location.first] == '#') 1 else 0
location += slope
}
return trees
}
private operator fun Pair<Int, Int>.plus(slope: Pair<Int, Int>) = Pair(
(first + slope.first) % width,
second + slope.second
)
}
| 0 | Kotlin | 0 | 1 | 43cbaac4e8b0a53e8aaae0f67dfc4395080e1383 | 901 | advent-of-kotlin | Apache License 2.0 |
kotlin/src/main/kotlin/AoC_Day11.kt | sviams | 115,921,582 | false | null | object AoC_Day11 {
data class Position(val x: Int, val y: Int) {
fun distance(): Int {
val absX = Math.abs(x)
val absY = Math.abs(y)
return if (absX < absY) Math.ceil((absY-absX).toDouble()/2).toInt() + absX else absX
}
}
data class State(val pos: Position, val maxSteps: Int)
private fun followMoves(moves: List<String>) : State =
moves.fold(State(Position(0, 0), 0)) { state, value ->
val oldPos = state.pos
val newPos = when (value) {
"ne" -> Position(oldPos.x +1, oldPos.y +1)
"se" -> Position(oldPos.x +1, oldPos.y -1)
"sw" -> Position(oldPos.x -1, oldPos.y -1)
"nw" -> Position(oldPos.x -1, oldPos.y +1)
"n" -> Position(oldPos.x, oldPos.y+2)
else -> Position(oldPos.x, oldPos.y-2)
}
State(newPos, Math.max(newPos.distance(), state.maxSteps))
}
fun solvePt1(input: String) : Int = followMoves(input.split(",")).pos.distance()
fun solvePt2(input: String) : Int = followMoves(input.split(",")).maxSteps
} | 0 | Kotlin | 0 | 0 | 19a665bb469279b1e7138032a183937993021e36 | 1,146 | aoc17 | MIT License |
src/Day06_part1.kt | abeltay | 572,984,420 | false | {"Kotlin": 91982, "Shell": 191} | fun main() {
fun part1(input: String): Int {
val inArr = input.toCharArray()
val map = mutableMapOf<Char, Int>()
for (i in inArr.indices) {
map[inArr[i]] = map.getOrDefault(inArr[i], 0) + 1
if (i - 4 >= 0) {
map[inArr[i - 4]] = map.getOrDefault(inArr[i - 4], 0) - 1
}
if (i >= 3 && !map.any { it.value > 1 }) {
return i + 1
}
}
return 0
}
val testInput = readInput("Day06_test")
check(part1(testInput.first()) == 7)
check(part1("bvwbjplbgvbhsrlpgdmjqwftvncz") == 5)
check(part1("nppdvjthqldpwncqszvftbrmjlhg") == 6)
check(part1("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg") == 10)
check(part1("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw") == 11)
val input = readInput("Day06")
println(part1(input.first()))
}
| 0 | Kotlin | 0 | 0 | a51bda36eaef85a8faa305a0441efaa745f6f399 | 864 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/g1701_1800/s1761_minimum_degree_of_a_connected_trio_in_a_graph/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1701_1800.s1761_minimum_degree_of_a_connected_trio_in_a_graph
// #Hard #Graph #2023_06_18_Time_590_ms_(50.00%)_Space_80_MB_(100.00%)
class Solution {
fun minTrioDegree(n: Int, edges: Array<IntArray>): Int {
val degrees = IntArray(n + 1)
val adjMatrix = Array(n + 1) { IntArray(n + 1) }
for (edge in edges) {
adjMatrix[edge[0]][edge[1]] = 1
adjMatrix[edge[1]][edge[0]] = 1
degrees[edge[0]]++
degrees[edge[1]]++
}
var minTrios = Int.MAX_VALUE
for (i in 1..n) {
for (j in i + 1..n) {
if (adjMatrix[i][j] == 0) {
continue
}
for (k in j + 1..n) {
if (adjMatrix[j][k] == 0 || adjMatrix[i][k] == 0) {
continue
}
val trioDegree = degrees[i] + degrees[j] + degrees[k] - 6
minTrios = Math.min(minTrios, trioDegree)
}
}
}
return if (minTrios == Int.MAX_VALUE) -1 else minTrios
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,113 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/de/niemeyer/aoc2022/Day17.kt | stefanniemeyer | 572,897,543 | false | {"Kotlin": 175820, "Shell": 133} | /**
* Advent of Code 2022, Day 17: Pyroclastic Flow
* Problem Description: https://adventofcode.com/2022/day/19
*/
package de.niemeyer.aoc2022
import de.niemeyer.aoc.utils.Resources.resourceAsText
import de.niemeyer.aoc.utils.getClassName
// chamber is 7 units wide
// rock appears so that its left edge is two units away from the left wall
// and the bottom is 3 units above the highest rock (or the floor)
//
// first move by jet (if possible),
// then fall downward (if possible)
// if falling is not possible, the rocks lands and the next rocks appears
fun main() {
data class CacheKey(val skyline: List<Int>, val jetIndex: Int)
data class CacheValue(val highestRock: Int, val cycle: Long)
fun solve(input: String, maxCycles: Long): Long {
val cache = mutableMapOf<CacheKey, CacheValue>()
val chamber = Chamber()
var cycle = 1L
val initialPad = 3
var jetIdx = 0
val moves = jetMoves(input)
var simulatedHeight = 0L
rocksSequence().forEach rockForEach@{ rock ->
val highestRock = chamber.highestRock()
if (((cycle - 1) % rocks.size) == 0L) {
val cacheKey = CacheKey(chamber.skyline(), jetIdx)
val cacheValue = CacheValue(highestRock, cycle)
if (cache.containsKey(cacheKey) && simulatedHeight == 0L) {
val storedCachedValue = cache.getValue(cacheKey)
val cycleLength = (cycle - storedCachedValue.cycle)
val simCyles = (maxCycles - cycle) / cycleLength
val restCyles = (maxCycles - cycle) % cycleLength
val gainingHeightPerCycle = highestRock - storedCachedValue.highestRock
simulatedHeight = simCyles * gainingHeightPerCycle
cycle = maxCycles - restCyles
log("cycle $cycle: cache hit for $cacheKey: $storedCachedValue now: $cacheValue")
log("simulating $simCyles cycles rest $restCyles cyclesLength $cycleLength gaining height $gainingHeightPerCycle")
log("simulated height $simulatedHeight\n")
} else {
cache[cacheKey] = cacheValue
}
}
val enlarge = maxOf(0, highestRock + initialPad + rock.stones.size - chamber.levels.size + 1)
chamber.enlarge(enlarge)
var movedRock = rock
var level = highestRock + initialPad + 1
var isLanded = false
while (isLanded == false) {
// try jet move
val direction = moves[jetIdx]
if (chamber.isMovable(movedRock, direction, level)) {
movedRock = movedRock.move(direction)
}
jetIdx = (jetIdx + 1) % moves.size
if (chamber.isMovable(movedRock, RockDirection.DOWN, level)) {
level--
} else {
// rock landed
movedRock.stones.mapIndexed { idx, stone ->
val testLevel = level + idx
chamber.levels[testLevel] = chamber.levels[testLevel] xor stone
}
// log("end of cycle: $cycle -> ${chamber.highestRock()}")
// chamber.print()
cycle++
isLanded = true
}
}
if (cycle > maxCycles) {
val res = chamber.highestRock() + simulatedHeight
return res + 1
}
}
return -1
}
fun part1(input: String): Long =
solve(input, 2_022L)
fun part2(input: String): Long =
solve(input, 1_000_000_000_000L)
val name = getClassName()
val testInput = resourceAsText(fileName = "${name}_test.txt").trim()
val puzzleInput = resourceAsText(fileName = "${name}.txt").trim()
check(part1(testInput) == 3_068L)
val puzzleResultPart1 = part1(puzzleInput)
println(puzzleResultPart1)
check(puzzleResultPart1 == 3_173L)
check(part2(testInput) == 1_514_285_714_288L)
val puzzleResultPart2 = part2(puzzleInput)
println(puzzleResultPart2)
check(puzzleResultPart2 == 1_570_930_232_582L)
}
enum class RockDirection {
LEFT, RIGHT, DOWN
}
val rocks = listOf(
listOf(
0b000111100
),
listOf(
0b000010000,
0b000111000,
0b000010000
),
listOf(
0b000001000,
0b000001000,
0b000111000
).reversed(),
listOf(
0b000100000,
0b000100000,
0b000100000,
0b000100000
),
listOf(
0b000110000,
0b000110000
)
)
fun rocksSequence() = sequence {
while (true) {
yieldAll(rocks.map { Rock(it) })
}
}
@Suppress("UNUSED_PARAMETER")
fun log(msg: String) {
// println(msg)
}
class Chamber(var levels: IntArray = IntArray(0)) {
val chamberBorder = 0b100000001
fun enlarge(size: Int) {
levels += IntArray(size)
if (size > levels.size) {
levels = IntArray(size) { 0 }
}
}
fun isMovable(rock: Rock, direction: RockDirection, startLevel: Int): Boolean {
val movedRock = rock.move(direction)
val newLevel = if (direction == RockDirection.DOWN) startLevel - 1 else startLevel
if (newLevel < 0) {
return false
}
val moveResults = movedRock.stones.mapIndexed { idx, stone ->
val testLevel = newLevel + idx
val movable = ((stone and levels[testLevel]) == 0) && ((stone and chamberBorder) == 0)
log("testLevel: $testLevel direction: $direction stone: ${stone.asBinaryString()} level: ${levels[testLevel].asBinaryString()} -> $movable")
movable
}
val retVal = moveResults.all { it == true }
return retVal
}
fun highestRock(): Int =
levels.indexOfLast { it != 0 }
fun skyline(): List<Int> {
val highestRock = highestRock()
if (highestRock == -1) {
return listOf()
}
val maxDepth = -highestRock - 1
val result = MutableList<Int>(7) { maxDepth }
for (column in 0..6) {
val pattern = 0b010000000 shr column
log("pattern: ${pattern.asBinaryString()}")
rowTesting@ for (row in highestRock downTo 0) {
val testLevel = levels[row]
log("row: $row: ${testLevel.asBinaryString()}")
if ((testLevel and pattern) != 0) {
if (result[column] == maxDepth) {
result[column] = row - highestRock
}
}
}
}
return result.toList()
}
@Suppress("unused")
fun print() {
(levels.lastIndex downTo 0).forEach { level ->
println(levels[level].asBinaryString())
}
}
}
fun jetMoves(input: String): List<RockDirection> =
input.map {
when (it) {
'>' -> RockDirection.RIGHT
'<' -> RockDirection.LEFT
else -> error("invalid input jet move '$it'")
}
}
class Rock(val stones: List<Int>) {
override fun toString(): String {
return stones.joinToString("") { it.toString(2).padStart(7, '0') }
}
fun move(direction: RockDirection): Rock {
return when (direction) {
RockDirection.LEFT -> Rock(stones.map { it shl 1 })
RockDirection.RIGHT -> Rock(stones.map { it shr 1 })
RockDirection.DOWN -> this
}
}
}
fun Int.asBinaryString() = Integer.toBinaryString(this).padStart(9, '0')
| 0 | Kotlin | 0 | 0 | ed762a391d63d345df5d142aa623bff34b794511 | 7,695 | AoC-2022 | Apache License 2.0 |
src/main/kotlin/com/kylecorry/sol/math/statistics/Statistics.kt | kylecorry31 | 294,668,785 | false | {"Kotlin": 714099, "Java": 18119, "Python": 298} | package com.kylecorry.sol.math.statistics
import com.kylecorry.sol.math.RoundingMethod
import com.kylecorry.sol.math.SolMath
import com.kylecorry.sol.math.SolMath.lerp
import com.kylecorry.sol.math.SolMath.round
import com.kylecorry.sol.math.SolMath.square
import com.kylecorry.sol.math.Vector2
import com.kylecorry.sol.math.algebra.*
import com.kylecorry.sol.math.regression.LinearRegression
import com.kylecorry.sol.math.sumOfFloat
import kotlin.math.exp
import kotlin.math.pow
import kotlin.math.roundToInt
import kotlin.math.sqrt
object Statistics {
/**
* Calculate the weighted sum of the provided values
* @param values a list of value to weights [0, 1]
*/
fun weightedMean(values: List<Pair<Float, Float>>): Float {
var sum = 0f
for (value in values) {
sum += value.first * value.second
}
return sum
}
fun mean(values: List<Float>): Float {
return values.average().toFloat()
}
fun geometricMean(values: List<Float>): Float {
if (values.isEmpty()) {
return 0f
}
var total = 1.0
for (value in values) {
total *= value
}
return total.pow(1 / values.size.toDouble()).toFloat()
}
fun harmonicMean(values: List<Float>): Float {
return values.size / values.sumOfFloat { 1 / it }
}
fun variance(values: List<Float>, forPopulation: Boolean = false, mean: Float? = null): Float {
if (values.size <= 1) {
return 0f
}
val average = mean?.toDouble() ?: values.average()
return values.sumOf { square(it.toDouble() - average) }
.toFloat() / (values.size - if (!forPopulation) 1 else 0)
}
fun stdev(values: List<Float>, forPopulation: Boolean = false, mean: Float? = null): Float {
return sqrt(variance(values, forPopulation, mean))
}
fun median(values: List<Float>): Float {
return quantile(values, 0.5f, interpolate = false)
}
fun quantile(values: List<Float>, quantile: Float, interpolate: Boolean = true): Float {
if (values.isEmpty()) {
return 0f
}
val sorted = values.sorted()
val idx = sorted.lastIndex * quantile
if (!interpolate){
// Round toward zero to match the behavior of numpy
return sorted[idx.round(RoundingMethod.TowardZero)]
}
// Index is an integer, short circuit
if (idx == idx.toInt().toFloat()) {
return sorted[idx.toInt()]
}
val lower = sorted[idx.toInt()]
val upper = sorted[(idx.toInt() + 1).coerceIn(0, sorted.lastIndex)]
val remainder = idx - idx.toInt()
return lerp(remainder, lower, upper)
}
fun skewness(
values: List<Float>,
mean: Float? = null,
stdev: Float? = null
): Float {
val average = mean ?: values.average().toFloat()
val deviation = stdev ?: stdev(values, mean = average)
return values.sumOf {
SolMath.power((it - average) / deviation.toDouble(), 3)
}.toFloat() / values.size
}
fun probability(values: List<Float>): List<Float> {
val sum = values.sum()
if (sum == 0f) {
return values
}
return values.map { it / sum }
}
fun probability(x: Float, distribution: GaussianDistribution): Float {
return distribution.probability(x)
}
fun softmax(values: List<Float>): List<Float> {
if (values.isEmpty()) {
return emptyList()
}
val maxZ = values.max()
val exponents = values.map { exp(it - maxZ) }
val sumExp = exponents.sum()
return exponents.map { if (sumExp == 0f) 0f else it / sumExp }
}
fun joint(distributions: List<GaussianDistribution>): GaussianDistribution? {
if (distributions.isEmpty()) {
return null
}
var mean = distributions.first().mean
var variance = distributions.first().variance
for (i in 1..distributions.lastIndex) {
val m2 = distributions[i].mean
val var2 = distributions[i].variance
val joint = mean * var2 + m2 * variance
val sumVar = variance + var2
val multVar = variance * var2
variance = multVar / sumVar
mean = joint / sumVar
}
return GaussianDistribution(mean, sqrt(variance))
}
fun zScore(value: Float, distribution: GaussianDistribution, n: Int = 1): Float {
return if (n == 1) {
(value - distribution.mean) / distribution.standardDeviation
} else {
(value - distribution.mean) / (distribution.standardDeviation / sqrt(n.toFloat()))
}
}
/**
* Calculates the slope of the best fit line
*/
fun slope(data: List<Vector2>): Float {
return LinearRegression(data).equation.m
}
/**
* Calculates the root mean square errors between the datasets. Actual and predicted must correspond 1-1 with eachother.
*/
fun rmse(actual: List<Float>, predicted: List<Float>): Float {
val n = actual.size
return sqrt(sse(actual, predicted) / n)
}
/**
* Calculates the sum of squared errors between the datasets. Actual and predicted must correspond 1-1 with eachother.
*/
fun sse(actual: List<Float>, predicted: List<Float>): Float {
var sum = 0f
for (i in actual.indices) {
sum += (actual[i] - predicted[i]).pow(2)
}
return sum
}
/**
* Calculates the accuracy given a confusion matrix (rows = predicted, columns = actual)
*/
fun accuracy(confusion: Matrix): Float {
val total = confusion.sum()
val correct = confusion.multiply(identityMatrix(confusion.rows())).sum()
return correct / total
}
/**
* Calculates the F1 score given a confusion matrix (rows = predicted, columns = actual)
* @param weighted if true, a weighted average will be used to combine f1 scores by number of examples per class
*/
fun f1Score(confusion: Matrix, weighted: Boolean = false): Float {
val all = confusion.sum()
val weight = 1 / confusion.rows().toFloat()
return confusion.mapIndexed { index, _ ->
val total = confusion.transpose()[index].sum()
f1Score(confusion, index) * if (weighted) total / all else weight
}.sum()
}
/**
* Calculates the F1 for a single class given a confusion matrix (rows = predicted, columns = actual)
*/
fun f1Score(confusion: Matrix, classIdx: Int): Float {
val precision = precision(confusion, classIdx)
val recall = recall(confusion, classIdx)
val f = (2 * precision * recall) / (precision + recall)
if (f.isNaN()) {
return 0f
}
return f
}
/**
* Calculates the recall for a single class given a confusion matrix (rows = predicted, columns = actual)
*/
fun recall(confusion: Matrix, classIdx: Int): Float {
val actual = confusion.transpose()[classIdx]
val tp = confusion[classIdx][classIdx]
val fn = actual.sum() - tp
if ((tp + fn) == 0f) {
return 0f
}
return tp / (tp + fn)
}
/**
* Calculates the precision for a single class given a confusion matrix (rows = predicted, columns = actual)
*/
fun precision(confusion: Matrix, classIdx: Int): Float {
val predicted = confusion[classIdx]
val tp = confusion[classIdx][classIdx]
val fp = predicted.sum() - tp
if ((tp + fp) == 0f) {
return 0f
}
return tp / (tp + fp)
}
} | 11 | Kotlin | 4 | 8 | ac1e4f9b3635e7b50a9668f74c9303c0152c94ce | 7,773 | sol | MIT License |
src/main/kotlin/be/amedee/adventofcode/aoc2015/day01/Day01.kt | amedee | 160,062,642 | false | {"Kotlin": 9459, "Markdown": 7503} | package be.amedee.adventofcode.aoc2015.day01
import java.io.BufferedReader
import java.io.InputStreamReader
/**
* Single move to the next floor, up or down.
*
* @return do we go up or down
*/
fun move(): (String) -> Int =
{
when (it) {
"(" -> 1
")" -> -1
else -> 0
}
}
/**
* The entire list of elevator instructions.
*
* @return at which floor Santa ends up
*/
fun followInstructions(): (String) -> Int =
{ instructionList ->
instructionList
.toList()
.sumOf { move()(it.toString()) }
}
/**
* Find the position of the first character that causes Santa to enter the
* basement (floor -1). The first character in the instructions has
* position 1, the second character has position 2, and so on.
*/
fun findBasementPosition(instructions: String): Int {
var floor = 0
return instructions.indexOfFirst {
when (it) {
'(' -> floor++
')' -> floor--
}
floor == -1
} + 1
}
class Day01 {
fun readElevatorInstructionsFromFile(fileName: String): String {
val packageName = javaClass.`package`.name.replace(".", "/")
val filePath = "/$packageName/$fileName"
val inputStream = javaClass.getResourceAsStream(filePath)
return BufferedReader(InputStreamReader(inputStream!!)).use { it.readText().trim() }
}
}
/**
* Santa is trying to deliver presents in a large apartment building,
* but he can't find the right floor - the directions he got are a little confusing.
*/
fun main() {
val inputFile = "input"
val puzzleInput = Day01().readElevatorInstructionsFromFile(inputFile)
val endFloor = followInstructions()(puzzleInput)
println("Santa ends up on floor $endFloor.")
val basementPosition = findBasementPosition(puzzleInput)
when (basementPosition) {
0 -> println("Santa never enters the basement.")
else -> println("Santa enters the basement at character position ${"%,d".format(basementPosition)}.")
}
}
| 0 | Kotlin | 0 | 1 | 02e8e0754f2252a2850175fc8b134dd36bc6d042 | 2,058 | adventofcode | MIT License |
src/main/kotlin/g1401_1500/s1405_longest_happy_string/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1401_1500.s1405_longest_happy_string
// #Medium #String #Greedy #Heap_Priority_Queue
// #2023_06_07_Time_119_ms_(100.00%)_Space_33.7_MB_(100.00%)
class Solution {
fun longestDiverseString(a: Int, b: Int, c: Int): String {
val sb = StringBuilder()
val remains = intArrayOf(a, b, c)
val chars = charArrayOf('a', 'b', 'c')
var preIndex = -1
do {
var index: Int
var largest: Boolean
if (preIndex != -1 &&
remains[preIndex]
== Math.max(remains[0], Math.max(remains[1], remains[2]))
) {
index = if (preIndex == 0) {
if (remains[1] > remains[2]) 1 else 2
} else if (preIndex == 1) {
if (remains[0] > remains[2]) 0 else 2
} else {
if (remains[0] > remains[1]) 0 else 1
}
largest = false
} else {
index = if (remains[0] > remains[1]) 0 else 1
index = if (remains[index] > remains[2]) index else 2
largest = true
}
remains[index]--
sb.append(chars[index])
if (remains[index] > 0 && largest) {
remains[index]--
sb.append(chars[index])
}
preIndex = index
} while (remains[0] + remains[1] + remains[2] != remains[preIndex])
return sb.toString()
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,495 | LeetCode-in-Kotlin | MIT License |
Algorithms_and_data_structures/ex01/ex.kt | Hasuk1 | 740,111,124 | false | {"Kotlin": 120039} | import kotlin.math.pow
import kotlin.math.sqrt
fun main() {
println(calculateTotalPoints(readInput()))
}
fun readInput(): List<Pair<Double, Double>> {
val points = mutableListOf<Pair<Double, Double>>()
for (i in 1..3) {
val (x, y) = readLine()!!.split(" ").map { it.toDouble() }
points.add(x to y)
}
return points
}
fun calculatePoints(x: Double, y: Double): Int {
val distance = sqrt(x.pow(2) + y.pow(2))
return when {
distance <= 0.1 -> 3
distance <= 0.8 -> 2
distance <= 1.0 -> 1
else -> 0
}
}
fun calculateTotalPoints(input: List<Pair<Double, Double>>): Int {
return input.sumOf { (x, y) -> calculatePoints(x, y) }
}
| 0 | Kotlin | 0 | 1 | 1dc4de50dd3cd875e3fe76e3da4a58aa04bb87c7 | 667 | Kotlin_bootcamp | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/IncreasingSubsequences.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import java.util.LinkedList
/**
* 491. Increasing Subsequences
* @see <a href="https://leetcode.com/problems/increasing-subsequences/">Source</a>
*/
fun interface IncreasingSubsequences {
fun findSubsequences(nums: IntArray): List<List<Int>>
}
class IncreasingSubsequencesBacktracking : IncreasingSubsequences {
override fun findSubsequences(nums: IntArray): List<List<Int>> {
val res: MutableList<List<Int>> = LinkedList()
helper(LinkedList(), 0, nums, res)
return res
}
private fun helper(list: LinkedList<Int>, index: Int, nums: IntArray, res: MutableList<List<Int>>) {
if (list.size > 1) res.add(LinkedList(list))
val used: MutableSet<Int> = HashSet()
for (i in index until nums.size) {
if (used.contains(nums[i])) continue
if (list.isEmpty() || nums[i] >= list.peekLast()) {
used.add(nums[i])
list.add(nums[i])
helper(list, i + 1, nums, res)
list.removeAt(list.size - 1)
}
}
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,708 | kotlab | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MergeKLists.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import java.util.PriorityQueue
/**
* 23. Merge k Sorted Lists
* @see <a href="https://leetcode.com/problems/merge-k-sorted-lists/">Source</a>
*/
fun interface MergeKLists {
operator fun invoke(lists: Array<ListNode?>): ListNode?
}
class MergeKListsPQ : MergeKLists {
override operator fun invoke(lists: Array<ListNode?>): ListNode? {
if (lists.isEmpty()) return null
val queue = PriorityQueue<ListNode>(
lists.size,
Comparator { o1, o2 ->
return@Comparator when {
o1.value < o2.value -> -1
o1.value == o2.value -> 0
else -> 1
}
},
)
val dummy = ListNode(0)
var tail: ListNode? = dummy
for (node in lists) {
queue.addIfNotNull(node)
}
while (queue.isNotEmpty()) {
tail?.next = queue.poll()
tail = tail?.next
val next = tail?.next
if (next.isNotNull()) {
queue.add(next)
}
}
return dummy.next
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,754 | kotlab | Apache License 2.0 |
year2020/src/main/kotlin/net/olegg/aoc/year2020/day4/Day4.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2020.day4
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.utils.toPair
import net.olegg.aoc.year2020.DayOf2020
/**
* See [Year 2020, Day 4](https://adventofcode.com/2020/day/4)
*/
object Day4 : DayOf2020(4) {
private val HEIGHT_PATTERN = "^([0-9]+)(cm|in)$".toRegex()
private val COLOR_PATTERN = "^#[0-9a-f]{6}$".toRegex()
private val ID_PATTERN = "^[0-9]{9}$".toRegex()
override fun first(): Any? {
val passports = data
.split("\n\n")
.map { it.replace("\n", " ") }
.map { line -> line.split(" ").associate { it.split(":").toPair() } }
return passports.count { (it - "cid").size == 7 }
}
override fun second(): Any? {
val passports = data
.split("\n\n")
.map { it.replace("\n", " ") }
.map { line -> line.split(" ").associate { it.split(":").toPair() } }
return passports.count { (it - "cid").size == 7 && it.all { (key, value) -> isValid(key, value) } }
}
private fun isValid(
field: String,
value: String
): Boolean {
return try {
when (field) {
"byr" -> value.toInt() in 1920..2002
"iyr" -> value.toInt() in 2010..2020
"eyr" -> value.toInt() in 2020..2030
"hgt" -> HEIGHT_PATTERN.find(value)?.destructured?.let { (length, measure) ->
(measure == "in" && length.toInt() in 59..76) or (measure == "cm" && length.toInt() in 150..193)
} ?: false
"hcl" -> COLOR_PATTERN.matches(value)
"ecl" -> value in setOf("amb", "blu", "brn", "gry", "grn", "hzl", "oth")
"pid" -> ID_PATTERN.matches(value)
"cid" -> true
else -> false
}
} catch (_: Exception) {
false
}
}
}
fun main() = SomeDay.mainify(Day4)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 1,739 | adventofcode | MIT License |
src/main/kotlin/dev/luna5ama/palbreed/BreedCalculator.kt | Luna5ama | 753,934,567 | false | {"Kotlin": 5433} | package dev.luna5ama.palbreed
import java.util.TreeMap
class BreedCalculator(passiveData: List<Pal.Passive>, speciesData: List<Pal.Species>) {
private val breedValueMap = TreeMap<Int, Pal.Species>()
private val indexOrderMap = TreeMap<Int, Pal.Species>()
private val passiveNameMap = passiveData.associateBy { it.name }
private val speciesNameMap = speciesData.associateBy { it.name }
init {
speciesData.forEach {
breedValueMap[it.breedValue] = it
indexOrderMap[it.indexOrder] = it
}
}
fun getSpecies(name: String): Pal.Species {
return speciesNameMap[name] ?: throw IllegalArgumentException("No species found")
}
fun getPassive(name: String): Pal.Passive {
return passiveNameMap[name] ?: throw IllegalArgumentException("No passive found")
}
private fun calc(a: Pal, b: Pal): List<Pal> {
val avgBreedValue = (a.species.breedValue + b.species.breedValue) / 2
val above = breedValueMap.ceilingEntry(avgBreedValue)
val below = breedValueMap.floorEntry(avgBreedValue)
check(above != null || below != null) { "No species found" }
val childSpecies = when {
above == null -> below.value
below == null -> above.value
else -> {
val diffAbove = above.key - avgBreedValue
val diffBelow = avgBreedValue - below.key
when {
diffAbove < diffBelow -> above.value
diffBelow < diffAbove -> below.value
below.value.indexOrder < above.value.indexOrder -> below.value
else -> above.value
}
}
}
return listOf(
Pal(childSpecies, null, a.passive),
Pal(childSpecies, null, b.passive),
Pal(childSpecies, null, a.passive + b.passive)
)
}
fun calcTree(pals: List<Pal>, targetSpecies: Pal.Species, targetPassive: List<Pal.Passive>): BreedTreeNode {
val checked = mutableSetOf<Pair<Pal, Pal>>()
val poolSet = pals
.filter { targetPassive.containsAll(it.passive) }
.map { BreedTreeNode(it) }
.toMutableSet()
check(poolSet.isNotEmpty()) { "No input pal found" }
val queue = ArrayDeque<BreedTreeNode>()
for (nodeA in poolSet) {
for (nodeB in poolSet) {
if (nodeA === nodeB) continue
if (!Pal.Sex.matched(nodeA.pal.sex, nodeB.pal.sex)) continue
if (!checked.add(nodeA.pal to nodeB.pal)) continue
queue.add(BreedTreeNode(calc(nodeA.pal, nodeB.pal).last(), nodeA, nodeB))
}
}
while (queue.isNotEmpty()) {
val nodeA = queue.removeFirst()
if (!poolSet.add(nodeA)) continue
val a = nodeA.pal
if (a.species == targetSpecies && a.passive.containsAll(targetPassive)) {
return nodeA
}
for (nodeB in poolSet) {
val b = nodeB.pal
if (nodeA === nodeB) continue
if (!checked.add(a to b)) continue
queue.add(BreedTreeNode(calc(nodeA.pal, nodeB.pal).last(), nodeA, nodeB))
}
}
throw IllegalStateException("No result found")
}
class BreedTreeNode(val pal: Pal, val father: BreedTreeNode? = null, val mother: BreedTreeNode? = null) {
fun pairTree(): List<List<BreedResult>> {
val result = mutableListOf<List<BreedResult>>()
var layer = listOf(this)
while (layer.isNotEmpty()) {
result.add(layer.mapNotNull { node ->
val father = node.father ?: return@mapNotNull null
val mother = node.mother ?: return@mapNotNull null
BreedResult(father, mother, node)
})
layer = layer.flatMap { listOfNotNull(it.father, it.mother) }
}
return result
}
}
class BreedResult(val father: BreedTreeNode, val mother: BreedTreeNode, val child: BreedTreeNode)
} | 0 | Kotlin | 0 | 1 | 2e16010ae6144f11f4531d6b7f60ee57c02219e0 | 4,162 | pal-breed | MIT License |
2022/08/08.kt | LiquidFun | 435,683,748 | false | {"Kotlin": 40554, "Python": 35985, "Julia": 29455, "Rust": 20622, "C++": 1965, "Shell": 1268, "APL": 191} |
fun main() {
val s = generateSequence(::readlnOrNull).toList()
val indices = (0..s.size-1).toList()
val visible: MutableSet<Pair<Int, Int>> = mutableSetOf()
var highest: Int
for (i in indices) {
for (order in listOf(indices, indices.reversed())) {
highest = 0
for (x in order) {
if (highest < s[i][x].code)
visible.add(Pair(i, x))
highest = maxOf(s[i][x].code, highest)
}
highest = 0
for (y in order) {
if (highest < s[y][i].code)
visible.add(Pair(y, i))
highest = maxOf(s[y][i].code, highest)
}
}
}
println(visible.size)
var best = 0
fun is_valid(y: Int, x: Int, size: Int) = 0 <= y && y < size && 0 <= x && x < size
for (Y in indices) {
for (X in indices) {
var scenic = 1
for ((ya, xa) in listOf(Pair(1, 0), Pair(-1, 0), Pair(0, 1), Pair(0, -1))) {
var dist = 0
var y = Y+ya
var x = X+xa
while (is_valid(y, x, s.size)) {
dist += 1
if (s[y][x] >= s[Y][X])
break
y = y+ya
x = x+xa
}
scenic *= dist
}
best = maxOf(best, scenic)
}
}
println(best)
}
| 0 | Kotlin | 7 | 43 | 7cd5a97d142780b8b33b93ef2bc0d9e54536c99f | 1,455 | adventofcode | Apache License 2.0 |
year2016/src/main/kotlin/net/olegg/aoc/year2016/day22/Day22.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2016.day22
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.year2016.DayOf2016
/**
* See [Year 2016, Day 22](https://adventofcode.com/2016/day/22)
*/
object Day22 : DayOf2016(22) {
val PATTERN = "/dev/grid/node-x(\\d+)-y(\\d+)\\s+(\\d+)T\\s+(\\d+)T\\s+(\\d+)T\\s+(\\d+)%".toRegex()
override fun first(): Any? {
val machines = lines
.mapNotNull { line ->
PATTERN.matchEntire(line)
?.groupValues
?.let { values ->
values.subList(1, 6).map { it.toInt() }
}
}
return machines
.filter { it[3] != 0 }
.flatMap { a ->
machines.filter { it != a }
.filter { it[4] >= a[3] }
.map { b -> a to b }
}
.size
}
override fun second(): Any? {
val machines = lines
.mapNotNull { line ->
PATTERN.matchEntire(line)
?.groupValues
?.let { values ->
values.subList(1, 6).map { it.toInt() }
}
}
return machines
.groupByTo(sortedMapOf()) { it[1] }
.map { (_, row) ->
row.sortedBy { it[0] }.joinToString(separator = "") { cell ->
when (cell[3]) {
0 -> "_"
in 1..100 -> "."
else -> "#"
}
}
}
.joinToString(separator = "\n", prefix = "\n")
}
}
fun main() = SomeDay.mainify(Day22)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 1,394 | adventofcode | MIT License |
codeforces/globalround8/e.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package codeforces.globalround8
private fun solve(out: List<MutableList<Int>>): String {
val layer = IntArray(out.size)
for (u in out.indices) {
if (layer[u] == 2) continue
for (v in out[u]) layer[v] = maxOf(layer[v], layer[u] + 1)
}
val ans = layer.indices.filter { layer[it] == 2 }
return "${ans.size}\n${ans.map { it + 1 }.joinToString(" ")}\n"
}
fun main() = repeat(readInt()) {
val (n, m) = readInts()
val out = List(n) { ArrayList<Int>(2) }
repeat(m) {
val (u, v) = readInts().map { it - 1 }
out[u].add(v)
}
for (s in out.indices) out[s].sort()
output.append(solve(out))
}.also { println(output) }
val output = StringBuilder()
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 | 838 | competitions | The Unlicense |
2017/src/main/kotlin/Day16.kt | dlew | 498,498,097 | false | {"Kotlin": 331659, "TypeScript": 60083, "JavaScript": 262} | import utils.splitCommas
import utils.toIntList
object Day16 {
fun part1(programs: String, instructions: String): String {
return dance(programs, parseInstructions(instructions))
}
fun part2(initialPrograms: String, inputInstructions: String, times: Int): String {
val instructions = parseInstructions(inputInstructions)
var programs = initialPrograms
for (a in 0 until times % findCycleLength(initialPrograms, instructions)) {
programs = dance(programs, instructions)
}
return programs
}
sealed class Instruction {
data class Spin(val num: Int) : Instruction()
data class Exchange(val a: Int, val b: Int) : Instruction()
data class Partner(val a: Char, val b: Char) : Instruction()
}
private fun parseInstructions(inputInstructions: String): List<Instruction> {
return inputInstructions.splitCommas().map { instruction ->
when (instruction[0]) {
's' -> Instruction.Spin(instruction.drop(1).toInt())
'x' -> {
val positions = instruction.drop(1).split("/").toIntList()
Instruction.Exchange(positions[0], positions[1])
}
'p' -> Instruction.Partner(instruction[1], instruction[3])
else -> throw IllegalArgumentException("Illegal instruction: $instruction")
}
}
}
private fun dance(initialPrograms: String, instructions: List<Instruction>): String {
var programs = initialPrograms.toCharArray()
var spinner = initialPrograms.toCharArray()
val numPrograms = programs.size
for (instruction in instructions) {
when (instruction) {
is Instruction.Spin -> {
val rotate = numPrograms - instruction.num
for (index in 0 until numPrograms) {
spinner[index] = programs[(index + rotate) % numPrograms]
}
val tmp = programs
programs = spinner
spinner = tmp
}
is Instruction.Exchange -> programs.swap(instruction.a, instruction.b)
is Instruction.Partner -> {
programs.swap(programs.indexOf(instruction.a), programs.indexOf(instruction.b))
}
}
}
return programs.joinToString("")
}
private fun CharArray.swap(a: Int, b: Int) {
val tmp = this[a]
this[a] = this[b]
this[b] = tmp
}
/**
* Key insight: the instructions, applied over and over, eventually create a cycle, so you don't
* actually need to apply it a billion times.
*/
private fun findCycleLength(initialPrograms: String, instructions: List<Instruction>): Int {
var programs = initialPrograms
val seen = mutableSetOf<String>()
var length = 0
while (programs !in seen) {
seen.add(programs)
programs = dance(programs, instructions)
length++
}
return length
}
} | 0 | Kotlin | 0 | 0 | 6972f6e3addae03ec1090b64fa1dcecac3bc275c | 2,783 | advent-of-code | MIT License |
src/main/kotlin/year_2023/Day01.kt | krllus | 572,617,904 | false | {"Kotlin": 97314} | package year_2023
import Day
import solve
class Day01 : Day(day = 1, year = 2023, "Trebuchet?!") {
override fun part1(): Int {
return input.sumOf {
val a = it.first { c: Char -> c.isDigit() }.digitToInt()
val b = it.last { c: Char -> c.isDigit() }.digitToInt()
a * 10 + b
}
}
override fun part2(): Int {
return input.sumOf { line ->
val parsedLine = line
.replace("oneight","oneeight")
.replace("threeight","threeeight")
.replace("fiveight","fiveeight")
.replace("twone","twoone")
.replace("sevenine","sevennine")
.replace("eightwo","eighttwo")
.replace("eighthree","eightthree")
.replace("nineight","nineeight")
val result = parsedLine
.replace("one", "1")
.replace("two", "2")
.replace("three", "3")
.replace("four", "4")
.replace("five", "5")
.replace("six", "6")
.replace("seven", "7")
.replace("eight", "8")
.replace("nine", "9")
val a = result.first { c: Char -> c.isDigit() }.digitToInt()
val b = result.last { c: Char -> c.isDigit() }.digitToInt()
a * 10 + b
}
}
}
fun main() {
solve<Day01>(offerSubmit = true) {
"""
two1nine
eightwothree
abcone2threexyz
xtwone3four
4nineeightseven2
zoneight234
7pqrstsixteen
""".trimIndent()(part2 = 281)
}
} | 0 | Kotlin | 0 | 0 | b5280f3592ba3a0fbe04da72d4b77fcc9754597e | 1,678 | advent-of-code | Apache License 2.0 |
src/main/kotlin/eu/michalchomo/adventofcode/year2023/Day10.kt | MichalChomo | 572,214,942 | false | {"Kotlin": 56758} | package eu.michalchomo.adventofcode.year2023
import eu.michalchomo.adventofcode.Day
import eu.michalchomo.adventofcode.main
import eu.michalchomo.adventofcode.toCharMatrix
object Day10 : Day {
override val number: Int = 10
private const val IN_CHAR = 'I'
private const val OUT_CHAR = 'O'
override fun part1(input: List<String>): String = input.toCharMatrix().findPath().let { it.size / 2 }.toString()
override fun part2(input: List<String>): String = input.toCharMatrix().let { charMatrix ->
charMatrix.findPath().let { path ->
val pathColsInRow = path.fold(mutableMapOf<Int, List<Int>>()) { acc, (position, _) ->
acc.merge(position.first, mutableListOf(position.second)) { old, _ ->
(old + position.second).sorted()
}
acc
}
val matCopy = charMatrix.copyOf()
charMatrix.indices.sumOf { i ->
val pathCols = pathColsInRow[i] ?: emptyList()
charMatrix[i].indices.count { j ->
if (j !in pathCols) {
val crossings = pathCols.findPathTilesBefore(j)
.minus(charMatrix[i].slice(0..<j).count { it == '-' || it == 'F' || it == '7' })
val isInside = crossings.isOdd()
if (isInside) {
matCopy[i][j] = IN_CHAR
} else {
matCopy[i][j] = OUT_CHAR
}
isInside
} else {
false
}
}
}
.also {
matCopy.forEach { r ->
r.forEach { c ->
if (c == IN_CHAR) {
print("\u001b[31m$c\u001b[0m")
} else if (c == OUT_CHAR) {
print("\u001b[34m$c\u001b[0m")
} else {
print(c)
}
}
println()
}
}
}
}.toString()
private fun Pair<Int, Int>.directions(pipe: Char, direction: Pair<Int, Int>): Pair<Pair<Int, Int>, Pair<Int, Int>> {
val newDirection = when (direction) {
0 to -1 -> when (pipe) { // left
'-' -> 0 to -1
'L' -> -1 to 0
'F' -> 1 to 0
else -> throw IllegalStateException("Wrong path")
}
0 to 1 -> when (pipe) { // right
'-' -> 0 to 1
'J' -> -1 to 0
'7' -> 1 to 0
else -> throw IllegalStateException("Wrong path")
}
-1 to 0 -> when (pipe) { // up
'|' -> -1 to 0
'7' -> 0 to -1
'F' -> 0 to 1
else -> throw IllegalStateException("Wrong path")
}
1 to 0 -> when (pipe) { // down
'|' -> 1 to 0
'L' -> 0 to 1
'J' -> 0 to -1
else -> throw IllegalStateException("Wrong path")
}
else -> throw IllegalStateException("Wrong path")
}
return (this.first + newDirection.first) to (this.second + newDirection.second) to newDirection
}
private fun Array<CharArray>.findPath(): List<Pair<Pair<Int, Int>, Pair<Int, Int>>> {
val startRow = this.indexOfFirst { 'S' in it }
val startCol = this[startRow].indexOf('S')
val path = mutableListOf(this.findStartPositionAndDirection(startRow to startCol))
while (path.size == 1 || path.last().first != (startRow to startCol)) {
val position = path.last().first
val directions = path.last().second
path.add(position.directions(this[position.first][position.second], directions))
}
return path
}
private fun Array<CharArray>.findStartPositionAndDirection(start: Pair<Int, Int>): Pair<Pair<Int, Int>, Pair<Int, Int>> {
// Search all straight directions from the start
listOf(-1 to 0, 1 to 0, 0 to -1, 0 to 1).forEach { direction ->
val position = (start.first + direction.first).coerceAtLeast(0) to (start.second + direction.second).coerceAtMost(this.size-1)
try {
// If this does not fail, then the path is correct
position.directions(this[position.first][position.second], direction)
// Use the current position, so it's only one step from the start
return position to direction
} catch (_: Throwable) {}
}
throw IllegalStateException("No start position found")
}
private fun List<Int>?.findPathTilesBefore(index: Int) = this?.indexOfLast { it < index }?.plus(1) ?: 0
private fun Int.isOdd() = this % 2 == 1
}
fun main() {
main(Day10)
}
| 0 | Kotlin | 0 | 0 | a95d478aee72034321fdf37930722c23b246dd6b | 5,061 | advent-of-code | Apache License 2.0 |
advent-of-code/src/main/kotlin/com/akikanellis/adventofcode/year2022/Day11.kt | akikanellis | 600,872,090 | false | {"Kotlin": 142932, "Just": 977} | package com.akikanellis.adventofcode.year2022
object Day11 {
fun monkeyBusinessLevel(input: String, rounds: Int, itemDivisor: Int): Long {
val monkeysWithoutHighWorryLevelItemDivisor = input
.split("\n\n")
.map {
Monkey(
monkeyLines = it.lines(),
itemDivisor = itemDivisor.toLong()
)
}
val highWorryLevelItemDivisor = monkeysWithoutHighWorryLevelItemDivisor
.map { it.testDivisor }
.reduce(Long::times)
val monkeys = monkeysWithoutHighWorryLevelItemDivisor
.map { it.copy(highWorryLevelItemDivisor = highWorryLevelItemDivisor) }
.toMutableList()
repeat(rounds) {
for (monkey in monkeys) {
val monkeyAfterInspectingItems = monkey.inspectItems()
val monkeyIdToThrownItems = monkeyAfterInspectingItems.monkeyIdToThrownItems()
val monkeyAfterThrowingAllItems = monkeyAfterInspectingItems.throwAllItems()
monkeys[monkey.id] = monkeyAfterThrowingAllItems
for ((monkeyId, thrownItems) in monkeyIdToThrownItems) {
monkeys[monkeyId] = monkeys[monkeyId].plusItems(thrownItems)
}
}
}
return monkeys
.map { it.numberOfInspections }
.sortedDescending()
.take(2)
.reduce(Long::times)
}
private data class Monkey(
val id: Int,
val items: List<Long>,
val operation: Pair<String, String>,
val testDivisor: Long,
val receiverIdOnTestPass: Int,
val receiverIdOnTestFail: Int,
val itemDivisor: Long,
val highWorryLevelItemDivisor: Long = itemDivisor,
val numberOfInspections: Long = 0
) {
constructor(monkeyLines: List<String>, itemDivisor: Long) : this(
id = monkeyLines[0][7].digitToInt(),
items = monkeyLines[1]
.substringAfter(": ")
.split(", ")
.map { it.toLong() },
operation = monkeyLines[2]
.substringAfter("old ")
.split(" ")
.let { Pair(it[0], it[1]) },
testDivisor = monkeyLines[3]
.substringAfter("by ")
.toLong(),
receiverIdOnTestPass = monkeyLines[4]
.substringAfter("monkey ")
.toInt(),
receiverIdOnTestFail = monkeyLines[5]
.substringAfter("monkey ")
.toInt(),
itemDivisor = itemDivisor
)
fun inspectItems() = copy(
items = items
.map { operate(it) }
.map { manageWorryLevel(it) },
numberOfInspections = numberOfInspections + items.size
)
private fun operate(item: Long): Long {
val other = operation.second.toLongOrNull() ?: item
return when (operation.first) {
"+" -> item + other
"*" -> item * other
else -> error("Unsupported operation: '${operation.first}'")
}
}
private fun manageWorryLevel(item: Long) =
if (lowWorryLevelMode()) item / itemDivisor else item % highWorryLevelItemDivisor
private fun lowWorryLevelMode() = itemDivisor == 3.toLong()
fun monkeyIdToThrownItems() = items
.map { item -> Pair(item % testDivisor == 0.toLong(), item) }
.map { (testPassed, worryLevel) ->
Pair(
if (testPassed) receiverIdOnTestPass else receiverIdOnTestFail,
worryLevel
)
}
.groupBy({ (monkeyId, _) -> monkeyId }) { (_, thrownItem) -> thrownItem }
fun throwAllItems() = copy(items = emptyList())
fun plusItems(newItems: List<Long>) = copy(items = items + newItems)
}
}
| 8 | Kotlin | 0 | 0 | 036cbcb79d4dac96df2e478938de862a20549dce | 3,998 | advent-of-code | MIT License |
src/main/kotlin/Day13.kt | pavittr | 317,532,861 | false | null | import java.io.File
import java.nio.charset.Charset
import kotlin.concurrent.thread
import kotlin.math.absoluteValue
import kotlin.streams.toList
fun main() {
val testDocs = File("test/day13").readLines(Charset.defaultCharset())
val puzzles = File("puzzles/day13").readLines(Charset.defaultCharset())
fun part1(input : List<String>) {
val minTime = input[0].toInt()
val schedules = input[1].split(",").filter { it != "x" }.map{it.toInt()}
println(schedules)
println(schedules.map { Pair(it - (minTime % it), it) }.minByOrNull { it.first }?.let{it.first * it?.second })
}
part1(testDocs)
part1(puzzles)
fun part2(input: List<String>, start: Long) {
val times = input[1].split(",").mapIndexed{index, id -> Pair(index, id) }.filter { it.second != "x" }.map { Pair(it.first.toLong(), it.second.toLong()) }
println(times)
// 7x + 0 = q
// 13y - 1 = q
// 59z - 4 = q
// 31w - 6 = q
// 19v - 7 = q
// The earliest timestamp that matches the list 17,x,13,19 is 3417.
// 67x , 7y - 1, 59z - 2, 61w - 3 = 754018.
// 67x , 7y - 2 59z - 3, 61w - 4 = 779210.
// 67,7,x,59,61 first occurs at timestamp 1261476.
//1789,37,47,1889 first occurs at timestamp 1202161486.
val highest = times.maxByOrNull { it.second } ?: Pair(0L, 0L)
val offsets = times.map{Pair(it.first - highest.first, it.second)}
var captured = 0L
val period = times.map{it.second}.reduce { acc, l -> acc.times(l) }
val increase = 19L.times(521L).times(37L).times(17L)
var i = start.minus(19L)
println("Period is $period, increase is $increase")
// while (i <= period.times(2L)) {
while (i <= period*2L) {
i = i.plus(increase)
//println("Testing $i")
var found = true
for (pair in times) {
if ((i.plus(pair.first).rem(pair.second)) != 0L) {
found = false
break
}
}
if (found) {
captured = i
break
}
}
println(captured)
// 100048220210295
// 1068781 1068782
// 7 13
// 152683 82214
// 1068781 = 7 * 61 * 2503
// 1068782 = 2 * 11 * 13 * 37 * 101
// 1068785 = 5 * 59 * 3623
// 1068787 = 23 * 31 * 1499
// 1068788 = 2 * 2 * 7 * 7 * 7 * 19 * 41
//
// println(times.map{it.first.plus(1L).times(it.second)}.reduce{acc, i -> acc.times(i)}.minus(highest.first))
}
// part2(testDocs, 0L)
// part2( listOf("","67,x,7,59,61"), 0L)
//
part2(puzzles, 0L)
// 1157701781269163
// Lower part2(puzzles, 100000000000000L)
// Upper part2(puzzles, 500000000000000L)
}
| 0 | Kotlin | 0 | 0 | 3d8c83a7fa8f5a8d0f129c20038e80a829ed7d04 | 3,182 | aoc2020 | Apache License 2.0 |
Практика 1/Coding/src/main/kotlin/Main.kt | ArtyomKopan | 691,592,839 | false | {"Kotlin": 5782} | import java.nio.file.Files
import java.nio.file.Path
fun coding(grammar: List<String>): Map<String, Int> {
val codes = mutableMapOf(
":" to 1,
"(" to 2,
")" to 3,
"." to 4,
"*" to 5,
";" to 6,
"," to 7,
"#" to 8,
"[" to 9,
"]" to 10,
"Eofgram" to 1000
)
var terminalNumber = 51
var nonterminalNumber = 11
var semanticNumber = 101
// кодируем нетерминалы
for (command in grammar) {
if (command == "Eofgram")
break
val nonterm = command.split(" : ")[0]
if (nonterminalNumber <= 50)
codes[nonterm] = nonterminalNumber++
else
break
}
// кодируем терминалы и семантики
for (command in grammar) {
if ("Eofgram" in command)
break
// кодируем семантики
val semantics = command
.split(" ")
.filter { it.matches(Regex("\\$[a-z]+[0-9]*")) }
for (semantic in semantics) {
if (semanticNumber >= 1000) {
break
}
if (semantic !in codes.keys) {
codes[semantic] = semanticNumber++
}
}
// кодируем нетерминалы, обозначенные заглавными буквами
val nonterminals = command
.split(" ")
.filter { it.matches(Regex("[A-Z]+")) }
for (nonterminal in nonterminals) {
if (nonterminalNumber > 50) {
break
}
if (nonterminal !in codes.keys) {
codes[nonterminal] = nonterminalNumber++
}
}
// кодируем терминалы
val rightPartCommand = command.split(" : ")[1]
val terminals = rightPartCommand
.split(" ")
.filter {
it.matches(Regex("'.+'")) ||
it.matches(Regex("[a-z]+"))
}
for (terminal in terminals) {
if (terminalNumber > 100) {
break
}
if (terminal !in codes.keys) {
codes[terminal] = terminalNumber++
}
}
}
val trash = mutableListOf<String>()
for (k in codes) {
if ("Eofgram" in k.key && k.value != 1000)
trash.add(k.key)
}
codes.filterKeys { it == "" || " " in it || it in trash }
return codes
}
fun main() {
println("Введите путь к файлу с описанием грамматики: ")
val pathToInputFile = readlnOrNull() ?: "../expression.txt"
val grammarDescription = Files
.readString(Path.of(pathToInputFile))
.split(" .")
.map { it.trim() }
val codes = coding(grammarDescription)
codes.forEach { (t, u) -> println("$t $u") }
for (line in grammarDescription) {
if ("Eofgram" in line) {
println(1000)
break
}
var buffer = ""
val encodedLine = mutableListOf<Int>()
for (ch in line) {
if (buffer in codes.keys) {
encodedLine.add(codes[buffer] ?: -1)
buffer = ""
} else if (ch != ' ' && ch != '\n' && ch != '\t') {
buffer += ch
}
}
if (buffer in codes.keys) {
encodedLine.add(codes[buffer] ?: -1)
}
encodedLine.forEach { print("$it, ") }
println(codes["."])
}
} | 1 | Kotlin | 0 | 0 | 7aa1075078a87b474097872bced3050eb9628deb | 3,575 | Formal_Languages | MIT License |
src/Day04.kt | annagergaly | 572,917,403 | false | {"Kotlin": 6388} | fun main() {
fun part1(input: List<String>): Int {
return input.map {
val n = it.split("[,-]".toRegex()).map { it.toInt() }
(n[0] <= n[2] && n[1] >= n[3]) || (n[2] <= n[0] && n[3] >= n[1])
}.count { it }
}
fun part2(input: List<String>): Int {
return input.map {
val n = it.split("[,-]".toRegex()).map { it.toInt() }
(n[0] in n[2]..n[3]) || (n[1] in n[2]..n[3]) || (n[2] in n[0]..n[1]) || (n[3] in n[0]..n[1])
}.count { it }
}
val input = readInput("Day04")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 89b71c93e341ca29ddac40e83f522e5449865b2d | 613 | advent-of-code22 | Apache License 2.0 |
coins.kt | LaraEstudillo | 753,726,266 | false | {"Kotlin": 1056} | import kotlin.collections.listOf
var amount = 11
var result: ArrayList<CoinsAndQuantity> = ArrayList()
fun main() {
println(minCoins())
}
fun minCoins() {
val coins = listOf(1,2,5).sorted()
val suma = coins.sum();
if(suma == amount) {
println(suma);
return;
}
calculation(coins.size, coins)
println(result)
println(sumItems())
if(sumItems() != amount) println(-1)
else println(result)
}
private fun sumItems(): Int {
var data = 0
result.forEach { item ->
data += item.coin * item.quantity
}
return data
}
private fun calculation(index: Int, coins: List<Int>) {
if(index > 0) {
val divisor = (amount / coins[index-1]).toInt()
val restante = (amount % coins[index-1]).toInt()
amount = restante
divisor.takeIf { it > 0 }?.also {
result.add(CoinsAndQuantity(coins[index-1], divisor))
}
calculation(index - 1, coins)
}
}
data class CoinsAndQuantity (
var coin: Int = 0,
var quantity: Int = 0
)
| 0 | Kotlin | 0 | 0 | b710f683d826f5d1b15702be5e3f0d7c7dc6a2d3 | 1,056 | coins_challenge_1 | Apache License 2.0 |
src/main/kotlin/day11.kt | tianyu | 574,561,581 | false | {"Kotlin": 49942} | import assertk.assertThat
import assertk.assertions.containsExactly
import assertk.assertions.isEmpty
import assertk.assertions.isEqualTo
private fun main() {
tests {
"Parse monkeys" {
val monkey = monkeys("day11-example.txt")[0]
assertThat(monkey.items).containsExactly(79.toWorry(), 98.toWorry())
assertThat(monkey.inspect(10.toWorry())).isEqualTo(190.toWorry())
assertThat(monkey.divisor).isEqualTo(23.toWorry())
assertThat(monkey.ifDivisible).isEqualTo(2)
assertThat(monkey.ifNotDivisible).isEqualTo(3)
}
"One round of monkey business" {
val monkeys = monkeys("day11-example.txt")
monkeys.forEach { monkey -> monkey.inspectItems(monkeys) { it / 3.toWorry() } }
assertThat(monkeys[0].items).containsExactly(20.toWorry(), 23.toWorry(), 27.toWorry(), 26.toWorry())
assertThat(monkeys[1].items).containsExactly(2080.toWorry(), 25.toWorry(), 167.toWorry(), 207.toWorry(), 401.toWorry(), 1046.toWorry())
assertThat(monkeys[2].items).isEmpty()
assertThat(monkeys[3].items).isEmpty()
}
"Part 1 Example" {
assertThat(monkeys("day11-example.txt").monkeyBusiness(20) { it / 3.toWorry() })
.containsExactly(101, 95, 7, 105)
}
"Part 2 Examples" {
assertThat(monkeys("day11-example.txt").monkeyBusiness(1))
.containsExactly(2, 4, 3, 6)
assertThat(monkeys("day11-example.txt").monkeyBusiness(20))
.containsExactly(99, 97, 8, 103)
assertThat(monkeys("day11-example.txt").monkeyBusiness(1000))
.containsExactly(5204, 4792, 199, 5192)
assertThat(monkeys("day11-example.txt").monkeyBusiness(10000))
.containsExactly(52166, 47830, 1938, 52013)
}
}
part1("The level of monkey business after 20 rounds is:") {
val (top1, top2) = monkeys().monkeyBusiness(20) { it / 3.toWorry() }.apply(LongArray::sortDescending)
top1 * top2
}
part2("The level of monkey business after 10000 rounds is:") {
val (top1, top2) = monkeys().monkeyBusiness(10000).apply(LongArray::sortDescending)
top1 * top2
}
}
private fun List<Monkey>.noComfort(): (Worry) -> Worry {
val mod = fold(1.toWorry()) { product, monkey -> product * monkey.divisor }
return { it % mod }
}
private fun List<Monkey>.monkeyBusiness(rounds: Int, comfort: (Worry) -> Worry = noComfort()): LongArray {
val inspections = LongArray(size)
repeat(rounds) {
forEachIndexed { index, monkey ->
inspections[index] += monkey.items.size.toLong()
monkey.inspectItems(this, comfort)
}
}
return inspections
}
private typealias Worry = Long
private fun String.toWorry(): Worry = toLong()
private fun Int.toWorry(): Worry = toLong()
private data class Monkey(
val items: MutableList<Worry>,
val inspect: (Worry) -> Worry,
val divisor: Worry,
val ifDivisible: Int,
val ifNotDivisible: Int,
) {
fun inspectItems(monkeys: List<Monkey>, comfort: (Worry) -> Worry) {
for (item in items) {
val worry = comfort(inspect(item))
val target = if (worry % divisor == 0.toWorry()) ifDivisible else ifNotDivisible
monkeys[target].items += worry
}
items.clear()
}
}
private fun monkeys(resource: String = "day11.txt") = withInputLines(resource) {
chunked(7) { (_, startingItems, operation, test, ifTrue, ifFalse) ->
Monkey(
startingItems.removePrefix(" Starting items: ").asItems(),
operation.removePrefix(" Operation: new = ").asOperation(),
test.removePrefix(" Test: divisible by ").toWorry(),
ifTrue.removePrefix(" If true: throw to monkey ").toInt(),
ifFalse.removePrefix(" If false: throw to monkey ").toInt(),
)
}.toList()
}
private fun String.asItems(): MutableList<Worry> =
splitToSequence(", ").mapTo(mutableListOf(), String::toWorry)
private fun String.asOperation(): (Worry) -> Worry {
if (this == "old") return { it }
if (all(Char::isDigit)) {
val const = toWorry()
return { const }
}
val (left, operator, right) = split(' ')
val leftOperation = left.asOperation()
val rightOperation = right.asOperation()
return when (operator) {
"+" -> {{ leftOperation(it) + rightOperation(it) }}
"*" -> {{ leftOperation(it) * rightOperation(it) }}
else -> throw AssertionError("Unknown operator: $operator")
}
} | 0 | Kotlin | 0 | 0 | 6144cc0ccf1a51ba2e28c9f38ae4e6dd4c0dc1ea | 4,291 | AdventOfCode2022 | MIT License |
src/main/java/challenges/cracking_coding_interview/sorting_and_searching/introduction/BinarySearch.kt | ShabanKamell | 342,007,920 | false | null | package challenges.cracking_coding_interview.sorting_and_searching.introduction
object BinarySearch {
private fun binarySearch(a: IntArray, x: Int): Int {
var low = 0
var high = a.size - 1
var mid: Int
while (low <= high) {
mid = low + (high - low) / 2
if (a[mid] < x) {
low = mid + 1
} else if (a[mid] > x) {
high = mid - 1
} else {
return mid
}
}
return -1
}
private fun binarySearchRecursive(a: IntArray, x: Int, low: Int, high: Int): Int {
if (low > high) return -1 // Error
val mid = (low + high) / 2
return if (a[mid] < x) {
binarySearchRecursive(a, x, mid + 1, high)
} else if (a[mid] > x) {
binarySearchRecursive(a, x, low, mid - 1)
} else {
mid
}
}
// Recursive algorithm to return the closest element
private fun binarySearchRecursiveClosest(
a: IntArray,
x: Int,
low: Int,
high: Int
): Int {
if (low > high) { // high is on the left side now
if (high < 0) return low
if (low >= a.size) return high
return if (x - a[high] < a[low] - x) high else low
}
val mid = (low + high) / 2
return if (a[mid] < x) {
binarySearchRecursiveClosest(a, x, mid + 1, high)
} else if (a[mid] > x) {
binarySearchRecursiveClosest(a, x, low, mid - 1)
} else {
mid
}
}
@JvmStatic
fun main(args: Array<String>) {
val array = intArrayOf(3, 6, 9, 12, 15, 18)
for (i in 0..19) {
val loc = binarySearch(array, i)
val loc2 = binarySearchRecursive(array, i, 0, array.size - 1)
val loc3 = binarySearchRecursiveClosest(array, i, 0, array.size - 1)
println("$i: $loc $loc2 $loc3")
}
}
} | 0 | Kotlin | 0 | 0 | ee06bebe0d3a7cd411d9ec7b7e317b48fe8c6d70 | 1,983 | CodingChallenges | Apache License 2.0 |
src/Day06.kt | benwicks | 572,726,620 | false | {"Kotlin": 29712} | const val numUniqueCharsInStartOfPacketMarker = 4
const val numUniqueCharsInStartOfMessageMarker = 14
fun main() {
fun findEndPositionOfMarker(input: String, numUniqueCharsInStartMarker: Int): Int {
var mostRecentUniqueChars = mutableListOf<Char>()
input.forEachIndexed { index, c ->
val indexOfChar = mostRecentUniqueChars.indexOf(c)
if (indexOfChar >= 0) {
// remove up to the first occurrence of it
mostRecentUniqueChars = mostRecentUniqueChars.subList(indexOfChar + 1, mostRecentUniqueChars.size)
}
mostRecentUniqueChars += c
if (mostRecentUniqueChars.size == numUniqueCharsInStartMarker) {
return index + 1
}
}
return -1
}
fun part1(input: String): Int {
return findEndPositionOfMarker(input, numUniqueCharsInStartOfPacketMarker)
}
fun part2(input: String): Int {
return findEndPositionOfMarker(input, numUniqueCharsInStartOfMessageMarker)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day06_test")
check(part1(testInput.first()) == 7)
check(part2(testInput.first()) == 19)
val input = readInput("Day06")
println(part1(input.first()))
println(part2(input.first()))
}
| 0 | Kotlin | 0 | 0 | fbec04e056bc0933a906fd1383c191051a17c17b | 1,351 | aoc-2022-kotlin | Apache License 2.0 |
src/chapter2/section3/QuickSort.kt | w1374720640 | 265,536,015 | false | {"Kotlin": 1373556} | package chapter2.section3
import chapter2.compare
import chapter2.section1.displaySortingProcessTemplate
import chapter2.swap
import edu.princeton.cs.algs4.StdRandom
/**
* 快速排序基础实现
*
* 具体实现为:从第二个值开始向右循环,找到一个大于第一个值的位置
* 从末尾向左循环,找到一个小于第一个值的位置,交换两个位置上的值
* 继续循环,直到左右两侧相遇,数组遍历完成
* 交换左侧的第一位和最后一位,以左侧最后一位为分界线,左边都小于等于它,右边都大于等于它
* 递归排序左右两侧
*/
fun <T : Comparable<T>> quickSort(array: Array<T>) {
//消除对输入的依赖
StdRandom.shuffle(array)
quickSort(array, 0, array.size - 1)
}
/**
* 用原始数组排序,不打乱
*/
fun <T : Comparable<T>> quickSortNotShuffle(array: Array<T>) {
quickSort(array, 0, array.size - 1)
}
fun <T : Comparable<T>> quickSort(array: Array<T>, start: Int, end: Int) {
if (start >= end) return
val mid = partition(array, start, end)
quickSort(array, start, mid - 1)
quickSort(array, mid + 1, end)
}
fun <T : Comparable<T>> partition(array: Array<T>, start: Int, end: Int): Int {
var i = start
var j = end + 1
while (true) {
while (array.compare(++i, start) < 0) {
if (i == end) break
}
while (array.compare(--j, start) > 0) {
if (j == start) break
}
if (i >= j) break
array.swap(i, j)
}
if (j != start) array.swap(start, j)
return j
}
fun main() {
//显示排序过程时,要用不预先打乱数组的版本,否则会显示异常
displaySortingProcessTemplate("Quick Sort", ::quickSortNotShuffle)
// performanceTesting("Quick Sort", ::quickSortWithOriginalArray)
} | 0 | Kotlin | 1 | 6 | 879885b82ef51d58efe578c9391f04bc54c2531d | 1,833 | Algorithms-4th-Edition-in-Kotlin | MIT License |
Coding Challenges/Advent of Code/2021/Day 3/part2.kt | Alphabeater | 435,048,407 | false | {"Kotlin": 69566, "Python": 5974} | import java.io.File
import kotlin.math.pow
fun getNewList(list: List<String>, position: Int, criteria: Char, length: Int): List<String> {
if (list.size == 1) return list
val criteriaBit = getBit(list, position, criteria) //get the new criteria bit which will determine the new list for the next step of the recursion.
val shorterList = mutableListOf<String>()
list.forEach { //if the position in each number matches the criteria bit, append the number to the new list.
if (it[position] == criteriaBit) shorterList += it
}
return getNewList(shorterList, position + 1, criteria, length) //next step of the recursion with the new list and the next position.
}
fun getBit(list: List<String>, position: Int, criteria: Char): Char {
var count = 0
list.forEach { //counts how many 1's in the number.
if (it[position] == '1') {
count++
}
}
val other = list.size - count //a variable that determines the remaining values (0's).
return if (criteria == '1') { //most
if (count >= other) '1'
else '0'
} else { //least
if (count < other) '1'
else '0'
}
}
fun convertToDecimal(exp: Int): Int {
return 2.0.pow(exp).toInt()
}
fun main() {
val file = File("src/input.txt")
val list = file.readLines().toList()
val length = list[0].length
val oxygenGeneratorRatingSequence = getNewList(list, 0, '1', length)
val CO2ScrubberRatingSequence = getNewList(list, 0, '0', length)
var oxygenGeneratorRating = 0
var CO2ScrubberRating = 0
for (i in 0 until length) { //converts each rating to their corresponding decimal value.
if (oxygenGeneratorRatingSequence.first()[i] == '1') {
oxygenGeneratorRating += convertToDecimal(length - i - 1)
}
if (CO2ScrubberRatingSequence.first()[i] == '1') {
CO2ScrubberRating += convertToDecimal(length - i - 1)
}
}
print(oxygenGeneratorRating * CO2ScrubberRating)
} | 0 | Kotlin | 0 | 0 | 05c8d4614e025ed2f26fef2e5b1581630201adf0 | 1,999 | Archive | MIT License |
src/main/kotlin/days/Day4.kt | sicruse | 315,469,617 | false | null | package days
class Day4 : Day(4) {
private val passports: List<Map<String, String>> by lazy {
inputString
// split the input at blank lines to form record text blocks
.split("\\n\\n".toRegex())
.map { record ->
// for every record text block gather the field text by splitting at whitespace
record.split("\\s".toRegex())
.map { field ->
// for every field text entry extract the key / value pairs
field.split(':').let { kv ->
Pair(kv[0], kv[1])
}
}
// convert the KV pairs into a map for ease of reference
.toMap()
}
}
class ValidationRule(val required: Boolean, pattern: String) {
val regex = pattern.toRegex()
}
private val rules = mapOf (
Pair("byr", ValidationRule(true, "(19[2-9]\\d|200[0-2])")), // byr (Birth Year) - four digits; at least 1920 and at most 2002.
Pair("iyr", ValidationRule(true,"(201\\d|2020)")), // iyr (Issue Year) - four digits; at least 2010 and at most 2020.
Pair("eyr", ValidationRule(true,"(202\\d|2030)")), // eyr (Expiration Year) - four digits; at least 2020 and at most 2030.
Pair("hgt", ValidationRule(true,"(1[5-8]\\dcm|19[0-3]cm|59in|6[0-9]in|7[0-6]in)")), // hgt (Height) - a number followed by either cm or in:
// If cm, the number must be at least 150 and at most 193.
// If in, the number must be at least 59 and at most 76.
Pair("hcl", ValidationRule(true, "(#[0-9a-f]{6})")), // hcl (Hair Color) - a # followed by exactly six characters 0-9 or a-f.
Pair("ecl", ValidationRule(true, "(amb|blu|brn|gry|grn|hzl|oth)")), // ecl (Eye Color) - exactly one of: amb blu brn gry grn hzl oth.
Pair("pid", ValidationRule(true, "([0-9]{9})")), // pid (Passport ID) - a nine-digit number, including leading zeroes.
Pair("cid", ValidationRule(false,"")), // cid (Country ID) - ignored, missing or not.
)
private val requiredRules = rules.filter{ it.value.required }
private val requiredFields = requiredRules.keys
private val requiredFieldRules = requiredRules.entries.associate { it.key to it.value.regex }
private val validPassports by lazy {
passports.count { fields -> fields.keys.containsAll(requiredFields) }
}
private val validPassportsWithValidData by lazy {
passports.count { fields ->
fields.filter {
field -> requiredFields.contains(field.key)
}.count {
field -> field.value.matches( requiredFieldRules[field.key]!! )
} == requiredFields.size
}
}
override fun partOne(): Any {
return validPassports
}
override fun partTwo(): Any {
return validPassportsWithValidData
}
}
| 0 | Kotlin | 0 | 0 | 9a07af4879a6eca534c5dd7eb9fc60b71bfa2f0f | 3,398 | aoc-kotlin-2020 | Creative Commons Zero v1.0 Universal |
app/src/main/kotlin/com/resurtm/aoc2023/day18/Part2Good.kt | resurtm | 726,078,755 | false | {"Kotlin": 119665} | package com.resurtm.aoc2023.day18
import kotlin.math.abs
/**
* https://en.wikipedia.org/wiki/Shoelace_formula
* https://artofproblemsolving.com/wiki/index.php/Shoelace_Theorem
*/
fun solvePart2Good(moves: List<Move>): Long {
val lines = mutableListOf<Line>()
val vertices = mutableListOf<Pos>()
var borderArea = 0L
var currPos = Pos()
for (move in moves) {
vertices.add(currPos)
val nextPos = getNextPosV2(currPos, move)
val newLine = Line(currPos, nextPos)
var addArea = newLine.length
lines.forEach {
if (newLine.intersects(it)) addArea--
}
borderArea += addArea
currPos = nextPos
lines.add(newLine)
}
vertices.add(vertices.first())
return calcShoelace(vertices) + borderArea / 2 + 1
}
/**
* https://en.wikipedia.org/wiki/Shoelace_formula
* https://artofproblemsolving.com/wiki/index.php/Shoelace_Theorem
*/
private fun calcShoelace(vertices: List<Pos>): Long {
var res = 0L
for (idx in 0..vertices.size - 2) {
val v0 = vertices[idx]
val v1 = vertices[idx + 1]
res += (v1.row + v0.row) * (v1.col - v0.col)
}
return abs(res / 2)
}
| 0 | Kotlin | 0 | 0 | fb8da6c246b0e2ffadb046401502f945a82cfed9 | 1,203 | advent-of-code-2023 | MIT License |
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[86]分隔链表.kt | maoqitian | 175,940,000 | false | {"Kotlin": 354268, "Java": 297740, "C++": 634} | //给你一个链表和一个特定值 x ,请你对链表进行分隔,使得所有小于 x 的节点都出现在大于或等于 x 的节点之前。
//
// 你应当保留两个分区中每个节点的初始相对位置。
//
//
//
// 示例:
//
//
//输入:head = 1->4->3->2->5->2, x = 3
//输出:1->2->2->4->3->5
//
// Related Topics 链表 双指针
// 👍 334 👎 0
//leetcode submit region begin(Prohibit modification and deletion)
/**
* Example:
* var li = ListNode(5)
* var v = li.`val`
* Definition for singly-linked list.
* class ListNode(var `val`: Int) {
* var next: ListNode? = null
* }
*/
class Solution {
fun partition(head: ListNode?, x: Int): ListNode? {
//两个链表分别记录小于 X 和大于 X 的节点随后拼接 时间复杂度 O(n)
var dyNode1 = ListNode(0)
var dyNode2 = ListNode(0)
var head1: ListNode? = head
var node1: ListNode = dyNode1
var node2: ListNode = dyNode2
while(head1 != null){
if(head1.`val` < x){
dyNode1.next = head1
dyNode1 = dyNode1.next
}else{
dyNode2.next = head1
dyNode2 = dyNode2.next
}
head1 = head1.next
}
dyNode2.next = null
dyNode1.next = node2.next
return node1.next
}
}
//leetcode submit region end(Prohibit modification and deletion)
| 0 | Kotlin | 0 | 1 | 8a85996352a88bb9a8a6a2712dce3eac2e1c3463 | 1,441 | MyLeetCode | Apache License 2.0 |
src/main/kotlin/g0401_0500/s0436_find_right_interval/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g0401_0500.s0436_find_right_interval
// #Medium #Array #Sorting #Binary_Search #Binary_Search_II_Day_11
// #2022_12_22_Time_333_ms_(100.00%)_Space_49.7_MB_(90.00%)
import java.util.function.Function
class Solution {
private fun findminmax(num: Array<IntArray>): IntArray {
var min = num[0][0]
var max = num[0][0]
for (i in 1 until num.size) {
min = Math.min(min, num[i][0])
max = Math.max(max, num[i][0])
}
return intArrayOf(min, max)
}
fun findRightInterval(intervals: Array<IntArray>): IntArray {
if (intervals.size <= 1) {
return intArrayOf(-1)
}
val n = intervals.size
val result = IntArray(n)
val map: MutableMap<Int, Int?> = HashMap()
for (i in 0 until n) {
map[intervals[i][0]] = i
}
val minmax = findminmax(intervals)
for (i in minmax[1] - 1 downTo minmax[0] + 1) {
map.computeIfAbsent(i, Function { k: Int -> map[k + 1] })
}
for (i in 0 until n) {
result[i] = map.getOrDefault(intervals[i][1], -1)!!
}
return result
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,173 | LeetCode-in-Kotlin | MIT License |
src/year2022/Day09.kt | Maetthu24 | 572,844,320 | false | {"Kotlin": 41016} | package year2022
import kotlin.math.abs
fun main() {
fun part1(input: List<String>): Int {
return buildSet {
var tailX = 0
var tailY = 0
var headX = 0
var headY = 0
add(Pair(tailX, tailY))
for ((dir, n) in input.map { Pair(it.split(" ")[0], it.split(" ")[1].toInt()) }) {
for (i in 1 .. n) {
headY = when (dir) {
"U" -> headY + 1
"D" -> headY - 1
else -> headY
}
headX = when (dir) {
"R" -> headX + 1
"L" -> headX - 1
else -> headX
}
if (abs(headX - tailX) <= 1 && abs(headY - tailY) <= 1)
continue
if (abs(headX - tailX) == 2) {
tailX = if (headX > tailX) tailX + 1 else tailX - 1
when (abs(tailY - headY)) {
1 -> tailY = if (headY > tailY) tailY + 1 else tailY - 1
2 -> error("Should not happen...")
}
}
if (abs(headY - tailY) == 2) {
tailY = if (headY > tailY) tailY + 1 else tailY - 1
when (abs(tailX - headX)) {
1 -> tailX = if (headX > tailX) tailX + 1 else tailX - 1
2 -> error("Should not happen...")
}
}
add(Pair(tailX, tailY))
}
}
}.size
}
fun part2(input: List<String>): Int {
return buildSet {
val positions = (0..9).map { Pair(0, 0) }.toMutableList()
add(positions.last())
for ((dir, n) in input.map { Pair(it.split(" ")[0], it.split(" ")[1].toInt()) }) {
for (i in 1 .. n) {
loop@ for (p in 0..8) {
var (headX, headY) = positions[p]
var (tailX, tailY) = positions[p+1]
if (p == 0) {
headY = when (dir) {
"U" -> headY + 1
"D" -> headY - 1
else -> headY
}
headX = when (dir) {
"R" -> headX + 1
"L" -> headX - 1
else -> headX
}
}
if (abs(headX - tailX) <= 1 && abs(headY - tailY) <= 1) {
positions[p] = Pair(headX, headY)
positions[p+1] = Pair(tailX, tailY)
if (p == 8) {
add(Pair(tailX, tailY))
}
continue@loop
}
if (abs(headX - tailX) == 2) {
tailX = if (headX > tailX) tailX + 1 else tailX - 1
when (abs(tailY - headY)) {
1 -> tailY = if (headY > tailY) tailY + 1 else tailY - 1
2 -> tailY = if (headY > tailY) tailY + 1 else tailY - 1
3 -> error("Should not happen...")
}
}
if (abs(headY - tailY) == 2) {
tailY = if (headY > tailY) tailY + 1 else tailY - 1
when (abs(tailX - headX)) {
1 -> tailX = if (headX > tailX) tailX + 1 else tailX - 1
2 -> tailX = if (headX > tailX) tailX + 1 else tailX - 1
3 -> error("Should not happen...")
}
}
if (p == 8) {
add(Pair(tailX, tailY))
}
positions[p] = Pair(headX, headY)
positions[p+1] = Pair(tailX, tailY)
}
}
}
}.size
}
val day = "09"
// Read inputs
val testInput = readInput("Day${day}_test")
val testInput2 = readInput("Day${day}_test2")
val input = readInput("Day${day}")
// Test & run part 1
val testResult = part1(testInput)
val testExpected = 13
check(testResult == testExpected) { "testResult should be $testExpected, but is $testResult" }
println(part1(input))
// Test & run part 2
val testResult2 = part2(testInput)
val testExpected2 = 1
check(testResult2 == testExpected2) { "testResult2 should be $testExpected2, but is $testResult2" }
val testResult3 = part2(testInput2)
val testExpected3 = 36
check(testResult3 == testExpected3) { "testResult2 should be $testExpected3, but is $testResult3" }
println(part2(input))
} | 0 | Kotlin | 0 | 1 | 3b3b2984ab718899fbba591c14c991d76c34f28c | 5,174 | adventofcode-kotlin | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/exercises/SumsToTarget.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.exercises
fun interface SumsToTarget {
fun perform(arr: IntArray, k: Int): Boolean
}
class SumsToTargetBF : SumsToTarget {
override fun perform(arr: IntArray, k: Int): Boolean {
for (i in arr.indices) {
for (j in i + 1 until arr.size) {
if (arr[i] + arr[j] == k) {
return true
}
}
}
return false
}
}
class SumsToTargetHashSet : SumsToTarget {
override fun perform(arr: IntArray, k: Int): Boolean {
val values: MutableSet<Int> = HashSet()
for (i in arr.indices) {
if (values.contains(k - arr[i])) {
return true
}
values.add(arr[i])
}
return false
}
}
class SumsToTargetSort : SumsToTarget {
override fun perform(arr: IntArray, k: Int): Boolean {
arr.sort()
for (i in arr.indices) {
val siblingIndex = arr.binarySearch(k - arr[i])
if (siblingIndex >= 0) {
val left = siblingIndex != i || i > 0 && i - 1 == arr[i]
val right = i < arr.size - 1 && arr[i + 1] == arr[i]
if (left || right) {
return true
}
}
}
return false
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,920 | kotlab | Apache License 2.0 |
src/main/kotlin/twentytwentytwo/Day10.kt | JanGroot | 317,476,637 | false | {"Kotlin": 80906} | package twentytwentytwo
fun main() {
val input = {}.javaClass.getResource("input-10.txt")!!.readText().linesFiltered { it.isNotEmpty() };
val day = Day10(input)
println(day.part1())
println(day.part2())
}
class Day10(private val input: List<String>) {
fun part1(): Int {
var cycle = 0
var value = 1
var result = mutableListOf<Int>()
input.forEach {
when (it) {
"noop" -> {
if (++cycle in intArrayOf(20, 60, 100, 140, 180, 220)) {
result.add(value * cycle)
}
}
else -> {
if (++cycle in intArrayOf(20, 60, 100, 140, 180, 220)) {
result.add(value * cycle)
}
if (++cycle in intArrayOf(20, 60, 100, 140, 180, 220)) {
result.add(value * cycle)
}
value += it.split(" ")[1].toInt()
}
}
}
return result.sum()
}
fun part2(): Int {
var cycle = 0
var value = 1
var row = ""
input.forEach {
when (it) {
"noop" -> {
row += if (cycle % 40 in value-1 ..value + 1 ) "#" else "."
cycle++
}
else -> {
row += if (cycle % 40 in value-1..value + 1) "#" else "."
cycle++
row += if (cycle % 40 in value-1..value + 1) "#" else "."
cycle++
value += it.split(" ")[1].toInt()
}
}
}
row.chunked(40).forEach { println(it) }
return 0
}
}
| 0 | Kotlin | 0 | 0 | 04a9531285e22cc81e6478dc89708bcf6407910b | 1,778 | aoc202xkotlin | The Unlicense |
aoc-2022/src/main/kotlin/nerok/aoc/aoc2022/day01/Day01.kt | nerok | 572,862,875 | false | {"Kotlin": 113337} | package nerok.aoc.aoc2022.day01
import nerok.aoc.utils.Input
import kotlin.time.DurationUnit
import kotlin.time.measureTime
fun main() {
fun part1(input: List<String>): Long {
var max = 0L
var current = 0L
for (item in input) {
current = (
item.toLongOrNull()?.plus(current) ?: if (current > max) {
max = current
0L
} else 0L
)
}
return max
}
fun part2(input: List<String>): Long {
val loads = mutableListOf<Long>()
var current = 0L
for (item in input) {
val readItem = item.toLongOrNull()
if (readItem == null) {
loads.add(current)
current = 0L
} else {
current += readItem
}
}
if (current != 0L) {
loads.add(current)
}
return loads.sorted().takeLast(3).sum()
}
// test if implementation meets criteria from the description, like:
val testInput = Input.readInput("Day01_test")
check(part1(testInput) == 24000L)
check(part2(testInput) == 45000L)
val input = Input.readInput("Day01")
println(measureTime { println(part1(input)) }.toString(DurationUnit.SECONDS, 3))
println(measureTime { println(part2(input)) }.toString(DurationUnit.SECONDS, 3))
}
| 0 | Kotlin | 0 | 0 | 7553c28ac9053a70706c6af98b954fbdda6fb5d2 | 1,400 | AOC | Apache License 2.0 |
LeetCode/0088. Merge Sorted Array/Solution.kt | InnoFang | 86,413,001 | false | {"C++": 501928, "Kotlin": 291271, "Python": 280936, "Java": 78746, "Go": 43858, "JavaScript": 27490, "Rust": 6410} | /**
* 59 / 59 test cases passed.
* Status: Accepted
* Runtime: 557 ms
*/
class Solution {
fun merge(nums1: IntArray, m: Int, nums2: IntArray, n: Int): Unit {
val nums3 = IntArray(m + n)
var i = 0
var j = 0
var k = 0
while (i < m + n) {
if (j < m && k < n && nums1[j] <= nums2[k]) nums3[i++] = nums1[j++]
else if (j < m && k < n && nums1[j] >= nums2[k]) nums3[i++] = nums2[k++]
else if (j == m) nums3[i++] = nums2[k++]
else if (k == n) nums3[i++] = nums1[j++]
}
nums3.indices.forEach{ nums1[it] = nums3[it] }
}
}
/**
* 59 / 59 test cases passed.
* Status: Accepted
* Runtime: 336 ms
*/
class Solution2 {
fun merge(nums1: IntArray, m: Int, nums2: IntArray, n: Int) {
var i = m - 1
var j = n - 1
var k = m + n - 1
while (j >= 0)
nums1[k--] = if (i >= 0 && nums1[i] > nums2[j]) nums1[i--] else nums2[j--]
nums1.forEach { print("$it ") }; println()
}
}
fun main(args: Array<String>) {
val a = IntArray(8)
a[0] = 1; a[1] = 2; a[2] = 2; a[3] = 4
Solution2().merge(a, 4, intArrayOf(5,6,7,8), 4)
} | 0 | C++ | 8 | 20 | 2419a7d720bea1fd6ff3b75c38342a0ace18b205 | 1,183 | algo-set | Apache License 2.0 |
day22/src/main/kotlin/de/havox_design/aoc2023/day22/Brick.kt | Gentleman1983 | 715,778,541 | false | {"Kotlin": 163912, "Python": 1048} | package de.havox_design.aoc2023.day22
data class Brick(val startPosition: Triple<Int, Int, Int>, val endPosition: Triple<Int, Int, Int>) {
val fallen: Brick
get() =
Brick(
Triple(startPosition.x(), startPosition.y(), startPosition.z() - 1),
Triple(endPosition.x(), endPosition.y(), endPosition.z() - 1)
)
val canFall: Boolean
get() =
canFall(Day22.getBricks())
fun contains(position: Triple<Int, Int, Int>): Boolean =
position.x() >= startPosition.x() && position.x() <= endPosition.x() &&
position.y() >= startPosition.y() && position.y() <= endPosition.y() &&
position.z() >= startPosition.z() && position.z() <= endPosition.z()
@SuppressWarnings("kotlin:S3776")
fun intersect(other: Brick): Boolean {
return when {
other.startPosition.z() > endPosition.z() || other.endPosition.z() < startPosition.z() -> false
else -> {
for (x in other.startPosition.x()..other.endPosition.x()) {
for (y in other.startPosition.y()..other.endPosition.y()) {
for (z in other.startPosition.z()..other.endPosition.z()) {
when {
contains(Triple(x, y, z)) -> return true
}
}
}
}
false
}
}
}
fun canFall(bricks: ArrayList<Brick>): Boolean {
val f = fallen
for (brick in bricks) {
when {
brick != this && brick.intersect(f) -> return false
}
}
return startPosition.third > 1
}
}
private fun Triple<Int, Any, Any>.x(): Int =
this.first
private fun Triple<Any, Int, Any>.y(): Int =
this.second
private fun Triple<Any, Any, Int>.z(): Int =
this.third
| 1 | Kotlin | 0 | 0 | eac8ff77420f061f5cef0fd4b8d05e7805c4cc5a | 1,953 | aoc2023 | Apache License 2.0 |
core-kotlin-modules/core-kotlin-collections-map/src/test/kotlin/com/baeldung/map/theMaxEntry/FindMaxEntryInMapUnitTest.kt | Baeldung | 260,481,121 | false | {"Kotlin": 1476024, "Java": 43013, "HTML": 4883} | package com.baeldung.map.theMaxEntry
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals
class FindMaxEntryInMapUnitTest {
val skillMap = mapOf(
"Kai" to "Kotlin, typescript, Javascript, C, C++",
"Saajan" to "Java, C, Python, Ruby, Shell, Go",
"Eric" to "Kotlin, Java, C, Python, Ruby, Php, Shell, Rust",
"Kevin" to "Java, Scala, Go, Ruby",
"Venus" to "Beauty!"
)
@Test
fun `when using maxBy then find the entry with most skills`() {
val result = skillMap.maxBy { (_, skills) -> skills.split(", ").size }
assertEquals("Eric" to "Kotlin, Java, C, Python, Ruby, Php, Shell, Rust", result.toPair())
}
@Test
fun `when using maxWith then find the entry with most skills`() {
val result = skillMap.maxWith { e1, e2 ->
e1.value.split(", ").size.compareTo(e2.value.split(", ").size)
}
assertEquals("Eric" to "Kotlin, Java, C, Python, Ruby, Php, Shell, Rust", result.toPair())
}
@Test
fun `when using maxBy and maxWith then find the entry with longest name`() {
val result1 = skillMap.maxBy { (name, _) -> name.length }
assertEquals("Saajan" to "Java, C, Python, Ruby, Shell, Go", result1.toPair())
val result2 = skillMap.maxWith { e1, e2 -> e1.key.length.compareTo(e2.key.length) }
assertEquals("Saajan" to "Java, C, Python, Ruby, Shell, Go", result2.toPair())
}
@Test
fun `when using maxOf then find the entry with largest (Lexicographic order) name`() {
val result = skillMap.maxOf { (name, _) -> name }
assertEquals("Venus", result)
}
@Test
fun `when using maxOf then find the entry with largest 2nd char in a name (Lexicographic order)`() {
val result = skillMap.maxOf { (name, _) -> name[1] }
assertEquals('r', result)
}
@Test
fun `when using maxOf then find the entry with largest skill count`() {
val result = skillMap.maxOf { it.value.split(", ").size }
assertEquals(8, result)
}
} | 10 | Kotlin | 273 | 410 | 2b718f002ce5ea1cb09217937dc630ff31757693 | 2,047 | kotlin-tutorials | MIT License |
src/2023/Day06.kt | nagyjani | 572,361,168 | false | {"Kotlin": 369497} | package `2023`
import java.io.File
import java.util.*
import kotlin.math.sqrt
fun main() {
Day06().solve()
}
class Day06 {
val input1 = """
Time: 7 15 30
Distance: 9 40 200
""".trimIndent()
val input2 = """
""".trimIndent()
fun solve() {
val f = File("src/2023/inputs/day06.in")
val s = Scanner(f)
// val s = Scanner(input1)
// val s = Scanner(input2)
var sum = 0
var sum1 = 0
var lineix = 0
var times = listOf<Int>()
var distances = listOf<Int>()
while (s.hasNextLine()) {
lineix++
val line = s.nextLine().trim()
if (line.isEmpty()) {
continue
}
if (line.startsWith("Time")) {
times = line.split(Regex("[ :]+")).filter { it.all { it1 -> it1.isDigit() } }.map { it.toInt() }
}
if (line.startsWith("Dist")) {
distances = line.split(Regex("[ :]+")).filter { it.all { it1 -> it1.isDigit() } }.map { it.toInt() }
}
}
val t1 = times.map { it.toString() }.joinToString("").toLong()
val d1 = distances.map { it.toString() }.joinToString("").toLong()
val r = mutableListOf<Int>()
for (i in times.indices) {
val t = times[i]
val d = distances[i]
var n = 0
for (j in 1..t) {
if ((t-j) * j > d) {
n ++
}
}
r.add(n)
}
val tf = t1.toDouble()
val df = d1.toDouble()
val a1 = (tf - sqrt(tf * tf - 4*df))/2
val a2 = (tf +sqrt(tf * tf - 4*df))/2
val a11 = a1.toInt() + 1
val a22 = a2.toInt()
print("$sum $sum1 ${r.fold(1){ a, it-> a * it}} ${a22-a11+1}\n")
}
} | 0 | Kotlin | 0 | 0 | f0c61c787e4f0b83b69ed0cde3117aed3ae918a5 | 1,872 | advent-of-code | Apache License 2.0 |
src/main/kotlin/io/korti/adventofcode/day/DayThree.kt | korti11 | 225,589,330 | false | null | package io.korti.adventofcode.day
import java.lang.Integer.sum
import kotlin.math.abs
class DayThree : AbstractDay() {
override fun getDay(): Int {
return 3
}
override fun getSubLevels(): Int {
return 1
}
override fun run(input: List<String>): String {
val wireOne = mutableListOf<Pos>()
val wireCrossings = sortedSetOf<Pair<Pos, Pos>>(
Comparator { o1, o2 ->
sum(o1.first.length, o1.second.length).compareTo(sum(o2.first.length, o2.second.length))
}
)
val pathOne = input[0].split(",")
val pathTwo = input[1].split(",")
val startPos = Pos(0, 0)
wireOne.add(startPos)
var currentPos = startPos
for (move in pathOne) {
val direction = move[0]
val moves = move.substring(1).toInt()
for(i in 1..moves) {
currentPos = currentPos.moveInDirection(direction)
wireOne.add(currentPos)
}
}
currentPos = startPos
for (move in pathTwo) {
val direction = move[0]
val moves = move.substring(1).toInt()
for(i in 1..moves) {
currentPos = currentPos.moveInDirection(direction)
val index = wireOne.indexOf(currentPos)
if (index != -1) {
wireCrossings.add(Pair(wireOne[index], currentPos))
}
}
}
return wireCrossings.first().let { it.first.length + it.second.length }.toString()
}
}
private data class Pos(val x: Int, val y: Int, val length: Int = 0) : Comparable<Pos> {
fun moveInDirection(direction: Char): Pos {
return when (direction) {
'U' -> Pos(x, y + 1, length + 1)
'R' -> Pos(x + 1, y, length + 1)
'D' -> Pos(x, y - 1, length + 1)
'L' -> Pos(x - 1, y, length + 1)
else -> throw RuntimeException("Direction $direction not supported.")
}
}
override fun equals(other: Any?): Boolean {
if((other is Pos).not()) {
return false
}
val otherPos = other as Pos
return x == otherPos.x && y == other.y
}
fun getDistanceFromCenter(): Int {
return abs(x) + abs(y)
}
override fun compareTo(other: Pos): Int {
return getDistanceFromCenter().compareTo(other.getDistanceFromCenter())
}
} | 0 | Kotlin | 0 | 0 | 410c82ef8782f874c2d8a6c687688716effc7edd | 2,448 | advent-of-code-2019 | MIT License |
src/Day14.kt | abeltay | 572,984,420 | false | {"Kotlin": 91982, "Shell": 191} | fun main() {
fun addVerticalLine(lines: HashMap<Int, MutableList<Pair<Int, Int>>>, column: Int, from: Int, to: Int) {
if (from > to) {
addVerticalLine(lines, column, to, from)
return
}
val existing = lines[column] ?: mutableListOf()
existing.add(Pair(from, to))
existing.sortBy { it.first }
lines[column] = existing
}
fun addHorizontalLine(lines: HashMap<Int, MutableList<Pair<Int, Int>>>, row: Int, from: Int, to: Int) {
if (from > to) {
addHorizontalLine(lines, row, to, from)
return
}
for (i in from..to) {
addVerticalLine(lines, i, row, row)
}
}
fun addLines(input: String, lines: HashMap<Int, MutableList<Pair<Int, Int>>>) {
val coordinates = input.split(" -> ")
var last: Pair<Int, Int>? = null
for (it in coordinates) {
val coordinate = it.split(",")
val location = Pair(coordinate[0].toInt(), coordinate[1].toInt())
if (last != null) {
if (location.first == last.first) {
addVerticalLine(lines, location.first, last.second, location.second)
} else {
addHorizontalLine(lines, location.second, last.first, location.first)
}
}
last = location
}
}
fun isBlocked(lines: List<Pair<Int, Int>>, position: Int): Boolean {
return lines.filter { it.first <= position }.any { it.second >= position }
}
fun isSandCollected(lines: HashMap<Int, MutableList<Pair<Int, Int>>>, from: Pair<Int, Int>): Boolean {
val line = lines[from.first] ?: return false
val stop = line.find { it.first > from.second } ?: return false
val leftDiagonal = Pair(from.first - 1, stop.first)
val leftLine = lines[leftDiagonal.first] ?: return false
if (!isBlocked(leftLine, leftDiagonal.second)) {
return isSandCollected(lines, leftDiagonal)
}
val rightDiagonal = Pair(from.first + 1, stop.first)
val rightLine = lines[rightDiagonal.first] ?: return false
if (!isBlocked(rightLine, rightDiagonal.second)) {
return isSandCollected(lines, rightDiagonal)
}
line[line.indexOf(stop)] = Pair(stop.first - 1, stop.second)
return true
}
fun part1(input: List<String>): Int {
val lines = hashMapOf<Int, MutableList<Pair<Int, Int>>>()
for (it in input) {
addLines(it, lines)
}
var answer = 0
while (isSandCollected(lines, Pair(500, 0))) {
answer++
}
return answer
}
fun addInfiniteFloor(
lines: HashMap<Int, MutableList<Pair<Int, Int>>>,
max: Int,
column: Int
): MutableList<Pair<Int, Int>> {
lines[column] = mutableListOf(Pair(max, max))
return lines[column]!!
}
fun isSourceBlocked(lines: HashMap<Int, MutableList<Pair<Int, Int>>>, max: Int, from: Pair<Int, Int>): Boolean {
var line = lines[from.first]
if (line == null) {
line = addInfiniteFloor(lines, max, from.first)
}
if (isBlocked(line, from.second)) {
return true
}
var stop = line.find { it.first >= from.second }
if (stop == null) {
stop = Pair(max, max)
line.add(stop)
}
val leftDiagonal = Pair(from.first - 1, stop.first)
if (!isSourceBlocked(lines, max, leftDiagonal)) {
return false
}
val rightDiagonal = Pair(from.first + 1, stop.first)
if (!isSourceBlocked(lines, max, rightDiagonal)) {
return false
}
line[line.indexOf(stop)] = Pair(stop.first - 1, stop.second)
return false
}
fun part2(input: List<String>): Int {
val lines = hashMapOf<Int, MutableList<Pair<Int, Int>>>()
for (it in input) {
addLines(it, lines)
}
var max = 0
for (line in lines) {
val cur = line.value.maxOf { it.second }
if (cur > max) max = cur
}
max += 2
var answer = 0
while (!isSourceBlocked(lines, max, Pair(500, 0))) {
answer++
}
return answer
}
val testInput = readInput("Day14_test")
check(part1(testInput) == 24)
check(part2(testInput) == 93)
val input = readInput("Day14")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | a51bda36eaef85a8faa305a0441efaa745f6f399 | 4,544 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/Problem2.kt | jimmymorales | 496,703,114 | false | {"Kotlin": 67323} | import kotlin.system.measureNanoTime
/**
* Even Fibonacci numbers
*
* Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the
* first 10 terms will be:
*
* 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
*
* By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the
* even-valued terms.
*
* https://projecteuler.net/problem=2
*/
fun main() {
val limit = 4_000_000
val solution1Time = measureNanoTime {
solution1(limit)
}
val solution2Time = measureNanoTime {
solution2(limit)
}
println(solution1Time)
println(solution2Time)
}
private fun solution1(limit: Int) {
var n1 = 1
var n2 = 1
var sum = 0
while (n2 < limit) {
if (n2 % 2 == 0) {
sum += n2
}
val fib = n1 + n2
n1 = n2
n2 = fib
}
println(sum)
}
private fun solution2(limit: Int) {
// 1 1 2 3 5 8 13 21 34 55 89 144
// a b c a b c a b c a b c
var a = 1
var b = 1
var c = a + b
var sum = 0
while (c < limit) {
sum += c
a = b + c
b = c + a
c = a + b
}
println(sum)
}
| 0 | Kotlin | 0 | 0 | e881cadf85377374e544af0a75cb073c6b496998 | 1,270 | project-euler | MIT License |
src/main/kotlin/Example2/Example2.kt | thomasnield | 116,161,739 | false | null | package Example2
import org.ojalgo.optimisation.ExpressionsBasedModel
import org.ojalgo.optimisation.Variable
import java.util.concurrent.atomic.AtomicInteger
// declare ojAlgo Model
val model = ExpressionsBasedModel()
// custom DSL for Example3.getModel expression inputs, eliminate naming and adding
val funcId = AtomicInteger(0)
val variableId = AtomicInteger(0)
fun variable() = Variable(variableId.incrementAndGet().toString().let { "Variable$it" }).apply(model::addVariable)
fun addExpression() = funcId.incrementAndGet().let { "Func$it"}.let { model.addExpression(it) }
fun main(args: Array<String>) {
Letter.values().forEach { it.addConstraints() }
Number.values().forEach { it.addConstraints() }
// C must be greater than or equal to THREE
addExpression().level(1).apply {
Letter.C.slots.asSequence().filter { it.number.value >= 3 }.forEach {
set(it.occupied, 1)
}
}
// D must be less than or equal to TWO
addExpression().level(1).apply {
Letter.D.slots.asSequence().filter { it.number.value <= 2 }.forEach {
set(it.occupied, 1)
}
}
model.minimise().run(::println)
Letter.values().joinToString(prefix = " ", separator = " ").run(::println)
Number.values().forEach { n ->
Letter.values().asSequence().map { l -> l.slots.first { it.number == n }.occupied.value.toInt() }
.joinToString(prefix = "$n ", separator = " ").run { println(this) }
}
}
enum class Letter {
A,
B,
C,
D,
E;
val slots by lazy {
Slot.all.filter { it.letter == this }.sortedBy { it.number.value }
}
fun addConstraints() {
// constrain each letter to only be assigned once
addExpression().upper(1).apply {
slots.forEach {
set(it.occupied, 1)
}
}
}
}
enum class Number(val value: Int) {
ONE(1),
TWO(2),
THREE(3),
FOUR(4),
FIVE(5);
val slots by lazy {
Slot.all.filter { it.number == this }.sortedBy { it.letter }
}
fun addConstraints() {
// constrain each NUMBER to only be assigned one slot
addExpression().upper(1).apply {
slots.forEach {
set(it.occupied, 1)
}
}
}
override fun toString() = value.toString()
}
data class Slot(val letter: Letter, val number: Number) {
val occupied = variable().binary()
companion object {
val all = Letter.values().asSequence().flatMap { letter ->
Number.values().asSequence().map { number -> Slot(letter, number) }
}.toList()
}
override fun toString() = "$letter$number: ${occupied?.value?.toInt()}"
}
| 0 | Kotlin | 0 | 4 | ae3822b00e459c9d65d1b637811635ae3da820cc | 2,735 | ojalgo_abstract_examples | Apache License 2.0 |
src/Day01.kt | ajesh-n | 573,125,760 | false | {"Kotlin": 8882} | fun main() {
fun part1(input: String): Int {
val elvesTotalFood =
input.split("\n\n").map { it.split("\n").sumOf { calories -> calories.toInt() } }
return elvesTotalFood.max()
}
fun part2(input: String): Int {
return input.split("\n\n").map { it.split("\n").sumOf { calories -> calories.toInt() } }
.sortedDescending().take(3).sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readText("Day01_test")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readText("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 2545773d7118da20abbc4243c4ccbf9330c4a187 | 680 | kotlin-aoc-2022 | Apache License 2.0 |
src/questions/SymmetricTree.kt | realpacific | 234,499,820 | false | null | package questions
import _utils.UseCommentAsDocumentation
import questions.common.TreeNode
import utils.shouldBe
import java.util.*
/**
* Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).
*
* [Source](https://leetcode.com/problems/symmetric-tree/)
*/
@UseCommentAsDocumentation
private fun isSymmetric(root: TreeNode?): Boolean {
if (root == null) return true
val queue: Queue<TreeNodeWithDepth> = LinkedList()
val depthToChildrenMap = TreeMap<Int, MutableList<TreeNode?>>()
queue.add(TreeNodeWithDepth(root, depth = 0))
traverse(queue, depthToChildrenMap)
// start the check from last as intermediate indices have already been checked
val sibilings = depthToChildrenMap.values.reversed()
sibilings.forEach {
// Check the symmetry of the list
if (!isPalindrome(it)) {
return false
}
}
return true
}
private fun traverse(
queue: Queue<TreeNodeWithDepth>,
depthToChildren: TreeMap<Int, MutableList<TreeNode?>>
) {
if (queue.isEmpty()) {
return
}
val node = queue.remove()
val depth = node.depth
if (!depthToChildren.containsKey(depth + 1) && depthToChildren.containsKey(depth)) {
val prevSiblings = depthToChildren[depth]!!
// Check if all the element in the previous depth was null i.e. all of them were leaf elements
// i.e. we are past the last depth
if (prevSiblings.all { it == null }) {
return
} else if (!isPalindrome(prevSiblings)) { // check if previously added siblings are symmetric
return // if it wasn't, break early
}
}
// use the parent depth to get the current depth
// add elements at current depth to the map
depthToChildren[depth + 1] = depthToChildren.getOrDefault(depth + 1, mutableListOf()).apply {
// count the nulls as well
this.add(node?.node?.left)
this.add(node?.node?.right)
}
// dont count the null as it can't be expanded further
// add it to queue as well
if (node?.node?.left != null) {
queue.add(TreeNodeWithDepth(node.node.left, depth + 1))
}
if (node?.node?.right != null) {
queue.add(TreeNodeWithDepth(node?.node?.right, depth + 1))
}
traverse(queue, depthToChildren)
}
private fun isPalindrome(list: List<TreeNode?>): Boolean {
for (i in 0..list.lastIndex) {
if (list[i]?.`val` != list[list.lastIndex - i]?.`val`) {
return false
}
}
return true
}
private data class TreeNodeWithDepth(val node: TreeNode?, val depth: Int)
fun main() {
isSymmetric(
TreeNode.from(
arrayOf(
9,
14,
14,
74,
null,
null,
74,
null,
12,
12,
null,
63,
null,
null,
63,
-8,
null,
null,
-8,
-53,
null,
null,
-53,
null,
-96,
-96,
null,
-65,
null,
null,
-65,
98,
null,
null,
98,
50,
null,
null,
50,
null,
91,
91,
null,
41,
-30,
-30,
41,
null,
86,
null,
-36,
-36,
null,
86,
null,
-78,
null,
9,
null,
null,
9,
null,
-78,
47,
null,
48,
-79,
-79,
48,
null,
47,
-100,
-86,
null,
47,
null,
67,
67,
null,
47,
null,
-86,
-100,
-28,
11,
null,
56,
null,
30,
null,
64,
64,
null,
30,
null,
56,
null,
11,
-28,
43,
54,
null,
-50,
44,
-58,
63,
null,
null,
-43,
-43,
null,
null,
63,
-58,
44,
-50,
null,
54,
43
)
)
) shouldBe true
isSymmetric(TreeNode.from(arrayOf(2, 3, 3, 4, 5, 5, 4, null, null, 8, 9, null, null, 9, 8))) shouldBe false
isSymmetric(TreeNode.from(arrayOf(1, 2, 2, null, 3, null, 3))) shouldBe false
isSymmetric(TreeNode.from(1, 2, 2, 3, 4, 4, 3)) shouldBe true
} | 4 | Kotlin | 5 | 93 | 22eef528ef1bea9b9831178b64ff2f5b1f61a51f | 5,518 | algorithms | MIT License |
src/main/kotlin/aoc23/Day16.kt | tahlers | 725,424,936 | false | {"Kotlin": 65626} | package aoc23
import io.vavr.kotlin.hashSet
import io.vavr.kotlin.toVavrSet
import io.vavr.collection.Set as VavrSet
object Day16 {
enum class Direction {
UP, LEFT, DOWN, RIGHT
}
data class Pos(val x: Int, val y: Int) {
fun newPos(dir: Direction): Pos =
when (dir) {
Direction.UP -> Pos(x, y - 1)
Direction.LEFT -> Pos(x - 1, y)
Direction.RIGHT -> Pos(x + 1, y)
Direction.DOWN -> Pos(x, y + 1)
}
fun inGrid(maxX: Int, maxY: Int) = x in 0..maxX && y in 0..maxY
}
data class Beam(val pos: Pos, val dir: Direction) {
private fun newBeamAt(direction: Direction) = Beam(pos.newPos(direction), direction)
fun newBeamAt(mirror: Char?): Pair<Beam, Beam?> =
when (mirror) {
'/' -> {
when (dir) {
Direction.UP -> newBeamAt(Direction.RIGHT) to null
Direction.LEFT -> newBeamAt(Direction.DOWN) to null
Direction.DOWN -> newBeamAt(Direction.LEFT) to null
Direction.RIGHT -> newBeamAt(Direction.UP) to null
}
}
'\\' -> {
when (dir) {
Direction.UP -> newBeamAt(Direction.LEFT) to null
Direction.LEFT -> newBeamAt(Direction.UP) to null
Direction.DOWN -> newBeamAt(Direction.RIGHT) to null
Direction.RIGHT -> newBeamAt(Direction.DOWN) to null
}
}
'|' -> {
when (dir) {
Direction.LEFT, Direction.RIGHT -> newBeamAt(Direction.UP) to newBeamAt(Direction.DOWN)
Direction.DOWN, Direction.UP -> newBeamAt(dir) to null
}
}
'-' -> {
when (dir) {
Direction.LEFT, Direction.RIGHT -> newBeamAt(dir) to null
Direction.DOWN, Direction.UP -> newBeamAt(Direction.LEFT) to newBeamAt(Direction.RIGHT)
}
}
else -> newBeamAt(dir) to null
}
}
data class Cavern(
val maxX: Int,
val maxY: Int,
val mirrors: Map<Pos, Char>,
val beams: VavrSet<Beam> = hashSet(Beam(Pos(0, 0), Direction.RIGHT)),
val beamsVisited: VavrSet<Beam> = beams
) {
fun next(): Cavern {
val newBeans = beams
.flatMap { beam ->
beam.newBeamAt(mirrors[beam.pos]).toList()
}
.filterNotNull()
val newBeamsInCavern = newBeans.filter { it.pos.inGrid(maxX, maxY) && it !in beamsVisited }.toSet().toVavrSet()
return Cavern(maxX, maxY, mirrors, newBeamsInCavern, beamsVisited.addAll(newBeamsInCavern))
}
}
fun calculateEnergizedTiles(input: String): Int {
val cavern = parseCavern(input)
val cavernSeq = generateSequence(cavern) { it.next() }
val stableConfiguration = cavernSeq.dropWhile { it.beams.nonEmpty() }.first()
return stableConfiguration.beamsVisited.map { it.pos }.size()
}
fun calculateMaxEnergizedTiles(input: String): Int {
val cavern = parseCavern(input)
val startBeans =
(0..cavern.maxX).flatMap { x ->
listOf(
Beam(Pos(x, 0), Direction.DOWN),
Beam(Pos(x, cavern.maxY), Direction.UP)
)
} +
(0..cavern.maxY).flatMap { y ->
listOf(
Beam(Pos(0, y), Direction.RIGHT),
Beam(Pos(cavern.maxX, y), Direction.LEFT)
)
}
val startCaverns = startBeans.map { Cavern(cavern.maxX, cavern.maxY, cavern.mirrors, hashSet(it)) }
val cavernSeq = generateSequence(startCaverns) { it.map { cavern -> cavern.next() } }
val stableConfiguration = cavernSeq.dropWhile { cavernList -> cavernList.any { it.beams.nonEmpty() } }.first()
val energized = stableConfiguration.map { cav ->
cav.beamsVisited.map { b -> b.pos }.size()
}
return energized.max()
}
private fun parseCavern(input: String): Cavern {
val lines = input.trim().lines()
val maxX = lines.first().length - 1
val maxY = lines.size - 1
val mirrors = lines.flatMapIndexed { y, line ->
line.mapIndexedNotNull { x, c ->
if (c in """/\-|""") {
Pos(x, y) to c
} else null
}
}
return Cavern(maxX, maxY, mirrors.toMap())
}
}
| 0 | Kotlin | 0 | 0 | 0cd9676a7d1fec01858ede1ab0adf254d17380b0 | 4,841 | advent-of-code-23 | Apache License 2.0 |
2019/src/main/kotlin/com/github/jrhenderson1988/adventofcode2019/day16/FFT.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.day16
import kotlin.math.abs
class FFT(private val signal: List<Int>, private val repetitions: Int = 1) {
fun signalAt(phases: Int, offset: Int, length: Int = 8): List<Int> {
val repeated = (0 until repetitions).map { signal }.flatten().drop(offset)
val applied = (0 until phases).fold(repeated) { input, _ -> next(input) }
return applied.subList(0, length)
}
private fun next(input: List<Int>): List<Int> {
val next = input.toMutableList()
(next.size - 1 downTo 0).forEach { i -> next[i] = (next[i] + next.getOrElse(i + 1) { 0 }) % 10 }
return next.toList()
}
fun applyPhases(n: Int): List<Int> {
return (0 until n).fold(signal) { input, _ ->
(input.indices)
.map { i ->
abs((input.indices).map { j -> input[j] * pattern(i)[j] }.sum() % 10)
}
}
}
fun applyPhasesAndTrim(phases: Int, trimTo: Int) = applyPhases(phases).subList(0, trimTo)
private fun pattern(i: Int): List<Int> {
val base = listOf(0, 1, 0, -1)
val repeated = base.map { item -> (0..i).map { item } }.flatten()
val multiplier = (signal.size + repeated.size) / repeated.size
return if (multiplier > 1) {
(0 until multiplier).map { repeated }.flatten()
} else {
repeated
}.drop(1).subList(0, signal.size)
}
companion object {
fun parse(input: String, repetitions: Int = 1) = FFT(input.map { it.toString().toInt() }, repetitions)
}
} | 0 | Kotlin | 0 | 0 | 7b56f99deccc3790c6c15a6fe98a57892bff9e51 | 1,610 | advent-of-code | Apache License 2.0 |
src/main/kotlin/net/voldrich/aoc2021/Day17.kt | MavoCz | 434,703,997 | false | {"Kotlin": 119158} | package net.voldrich.aoc2021
import net.voldrich.BaseDay
import kotlin.math.abs
import kotlin.math.max
// https://adventofcode.com/2021/day/17
fun main() {
Day17().run()
}
class Day17 : BaseDay() {
override fun task1() : Int {
val canon = ProbeCanon(input.lines()[0])
return canon.findHighestShot()
}
override fun task2() : Int {
val canon = ProbeCanon(input.lines()[0])
val shotList = canon.findAllPossibleShots()
return shotList.size
}
class ProbeCanon(targetAreaStr : String) {
val targetMinX : Int
val targetMaxX : Int
val targetMinY : Int
val targetMaxY : Int
init {
val regex = Regex("x=([0-9\\-]+)..([0-9\\-]+), y=([0-9\\-]+)..([0-9\\-]+)")
val matches = regex.find(targetAreaStr) ?: throw Exception("Failed to parse target area")
targetMinX = matches.groups[1]!!.value.toInt()
targetMaxX = matches.groups[2]!!.value.toInt()
targetMinY = matches.groups[3]!!.value.toInt()
targetMaxY = matches.groups[4]!!.value.toInt()
}
fun findHighestShot() : Int {
val velocityMinX = findMinHorizontalVelocity(targetMinX)
val velocityMaxX = targetMaxX
val velocityMinY = 0
val velocityMaxY = abs(targetMinY)
println("Velocity candidate area x: $velocityMinX $velocityMaxX, y: $velocityMinY $velocityMaxY ")
var maxy = Integer.MIN_VALUE
for (vy in (velocityMinY..velocityMaxY)) {
for (vx in (velocityMinX..velocityMaxX)) {
val probeShot = ProbeShot(vy, vx)
if (testShot(probeShot)) {
maxy = max(probeShot.maxy, maxy)
}
}
}
return maxy
}
fun findAllPossibleShots(): ArrayList<ProbeShot> {
val velocityMinX = findMinHorizontalVelocity(targetMinX)
val velocityMaxX = targetMaxX
val velocityMinY = targetMinY
val velocityMaxY = abs(targetMinY)
println("Velocity candidate area x: $velocityMinX $velocityMaxX, y: $velocityMinY $velocityMaxY ")
val shotList = ArrayList<ProbeShot>()
for (vy in (velocityMinY..velocityMaxY)) {
for (vx in (velocityMinX..velocityMaxX)) {
val probeShot = ProbeShot(vy, vx)
if (testShot(probeShot)) {
shotList.add(probeShot)
}
}
}
return shotList
}
private fun testShot(probeShot: ProbeShot): Boolean {
while (probeShot.posx < targetMaxX && probeShot.posy > targetMinY) {
probeShot.moveToNextProbeLocation()
if (probeShot.posx in targetMinX..targetMaxX
&& probeShot.posy in targetMinY..targetMaxY) {
return true
}
}
return false
}
private fun findMinHorizontalVelocity(targetMinX: Int): Int {
for (i in (1.. targetMinX)) {
val sum = (i*(i +1)) / 2
if (sum > targetMinX) {
return i
}
}
throw Exception("Could not find minX")
}
}
data class ProbeShot(val vy: Int, val vx: Int) {
var step = 0
var posx = 0
var posy = 0
var maxy = Integer.MIN_VALUE
var currentVy = vy
var currentVx = vx
fun moveToNextProbeLocation() {
posx += currentVx
posy += currentVy
if (currentVx > 0) {
currentVx -= 1
} else if (currentVx < 0) {
currentVx += 1
}
currentVy -= 1
step++
maxy = max(posy, maxy)
}
}
}
| 0 | Kotlin | 0 | 0 | 0cedad1d393d9040c4cc9b50b120647884ea99d9 | 3,947 | advent-of-code | Apache License 2.0 |
src/main/kotlin/com/frankandrobot/rapier/nlp/generalize.patterns.kt | frankandrobot | 62,833,944 | false | null | /*
* Copyright 2016 <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 com.frankandrobot.rapier.nlp
import com.frankandrobot.rapier.meta.RapierParams
import com.frankandrobot.rapier.pattern.Pattern
import com.frankandrobot.rapier.util.combinations
import com.frankandrobot.rapier.util.sort
import org.funktionale.option.Option
import org.funktionale.option.Option.None
import org.funktionale.option.Option.Some
import java.util.*
internal data class MatchIndices(val leftIndex: Int, val rightIndex: Int)
/**
* Find identical pattern elements in the two patterns subject to constraints:
*
* 1. matches must be in order i.e., in the patterns a:[x,y] and b:[y,x], pattern elements
* x and y cannot both match.
* 2. every pattern element in the shorter pattern must be allowed to match one element
* in the longer pattern.
*/
internal fun findExactMatchIndices(a : Pattern, b : Pattern) : ArrayList<MatchIndices> {
val patterns = sort(a, b)
val left = patterns.first
val right = patterns.second
val matches = arrayListOf(MatchIndices(-1, -1))
left().withIndex().forEach { patternElement ->
val prevMatchIndex = matches[matches.lastIndex].rightIndex
val searchRangeStart = Math.max(patternElement.index, prevMatchIndex + 1)
val searchRangeEnd = right().size - left().size + patternElement.index
var i = searchRangeStart
while (i <= searchRangeEnd) {
if (patternElement.value == right()[i]) {
matches.add(MatchIndices(patternElement.index, i))
break
}
++i
}
}
return (matches + arrayListOf(MatchIndices(left().lastIndex+1, right().lastIndex+1)))
as ArrayList<MatchIndices>
}
/**
* Splits the patterns by exact matches (if any). For example, given patterns
*
* a:[x,y,z] and b:[1,x,2,3,z,4],
*
* it matches "x" and "z", so returns
*
* [
* Pair([], [1]),
* Pair([x], [x]),
* Pair([y], [2,3]),
* Pair([z], [z]),
* Pair([], [4])
* ]
*/
internal fun partitionByExactMatches(a : Pattern, b : Pattern) : List<Pair<Pattern,Pattern>> {
val patterns = sort(a, b)
val left = patterns.first
val right = patterns.second
val matches = findExactMatchIndices(a, b)
if (matches.size > 2) {
return matches.foldIndexed(emptyList<Pair<Pattern,Pattern>>()){ i, total, match ->
if (i > 0) {
val prevLeftIndex = matches[i - 1].leftIndex + 1
val prevRightIndex = matches[i - 1].rightIndex + 1
val leftPatterns = left().subList(prevLeftIndex, match.leftIndex)
val rightPatterns = right().subList(prevRightIndex, match.rightIndex)
if (i < matches.lastIndex) {
total +
Pair(Pattern(leftPatterns), Pattern(rightPatterns)) +
Pair(Pattern(left()[match.leftIndex]), Pattern(right()[match.rightIndex]))
}
else {
total +
Pair(Pattern(leftPatterns), Pattern(rightPatterns))
}
}
else {
total
}
}.filter{ it.first().size > 0 || it.second().size > 0 }
}
return listOf(Pair(a, b))
}
fun generalize(a : Pattern, b : Pattern, params : RapierParams) : List<Pattern> {
val segments : List<Pair<Pattern,Pattern>> = partitionByExactMatches(a, b)
// find the generalized patterns for the partitions
val partitionPatterns : List<List<Pattern>> = segments.map{ patterns ->
val veryLongPatterns = caseVeryLongPatterns(patterns.first, patterns.second, params)
val equalSizePatterns = caseEqualLengthPatterns(patterns.first, patterns.second)
val hasSingleElementPattern = casePatternHasSingleElement(patterns.first, patterns.second)
val hasEmptyPattern = caseAnEmptyPattern(patterns.first, patterns.second)
when(veryLongPatterns) {
is Some<List<Pattern>> -> veryLongPatterns.get()
else -> when (equalSizePatterns) {
is Some<List<Pattern>> -> equalSizePatterns.get()
else -> when (hasSingleElementPattern) {
is Some<List<Pattern>> -> hasSingleElementPattern.get()
else -> when (hasEmptyPattern) {
is Some<List<Pattern>> -> hasEmptyPattern.get()
else -> caseGeneral(patterns.first, patterns.second).get()
}
}
}
}
}
//now combine the partition patterns
return partitionPatterns.foldIndexed(emptyList()){ i, total, curPatternListForSegment ->
if (i == 0) {
curPatternListForSegment
}
else {
combinations(total, curPatternListForSegment) { a : Pattern, b : Pattern -> a + b }
}
}
}
fun generalize(a : Option<Pattern>,
b : Option<Pattern>,
params : RapierParams) : List<Option<Pattern>> {
if (a.isDefined() && b.isDefined()) {
return generalize(a.get(), b.get(), params = params).map{Some(it)}
}
return listOf(None)
}
| 1 | Kotlin | 1 | 1 | ddbc0dab60ca595e63a701e2f8cd6694ff009adc | 5,377 | rapier | Apache License 2.0 |
src/main/kotlin/day7/SomeAssemblyRequired.kt | SaujanShr | 685,121,393 | false | null | package day7
import day7.GateType.*
import getInput
val INPUT = getInput("day7")
fun run1(): String {
val circuit = getCircuit(INPUT)
val wires = getWires(circuit)
processSignals(wires)
val signals = getSignals(wires)
return signals["a"]!!.toString()
}
fun run2(): String {
val circuit = getCircuit(INPUT)
val wires = getWires(circuit)
processSignals(wires)
val aSignal = wires["a"]!!.value
wires.values.forEach(Wire::resetDependencies)
wires["b"]!!.setRawInput(aSignal)
processSignals(wires)
val signals = getSignals(wires)
return signals["a"]!!.toString()
}
fun getCircuit(instructions: String): List<List<String>> {
return instructions
.split('\n')
.map { it.split(" -> ") }
}
fun getWires(circuit: List<List<String>>): Map<String,Wire> {
val gates = circuit
.map { (input, output) ->
Pair(output, input.split(' '))
}
.toMap()
val wires = gates
.map { (output, _) ->
Pair(output, Wire())
}
.toMap()
wires.forEach { (output, wire) ->
val gate = gates[output]!!
val gateType = GateType.getValue(gates[output]!!)
wire.setType(gateType)
when (gateType) {
SOURCE -> when (val value = gate.first().toUShortOrNull()) {
null -> setWireConnection(wire, wires[gate.first()]!!)
else -> setSourceConnection(wire, value)
}
NOT -> when (val value = gate.last().toUShortOrNull()) {
null -> setWireConnection(wire, wires[gate.last()]!!)
else -> setSourceConnection(wire, value)
}
AND, OR, LSHIFT, RSHIFT -> {
when (val value = gate.first().toUShortOrNull()) {
null -> setWireConnection(wire, wires[gate.first()]!!)
else -> setSourceConnection(wire, value)
}
when (val value = gate.last().toUShortOrNull()) {
null -> setWireConnection(wire, wires[gate.last()]!!)
else -> setSourceConnection(wire, value)
}
}
UNKNOWN -> {}
}
}
return wires
}
fun setWireConnection(wire: Wire, inputWire: Wire) {
wire.addDependencyToWire(inputWire)
inputWire.addDependencyOf(wire)
}
fun setSourceConnection(wire: Wire, value: UShort) {
val source = Source(value)
wire.addDependencyToSource(source)
}
fun processSignals(wires: Map<String,Wire>) {
wires.values
.filter(Wire::isRawInput)
.forEach(Wire::resolveRawInput)
}
fun getSignals(wires: Map<String,Wire>): Map<String,UShort> {
return wires
.map { (output, wire) -> Pair(output, wire.value) }
.toMap()
}
| 0 | Kotlin | 0 | 0 | c6715a9570e62c28ed022c5d9b330a10443206c4 | 2,802 | adventOfCode2015 | Apache License 2.0 |
src/main/kotlin/com/staricka/adventofcode2022/Day18.kt | mathstar | 569,952,400 | false | {"Kotlin": 77567} | package com.staricka.adventofcode2022
import com.staricka.adventofcode2022.Day18.Cube.Companion.parseCube
class Day18 : Day {
override val id = 18
data class Cube(val x: Int, val y: Int, val z: Int) {
val neighbors by lazy {
listOf(
Cube(x - 1, y, z),
Cube(x + 1, y, z),
Cube(x, y - 1, z),
Cube(x, y + 1, z),
Cube(x, y, z - 1),
Cube(x, y, z + 1),
)
}
companion object {
fun String.parseCube(): Cube {
val split = this.split(",")
return Cube(split[0].toInt(), split[1].toInt(), split[2].toInt())
}
}
}
override fun part1(input: String): Any {
val cubes = input.lines().map { it.parseCube() }.toHashSet()
var exposedSides = 0
for (cube in cubes) {
exposedSides += cube.neighbors.count { !cubes.contains(it) }
}
return exposedSides
}
override fun part2(input: String): Any {
val cubes = input.lines().map { it.parseCube() }.toHashSet()
val xNegBound = cubes.minOfOrNull { it.x }!! - 1
val xPosBound = cubes.maxOfOrNull { it.x }!! + 1
val yNegBound = cubes.minOfOrNull { it.y }!! - 1
val yPosBound = cubes.maxOfOrNull { it.y }!! + 1
val zNegBound = cubes.minOfOrNull { it.z }!! - 1
val zPosBound = cubes.maxOfOrNull { it.z }!! + 1
val water = HashSet<Cube>()
val flow = ArrayDeque<Cube>()
flow.add(Cube(xNegBound, yNegBound, zNegBound))
water.add(flow.first())
var surface = 0
while (flow.isNotEmpty()) {
val w = flow.removeFirst()
surface += w.neighbors.count { cubes.contains(it) }
w.neighbors.filter { !cubes.contains(it) }
.filter { !water.contains(it) }
.filter { it.x in xNegBound..xPosBound &&
it.y in yNegBound..yPosBound &&
it.z in zNegBound..zPosBound}
.forEach {
water.add(it)
flow.add(it)
}
}
return surface
}
} | 0 | Kotlin | 0 | 0 | 2fd07f21348a708109d06ea97ae8104eb8ee6a02 | 1,928 | adventOfCode2022 | MIT License |
dynamic_programming/highest_route/HighestRouteValue.kt | YaroslavHavrylovych | 78,222,218 | false | {"Java": 284373, "Kotlin": 35978, "Shell": 2994} | /**
* TODO it's an old implementation I did which is not
* dynamic programming approach. I hope soon I would replace that with the new
* solution (today I'm focused on java).
* <br/>
* Check README to find the description.
*/
class HighestRouteValue {
fun calculate(cell: Coordinate): Int {
return nextStep(cell)
}
fun nextStep(cell: Coordinate): Int {
if (cell.n == 0 && cell.m == 0) return matrix[0][0]
if (cell.n > 0 && cell.m > 0)
return matrix[cell.n][cell.m] + Math.max(
nextStep(Coordinate(cell.n - 1, cell.m)),
nextStep(Coordinate(cell.n, cell.m - 1)))
if (cell.n > 0)
return matrix[cell.n][cell.m] + nextStep(
Coordinate(cell.n - 1, cell.m))
return matrix[cell.n][cell.m] + nextStep(
Coordinate(cell.n, cell.m - 1))
}
class Coordinate constructor(val n: Int, val m: Int) {
override fun toString(): String {
return "{$n, $m}"
}
override fun hashCode(): Int {
return Integer.hashCode((n + 1) * (m + 1) + m)
}
override fun equals(other: Any?): Boolean {
if (other !is Coordinate) {
return false
}
return other.n == n && other.m == m
}
}
}
private val matrix = arrayOf(
intArrayOf(1, 2, 3),
intArrayOf(6, 9, 11),
intArrayOf(8, 10, 7),
intArrayOf(4, 9, 5),
intArrayOf(10, 8, 3))
private val N = 5
private val M = 3
fun printMatrix(matrix: Array<IntArray>) {
for (n in matrix.indices) {
for (m in 0..matrix[n].size - 1) {
System.out.print(matrix[n][m].toString() + "\t")
}
System.out.println("")
}
}
fun main(args: Array<String>) {
printMatrix(matrix)
System.out.println()
val value = HighestRouteValue().calculate(
HighestRouteValue.Coordinate(N - 1, M - 1))
System.out.println(Integer.toString(value))
}
| 0 | Java | 0 | 2 | cb8e6f7e30563e7ced7c3a253cb8e8bbe2bf19dd | 2,027 | codility | MIT License |
AdventOfCodeDay13/src/nativeMain/kotlin/Day13.kt | bdlepla | 451,510,571 | false | {"Kotlin": 165771} | class Day13(private val lines:List<String>) {
fun solvePart1():Int {
val (points, folds) = parseInput(lines)
val matrix = Matrix.create(points)
val newMatrix = folds.take(1).foldMatrix(matrix)
return newMatrix.allPointValues().count { it }
}
fun solvePart2():String {
val (points, folds) = parseInput(lines)
val matrix = Matrix.create(points)
val newMatrix = folds.foldMatrix(matrix)
return newMatrix.print()
}
private fun List<Fold>.foldMatrix(matrix:Matrix):Matrix {
return this.fold(matrix) { m, f ->
if (f.which == 'y'){
//println("in fold, current matrix:")
// println(m.print())
val (m1, m2) = m.splitAtY(f.where)
//println("splitting at y=${f.where}")
//println(m1.print())
//println(m2.print())
val flippedM2 = m2.flipUpDown()
//println("m2 flipped up to down")
//println(flippedM2.print())
val (max1, max2) = if (m1.height < m2.height) Pair(flippedM2,m1) else Pair(m1,flippedM2)
val ret = max1.mergeFromBottom(max2)
//println(ret.print())
ret
} else {
//println("in fold, current matrix:")
//println(m.print())
val (m1,m2) = m.splitAtX(f.where)
//println("splitting at x=${f.where}")
//println(m1.print())
//println(m2.print())
val flippedM2 = m2.flipRightLeft()
//println("m2 flipped left to right")
//println(flippedM2.print())
val (max1, max2) = if (m1.width < m2.width) Pair(flippedM2,m1) else Pair(m1,flippedM2)
val ret = max1.mergeFromLeft(max2)
//println(ret.print())
ret
}
}
}
private fun Matrix.splitAtY(y:Int):Pair<Matrix, Matrix> {
val mTop = Matrix(width, y)
(0 until y).forEach { py ->
(0 until width).forEach { px ->
mTop[px,py] = this[px,py]
}
}
val mBottom = Matrix(width, height - y-1)
(y+1 until height).forEachIndexed { idy, py ->
(0 until width).forEach { px ->
mBottom[px,idy] = this[px,py]
}
}
return Pair(mTop, mBottom)
}
private fun Matrix.splitAtX(x:Int):Pair<Matrix,Matrix> {
val mLeft = Matrix(x, height)
(0 until height).forEach { py ->
(0 until x).forEach { px ->
mLeft[px,py] = this[px,py]
}
}
val mRight = Matrix(width - x-1, height)
(0 until height).forEach { py ->
(x+1 until width).forEachIndexed {idx, px ->
mRight[idx,py] = this[px,py]
}
}
return Pair(mLeft, mRight)
}
private fun Matrix.flipUpDown():Matrix {
val ret = Matrix(width, height)
(height-1 downTo 0).forEachIndexed { idy, py ->
(0 until width).forEach { px ->
ret[px,idy] = this[px,py]
}
}
return ret
}
private fun Matrix.flipRightLeft():Matrix {
val ret = Matrix(width, height)
(0 until height).forEach { py ->
(width-1 downTo 0).forEachIndexed { idx, px ->
ret[idx,py] = this[px,py]
}
}
return ret
}
private fun Matrix.mergeFromBottom(other:Matrix):Matrix {
// this is always bigger height (or same); other is always smaller (or same)
val offset = this.height - other.height
(0 until other.height).forEach { y ->
(0 until other.width).forEach { x ->
this[x,y+offset] = this[x,y+offset] || other[x,y]
}
}
return this
}
private fun Matrix.mergeFromLeft(other:Matrix):Matrix {
// this is always bigger width (or same); other is always smaller (or same)
(0 until height).forEach { y ->
(0 until other.width).forEach { x ->
this[x,y] = this[x,y] || other[x,y]
}
}
return this
}
private fun parseInput(lines:List<String>):Pair<List<Point>, List<Fold>> {
val points = lines.takeWhile{it.isNotBlank()}
val pointList = points
.map{it.split(',')}
.map{Point(it[0].toInt(), it[1].toInt())}
val folds = lines.dropWhile{it.isNotBlank()}.dropWhile{it.isBlank()}
val foldList = folds
.map{it.substringAfter("fold along ")}
.map{it.split('=')}
.map{Fold(it[0][0], it[1].toInt())}
return pointList to foldList
}
} | 0 | Kotlin | 0 | 0 | 1d60a1b3d0d60e0b3565263ca8d3bd5c229e2871 | 4,800 | AdventOfCode2021 | The Unlicense |
core/src/main/kotlin/org/eln2/space/Location.kt | resnidar | 403,165,234 | true | {"Kotlin": 328082, "Nix": 4408, "Java": 3507} | package org.eln2.space
import kotlin.math.abs
/**
* A vector in a two-dimensional space of integers.
*/
data class Vec2i(val x: Int, val y: Int) {
/**
* Gets the opposite vector.
*/
operator fun unaryMinus() = Vec2i(-x, -y)
/**
* Gets the sum of this vector and another vector.
*/
operator fun plus(other: Vec2i) = Vec2i(x + other.x, y + other.y)
/**
* Gets the sum of this vector and the opposite of another vector.
*/
operator fun minus(other: Vec2i) = this + (-other)
/**
* Gets the scalar multiple of this vector.
*/
operator fun times(scalar: Int) = Vec2i(x * scalar, y * scalar)
val isZero: Boolean get() = this == ZERO
companion object {
val ZERO = Vec2i(0, 0)
val XU = Vec2i(1, 0)
val YU = Vec2i(0, 1)
}
}
/**
* A vector in a three-dimensional space of integers.
*/
data class Vec3i(val x: Int, val y: Int, val z: Int) {
/**
* Gets the opposite vector.
*/
operator fun unaryMinus() = Vec3i(-x, -y, -z)
/**
* Gets the sum of this vector and another vector.
*/
operator fun plus(other: Vec3i) = Vec3i(x + other.x, y + other.y, z + other.z)
/**
* Gets the sum of this vector and the opposite of another vector.
*/
operator fun minus(other: Vec3i) = this + (-other)
/**
* Gets the scalar multiple of this vector.
*/
operator fun times(other: Int) = Vec3i(x * other, y * other, z * other)
val isZero: Boolean get() = (x == 0) && (y == 0) && (z == 0)
/**
* Calculates the L1 distance between two vectors.
* See https://en.wikipedia.org/wiki/Taxicab_geometry
*/
fun l1norm(v: Vec3i): Int = abs(v.x - x) + abs(v.y - y) + abs(v.z - z)
companion object {
val ZERO = Vec3i(0, 0, 0)
val XU = Vec3i(1, 0, 0)
val YU = Vec3i(0, 1, 0)
val ZU = Vec3i(0, 0, 1)
}
}
/**
* A direction oriented in two-dimensional space.
*/
enum class PlanarDir(val int: Int) {
Up(0), Right(1), Down(2), Left(3);
companion object {
fun fromInt(i: Int) = when (i) {
0 -> Up
1 -> Right
2 -> Down
3 -> Left
else -> error("Not a PlanarDir: $i")
}
}
val rotated: PlanarDir get() = fromInt((int + 1) % 4)
val inverted: PlanarDir get() = fromInt((int + 2) % 4)
val rotated_left: PlanarDir get() = fromInt((int + 3) % 4)
}
/**
* A set of unit vectors that represents each direction in three-dimensional space.
*/
enum class Axis(val int: Int) {
X(0), Y(1), Z(2);
companion object {
fun fromInt(i: Int) = when (i) {
0 -> X
1 -> Y
2 -> Z
else -> null
}
/**
* Returns the axis in which a given vector is closest to. Perfect diagonals may return an axis that is nonsense.
*/
fun fromVecMajor(v: Vec3i): Axis {
var (x, y, z) = v
x = abs(x); y = abs(y); z = abs(z)
val max = arrayOf(x, y, z).maxOrNull()
return when (max) {
x -> X
y -> Y
else -> Z
}
}
/* Microoptimization: avoid the overhead from constructing these repeatedly */
val X_VEC = Vec3i.XU
val Y_VEC = Vec3i.YU
val Z_VEC = Vec3i.ZU
}
val vec3i: Vec3i
get() = when (this) {
X -> X_VEC
Y -> Y_VEC
Z -> Z_VEC
}
/**
* Returns the cross product of this axis and another.
*/
fun cross(other: Axis): Axis? = when (this) {
X -> when (other) {
X -> null
Y -> Z
Z -> Y
}
Y -> when (other) {
X -> Z
Y -> null
Z -> X
}
Z -> when (other) {
X -> Y
Y -> X
Z -> null
}
}
}
/**
* The six orthogonal vectors corresponding to the faces of a cube as seen from the center.
*/
enum class PlanarFace(val int: Int) {
PosX(0), PosY(1), PosZ(2), NegX(3), NegY(4), NegZ(5);
companion object {
/**
* Gets the face corresponding to a number.
*/
fun fromInt(i: Int) = when (i) {
0 -> PosX
1 -> PosY
2 -> PosZ
3 -> NegX
4 -> NegY
5 -> NegZ
else -> error("Invalid PlanarFace: $i")
}
/**
* Gets the plane that the axis is pointing to from the center.
*/
fun fromAxis(a: Axis, n: Boolean): PlanarFace = fromInt(a.int + if (n) 3 else 0)
/**
* Gets the plane that the vector is pointing to in respect to the center of the cube.
*/
fun fromVec(v: Vec3i): PlanarFace {
val axis = Axis.fromVecMajor(v)
return fromAxis(
axis, when (axis) {
Axis.X -> v.x < 0
Axis.Y -> v.y < 0
Axis.Z -> v.z < 0
}
)
}
/**
* Gets the plane that has the closest normal vector to the given vector.
*/
fun fromNormal(v: Vec3i): PlanarFace = fromVec(v).inverse
/* See the microopt in Axis above */
val PosX_VEC = Axis.X_VEC
val PosY_VEC = Axis.Y_VEC
val PosZ_VEC = Axis.Z_VEC
val NegX_VEC = -PosX_VEC
val NegY_VEC = -PosY_VEC
val NegZ_VEC = -PosZ_VEC
val ADJACENCIES = arrayOf(
arrayOf(PosY, PosZ, NegY, NegZ),
arrayOf(PosX, PosZ, NegX, NegZ),
arrayOf(PosX, PosY, NegX, NegY)
)
}
val neg: Boolean get() = int > 2
val axis: Axis
get() = when (this) {
PosX, NegX -> Axis.X
PosY, NegY -> Axis.Y
PosZ, NegZ -> Axis.Z
}
val inverse: PlanarFace
get() = when (this) {
PosX -> NegX
NegX -> PosX
PosY -> NegY
NegY -> PosY
PosZ -> NegZ
NegZ -> PosZ
}
/**
"Vector": the vec that points out of the block center toward this face.
*/
val vec3i: Vec3i
get() = if (neg) when (axis) {
Axis.X -> NegX_VEC
Axis.Y -> NegY_VEC
Axis.Z -> NegZ_VEC
} else axis.vec3i
/**
* "Normal": the vec that points, normal to this face, toward the block center.
*/
val normal: Vec3i
get() = if (neg) axis.vec3i else when (axis) {
Axis.X -> NegX_VEC
Axis.Y -> NegY_VEC
Axis.Z -> NegZ_VEC
}
val adjacencies: Array<PlanarFace> get() = ADJACENCIES[int % 3]
}
/**
* A generic location in a generic space. Also contains a method to check if something can connect with this and list
* of locatable objects that can connect with this.
*/
interface Locator {
val vec3i: Vec3i
/**
* A list of neighbors in which connections are possible with.
*/
fun neighbors(): List<Locator>
/**
* Returns true if it is possible for this node and another node to connect.
* When overriding this, make sure a specific test is implemented for the specific
* locator that extended this interface. Ensure that the coverage of the test is
* proportional to the size of the implementation.
*/
fun canConnect(other: Locator): Boolean = true
}
/**
* Locator support for "simple nodes" that take up an entire block in three-dimensional space.
*/
data class BlockPos(override val vec3i: Vec3i) : Locator {
companion object {
val CONNECTIVITY_DELTAS = arrayListOf(
// Cardinal directions on the horizontal plane (Y-normal)
Vec3i(1, 0, 0), Vec3i(-1, 0, 0), Vec3i(0, 0, 1), Vec3i(0, 0, -1),
// Up a block
Vec3i(1, 1, 0), Vec3i(-1, 1, 0), Vec3i(0, 1, 1), Vec3i(0, 1, -1),
// Down a block
Vec3i(1, -1, 0), Vec3i(-1, -1, 0), Vec3i(0, -1, 1), Vec3i(0, -1, -1)
)
}
override fun neighbors(): List<Locator> = CONNECTIVITY_DELTAS.map { translate(it) }
/**
* Offsets a vector based on the position of this node.
*/
fun translate(v: Vec3i) = BlockPos(vec3i + v)
}
/**
* Locator support for surface-mounted nodes the exist on a three-dimensional block. Up to six can exist per block,
* corresponding to each face.
*/
data class SurfacePos(override val vec3i: Vec3i, val face: PlanarFace) : Locator {
companion object {
// On the same plane:
val PLANAR_DELTAS = arrayListOf(
Vec3i(1, 0, 0), Vec3i(-1, 0, 0), Vec3i(0, 0, 1), Vec3i(0, 0, -1)
)
// On adjacent planes:
val ADJACENT_DELTAS = arrayListOf(
// SurfacePos locators can connect to adjacent planes on the same block:
Vec3i(0, 0, 0),
// One unit down (anti-normal) in cardinal directions ("wrapping around")
Vec3i(1, -1, 0), Vec3i(-1, -1, 0), Vec3i(0, -1, 1), Vec3i(0, -1, -1)
)
}
// Preserve chirality: invert _two_ components, or none.
// There's very little thought in the permutation otherwise, however; if those need to be changed, they can be.
/**
* Orients a vector based on which plane of a cube this node is on. This preserves chirality.
*/
fun toReference(v: Vec3i): Vec3i = when (face) {
PlanarFace.NegX -> Vec3i(v.y, v.x, v.z)
PlanarFace.PosX -> Vec3i(-v.y, -v.x, v.z)
PlanarFace.PosY -> Vec3i(-v.x, -v.y, v.z)
PlanarFace.NegY -> v
PlanarFace.NegZ -> Vec3i(v.x, v.z, v.y)
PlanarFace.PosZ -> Vec3i(-v.x, v.z, -v.y)
}
/**
* Offsets a vector based on the position and orientation of this node.
*/
fun translate(v: Vec3i) = SurfacePos(vec3i + toReference(v), face)
override fun neighbors(): List<Locator> = (PLANAR_DELTAS
.map { translate(it) } + // Other adjacent blocks on the same plane
face.adjacencies.map { SurfacePos(vec3i, it) } + // Connections within the same block
face.adjacencies.map { SurfacePos(vec3i + face.vec3i + it.normal, it) } // "Wrapping" (L1=2) connections
)
override fun canConnect(other: Locator): Boolean = when (other) {
is SurfacePos -> when (other.vec3i.l1norm(vec3i)) {
0 -> other.face != face && other.face != face.inverse
1 -> face == other.face
2 -> {
val delta = other.vec3i - vec3i
val other_norm = delta + face.normal
println(
"SP.cC: L1=2: delta $delta other_norm $other_norm face.normal ${face.normal} this.vec $vec3i other.vec ${other.vec3i} other.face ${other.face} PF.fN(on) ${PlanarFace.fromNormal(
other_norm
)}"
)
other.face == PlanarFace.fromNormal(other_norm)
}
else -> error("Illegal norm")
}
is BlockPos -> true
else -> true
}
}
| 0 | Kotlin | 1 | 0 | d1fa0e39bf4008e459936ef789d76f5cc9662413 | 11,060 | eln2 | MIT License |
src/main/kotlin/17.kts | reitzig | 318,492,753 | false | null | @file:Include("shared.kt")
import java.io.File
enum class GridElement(val rep: Char) {
Active('#'),
Inactive('.');
companion object {
fun valueOfRep(rep: Char): GridElement =
values().firstOrNull { it.rep == rep }
?: throw IllegalArgumentException("No element with rep $rep")
}
}
interface Position<Self : Position<Self>> {
val neighbours: Sequence<Self>
}
data class Position3(val x: Int, val y: Int, val z: Int) : Position<Position3> {
override val neighbours: Sequence<Position3>
get() = listOf(-1, 0, 1)
.combinations(3)
.asSequence()
.filterNot { l -> l.all { it == 0 } }
.map { (dx, dy, dz) ->
Position3(x + dx, y + dy, z + dz)
}
}
data class Position4(val x: Int, val y: Int, val z: Int, val zz: Int) : Position<Position4> {
override val neighbours: Sequence<Position4>
get() = listOf(-1, 0, 1)
.combinations(4)
.asSequence()
.filterNot { l -> l.all { it == 0 } }
.map { (dx, dy, dz, dzz) ->
Position4(x + dx, y + dy, z + dz, zz + dzz)
}
}
data class PocketDimension<P : Position<P>>(var grid: MutableMap<P, GridElement>) {
init {
grid.keys.toList().forEach { expandAround(it) }
}
val activeElements: List<P>
get() = grid.filterValues { it == GridElement.Active }
.map { it.key }
fun activeNeighbours(position: P): Int =
position.neighbours.count { grid[it] == GridElement.Active }
private fun expandAround(position: P) {
if (grid[position] == GridElement.Active) {
position.neighbours.forEach {
grid.putIfAbsent(it, GridElement.Inactive)
}
}
}
fun blink(willGoInactive: (P) -> Boolean, willGoActive: (P) -> Boolean) {
val toExpand = mutableListOf<P>()
grid = grid.mapValues { (pos, elem) ->
if (elem == GridElement.Active && willGoInactive(pos)) {
GridElement.Inactive
} else if (elem == GridElement.Inactive && willGoActive(pos)) {
toExpand.add(pos)
GridElement.Active
} else {
elem
}
}.toMutableMap()
toExpand.forEach { expandAround(it) }
}
companion object {
operator fun <P : Position<P>> invoke(
initialConfiguration: List<String>,
position: (Int, Int) -> P
): PocketDimension<P> =
initialConfiguration
.flatMapIndexed { x, row ->
row.mapIndexed { y, elem ->
Pair(position(x, y), GridElement.valueOfRep(elem))
}
}
.toMap().toMutableMap()
.let { PocketDimension(it) }
}
}
val input = File(args[0]).readLines()
// Part 1:
val pocketDimension3 = input.let {
PocketDimension(it) { x, y -> Position3(x, y, 0) }
}
for (i in 1..6) {
pocketDimension3.apply {
blink({ activeNeighbours(it) !in 2..3 }, { activeNeighbours(it) == 3 })
}
}
println(pocketDimension3.activeElements.size)
// Part 3:
val pocketDimension4 = input.let {
PocketDimension(it) { x, y -> Position4(x, y, 0, 0) }
}
for (i in 1..6) {
pocketDimension4.apply {
blink({ activeNeighbours(it) !in 2..3 }, { activeNeighbours(it) == 3 })
}
}
println(pocketDimension4.activeElements.size) | 0 | Kotlin | 0 | 0 | f17184fe55dfe06ac8897c2ecfe329a1efbf6a09 | 3,495 | advent-of-code-2020 | The Unlicense |
2023/src/main/kotlin/de/skyrising/aoc2023/day4/solution.kt | skyrising | 317,830,992 | false | {"Kotlin": 411565} | package de.skyrising.aoc2023.day4
import de.skyrising.aoc.*
val test = TestInput("""
Card 1: 41 48 83 86 17 | 83 86 6 31 17 9 48 53
Card 2: 13 32 20 16 61 | 61 30 68 82 17 32 24 19
Card 3: 1 21 53 59 44 | 69 82 63 72 16 21 14 1
Card 4: 41 92 73 84 69 | 59 84 76 51 58 5 54 83
Card 5: 87 83 26 28 32 | 88 30 70 12 93 22 82 36
Card 6: 31 18 13 56 72 | 74 77 10 23 35 67 36 11
""")
fun parse(input: PuzzleInput) = input.lines.map { line ->
val (winning, have) = line.substringAfter(": ").split(" | ")
have.ints().intersect(winning.ints()).size
}
@PuzzleName("")
fun PuzzleInput.part1() = parse(this).sumOf { if (it == 0) 0 else (1 shl (it - 1)) }
fun PuzzleInput.part2(): Any {
val wins = parse(this)
val deck = IntArray(wins.size) { 1 }
deck.forEachIndexed { i, count ->
for (j in i+1..i+wins[i]) deck[j] += count
}
return deck.sum()
}
| 0 | Kotlin | 0 | 0 | 19599c1204f6994226d31bce27d8f01440322f39 | 904 | aoc | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.