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/leetcodeProblem/leetcode/editor/en/MaximumSubarray.kt | faniabdullah | 382,893,751 | false | null | //Given an integer array nums, find the contiguous subarray (containing at
//least one number) which has the largest sum and return its sum.
//
// A subarray is a contiguous part of an array.
//
//
// Example 1:
//
//
//Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
//Output: 6
//Explanation: [4,-1,2,1] has the largest sum = 6.
//
//
// Example 2:
//
//
//Input: nums = [1]
//Output: 1
//
//
// Example 3:
//
//
//Input: nums = [5,4,-1,7,8]
//Output: 23
//
//
//
// Constraints:
//
//
// 1 <= nums.length <= 10⁵
// -10⁴ <= nums[i] <= 10⁴
//
//
//
// Follow up: If you have figured out the O(n) solution, try coding another
//solution using the divide and conquer approach, which is more subtle.
// Related Topics Array Divide and Conquer Dynamic Programming 👍 15318 👎 717
package leetcodeProblem.leetcode.editor.en
class MaximumSubarray {
fun solution() {
}
//below code will be used for submission to leetcode (using plugin of course)
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
fun maxSubArray(nums: IntArray): Int {
var maxNow = Int.MIN_VALUE
var current = 0
nums.forEach {
current = maxOf(current + it, it)
maxNow = maxOf(current, maxNow)
}
return maxNow
}
}
//leetcode submit region end(Prohibit modification and deletion)
}
fun main() {}
| 0 | Kotlin | 0 | 6 | ecf14fe132824e944818fda1123f1c7796c30532 | 1,452 | dsa-kotlin | MIT License |
aoc2023/src/main/kotlin/de/havox_design/aoc2023/day02/CubeConundrum.kt | Gentleman1983 | 737,309,232 | false | {"Kotlin": 746488, "Java": 441473, "Scala": 33415, "Groovy": 5725, "Python": 3319} | package de.havox_design.aoc2023.day02
class CubeConundrum(private var filename: String) {
fun solvePart1(): Long =
getResourceAsText(filename)
.mapNotNull(::getGameIdOfValidInputLine)
.sum()
.toLong()
fun solvePart2(): Long =
getResourceAsText(filename).sumOf { game ->
val indicators = parseIndicators(game)
val subsets = parseSubsets(indicators)
val (minRed, minGreen, minBlue) = getMinSetOfCubes(subsets)
(minRed * minGreen * minBlue).toLong()
}
private fun getGameIdOfValidInputLine(line: String): Int? {
val (game, indicators) = line.split(":")
val gameId = parseGameId(game)
val subsets = parseSubsets(indicators)
val valid = subsets.all(::isValidSubset)
return if (valid) gameId else null
}
private fun parseGameId(game: String): Int =
game
.filter { it.isDigit() }
.toInt()
private fun parseSubsets(indicators: String): List<Pair<String, Int>> =
indicators
.split(";", ",")
.map { sets -> sets.filter { it.isLetter() } to sets.filter { it.isDigit() }.toInt() }
private fun parseIndicators(string: String) =
string
.split(":")
.last()
private fun isValidSubset(subset: Pair<String, Int>): Boolean {
val (color, count) = subset
return when {
color == "red" && count <= 12 -> true
color == "green" && count <= 13 -> true
color == "blue" && count <= 14 -> true
else -> false
}
}
@SuppressWarnings("kotlin:S6611")
private fun getMinSetOfCubes(subsets: List<Pair<String, Int>>): Triple<Int, Int, Int> {
val countMap = mutableMapOf("red" to 0, "green" to 0, "blue" to 0)
subsets
.forEach { (color, count) ->
if (count > countMap[color]!!) {
countMap[color] = count
}
}
return Triple(countMap["red"]!!, countMap["green"]!!, countMap["blue"]!!)
}
private fun getResourceAsText(path: String): List<String> =
this.javaClass.classLoader.getResourceAsStream(path)!!.bufferedReader().readLines()
} | 4 | Kotlin | 0 | 1 | 35ce3f13415f6bb515bd510a1f540ebd0c3afb04 | 2,265 | advent-of-code | Apache License 2.0 |
src/test/kotlin/chapter4/boilerplate.kt | DavidGomesh | 680,857,367 | false | {"Kotlin": 204685} | package chapter4
import chapter3.Cons
import chapter3.List
import chapter3.Nil
fun <A, B> List<A>.map(f: (A) -> B): List<B> =
this.foldRight(
List.empty(),
{ a, b -> Cons(f(a), b) })
fun <A, B> List<A>.foldRight(z: B, f: (A, B) -> B): B =
when (this) {
is Nil -> z
is Cons -> f(this.head, this.tail.foldRight(z, f))
}
fun List<Double>.sum(): Double =
this.foldRight(0.0, { a, b -> a + b })
fun <A> List<A>.size(): Int =
this.foldRight(0, { _, acc -> 1 + acc })
fun List<Double>.isEmpty(): Boolean = when (this) {
is Nil -> true
is Cons -> false
}
fun <A, B, C> map2(
oa: Option<A>,
ob: Option<B>,
f: (A, B) -> C
): Option<C> =
oa.flatMap { a ->
ob.map { b ->
f(a, b)
}
}
fun <E, A, B> Either<E, A>.map(f: (A) -> B): Either<E, B> =
when (this) {
is Left -> this
is Right -> Right(f(this.value))
}
fun <E, A> Either<E, A>.orElse(f: () -> Either<E, A>): Either<E, A> =
when (this) {
is Left -> f()
is Right -> this
}
fun <E, A, B> Either<E, A>.flatMap(f: (A) -> Either<E, B>): Either<E, B> =
when (this) {
is Left -> this
is Right -> f(this.value)
}
fun <E, A, B, C> map2(
ae: Either<E, A>,
be: Either<E, B>,
f: (A, B) -> C
): Either<E, C> =
ae.flatMap { a -> be.map { b -> f(a, b) } }
| 0 | Kotlin | 0 | 0 | 41fd131cd5049cbafce8efff044bc00d8acddebd | 1,390 | fp-kotlin | MIT License |
src/main/java/dev/haenara/mailprogramming/solution/y2019/m08/d04/Solution190804.kt | HaenaraShin | 226,032,186 | false | null | package dev.haenara.mailprogramming.solution.y2019.m08.d04
import dev.haenara.mailprogramming.solution.Solution
/**
* 매일프로그래밍 2019. 08. 04
* 0, 1, 2로 이루어진 배열을 가장 효율적으로 정렬 하시오. 시간복잡도 O(n).
* Given an array consisting of 0, 1 and 2s, sort this array.
* Input: [0, 1, 2, 2, 0, 0, 0, 1]
* Output: [0, 0, 0, 0, 1, 1, 2, 2]
*
* 풀이
* 퀵소트마냥 양쪽에서 진행하면서 0과 2로만 채워진 정렬된 배열을 우선 만든다.
* 즉 좌측피벗이 2를 찾을때까지, 우측피벗이 0을 찾을때까지 진행하면서 정렬 되지 않은 0과 2를 찾으면 바꿔서 정렬하는 식이다.
* 최종적으로 좌측에는 0만, 우측에는 2만 모조리 채워넣고 정렬이 끝난 뒤 1의 갯수만큼 중간에 삽입한다.
*/
class Solution190804 : Solution<Array<Int>, Array<Int>>{
override fun solution(numbers: Array<Int>): Array<Int> {
var left = 0
var right = numbers.lastIndex
var leftMiddle = 0
var rightMiddle = 0
while (left < right) {
while (numbers[left] != 2 && left < right) {
if (numbers[left] == 1) {
numbers[left] = 0 // 좌측은 무조건 0
leftMiddle++ // 1은 갯수만 세두었다가 마지막에 채운다.
}
left++
}
while (numbers[right] != 0 && left < right) {
if (numbers[right] == 1) {
numbers[right] = 2 // 우측은 무조건 2
rightMiddle++ // 1은 갯수만 세두었다가 마지막에 채운다.
}
right--
}
if (left < right) {
swap(numbers, left, right)
} else {
when (numbers[left]) {
0 -> {
for (i in 0 until leftMiddle) {
numbers[left - i] = 1
}
}
1 -> {
for (i in 0 until leftMiddle) {
numbers[left - 1 - i] = 1
}
}
2 -> {
left
for (i in 0 until rightMiddle) {
numbers[left + i] = 1
}
for (i in 0 until leftMiddle) {
numbers[left -1 - i] = 1
}
}
}
break
}
}
return numbers
}
private fun swap(arr: Array<Int>, left: Int, right: Int) {
val temp = arr[right]
arr[right] = arr[left]
arr[left] = temp
}
}
| 0 | Kotlin | 0 | 7 | b5e50907b8a7af5db2055a99461bff9cc0268293 | 2,813 | MailProgramming | MIT License |
2019/07 - Amplification Circuit/kotlin/src/app.kt | Adriel-M | 225,250,242 | false | null | import java.io.File
import kotlin.math.pow
fun main() {
val instructions = getInstructions("../input2")
// println("===== Part 1 ===== ")
// println(runPart1(instructions))
println("===== Part 2 ===== ")
println(runPart2(instructions))
}
fun runPart1(instructions: List<Int>): Int {
val iter = PermutationIterator(0, 4)
var bestAmplification = -1
while (iter.hasNext()) {
var previousOutput = 0
for (i in iter.next()) {
val runner = ProgramRunner(instructions, listOf(i, previousOutput))
runner.runProgram()
previousOutput = runner.getOutputValue()
}
if (previousOutput > bestAmplification) {
bestAmplification = previousOutput
}
}
return bestAmplification
}
fun runPart2(instructions: List<Int>): Int {
val iter1 = PermutationIterator(0, 4)
var bestAmplification = -1
while (iter1.hasNext()) {
var previousOutput = 0
for (i in iter1.next()) {
val runner = ProgramRunner(instructions, listOf(i, previousOutput))
runner.runProgram()
previousOutput = runner.getOutputValue()
}
val wow = listOf(9, 8, 7, 6, 5)
for (i in wow) {
val runner = ProgramRunner(instructions, listOf(i, previousOutput))
runner.runProgram()
previousOutput = runner.getOutputValue()
}
if (previousOutput > bestAmplification) {
bestAmplification = previousOutput
}
// val iter2 = PermutationIterator(5, 9)
// while (iter2.hasNext()) {
// for (i in iter2.next()) {
// val runner = ProgramRunner(instructions, listOf(i, previousOutput))
// runner.runProgram()
// previousOutput = runner.getOutputValue()
// }
// if (previousOutput > bestAmplification) {
// bestAmplification = previousOutput
// }
// }
}
return bestAmplification
}
fun getInstructions(path: String): List<Int> {
val unparsedProgram = File(path).readLines()
return unparsedProgram[0].split(",").map { it.toInt() }
}
class PermutationIterator(private val minValue: Int, private val maxValue: Int): Iterator<List<Int>> {
private var currentState: MutableList<Int> = mutableListOf()
private val finalState = (maxValue downTo minValue).toList()
override fun hasNext(): Boolean {
return currentState != finalState
}
override fun next(): List<Int> {
if (currentState.size == 0) {
currentState = (minValue..maxValue).toMutableList()
} else {
generateNextPermutation()
}
return currentState
}
private fun generateNextPermutation() {
val decreasingIndex = findDecreasingIndexFromRight()
if (decreasingIndex < 0) {
reverse(0, currentState.size - 1)
return
}
var targetIndex = currentState.size - 1
while (targetIndex >= 0 && currentState[targetIndex] < currentState[decreasingIndex]) {
targetIndex--
}
swap(decreasingIndex, targetIndex)
swap(decreasingIndex + 1, currentState.size - 1)
}
private fun findDecreasingIndexFromRight(): Int {
var index = currentState.size - 2
while (index >= 0 && currentState[index + 1] < currentState[index]) {
index--
}
return index
}
private fun reverse(start: Int, end: Int) {
var i = start
var j = end
while (i < j) {
swap(i, j)
i++
j--
}
}
private fun swap(firstIndex: Int, secondIndex: Int) {
val tmp = currentState[firstIndex]
currentState[firstIndex] = currentState[secondIndex]
currentState[secondIndex] = tmp
}
}
class ProgramRunner(private val originalInstructions: List<Int>, private val inputValues: List<Int>) {
private val instructions = originalInstructions.toMutableList()
private var currentIndex = 0
private var inputIndex = 0
private var outputValue = -1
fun getOutputValue(): Int {
return outputValue
}
fun runProgram() {
while (currentIndex < instructions.size && getCurrentCommandType() != 99) {
val nextIndex = getNextIndex()
executeCommand()
currentIndex = nextIndex
}
}
private fun getCurrentCommandType(): Int {
return instructions[currentIndex] % 100
}
private fun getModeForOffset(offset: Int): Int {
val currentInstruction = instructions[currentIndex]
val divValue = 10.toFloat().pow(offset + 1).toInt()
return (currentInstruction / divValue) % 10
}
private fun executeCommand() {
when (getCurrentCommandType()) {
1 -> executeAddCommand()
2 -> executeMultiplyCommand()
3 -> executeInputCommand()
4 -> executeOutputCommand()
5, 6 -> noop()
7 -> executeLessThanAndStore()
8 -> executeEqualAndStore()
else -> throw IllegalArgumentException()
}
}
private fun executeAddCommand() {
val a = getValue(currentIndex + 1, getModeForOffset(1))
val b = getValue(currentIndex + 2, getModeForOffset(2))
val targetIndex = getValue(currentIndex + 3, 1)
instructions[targetIndex] = a + b
}
private fun executeMultiplyCommand() {
val a = getValue(currentIndex + 1, getModeForOffset(1))
val b = getValue(currentIndex + 2, getModeForOffset(2))
val targetIndex = getValue(currentIndex + 3, 1)
instructions[targetIndex] = a * b
}
private fun executeInputCommand() {
val targetIndex = getValue(currentIndex + 1, 1)
instructions[targetIndex] = inputValues[inputIndex]
inputIndex++
}
private fun executeOutputCommand() {
outputValue = getValue(currentIndex + 1, getModeForOffset(1))
}
private fun noop() {}
private fun executeLessThanAndStore() {
val a = getValue(currentIndex + 1, getModeForOffset(1))
val b = getValue(currentIndex + 2, getModeForOffset(2))
val targetIndex = getValue(currentIndex + 3, 1)
val valueToStore = if (a < b) 1 else 0
instructions[targetIndex] = valueToStore
}
private fun executeEqualAndStore() {
val a = getValue(currentIndex + 1, getModeForOffset(1))
val b = getValue(currentIndex + 2, getModeForOffset(2))
val targetIndex = getValue(currentIndex + 3, 1)
val valueToStore = if (a == b) 1 else 0
instructions[targetIndex] = valueToStore
}
private fun getValue(index: Int, mode: Int): Int {
val currentValue = instructions[index]
return when (mode) {
0 -> instructions[currentValue]
1 -> currentValue
else -> throw IllegalArgumentException()
}
}
private fun getNextIndex(): Int {
return when (getCurrentCommandType()) {
1, 2 -> currentIndex + 4
3 -> currentIndex + 2
4 -> instructions.size
5 -> {
val nextVal = getValue(currentIndex + 1, getModeForOffset(1))
val possiblePosition = getValue(currentIndex + 2, getModeForOffset(2))
if (nextVal != 0) {
possiblePosition
} else {
currentIndex + 3
}
}
6 -> {
val nextVal = getValue(currentIndex + 1, getModeForOffset(1))
val possiblePosition = getValue(currentIndex + 2, getModeForOffset(2))
if (nextVal == 0) {
possiblePosition
} else {
currentIndex + 3
}
}
7, 8 -> currentIndex + 4
else -> throw IllegalArgumentException()
}
}
}
| 0 | Kotlin | 0 | 0 | ceb1f27013835f13d99dd44b1cd8d073eade8d67 | 8,001 | advent-of-code | MIT License |
archive/src/main/kotlin/com/grappenmaker/aoc/year22/Day07.kt | 770grappenmaker | 434,645,245 | false | {"Kotlin": 409647, "Python": 647} | package com.grappenmaker.aoc.year22
import com.grappenmaker.aoc.PuzzleSet
import com.grappenmaker.aoc.queueOf
import kotlin.math.abs
fun PuzzleSet.day7() = puzzle {
val normalFiles = mutableMapOf<String, Int>()
val dirs = buildMap<String, List<String>> {
val stack = queueOf<String>()
val current = { stack.joinToString("/") }
inputLines.forEach { line ->
val split = line.split(" ")
if (line.startsWith("$")) {
if (split[1] == "cd") when {
split[2] == ".." -> stack.removeLast()
split[2] == "/" -> { /* ignore */ }
else -> stack.addLast(split[2])
}
} else {
val curr = current()
val new = (curr + "/" + split[1]).removePrefix("/")
this[curr] = getOrDefault(curr, listOf()) + new
if (split[0] != "dir") normalFiles[new] = split[0].toInt()
}
}
}
fun getSize(dir: String): Int = (dirs[dir] ?: listOf()).sumOf { v -> normalFiles[v] ?: getSize(v) }
val mapped = dirs.mapValues { (k) -> getSize(k) }
partOne = mapped.filter { (_, v) -> v <= 100000 }.values.sum().s()
val shouldFree = mapped[""]!! - (70000000 - 30000000)
val toDelete = mapped.filter { (_, u) -> u > shouldFree }.minBy { (_, u) -> abs(shouldFree - u) }.key
partTwo = mapped[toDelete].s()
} | 0 | Kotlin | 0 | 7 | 92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585 | 1,429 | advent-of-code | The Unlicense |
day14/src/main/kotlin/aoc2015/day14/Day14.kt | sihamark | 581,653,112 | false | {"Kotlin": 263428, "Shell": 467, "Batchfile": 383} | package aoc2015.day14
/**
* Created by <NAME> on 31.01.2019.
*/
object Day14 {
private const val RACE_DURATION = 2503
fun calculateDistanceOfWinningReindeer(): Int {
val reindeers = input.map { Parser.parse(it) }
return Race(reindeers, RACE_DURATION).calculateFarthestDistance()
}
fun calculatePointsOfBestReindeer(): Int {
val reindeers = input.map { Parser.parse(it) }
return Race(reindeers, RACE_DURATION).calculateMaximalPoints()
}
private data class Reindeer(
val name: String,
val speed: Int,
val speedingDuration: Int,
val restDuration: Int
) {
val cycleDuration = speedingDuration + restDuration
val cycleDistance = speed * speedingDuration
fun distanceAfter(duration: Int): Int {
val completeCycles = duration / cycleDuration
val completeCycleDuration = completeCycles * cycleDuration
val completeCycleDistance = completeCycles * cycleDistance
val remainingTime = duration - completeCycleDuration
val lastCycleSpeedingDuration = if (remainingTime > speedingDuration) speedingDuration else remainingTime
return completeCycleDistance + speed * lastCycleSpeedingDuration
}
}
private object Parser {
private val validDescription = Regex("""(\w+) can fly (\d+) km/s for (\d+) seconds, but then must rest for (\d+) seconds.""")
fun parse(rawReindeer: String): Reindeer {
val parsedValues = validDescription.find(rawReindeer)?.groupValues
?: error("invalid raw reindeer: $rawReindeer")
return Reindeer(
parsedValues[1],
parsedValues[2].toInt(),
parsedValues[3].toInt(),
parsedValues[4].toInt()
)
}
}
private class Race(
private val reindeers: List<Reindeer>,
private val duration: Int
) {
init {
if (reindeers.isEmpty()) error("must input at least one reindeer")
}
fun calculateFarthestDistance(): Int = reindeers
.map { it.distanceAfter(duration) }
.max()!!
fun calculateMaximalPoints(): Int {
val points = reindeers.associateWith { 0 }.toMutableMap()
(1..duration).forEach { passedSeconds ->
val reindeersDistance = reindeers.associateWith { it.distanceAfter(passedSeconds) }
val max = reindeersDistance.maxBy { it.value }!!.value
reindeersDistance.filterValues { it == max }
.forEach { (reindeer, _) -> points[reindeer] = points[reindeer]!! + 1 }
}
return points.values.max()!!
}
}
} | 0 | Kotlin | 0 | 0 | 6d10f4a52b8c7757c40af38d7d814509cf0b9bbb | 2,840 | aoc2015 | Apache License 2.0 |
kotlin/backtracking/MisWeighted.kt | polydisc | 281,633,906 | true | {"Java": 540473, "Kotlin": 515759, "C++": 265630, "CMake": 571} | package backtracking
import java.util.Random
object MisWeighted {
// maximum independent weighted set in O(3^(n/3))
// prerequisite: g[i] has i'th bit set
fun mis(g: LongArray, unused: Long, weights: IntArray): Int {
if (unused == 0L) return 0
var v = -1
var u: Int = Long.numberOfTrailingZeros(unused)
while (u < g.size) {
if (v == -1 || Long.bitCount(g[v] and unused) > Long.bitCount(g[u] and unused)) v = u
u += Long.numberOfTrailingZeros(unused shr u + 1) + 1
}
var res = 0
val nv = g[v] and unused
var y: Int = Long.numberOfTrailingZeros(nv)
while (y < g.size) {
res = Math.max(res, weights[y] + mis(g, unused and g[y].inv(), weights))
y += Long.numberOfTrailingZeros(nv shr y + 1) + 1
}
return res
}
// random test
fun main(args: Array<String?>?) {
val rnd = Random(1)
for (step in 0..999) {
val n: Int = rnd.nextInt(16) + 1
val g = LongArray(n)
val weights = IntArray(n)
for (i in 0 until n) weights[i] = rnd.nextInt(1000)
for (i in 0 until n) for (j in 0 until i) if (rnd.nextBoolean()) {
g[i] = g[i] or (1L shl j)
g[j] = g[j] or (1L shl i)
}
for (i in 0 until n) g[i] = g[i] or (1 shl i).toLong()
val res1 = mis(g, (1L shl n) - 1, weights)
val res2 = misSlow(g, weights)
if (res1 != res2) throw RuntimeException()
}
}
fun misSlow(g: LongArray, weights: IntArray): Int {
var res = 0
val n = g.size
for (set in 0 until 1 shl n) {
var ok = true
for (i in 0 until n) for (j in 0 until i) ok =
ok and (set and (1 shl i) == 0 || set and (1 shl j) == 0 || g[i] and (1L shl j) == 0L)
if (ok) {
var cur = 0
for (i in 0 until n) if (set and (1 shl i) != 0) cur += weights[i]
res = Math.max(res, cur)
}
}
return res
}
}
| 1 | Java | 0 | 0 | 4566f3145be72827d72cb93abca8bfd93f1c58df | 2,122 | codelibrary | The Unlicense |
year2020/day05/part1/src/main/kotlin/com/curtislb/adventofcode/year2020/day05/part1/Year2020Day05Part1.kt | curtislb | 226,797,689 | false | {"Kotlin": 2146738} | /*
--- Day 5: Binary Boarding ---
You board your plane only to discover a new problem: you dropped your boarding pass! You aren't sure
which seat is yours, and all of the flight attendants are busy with the flood of people that
suddenly made it through passport control.
You write a quick program to use your phone's camera to scan all of the nearby boarding passes (your
puzzle input); perhaps you can find your seat through process of elimination.
Instead of zones or groups, this airline uses binary space partitioning to seat people. A seat might
be specified like FBFBBFFRLR, where F means "front", B means "back", L means "left", and R means
"right".
The first 7 characters will either be F or B; these specify exactly one of the 128 rows on the plane
(numbered 0 through 127). Each letter tells you which half of a region the given seat is in. Start
with the whole list of rows; the first letter indicates whether the seat is in the front (0 through
63) or the back (64 through 127). The next letter indicates which half of that region the seat is
in, and so on until you're left with exactly one row.
For example, consider just the first seven characters of FBFBBFFRLR:
- Start by considering the whole range, rows 0 through 127.
- F means to take the lower half, keeping rows 0 through 63.
- B means to take the upper half, keeping rows 32 through 63.
- F means to take the lower half, keeping rows 32 through 47.
- B means to take the upper half, keeping rows 40 through 47.
- B keeps rows 44 through 47.
- F keeps rows 44 through 45.
- The final F keeps the lower of the two, row 44.
The last three characters will be either L or R; these specify exactly one of the 8 columns of seats
on the plane (numbered 0 through 7). The same process as above proceeds again, this time with only
three steps. L means to keep the lower half, while R means to keep the upper half.
For example, consider just the last 3 characters of FBFBBFFRLR:
- Start by considering the whole range, columns 0 through 7.
- R means to take the upper half, keeping columns 4 through 7.
- L means to take the lower half, keeping columns 4 through 5.
- The final R keeps the upper of the two, column 5.
So, decoding FBFBBFFRLR reveals that it is the seat at row 44, column 5.
Every seat also has a unique seat ID: multiply the row by 8, then add the column. In this example,
the seat has ID 44 * 8 + 5 = 357.
Here are some other boarding passes:
- BFFFBBFRRR: row 70, column 7, seat ID 567.
- FFFBBBFRRR: row 14, column 7, seat ID 119.
- BBFFBBFRLL: row 102, column 4, seat ID 820.
As a sanity check, look through your list of boarding passes. What is the highest seat ID on a
boarding pass?
*/
package com.curtislb.adventofcode.year2020.day05.part1
import com.curtislb.adventofcode.year2020.day05.boarding.Seat
import java.nio.file.Path
import java.nio.file.Paths
/**
* Returns the solution to the puzzle for 2020, day 5, part 1.
*
* @param inputPath The path to the input file for this puzzle.
*/
fun solve(inputPath: Path = Paths.get("..", "input", "input.txt")): Int? {
val file = inputPath.toFile()
var highestId: Int? = null
file.forEachLine { line ->
val seat = Seat.from(line)
highestId = highestId?.coerceAtLeast(seat.id) ?: seat.id
}
return highestId
}
fun main() = when (val solution = solve()) {
null -> println("No solution found.")
else -> println(solution)
}
| 0 | Kotlin | 1 | 1 | 6b64c9eb181fab97bc518ac78e14cd586d64499e | 3,418 | AdventOfCode | MIT License |
src/main/kotlin/g1801_1900/s1900_the_earliest_and_latest_rounds_where_players_compete/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1801_1900.s1900_the_earliest_and_latest_rounds_where_players_compete
// #Hard #Dynamic_Programming #Memoization #2023_06_22_Time_142_ms_(100.00%)_Space_33.6_MB_(100.00%)
class Solution {
fun earliestAndLatest(n: Int, firstPlayer: Int, secondPlayer: Int): IntArray {
var p1 = Math.min(firstPlayer, secondPlayer)
var p2 = Math.max(firstPlayer, secondPlayer)
if (p1 + p2 == n + 1) {
// p1 and p2 compete in the first round
return intArrayOf(1, 1)
}
if (n == 3 || n == 4) {
// p1 and p2 must compete in the second round (only two rounds).
return intArrayOf(2, 2)
}
// Flip to make p1 be more closer to left than p2 to right end for convenience
if (p1 - 1 > n - p2) {
val t = n + 1 - p1
p1 = n + 1 - p2
p2 = t
}
val m = (n + 1) / 2
var min = n
var max = 1
if (p2 * 2 <= n + 1) {
// p2 is in first half (n odd or even) or exact middle (n odd)
// 1 2 3 4 5 6 7 8 9 10 11 12 13 14
// . . * . . * . . . . . . . .
// ^ ^
// p1 p2
// Group A are players in front of p1
// Group B are players between p1 and p2
val a = p1 - 1
val b = p2 - p1 - 1
// i represents number of front players in A wins
// j represents number of front players in B wins
for (i in 0..a) {
for (j in 0..b) {
val ret = earliestAndLatest(m, i + 1, i + j + 2)
min = Math.min(min, 1 + ret[0])
max = Math.max(max, 1 + ret[1])
}
}
} else {
// p2 is in the later half (and has >= p1 distance to the end)
// 1 2 3 4 5 6 7 8 9 10 11 12 13 14
// . . * . . . . . . * . . . .
// ^ ^
// p1 p4 p2 p3
// ^--------------^
// ^--------------------------^
val p4 = n + 1 - p2
val a = p1 - 1
val b = p4 - p1 - 1
// Group C are players between p4 and p2, (c+1)/2 will advance to next round.
val c = p2 - p4 - 1
for (i in 0..a) {
for (j in 0..b) {
val ret = earliestAndLatest(m, i + 1, i + j + 1 + (c + 1) / 2 + 1)
min = Math.min(min, 1 + ret[0])
max = Math.max(max, 1 + ret[1])
}
}
}
return intArrayOf(min, max)
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 2,756 | LeetCode-in-Kotlin | MIT License |
Coding Challenges/Advent of Code/2021/Day 11/part2.kt | Alphabeater | 435,048,407 | false | {"Kotlin": 69566, "Python": 5974} | import java.io.File
import java.util.Scanner
val octopusMatrix: ArrayList<ArrayList<Int>> = arrayListOf() //energy matrix of the octupi.
val octopusMatrixFlash: ArrayList<ArrayList<Boolean>> = arrayListOf() //keep track of which octopi flashed.
fun sincronizationOfFlashes(n: Int): Boolean {
var count = 0
for (l in octopusMatrix) {
count += l.count { it == 0 }
}
return count == n*n
}
fun addtoNeighbors(i: Int, j: Int, n: Int) { //recursive function that gets valid neighbors and add energy to them.
var directions = mutableListOf(true, true, true, true, true, true, true, true) //N NE E SE S SW W NW
octopusMatrixFlash[i][j] = true //this particular octopus already flashed, so it should not flash again.
if (i == 0) { //N
directions[7] = false
directions[0] = false
directions[1] = false
}
if (i == n - 1) { //S
directions[3] = false
directions[4] = false
directions[5] = false
}
if (j == 0) { //W
directions[5] = false
directions[6] = false
directions[7] = false
}
if (j == n - 1) { //E
directions[1] = false
directions[2] = false
directions[3] = false
}
for ((k, d) in directions.withIndex()) //N NE E SE S SW W NW
if (d) when (k) { //all possibilities (if direction, then repeat recursive function for this neighbor.
0 -> { //N
helper(i - 1, j, n)
}
1 -> { //NE
helper(i - 1, j + 1, n)
}
2 -> { //E
helper(i, j + 1, n)
}
3 -> { //SE
helper(i + 1, j + 1, n)
}
4 -> { //S
helper(i + 1, j, n)
}
5 -> { //SW
helper(i + 1, j - 1, n)
}
6 -> { //W
helper(i, j - 1, n)
}
7 -> { //NW
helper(i - 1, j - 1, n)
}
}
}
fun helper(i: Int, j: Int, n: Int) { //function to avoid boilerplate.
octopusMatrix[i][j]++
if (!octopusMatrixFlash[i][j] && octopusMatrix[i][j] > 9) addtoNeighbors(i, j, n) //if it's not already flashed but has more than 9 energy.
}
fun zeroAndPrintMatrix(n: Int) {
for (i in 0 until n) {
for (j in 0 until n) {
if (octopusMatrix[i][j] > 9) octopusMatrix[i][j] = 0
// if (octopusMatrix[i][j] != 0) print("\u001b[0;37m${octopusMatrix[i][j]}\u001B[0m ") //optional
// else print("\u001B[0;29m${octopusMatrix[i][j]}\u001B[0m ") //optional
}
// println() //optional
}
// println() //optional
}
fun falseMatrix(n: Int) {
for (i in 0 until n)
for (j in 0 until n)
octopusMatrixFlash[i][j] = false
}
fun main() {
val file = File("src/input.txt")
val scanner = Scanner(file)
while (scanner.hasNextLine()) {
val line = scanner.nextLine()!!
octopusMatrix.add(line.map { it.digitToInt() } as ArrayList<Int>)
}
val n = octopusMatrix.size //assuming matrix is NxN.
for (i in 0 until n) {
octopusMatrixFlash.add(arrayListOf(false, false, false, false, false, false, false, false, false, false))
}
// zeroAndPrintMatrix(n) //optional
var step = 0 //keeps track of the step number.
while (!sincronizationOfFlashes(n)) { //breaks the loop if all of the octopi flash at the same time.
step++
for (i in 0 until n)
for (j in 0 until n) {
octopusMatrix[i][j]++
if (octopusMatrix[i][j] > 9) {
if (!octopusMatrixFlash[i][j]) addtoNeighbors(i, j, n)
}
}
zeroAndPrintMatrix(n) //change values > 9 to 0 (just to print it better).
falseMatrix(n) //need to give false values on all flash matrix to use in the next iteration.
}
println(step)
}
| 0 | Kotlin | 0 | 0 | 05c8d4614e025ed2f26fef2e5b1581630201adf0 | 3,943 | Archive | MIT License |
src/main/kotlin/days/Day14.kt | hughjdavey | 317,575,435 | false | null | package days
class Day14 : Day(14) {
// 11327140210986
override fun partOne(): Any {
return InstructionRunner().run(getInstructions(true))
}
// 2308180581795
override fun partTwo(): Any {
return InstructionRunner().run(getInstructions(false))
}
fun getInstructions(v1: Boolean, input: List<String> = inputList): List<MaskedInstruction> {
return input.fold("" to listOf<MaskedInstruction>()) { (mask, ins), line ->
if (line.startsWith("mask")) line.replace("mask = ", "") to ins else {
val assignment = Regex("mem\\[(\\d+)] = (\\d+)").matchEntire(line)!!.groupValues
val (addr, value) = assignment[1] to assignment[2]
mask to ins.plus(getInstruction(mask, value.toLong(), addr.toLong(), v1))
}
}.second
}
private fun getInstruction(mask: String, value: Long, addr: Long, v1: Boolean): MaskedInstruction {
return if (v1) MaskedInstructionV1(mask, value, addr) else MaskedInstructionV2(mask, value, addr)
}
interface MaskedInstruction {
val mask: String
val unmaskedValue: Long
val unmaskedMemoryAddress: Long
val memoryAddresses: List<Long>
val maskedValue: Long
}
data class MaskedInstructionV1(override val mask: String, override val unmaskedValue: Long, override val unmaskedMemoryAddress: Long) : MaskedInstruction {
override val memoryAddresses = listOf(unmaskedMemoryAddress)
override val maskedValue: Long by lazy {
val unmaskedBin = unmaskedValue.toString(2).padStart(mask.length, '0')
unmaskedBin.mapIndexed { index, c -> if (mask[index] == 'X') c else mask[index] }.joinToString("").toLong(2)
}
}
data class MaskedInstructionV2(override val mask: String, override val unmaskedValue: Long, override val unmaskedMemoryAddress: Long) : MaskedInstruction {
override val maskedValue = unmaskedValue
override val memoryAddresses: List<Long> by lazy {
val unmaskedBin = unmaskedMemoryAddress.toString(2).padStart(mask.length, '0')
val result = unmaskedBin.mapIndexed { index, c -> if (mask[index] == '0') c else mask[index] }.joinToString("")
allBinariesOfLength(result.count { it == 'X' })
.map { result.replace("X", "%s").format(*it.toList().toTypedArray()) }
.map { it.toLong(2) }
}
companion object {
// e.g. if length = 2, this returns ["00", "01", "10", "11"]
fun allBinariesOfLength(length: Int): List<String> {
val high = "1".repeat(length).toLong(2)
return (high downTo 0).map { it.toString(2).padStart(length, '0') }
}
}
}
class InstructionRunner {
// had to use a map as the indices in part 2 exceed Integer.MAX_VALUE
private val memory = mutableMapOf<Long, Long>()
fun run(instructions: List<MaskedInstruction>): Long {
instructions.forEach { instruction ->
instruction.memoryAddresses.forEach { addr -> memory[addr] = instruction.maskedValue }
}
return memory.values.sum()
}
}
}
| 0 | Kotlin | 0 | 1 | 63c677854083fcce2d7cb30ed012d6acf38f3169 | 3,243 | aoc-2020 | Creative Commons Zero v1.0 Universal |
year2023/src/main/kotlin/net/olegg/aoc/year2023/day17/Day17.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2023.day17
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.utils.Directions
import net.olegg.aoc.utils.Vector2D
import net.olegg.aoc.utils.fit
import net.olegg.aoc.utils.get
import net.olegg.aoc.year2023.DayOf2023
import java.util.PriorityQueue
/**
* See [Year 2023, Day 17](https://adventofcode.com/2023/day/17)
*/
object Day17 : DayOf2023(17) {
private val FINISH = Vector2D(
x = matrix.last().lastIndex,
y = matrix.lastIndex,
)
override fun first(): Any? {
val seen = mutableSetOf<Config>()
val queue = PriorityQueue<Pair<Config, Int>>(
compareBy(
{ it.second },
{ -it.first.pos.manhattan() },
),
)
queue.add(Config(Vector2D(), Directions.R, 0) to 0)
while (queue.isNotEmpty()) {
val (config, score) = queue.remove()
if (config in seen) {
continue
}
seen += config
if (config.pos == FINISH) {
return score
}
val forward = config.pos + config.dir.step
if (config.count < 3 && matrix.fit(forward)) {
queue.add(
Config(
pos = forward,
dir = config.dir,
count = config.count + 1,
) to (score + matrix[forward]!!.digitToInt()),
)
}
listOfNotNull(Directions.CW[config.dir], Directions.CCW[config.dir])
.filter { matrix.fit(config.pos + it.step) }
.forEach {
val next = config.pos + it.step
queue.add(
Config(
pos = next,
dir = it,
count = 1,
) to (score + matrix[next]!!.digitToInt()),
)
}
}
return null
}
override fun second(): Any? {
val seen = mutableSetOf<Config>()
val queue = PriorityQueue<Pair<Config, Int>>(
compareBy(
{ it.second },
{ -it.first.pos.manhattan() },
),
)
queue.add(Config(Vector2D(), Directions.R, 0) to 0)
queue.add(Config(Vector2D(), Directions.D, 0) to 0)
while (queue.isNotEmpty()) {
val (config, score) = queue.remove()
if (config in seen) {
continue
}
seen += config
if (config.pos == FINISH) {
return score
}
queue += listOfNotNull(Directions.CW[config.dir], Directions.CCW[config.dir])
.flatMap { dir ->
(1..10).scan(config to score) { (prev, acc), _ ->
val next = prev.pos + dir.step
Config(
pos = next,
dir = dir,
count = 0,
) to (acc + (matrix[next]?.digitToInt() ?: 0))
}
.drop(4)
.filter { matrix.fit(it.first.pos) }
}
}
return null
}
data class Config(
val pos: Vector2D,
val dir: Directions,
val count: Int,
)
}
fun main() = SomeDay.mainify(Day17)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 2,853 | adventofcode | MIT License |
src/main/kotlin/data/CDataClass.kt | tamilschool | 711,222,508 | false | {"Kotlin": 153687, "HTML": 1758} | package data
data class CQuestionState(
var selectedGroup: Group,
var selectedRound: Round,
var selectedTopic: Topic,
var round2Kurals: List<Thirukkural>,
var athikaramState: CAthikaramState,
var kuralState: CThirukkuralState,
var porulState: CThirukkuralState,
var firstWordState: CFirstWordState,
var lastWordState: CLastWordState,
var timerState: CTimerState,
var scoreState: ScoreState
) {
fun getCurrentQuestion(): String {
return when (selectedTopic) {
Topic.Athikaram -> athikaramState.getCurrent()
Topic.Porul -> porulState.getCurrent().porul
Topic.Kural -> kuralState.getCurrent().kural.toString()
Topic.FirstWord -> firstWordState.getCurrent()
Topic.LastWord -> lastWordState.getCurrent()
Topic.AllKurals -> "Error"
}
}
private fun getIndexQuestion(index: Int): String {
return when (selectedTopic) {
Topic.Athikaram -> athikaramState.targets[index]
Topic.Porul -> porulState.targets[index].porul
Topic.Kural -> kuralState.targets[index].kural.toString()
Topic.FirstWord -> firstWordState.targets[index]
Topic.LastWord -> lastWordState.targets[index]
Topic.AllKurals -> "Error"
}
}
fun isAnswered(): Boolean =
scoreState.group23Score.round2[selectedTopic]?.contains(getCurrentQuestion()) ?: false
fun isAnswered(index: Int): Boolean =
scoreState.group23Score.round2[selectedTopic]?.contains(getIndexQuestion(index)) ?: false
fun maxQuestionsAnswered(): Boolean {
val currentAnsweredCount: Int = scoreState.group23Score.round2[selectedTopic]?.size ?: 0
return !isAnswered() && (currentAnsweredCount >= maxAnswers)
}
}
data class CTimerState(
var isLive: Boolean = false,
var isPaused: Boolean = false,
var time: Long = 1201
)
const val maxQuestions = 15
const val maxAnswers = 10
data class CAthikaramState(
override var targets: List<String>,
override var index: Int
) : CHistoryState<String> {
constructor(targets: List<Thirukkural>, expected: List<String>) : this(cGetAthikarams(targets, maxQuestions, expected), 0)
}
data class CThirukkuralState(
override var targets: List<Thirukkural>,
override var index: Int
) : CHistoryState<Thirukkural> {
constructor(targets: List<Thirukkural>) : this(targets.shuffled().take(maxQuestions).toList(), 0)
}
data class CFirstWordState(
override var targets: List<String>,
override var index: Int
) : CHistoryState<String> {
constructor(targets: List<Thirukkural>) : this(cGetFirstWords(targets, maxQuestions), 0)
}
data class CLastWordState(
override var targets: List<String>,
override var index: Int
) : CHistoryState<String> {
constructor(targets: List<Thirukkural>) : this(cGetLastWords(targets, maxQuestions), 0)
}
fun cGetAthikarams(thirukkurals: List<Thirukkural>, max: Int, expected: List<String>) =
expected + thirukkurals.shuffled()
.map { it.athikaram }
.distinct()
.filter { !expected.contains(it) }
.take(max - expected.size)
fun cGetFirstWords(thirukkurals: List<Thirukkural>, max: Int) =
thirukkurals.shuffled().map { it.words.first() }.distinct().take(max)
fun cGetLastWords(thirukkurals: List<Thirukkural>, max: Int) =
thirukkurals.shuffled().map { it.words.last() }.distinct().take(max)
interface CHistoryState<T> {
var index: Int
var targets: List<T>
fun getCurrent(): T = targets[index]
fun goNext() {
index++
if (index == targets.size) {
index = 0
}
println("${this::class} Moved to : $index of Total: ${targets.size}")
}
fun goPrevious() {
--index
if (index < 0) {
index = targets.size - 1
}
println("${this::class} Moved to : $index of Total: ${targets.size}")
}
fun go(targetIndex: Int) {
if (index >= 0 && index < targets.size) {
index = targetIndex
println("${this::class} Moved to : $index of Total: ${targets.size}")
}
}
}
enum class Group23Round1Type {
KURAL, PORUL;
}
enum class Group1RoundType(val tamil: String) {
KURAL("குறள்"),
PORUL("பொருள்"),
CLARITY("உச்சரிப்பு")
}
data class ScoreState(
val group1Score: Group1Score = Group1Score(),
val group23Score: Group23Score = Group23Score()
)
data class Group1Score(
var round1: MutableMap<Int, Group1Round1Score> = mutableMapOf(),
var bonus: Number = 0
) {
fun getKuralCount(): Int {
return round1.values
.mapNotNull { it.score[Group1RoundType.KURAL] }
.count { it > 0 }
}
fun getPorulCount(): Int {
return round1.values
.mapNotNull { it.score[Group1RoundType.PORUL] }
.count { it > 0 }
}
fun getDollars(scoreType: ScoreType): Float {
return when (scoreType) {
ScoreType.KuralOnly -> getKuralCount().toFloat()
else -> (getKuralCount().toFloat() + getPorulCount().toFloat()) / 2
}
}
fun getAnsweredKuralList(): String =
round1.filter { it.value.score.values.sum() > 0 }.keys.joinToString(",")
fun getScore(type: Group1RoundType): Float = round1.values.mapNotNull { it.score[type] }.sum()
fun getTotal(): Float =
getScore(Group1RoundType.KURAL) + getScore(Group1RoundType.PORUL) + getScore(Group1RoundType.CLARITY) + bonus.toFloat()
}
data class Group1Round1Score(
var thirukkural: Thirukkural,
var score: MutableMap<Group1RoundType, Float> = Group1RoundType.values().associateWith { 0F }
.toMutableMap()
)
data class Group23Score(
val round1: MutableMap<Int, Group23Round1Score> = mutableMapOf(),
val round2: Map<Topic, MutableSet<String>> = Topic.values()
.filter { it != Topic.AllKurals }
.associateWith { mutableSetOf() }
) {
fun getKuralCount(): Int = round1.values.count { it.score[Group23Round1Type.KURAL] == true }
fun getPorulCount(): Int = round1.values.count { it.score[Group23Round1Type.PORUL] == true }
fun getDollars(): Float = (getKuralCount().toFloat() + getPorulCount().toFloat()) / 2
fun getAnsweredKuralList(): String =
round1.filter { it.value.score.values.contains(true) }.keys.joinToString(",")
fun getScore(topic: Topic): Int = round2[topic]?.count() ?: 0
fun getTotal(): Int = round2.values.flatten().count()
}
data class Group23Round1Score(
var thirukkural: Thirukkural,
var score: MutableMap<Group23Round1Type, Boolean> = Group23Round1Type.values()
.associateWith { false }.toMutableMap()
)
| 0 | Kotlin | 0 | 0 | 39190f307d6f4ebdd63c5727dee4b89ff80176b6 | 6,330 | tamilschool.github.io | Apache License 2.0 |
src/main/kotlin/aoc2022/Day22.kt | lukellmann | 574,273,843 | false | {"Kotlin": 175166} | package aoc2022
import AoCDay
import aoc2022.Day22.Direction.*
import aoc2022.Day22.Space.*
import util.illegalInput
// https://adventofcode.com/2022/day/22
object Day22 : AoCDay<Int>(
title = "Monkey Map",
part1ExampleAnswer = 6032,
part1Answer = 50412,
part2ExampleAnswer = null,
part2Answer = null,
) {
private enum class Space { EMPTY, TILE, WALL }
private fun parseMap(input: String): Array<Array<Space>> {
val lines = input.lines()
val maxLength = lines.maxOf { it.length }
val map = Array(lines.size) { Array(size = maxLength) { EMPTY } }
for ((row, line) in lines.withIndex()) {
for ((col, char) in line.withIndex()) {
map[row][col] = when (char) {
' ' -> EMPTY
'.' -> TILE
'#' -> WALL
else -> illegalInput(input)
}
}
}
return map
}
private sealed interface Path {
object Right : Path
object Left : Path
class Number(val number: Int) : Path
}
private fun parsePath(input: String) = sequence {
val num = StringBuilder()
suspend fun SequenceScope<Path>.yieldNum() {
if (num.isNotEmpty()) {
yield(Path.Number(num.toString().toInt()))
num.clear()
}
}
for (char in input) {
when (char) {
'R' -> {
yieldNum()
yield(Path.Right)
}
'L' -> {
yieldNum()
yield(Path.Left)
}
in '0'..'9' -> num.append(char)
else -> illegalInput(input)
}
}
yieldNum()
}
private enum class Direction { RIGHT, DOWN, LEFT, UP }
override fun part1(input: String): Int {
val (m, p) = input.split("\n\n", limit = 2)
val map = parseMap(m)
var row = 0
var col = map[row].indexOf(TILE)
var facing = RIGHT
for (path in parsePath(p)) {
when (path) {
Path.Right -> facing = when (facing) {
RIGHT -> DOWN
DOWN -> LEFT
LEFT -> UP
UP -> RIGHT
}
Path.Left -> facing = when (facing) {
RIGHT -> UP
DOWN -> RIGHT
LEFT -> DOWN
UP -> LEFT
}
is Path.Number -> repeat(path.number) {
when (facing) {
RIGHT -> {
val r = map[row]
var c = (col + 1) % r.size
while (r[c] == EMPTY) c = (c + 1) % r.size
if (r[c] == TILE) col = c
}
DOWN -> {
var r = (row + 1) % map.size
while (map[r][col] == EMPTY) r = (r + 1) % map.size
if (map[r][col] == TILE) row = r
}
LEFT -> {
val r = map[row]
var c = (col - 1).mod(r.size)
while (r[c] == EMPTY) c = (c - 1).mod(r.size)
if (r[c] == TILE) col = c
}
UP -> {
var r = (row - 1).mod(map.size)
while (map[r][col] == EMPTY) r = (r - 1).mod(map.size)
if (map[r][col] == TILE) row = r
}
}
}
}
}
return 1000 * (row + 1) + 4 * (col + 1) + facing.ordinal
}
// for future me
override fun part2(input: String) = 0
}
| 0 | Kotlin | 0 | 1 | 344c3d97896575393022c17e216afe86685a9344 | 3,946 | advent-of-code-kotlin | MIT License |
app/src/main/java/com/joyfulmath/datastructandalgorithms/algorthms/MaximumSubarray.kt | demanluandyuki | 130,544,190 | false | null | package com.joyfulmath.datastructandalgorithms.algorthms
import com.joyfulmath.datastructandalgorithms.utils.TraceLog
/**
* leetcode 53
*/
class MaximumSubarray {
companion object {
fun maxSubArray(nums: IntArray): Int {
return maxSumRec(nums, 0, nums.lastIndex)
}
/**
* 分治思想,先获得左边最大值。右边最大值,还有一种是中间值是最大值。
*/
fun maxSumRec(nums: IntArray, left: Int, right: Int): Int {
if (left == right) {
return when {
nums[left] > 0 -> nums[left]
else -> 0
}
}
var center = (left + right) / 2
var maxLeftSum = maxSumRec(nums, left, center)
var maxRightSum = maxSumRec(nums, center + 1, right)
var maxLeftBorderSum = Int.MIN_VALUE
var leftBorderSum = Int.MIN_VALUE
for (i in center downTo left) {
leftBorderSum += nums[i]
if (leftBorderSum > maxLeftBorderSum) {
maxLeftBorderSum = leftBorderSum
}
}
var maxRightBorderSum = Int.MIN_VALUE
var rightBorderSum = Int.MIN_VALUE
for (i in (center + 1)..right) {
rightBorderSum += nums[i]
if (rightBorderSum > maxRightBorderSum) {
maxRightBorderSum = rightBorderSum
}
}
// TraceLog.i("maxLeftSum:$maxLeftSum,maxRightSum:$maxRightSum,maxLeftBorderSum + maxRightBorderSum:${maxLeftBorderSum + maxRightBorderSum}")
return Math.max(Math.max(maxLeftSum, maxRightSum), maxLeftBorderSum + maxRightBorderSum)
}
fun sample(){
TraceLog.i()
var numArray:IntArray = intArrayOf(1,2,3,-2,10,-5,12,11,3,-8,18)
TraceLog.i("${maxSubArray(numArray)}")
}
}
} | 0 | Kotlin | 0 | 0 | ae9c577a264929788430368868391fe534f750bf | 1,961 | datastructure | MIT License |
src/Day03.kt | Tiebe | 579,377,778 | false | {"Kotlin": 17146} | fun main() {
fun part1(input: List<String>): Int {
var total = 0
for (bag in input) {
val firstHalf = bag.substring(0, bag.length/2)
val secondHalf = bag.substring(bag.length/2)
for (it in firstHalf) {
if (it in secondHalf) {
total += if (it.isUpperCase()) {
it.code - 65 + 26 + 1
} else {
it.code - 97 + 1
}
break
}
}
}
return total
}
fun part2(input: List<String>): Int {
val letters = mutableListOf<Char>()
val groups = mutableListOf<List<String>>()
val groupList = mutableListOf<String>()
input.forEachIndexed { index, bag ->
groupList.add(bag)
if ((index+1) % 3 == 0) {
groups.add(groupList.toMutableList())
groupList.clear()
}
}
groups.forEach {
for (letter in it[0]) {
if (letter in it[1] && letter in it[2]) {
letters.add(letter)
break
}
}
}
var total = 0
letters.forEach {
total += if (it.isUpperCase()) {
it.code - 65 + 26 + 1
} else {
it.code - 97 + 1
}
}
return total
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
part1(input).println()
part2(input).println()
} | 1 | Kotlin | 0 | 0 | afe9ac46b38e45bd400e66d6afd4314f435793b3 | 1,746 | advent-of-code | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/SnakesAndLadders.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import java.util.LinkedList
import java.util.Queue
/**
* 909. Snakes and Ladders
* @see <a href="https://leetcode.com/problems/snakes-and-ladders/">Source</a>
*/
fun interface SnakesAndLadders {
operator fun invoke(board: Array<IntArray>): Int
}
class SnakesAndLaddersBFS : SnakesAndLadders {
override operator fun invoke(board: Array<IntArray>): Int {
if (board.isEmpty() || board[0].isEmpty()) {
return -1
}
val rows: Int = board.size
val cols: Int = board[0].size
val dest = rows * cols
val queue: Queue<Int> = LinkedList()
queue.offer(1)
val set: MutableSet<Int> = HashSet()
set.add(1)
var steps = 0
while (queue.isNotEmpty()) {
val size: Int = queue.size
for (i in 0 until size) {
val curr: Int = queue.poll()
if (curr == dest) {
return steps
}
var diff = 1
while (diff <= 6 && curr + diff <= dest) {
val pos = getCoordinate(curr + diff, rows, cols)
val next = if (board[pos[0]][pos[1]] == -1) curr + diff else board[pos[0]][pos[1]]
if (!set.contains(next)) {
queue.offer(next)
set.add(next)
}
diff++
}
}
steps++
}
return -1
}
private fun getCoordinate(n: Int, rows: Int, cols: Int): IntArray {
val r = rows - 1 - (n - 1) / cols
val c = (n - 1) % cols
return if (r % 2 == rows % 2) {
intArrayOf(r, cols - 1 - c)
} else {
intArrayOf(r, c)
}
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,409 | kotlab | Apache License 2.0 |
kotlin/src/main/kotlin/dev/mikeburgess/euler/problems/Problem030.kt | mddburgess | 261,028,925 | false | null | package dev.mikeburgess.euler.problems
import dev.mikeburgess.euler.common.digits
import kotlin.math.pow
/**
* Problem 30
*
* Surprisingly there are only three numbers that can be written as the sum of fourth powers of
* their digits:
*
* 1634 = 1^4 + 6^4 + 3^4 + 4^4
* 8208 = 8^4 + 2^4 + 0^4 + 8^4
* 9474 = 9^4 + 4^4 + 7^4 + 4^4
*
* As 1 = 1^4 is not a sum it is not included.
*
* The sum of these numbers is 1634 + 8208 + 9474 = 19316.
*
* Find the sum of all the numbers that can be written as the sum of fifth powers of their digits.
*/
class Problem030 : Problem {
private val fifthPowers = (0..9).map { it.toDouble().pow(5).toInt() }
override fun solve(): Long =
(2..354294)
.associateWith { it.digits.map { digit -> fifthPowers[digit] }.sum() }
.filter { (number, digitSum) -> number == digitSum }
.keys.sum().toLong()
}
| 0 | Kotlin | 0 | 0 | 86518be1ac8bde25afcaf82ba5984b81589b7bc9 | 899 | project-euler | MIT License |
src/main/kotlin/dev/bogwalk/batch2/Problem25.kt | bog-walk | 381,459,475 | false | null | package dev.bogwalk.batch2
import dev.bogwalk.util.strings.digitCount
import java.math.BigInteger
import kotlin.math.*
/**
* Problem 25: N-digit Fibonacci Number
*
* https://projecteuler.net/problem=25
*
* Goal: Find the first term in the Fibonacci sequence to have N digits.
*
* Constraints: 2 <= N <= 5000
*
* e.g.: N = 3
* Fibonacci sequence = {0,1,1,2,3,5,8,13,21,34,55,89,144}
* first term with 3 digits = F(12)
*/
class NDigitFibonacciNumber {
private val phi = (1 + sqrt(5.0)) / 2
/**
* Iterative solution that checks all Fibonacci numbers.
*
* SPEED (WORST for low N) 1.2ms for N = 10
* SPEED (BETTER for high N) 666.91ms for N = 5000
*
* @return list of the first Fibonacci terms to have (index + 2) digits.
*/
fun nDigitFibTermsBrute(maxDigits: Int): IntArray {
var term = 7
var fN = BigInteger.valueOf(13)
val terms = IntArray(maxDigits - 1).apply { this[0] = term }
var fNMinus1 = BigInteger.valueOf(8)
var digits = 3
while (digits <= maxDigits) {
term++
val fNMinus2 = fNMinus1
fNMinus1 = fN
fN = fNMinus1 + fNMinus2
if (fN.digitCount() == digits) {
terms[digits++ - 2] = term
}
}
return terms
}
/**
* Iterative solution uses the Golden Ratio to check all Fibonacci numbers.
*
* Original solution compared digit lengths by casting fN to a String. This
* has been replaced by calling log10(fN) and comparing it to the required digits minus 1,
* with significant performance improvement.
*
* SPEED (BETTER for low N) 4.0e4ns for N = 10
* SPEED (IMPOSSIBLE for N > 10) Significantly slower execution due to the exponential need
* to calculate larger Phi^N and resulting OverflowError
*
* @return first Fibonacci term to have N digits.
*/
fun nDigitFibTermGoldenBrute(n: Int): Int {
var term = 7
var fN = 13
// pattern shows the amount of digits increases every 4th-5th term
val step = 4
while (log10(1.0 * fN) < n - 1) {
term += step
fN = nthFibUsingGoldenRatio(term)
while (log10(1.0 * fN) < n - 1) {
term++
fN = nthFibUsingGoldenRatio(term)
}
}
return term
}
/**
* Finds the [n]th Fibonacci number using Binet's formula.
*
* The Golden Ration, Phi, provides an alternative to iteration, based on the closed-form
* formula:
*
* Fn = (Phi^n - Psi^n) / sqrt(5),
* with Phi = (1 + sqrt(5)) / 2 ~= 1.61803... & Psi = -Phi^-1
*
* Rounding, using the nearest integer function, reduces the formula to:
*
* Fn = round(Phi^n / sqrt(5)), where n >= 0.
*
* Truncation, using the floor function, would result instead in:
*
* Fn = floor((Phi^n / sqrt(5)) + 0.5), where n >= 0.
*/
fun nthFibUsingGoldenRatio(n: Int): Int {
return round(phi.pow(n) / sqrt(5.0)).toInt()
}
/**
* O(n) solution based on the inversion of closed-form Binet's formula.
*
* Phi^t / sqrt(5) > 10^(n-1)
*
* Phi^t > 10^(n-1) * sqrt(5)
*
* log(Phi)t > log(10)(n - 1) + log(5)/2
*
* t > (1(n - 1) + log(5)/2) / log(Phi)
*
* t = ceil((n - 1 + log(5)/2) / log(Phi))
*
* SPEED (BEST for low N) 3.2e4ns for N = 10
* SPEED (BEST for high N) 3.9e4ns for N = 5000
*
* @return first Fibonacci term to have N digits.
*/
fun nDigitFibTermGoldenFormula(n: Int): Int {
return ceil((n - 1 + log10(5.0) / 2) / log10(phi)).toInt()
}
} | 0 | Kotlin | 0 | 0 | 62b33367e3d1e15f7ea872d151c3512f8c606ce7 | 3,778 | project-euler-kotlin | MIT License |
src/main/kotlin/Day06.kt | robfletcher | 724,814,488 | false | {"Kotlin": 18682} | class Day06 : Puzzle {
override fun test() {
val input = """
Time: 7 15 30
Distance: 9 40 200""".trimIndent()
assert(part1(input.lineSequence()) == 288)
assert(part2(input.lineSequence()) == 71503)
}
override fun part1(input: Sequence<String>) =
parseInput1(input)
.map { race ->
(0..race.time).count { hold ->
((race.time - hold) * hold) > race.distance
}
}
.reduce(Int::times)
override fun part2(input: Sequence<String>) =
parseInput2(input).let {race ->
(0..race.time).count { hold ->
((race.time - hold) * hold) > race.distance
}
}
private fun parseInput1(input: Sequence<String>) =
input.toList().let {
Regex("""\d+""").run {
findAll(it.first()).map { it.value.toInt() }
.zip(findAll(it.last()).map { it.value.toInt() })
.map { (time, distance) -> Race(time, distance) }
}
}
private fun parseInput2(input: Sequence<String>) =
input.toList().let {
Race(
it.first().filter(Char::isDigit).toLong(),
it.last().filter(Char::isDigit).toLong()
)
}
data class Race<N : Number>(val time: N, val distance: N)
} | 0 | Kotlin | 0 | 0 | cf10b596c00322ea004712e34e6a0793ba1029ed | 1,220 | aoc2023 | The Unlicense |
src/main/kotlin/io/opencui/du/matcher.kt | opencui | 550,521,089 | false | {"Kotlin": 944279, "Shell": 44} | package io.opencui.du
// For only the candidates that are returned from retrieval phase, we do nested matcher.
// There are two different places that we need nested matching:
// 1. Find the exact match. This requires us to test whether utterance and examplar are the same, and
// at the same time keep the filling information. This matches against the exemplar on the container frame.
// 2. Find the slot frame match, this only matching the exemplar on the slot type.
//
// For now, we assume the tokenization is done by Lucene, for each token we also keep the character offset in
// the original utterance so that we can.
/**
* extractive matching of potentially nested expression. This is useful for simpler noun phrases
* where the structure is relatively stable, and QA model alone is not a good indicate.
* We will also use this for exact matching, where it is not as efficient as we like.
* We can have a list of matcher with more and more complexity.
*
*/
interface Matcher {
fun markMatch(document: IExemplar)
}
//
class NestedMatcher(val context: DuContext) : Matcher {
private val analyzer = LanguageAnalyzer.get(context.duMeta!!.getLang(), stop = false)
private val duMeta = context.duMeta!!
private var trueType : String? = null
// This function try to see if we can use doc to explain utterance from tokenStart.
// return -1, if there is no match, or position of last token that got matched.
// We pay attention to typed expression, whenever we see a type, we try to figure out whether
// one of the production can explain the rest utterance from the current start.
// utterance start is token based, and doc start is character based.
private fun coverFind(uStart: Int, doc: MetaExprSegments): Int {
var start = uStart
for(segment in doc.segments) {
val end = when(segment) {
is MetaSegment -> typeMatch(start, segment)
is ExprSegment -> exprMatch(start, segment)
}
if (end == -1) return -1
start = end
}
return start
}
//
private fun exprMatch(uStart: Int, doc: ExprSegment): Int {
val tokens = analyzer!!.tokenize(doc.expr)
for ((index, token) in tokens.withIndex()) {
if (uStart + index >= context.tokens!!.size) return -1
val userToken = context.tokens!![uStart + index].token
val docToken = token.token
if (userToken != docToken) return -1
}
return uStart + tokens.size
}
private fun typeMatch(uStart: Int, doc: MetaSegment): Int {
// Go through every exemplar, and find one that matches.
return when(duMeta.typeKind(doc.meta)) {
TypeKind.Entity -> entityCover(uStart, doc.meta)
TypeKind.Frame -> frameMatch(uStart, doc.meta)
TypeKind.Generic -> genericMatch(uStart)
}
}
// Try to find some entities to cover this, using the longest match.
private fun entityCover(uStart: Int, entityType: String): Int {
// TODO: why we got this point need to be checked.
if (uStart >= context.tokens!!.size) return -1
val charStart = context.tokens!![uStart].start
val entities = context.emapByCharStart[charStart] ?: return -1
var end = -1
// for now, we try the longest match.
for (entity in entities) {
if(isSubEntityOf(entity.first, entityType)) {
if (end < entity.second) end = entity.second
}
}
return end
}
private fun genericMatch(uStart: Int): Int {
// TODO: we need to consider this under expectation.
val charStart = context.tokens!![uStart].start
val entities = context.emapByCharStart[charStart] ?: return -1
var end = -1
// for now, we try the longest match.
for (entity in entities) {
if (end < entity.second && entity.first == trueType) end = entity.second
}
return end
}
private fun frameMatch(uStart: Int, frameType: String): Int {
val expressions = duMeta.expressionsByFrame[frameType] ?: return -1
var last = -1
for (expression in expressions) {
val typeExpr = Exemplar.segment(expression.typedExpression(context.duMeta!!), frameType)
val res = coverFind(uStart, typeExpr)
if (res > last) last = res
}
return last
}
private fun isSubEntityOf(first: String, second:String): Boolean {
var parent : String? = first
while (parent != null) {
if (parent == second) return true
parent = duMeta.getEntityMeta(first)?.getSuper()
}
return false
}
override fun markMatch(document: IExemplar) {
// We need to figure out whether there are special match.
val segments = Exemplar.segment(document.typedExpression, document.ownerFrame)
val slotTypes = segments.segments.filter { it is MetaSegment && it.meta == SLOTTYPE}
if (slotTypes.size > 1) throw IllegalStateException("Don't support multiple slots with SlotType yet.")
if (slotTypes.isEmpty() || context.entityTypeToValueInfoMap[SLOTTYPE].isNullOrEmpty()) {
if (!segments.useGenericType()) {
trueType = null
document.exactMatch = coverFind(0, segments) == context.tokens!!.size
} else {
// Here we find a potential exact match, based on guess a slot.
// Another choice when there are multiple choices we clarify.
val slots = duMeta.getSlotMetas(context.expectations)
for (slot in slots) {
if (context.entityTypeToValueInfoMap.containsKey(slot.type)) {
trueType = slot.type
val matched = coverFind(0, segments) == context.tokens!!.size
if (matched) {
// TODO: how do we handle the
document.possibleExactMatch = true
assert(document.ownerFrame == "io.opencui.core.SlotUpdate")
document.guessedSlot = slot
// find the first one and escape.
break
}
}
}
}
} else {
val matchedSlots = context.entityTypeToValueInfoMap[SLOTTYPE]!!
for (matchedSlot in matchedSlots) {
val trueSlot = matchedSlot.value as String
val tkns = trueSlot.split(".")
val frame = tkns.subList(0, tkns.size - 1).joinToString(".")
if (!context.expectations.isFrameCompatible(frame)) continue
val slotName = tkns.last()
trueType = context.duMeta!!.getSlotType(frame, slotName)
document.exactMatch = coverFind(0, segments) == context.tokens!!.size
}
}
}
companion object {
const val SLOTTYPE = "io.opencui.core.SlotType"
}
}
| 0 | Kotlin | 1 | 0 | 163f47189a37f66c02ca8090366bf21d4e5e960a | 7,125 | core | Apache License 2.0 |
src/main/kotlin/days/Day08.kt | TheMrMilchmann | 433,608,462 | false | {"Kotlin": 94737} | /*
* Copyright (c) 2021 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package days
import utils.readInput
fun main() {
data class Data(val input: List<Set<Char>>, val output: List<Set<Char>>)
val data = readInput().map { line ->
val (i, o) = line.split(" | ")
Data(i.split(" ").map { it.toSet() }, o.split(" ").map { it.toSet() })
}
fun Data.solve(): Int {
/*
* Segments/Digits
* - 2 => 1
* - 3 => 7
* - 4 => 4
* - 5 => 2, 3, 5
* - 6 => 6, 9, 0
* - 7 => 8
*/
val one = input.single { it.size == 2 }
val four = input.single { it.size == 4 }
val seven = input.single { it.size == 3 }
val eight = input.single { it.size == 7 }
val fiveSegmentsDigits = input.filter { it.size == 5 }
val sixSegmentsDigits = input.filter { it.size == 6 }
val three = fiveSegmentsDigits.single { fiveSegmentsDigit -> one.all { it in fiveSegmentsDigit } }
val nine = sixSegmentsDigits.single { sixSegmentsDigit -> four.all { it in sixSegmentsDigit } }
val five = fiveSegmentsDigits.single { fiveSegmentsDigit -> fiveSegmentsDigit != three && fiveSegmentsDigit.all { it in nine } }
val six = sixSegmentsDigits.single { sixSegmentsDigit -> sixSegmentsDigit != nine && five.all { it in sixSegmentsDigit } }
val zero = sixSegmentsDigits.single { it != six && it != nine }
val two = fiveSegmentsDigits.single { it != three && it != five }
return output.joinToString(separator = "") {
when (it) {
zero -> "0"
one -> "1"
two -> "2"
three -> "3"
four -> "4"
five -> "5"
six -> "6"
seven -> "7"
eight -> "8"
nine -> "9"
else -> error("")
}
}.toInt()
}
println("Part 1: ${data.sumOf { it.solve().toString().map(Char::digitToInt).count { it == 1 || it == 4 || it == 7 || it == 8 } }}")
println("Part 2: ${data.sumOf { it.solve() }}")
} | 0 | Kotlin | 0 | 1 | dfc91afab12d6dad01de552a77fc22a83237c21d | 3,193 | AdventOfCode2021 | MIT License |
archive/src/main/kotlin/com/grappenmaker/aoc/year23/Day23.kt | 770grappenmaker | 434,645,245 | false | {"Kotlin": 409647, "Python": 647} | package com.grappenmaker.aoc.year23
import com.grappenmaker.aoc.*
import com.grappenmaker.aoc.Direction.*
fun PuzzleSet.day23() = puzzle(day = 23) {
val g = inputLines.asCharGrid()
val s = Point(1, 0)
val e = Point(g.width - 2, g.height - 1)
val ps = (g.points.filter { p ->
g[p] != '#' && entries.filter { p + it in g && g[p + it] != '#' }.size > 2
} + s + e).toSet()
fun find(
gr: Map<Point, List<Edge<Point>>>,
seen: HashSet<Point> = hashSetOf(),
curr: Point = s,
dist: Int = 0
): Int {
if (curr == e) return dist
if (curr in seen) return -1
seen += curr
return (gr.getValue(curr).maxOfOrNull { (to, d) -> find(gr, seen, to, dist + d) } ?: -1).also { seen -= curr }
}
fun solve(partTwo: Boolean) = find(ps.asWeightedGraph { p ->
(if (partTwo) with(g) { p.adjacentSides() }
else when (g[p]) {
'^' -> listOf(p + UP)
'v' -> listOf(p + DOWN)
'<' -> listOf(p + LEFT)
'>' -> listOf(p + RIGHT)
else -> with(g) { p.adjacentSides() }
}).filter { g[it] != '#' }
})
partOne = solve(false).s()
partTwo = solve(true).s()
} | 0 | Kotlin | 0 | 7 | 92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585 | 1,223 | advent-of-code | The Unlicense |
app/src/main/java/com/example/posetrackervrc/data/Vector3D.kt | t-34400 | 743,037,050 | false | {"Kotlin": 69476} | package com.example.posetrackervrc.data
import kotlin.math.sqrt
data class Vector3D(val x: Float, val y: Float, val z: Float) {
companion object {
val zero = Vector3D(0.0f, 0.0f, 0.0f)
val right = Vector3D(1.0f, 0.0f, 0.0f)
val up = Vector3D(0.0f, 1.0f, 0.0f)
val forward = Vector3D(0.0f, 0.0f, 1.0f)
fun getRotationAxis(from: Vector3D, to: Vector3D): Vector3D {
val crossProduct = from.cross(to)
return crossProduct.normalized
}
}
val sqrMagnitude: Float get() = x * x + y * y + z * z
val magnitude: Float get() = sqrt(sqrMagnitude)
val normalized: Vector3D
get() {
val magnitude = magnitude
return if (magnitude != 0.0f) {
Vector3D(x / magnitude, y / magnitude, z / magnitude)
} else {
zero
}
}
operator fun plus(vector: Vector3D): Vector3D {
return Vector3D(x + vector.x, y + vector.y, z + vector.z)
}
operator fun minus(vector: Vector3D): Vector3D {
return Vector3D(x - vector.x, y - vector.y, z - vector.z)
}
operator fun times(multiplier: Float): Vector3D {
return Vector3D(x * multiplier, y * multiplier, z * multiplier)
}
operator fun times(multiplier: Int): Vector3D {
return Vector3D(x * multiplier, y * multiplier, z * multiplier)
}
operator fun div(divisor: Float): Vector3D {
return Vector3D(x / divisor, y / divisor, z / divisor)
}
operator fun div(divisor: Int): Vector3D {
return Vector3D(x / divisor, y / divisor, z / divisor)
}
operator fun unaryMinus(): Vector3D {
return Vector3D(-x, -y, -z)
}
fun dot(vector: Vector3D): Float {
return x * vector.x + y * vector.y + z * vector.z
}
fun cross(vector: Vector3D): Vector3D {
return Vector3D(
x = y * vector.z - z * vector.y,
y = z * vector.x - x * vector.z,
z = x * vector.y - y * vector.x
)
}
fun project(vector: Vector3D): Vector3D {
val normalized = normalized
return vector - normalized.dot(vector) * normalized
}
}
operator fun Float.times(vector: Vector3D): Vector3D {
return vector * this
}
| 0 | Kotlin | 0 | 0 | 89daad8d0c9065e1954f38faf823a72b05a2fd99 | 2,280 | PoseTrackerVRC | MIT License |
src/main/kotlin/com/hj/leetcode/kotlin/problem222/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem222
import com.hj.leetcode.kotlin.common.model.TreeNode
/**
* LeetCode page: [222. Count Complete Tree Nodes](https://leetcode.com/problems/count-complete-tree-nodes/);
*/
class Solution {
/* Complexity:
* Time O((LogN)^2) and Space O(LogN) where N is the number of nodes in root;
*/
fun countNodes(root: TreeNode?): Int {
if (root == null) return 0
val heightOfLeft = getHeightOfCompleteBinaryTree(root.left)
val heightOfRight = getHeightOfCompleteBinaryTree(root.right)
return when (heightOfRight) {
heightOfLeft ->
1 + getSizeOfPerfectBinaryTree(heightOfLeft) + countNodes(root.right)
heightOfLeft - 1 ->
1 + countNodes(root.left) + getSizeOfPerfectBinaryTree(heightOfRight)
else -> throw IllegalStateException()
}
}
private fun getHeightOfCompleteBinaryTree(root: TreeNode?): Int {
var height = -1
var node = root
while (node != null) {
height++
node = node.left
}
return height
}
private fun getSizeOfPerfectBinaryTree(height: Int): Int {
require(height >= -1)
return if (height == -1) 0 else (2 shl height) - 1
}
}
| 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 1,294 | hj-leetcode-kotlin | Apache License 2.0 |
src/Day03.kt | slawa4s | 573,050,411 | false | {"Kotlin": 20679} | const val CHUNK_SIZE = 3
fun main() {
fun setOfCharsToSumInt(set: Set<Char>) =
set.sumOf {
Character.getNumericValue(it) + if (it.isUpperCase()) 17 else -9
}
fun getChunkToInt(input: List<Set<Char>>): Int =
setOfCharsToSumInt(input.reduce { first, second -> first.intersect(second) }.toSet())
fun part1(input: List<String>): Int = input
.sumOf {
getChunkToInt(listOf(it.take((it.length + 1) / 2).toSet(), it.takeLast((it.length + 1) / 2).toSet()))
}
fun part2(input: List<String>): Int = input
.map { it.toSet() }
.chunked(CHUNK_SIZE)
.sumOf { getChunkToInt(it) }
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | cd8bbbb3a710dc542c2832959a6a03a0d2516866 | 764 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day01.kt | allisonjoycarter | 574,207,005 | false | {"Kotlin": 22303} | fun main() {
fun part1(input: List<String>): Int {
var amount = 0
var max = 0
for (i in input) {
if (i.isEmpty()) {
if (amount > max) {
max = amount
}
amount = 0
} else if (i.isNotEmpty()) {
amount += i.toInt()
}
}
return max
}
fun part2(input: List<String>): Int {
val amounts = arrayListOf<Int>()
var current = 0
for (i in input) {
if (i.isEmpty()) {
amounts.add(current)
current = 0
} else {
current += i.toInt()
}
}
return amounts.sortedDescending().take(3).sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("day1test")
check(part1(testInput) == 24000)
val input = readInput("Day01")
println("Part 1:")
println(part1(input))
println("Part 2:")
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 86306ee6f4e90c1cab7c2743eb437fa86d4238e5 | 1,062 | adventofcode2022 | Apache License 2.0 |
src/Day06.kt | karlwalsh | 573,854,263 | false | {"Kotlin": 32685} | fun main() {
fun part1(input: String): Int = input.windowedSequence(4)
.mapIndexed { index, chunk -> index to chunk }
.filter { (_, chunk) -> chunk.toSet().size == 4 }
.first()
.first + 4
fun part2(input: String): Int = input.windowedSequence(14)
.mapIndexed { index, chunk -> index to chunk }
.filter { (_, chunk) -> chunk.toSet().size == 14 }
.first()
.first + 14
val input = readInput("Day06").first()
with(::part1) {
mapOf(
"mjqjpqmgbljsphdztnvjfqwrcgsmlb" to 7,
"bvwbjplbgvbhsrlpgdmjqwftvncz" to 5,
"nppdvjthqldpwncqszvftbrmjlhg" to 6,
"nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg" to 10,
"zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw" to 11
).forEach { (example, expectedResult) ->
val exampleResult = this(example)
check(exampleResult == expectedResult) {
"Part 1 result for '$example' was $exampleResult but expected $expectedResult: '${
example.substring(
0 until expectedResult
)
}|${example.substring(expectedResult until example.length)}'"
}
}
println("Part 1: ${this(input)}")
}
with(::part2) {
mapOf(
"mjqjpqmgbljsphdztnvjfqwrcgsmlb" to 19,
"bvwbjplbgvbhsrlpgdmjqwftvncz" to 23,
"nppdvjthqldpwncqszvftbrmjlhg" to 23,
"nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg" to 29,
"zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw" to 26
).forEach { (example, expectedResult) ->
val exampleResult = this(example)
check(exampleResult == expectedResult) {
"Part 2 result for '$example' was $exampleResult but expected $expectedResult: '${
example.substring(
0 until expectedResult
)
}|${example.substring(expectedResult until example.length)}'"
}
}
println("Part 2: ${this(input)}")
}
} | 0 | Kotlin | 0 | 0 | f5ff9432f1908575cd23df192a7cb1afdd507cee | 2,086 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/d16/d16t.kt | LaurentJeanpierre1 | 573,454,829 | false | {"Kotlin": 118105} | package d16
import readInput
import java.lang.IllegalStateException
import java.util.PriorityQueue
val openable = mutableListOf<Valve>()
data class Path(val valve: Valve, val len: Int) : Comparable<Path> {
override fun compareTo(other: Path): Int {
return len.compareTo(other.len)
}
}
fun dijkstra(from : Valve, to:Valve) :Int {
val queue = PriorityQueue<Path>()
queue.add(Path(from, 0))
while (queue.isNotEmpty()) {
val pos = queue.poll()
if (pos.valve == to) return pos.len
for (next in pos.valve.next)
queue.add(Path(valves[next]!!, pos.len+1))
}
throw IllegalStateException("No path from $from to $to")
}
var bestT = 0
data class Pair(val v1: Valve, val v2:Valve)
var cache = mutableMapOf<Pair, Int>()
fun open1(here: Valve, openable: List<Valve>, pression: Int, flow: Int, time: Int) : Int {
if (time > 30) {
if (pression> bestT) {
bestT = pression
println("time $time : pression $pression, left ${openable.map { v -> v.name }.toString()}")
}
return pression
}
var max = pression + flow*(30-time)
for (valve in openable) {
val delta = cache.computeIfAbsent( Pair(here, valve)) { dijkstra(here, valve)+1}
if (time+delta > 30) continue
val value = open1(valve, openable.minus(valve), pression+flow*delta+valve.flow, flow+valve.flow, time+delta)
if (value > max)
max = value
}
return max
}
fun part1c(input: List<String>): Int {
readFile(input)
for (valve in valves)
if (valve.value.flow > 0)
openable.add(valve.value)
openable.sortWith {v1, v2 -> v2.flow.compareTo(v1.flow)}
return open1(valves["AA"]!!, openable,0,0, 1)
}
fun part2c(input: List<String>): Int {
readFile(input)
for (valve in valves)
if (valve.value.flow > 0)
openable.add(valve.value)
openable.sortWith {v1, v2 -> v2.flow.compareTo(v1.flow)}
return open2(valves["AA"]!!,valves["AA"]!!, openable,0,0, 1,1,1,1,1)
}
fun open2(me: Valve, him: Valve, openable: List<Valve>, pression: Int, flow: Int, time: Int, timeMe: Int, timeHim : Int, fromMe : Int, fromHim: Int) : Int {
if (time > 26) {
if (pression> bestT) {
bestT = pression
println("time $time : pression $pression, left ${openable.map { v -> v.name }.toString()}")
}
return pression
}
var max = pression + flow*(26-time)
if (timeMe == time) { // decision for me
val curFlow = flow + me.flow
val curPression = pression + flow * (time-fromMe) + me.flow
max = curPression + curFlow*(26-time)
for (valve in openable) {
val valve1 = valve
val delta = cache.computeIfAbsent( Pair(me, valve1)) { dijkstra(me, valve1)+1}
if (time+delta > 26) continue
val value = open2(valve1, him, openable.minus(valve1), curPression, curFlow, time, time+delta, timeHim, time, fromHim)
if (value > max)
max = value
}
if (timeHim > time) {
val value = open2(me, him, openable, curPression, curFlow, timeHim, 0, timeHim, 0, time) // flow accounted till now
if (value > max)
max = value
}
} else if (timeHim == time) { // decision for elephant
val curFlow = flow + him.flow
val curPression = pression + flow * (time-fromHim) + him.flow
max = curPression + curFlow*(26-time)
for (valve in openable) {
val valve1 = valve
val delta = cache.computeIfAbsent( Pair(him, valve1)) { dijkstra(him, valve1)+1}
if (time+delta > 26) continue
val value = open2(me,
valve1, openable.minus(valve1), curPression, curFlow, time, timeMe, timeHim+delta, fromMe, time)
if (value > max)
max = value
}
if (timeMe > time) {
val value = open2(me, him, openable, curPression, curFlow, timeMe, timeMe, 0, time, 0) // flow accounted till now
if (value > max)
max = value
}
} else {
if (timeMe <= timeHim && timeMe != 0) {
val value = open2(me, him, openable, pression, flow, timeMe, timeMe, timeHim, fromMe, timeMe) // flow accounted till now
if (value > max)
max = value
} else if (timeHim != 0){
val value = open2(me, him, openable, pression, flow, timeHim, timeMe, timeHim, timeHim, fromHim) // flow accounted till now
if (value > max)
max = value
}
}
return max
}
// <2436
// >2248
// <2400
// !=2300
// !=2282
// Answer is 2261 - why?
fun main() {
//val input = readInput("d16/test")
//val input = readInput("d16/input1")
val input = readInput("d16/liquifun")
//println(part1c(input))
println(part2c(input))
}
| 0 | Kotlin | 0 | 0 | 5cf6b2142df6082ddd7d94f2dbde037f1fe0508f | 4,917 | aoc2022 | Creative Commons Zero v1.0 Universal |
src/main/kotlin/com/chriswk/aoc/advent2021/Day15.kt | chriswk | 317,863,220 | false | {"Kotlin": 481061} | package com.chriswk.aoc.advent2021
import com.chriswk.aoc.AdventDay
import com.chriswk.aoc.util.Pos
import com.chriswk.aoc.util.asInt
import com.chriswk.aoc.util.report
import java.util.PriorityQueue
import kotlin.math.max
class Day15: AdventDay(2021, 15) {
companion object {
@JvmStatic
fun main(args: Array<String>) {
val day = Day15()
report {
day.part1()
}
report {
day.part2()
}
}
}
fun buildRiskMap(input: List<String>): Map<Pos, Int> {
return input.flatMapIndexed { y, line ->
line.mapIndexed { x, risk ->
Pos(x, y) to risk.asInt()
}
}.toMap()
}
fun lowestRisk(riskMap: Map<Pos, Int>, start: Pos, end: Pos): Int {
val maxX = riskMap.maxOf { it.key.x } + 1
val maxY = riskMap.maxOf { it.key.y } + 1
return dijkstra(riskMap, start, end, maxX = maxX, maxY = maxY)[end]!!
}
fun expandMap(riskMap: Map<Pos, Int>, times: Int = 4): Map<Pos, Int> {
val sizeX = riskMap.maxOf { it.key.x } + 1
val sizeY = riskMap.maxOf { it.key.y } + 1
// First expand x
val xExpanded: Map<Pos, Int> = buildMap {
riskMap.entries.forEach { entry ->
put(entry.key, entry.value)
(1..times).forEach { multiplier ->
val newXCoord = sizeX * multiplier
val newPos = entry.key + Pos(newXCoord, 0)
val previousPos = newPos - Pos(sizeX, 0)
val previousValue = this.getValue(previousPos)
val newRisk = max((previousValue + 1) % 10, 1)
put(newPos, newRisk)
}
}
}
val yExpanded: Map<Pos, Int> = buildMap {
xExpanded.entries.forEach { entry ->
put(entry.key, entry.value)
(1..times).forEach { multiplier ->
val newYCoord = sizeY * multiplier
val newPos = entry.key + Pos(0, newYCoord)
val previousPos = newPos - Pos(0, sizeY)
val previousValue = this.getValue(previousPos)
val newRisk = max((previousValue + 1) % 10, 1)
put(newPos, newRisk)
}
}
}
return yExpanded
}
private val riskComparator: Comparator<Pair<Pos, Int>> =
Comparator { o1, o2 -> o1!!.second.compareTo(o2!!.second) }
private fun dijkstra(riskMap: Map<Pos, Int>, start: Pos, target: Pos, maxX: Int, maxY: Int): Map<Pos, Int> {
val accumulatedRiskMap: MutableMap<Pos, Int> = mutableMapOf(start to 0)
val q = PriorityQueue(riskComparator)
q.add(start to 0)
while(q.isNotEmpty()) {
val (current, myRisk) = q.remove()
current.cardinalNeighbours(maxX, maxY).forEach { neighbour ->
if (riskMap.containsKey(neighbour) && !accumulatedRiskMap.containsKey(neighbour)) {
val totalRisk = myRisk + riskMap.getValue(neighbour)
accumulatedRiskMap[neighbour] = totalRisk
if (neighbour == target) {
return accumulatedRiskMap
}
q.add(neighbour to totalRisk)
}
}
}
return accumulatedRiskMap
}
val inputRisk = buildRiskMap(inputAsLines)
fun part1(): Int {
return lowestRisk(inputRisk, Pos(0, 0), inputRisk.maxByOrNull { it.key }!!.key)
}
fun part2(): Int {
val expanded = expandMap(inputRisk)
val target = expanded.maxByOrNull { it.key }!!.key
return lowestRisk(expandMap(inputRisk), Pos(0, 0), target)
}
}
| 116 | Kotlin | 0 | 0 | 69fa3dfed62d5cb7d961fe16924066cb7f9f5985 | 3,819 | adventofcode | MIT License |
src/2022/Day15.kt | nagyjani | 572,361,168 | false | {"Kotlin": 369497} | package `2022`
import common.Interval
import common.Point
import java.io.File
import java.util.*
import kotlin.math.abs
fun main() {
Day15().solve()
}
class Day15 {
val input1 = """
Sensor at x=2, y=18: closest beacon is at x=-2, y=15
Sensor at x=9, y=16: closest beacon is at x=10, y=16
Sensor at x=13, y=2: closest beacon is at x=15, y=3
Sensor at x=12, y=14: closest beacon is at x=10, y=16
Sensor at x=10, y=20: closest beacon is at x=10, y=16
Sensor at x=14, y=17: closest beacon is at x=10, y=16
Sensor at x=8, y=7: closest beacon is at x=2, y=10
Sensor at x=2, y=0: closest beacon is at x=2, y=10
Sensor at x=0, y=11: closest beacon is at x=2, y=10
Sensor at x=20, y=14: closest beacon is at x=25, y=17
Sensor at x=17, y=20: closest beacon is at x=21, y=22
Sensor at x=16, y=7: closest beacon is at x=15, y=3
Sensor at x=14, y=3: closest beacon is at x=15, y=3
Sensor at x=20, y=1: closest beacon is at x=15, y=3
""".trimIndent()
class ExcludeLine {
val exclusions = mutableListOf<Interval>()
val beacons = mutableSetOf<Int>()
fun exclude(start: Int, length: Int) {
var ix: Int = 0
var interval = Interval(start, length)
while (ix<exclusions.size) {
when (interval.compare(exclusions[ix])) {
0 -> {
interval = interval.merge(exclusions[ix])
exclusions.removeAt(ix)
}
1 -> {
exclusions.add(ix, interval)
return
}
-1 ->
++ix
}
}
exclusions.add(interval)
return
}
fun minPos(start: Int, end: Int): Int {
var r = -1
exclusions.windowed(2){
if (it[0].end() in start until end) {
r = it[0].end()+1
}}
return r
}
fun addBeacon(pos: Int) {
beacons.add(pos)
}
fun excluded(pos: Int): Boolean {
return exclusions.any { it.has(pos) }
}
fun noBeaconSize(): Int {
var s = exclusions.sumOf { it.length }
for (b in beacons) {
if (excluded(b)) {
--s
}
}
return s
}
fun render(start: Int, end: Int): String {
val s = StringBuilder()
for (i in start .. end) {
if (beacons.contains(i)) {
s.append('B')
} else if (excluded(i)) {
s.append('#')
} else {
s.append('.')
}
}
return s.toString()
}
}
fun solve() {
val f = File("src/2022/inputs/day15.in")
val s = Scanner(f)
val l = 2000000
// val s = Scanner(input1)
// val l = 10
val beacons = mutableListOf<Point>()
val scanners = mutableListOf<Point>()
val min = 0
// val max = 20
val max = 4000000
val excludeLines = MutableList<ExcludeLine> (max+1) {ExcludeLine()}
while (s.hasNextLine()) {
val line = s.nextLine().trim()
val words = line.split(" ")
if (!words.isEmpty()) {
val sX = words[2].split(Regex("[=,:]"))[1].toInt()
val sY = words[3].split(Regex("[=,:]"))[1].toInt()
val bX = words[8].split(Regex("[=,:]"))[1].toInt()
val bY = words[9].split(Regex("[=,:]"))[1].toInt()
val scanner = Point(sX, sY)
val beacon = Point(bX, bY)
val distance = abs(sX-bX) + abs(sY-bY)
for (y in min..max) {
val vd = abs(sY - y)
if (vd <= distance) {
val hd = abs(distance - vd)
excludeLines[y].exclude(sX - hd, hd*2+1)
}
}
if (bY >= min && bY <= max) {
excludeLines[bY].addBeacon(bX)
}
println("${words}")
println("$sX $sY $bX $bY")
}
}
println("${true}")
println("${excludeLines[10].render(-10, 30)}")
println("${excludeLines[11].render(-10, 30)}")
println("${excludeLines[10].noBeaconSize()}")
println("${excludeLines[2000000].noBeaconSize()}")
var rx = 0
var ry = 0
for (y in min..max) {
var x = excludeLines[y].minPos(min, max)
if (x != -1) {
println("$x $y ${x.toLong()*4000000+y.toLong()}")
}
}
}
}
| 0 | Kotlin | 0 | 0 | f0c61c787e4f0b83b69ed0cde3117aed3ae918a5 | 4,923 | advent-of-code | Apache License 2.0 |
src/y2022/Day03.kt | Yg0R2 | 433,731,745 | false | null | package y2022
import DayX
class Day03 : DayX<Int>(157, 70) {
/**
* Lowercase item types a through z have priorities 1 through 26.
* ascii a-z 97-122
* Uppercase item types A through Z have priorities 27 through 52.
* ascii A-Z 65-90
*/
override fun part1(input: List<String>): Int =
input.map {
val middleIndex = it.length / 2
val leftCompartment = it.subSequence(0, middleIndex)
val rightCompartment = it.subSequence(middleIndex, it.length)
leftCompartment.toSet()
.intersect(rightCompartment.toSet())
.first()
}.sumOf { it.getPriority() }
override fun part2(input: List<String>): Int =
input.windowed(3, 3)
.map { group ->
val rucksack1 = group[0].toSet()
val rucksack2 = group[1].toSet()
val rucksack3 = group[2].toSet()
rucksack1
.filter { rucksack2.contains(it) }
.first { rucksack3.contains(it) }
}
.sumOf { it.getPriority() }
companion object {
fun Char.getPriority() =
if (isLowerCase()) {
code - 96
} else {
code - 38
}
}
}
| 0 | Kotlin | 0 | 0 | d88df7529665b65617334d84b87762bd3ead1323 | 1,307 | advent-of-code | Apache License 2.0 |
src/adventofcode/Day22.kt | Timo-Noordzee | 573,147,284 | false | {"Kotlin": 80936} | package adventofcode
import org.openjdk.jmh.annotations.*
import java.util.concurrent.TimeUnit
import kotlin.math.sqrt
private operator fun IntRange.component1() = first
private operator fun IntRange.component2() = last
private operator fun List<CharArray>.contains(point: Point) = point.y in indices && point.x in this[point.y].indices
private operator fun List<CharArray>.get(point: Point) = this[point.y][point.x]
private enum class Facing(val value: Int, val move: Move) {
RIGHT(0, Move(1, 0)),
DOWN(1, Move(0, 1)),
LEFT(2, Move(-1, 0)),
UP(3, Move(0, -1));
companion object {
fun from(value: Int) = values().first { it.value == value }
}
}
private data class Jump(val x: Int, val y: Int, val facing: Facing)
private class Board(
val grid: Array<CharArray>,
val jumps: Map<Jump, Point>
) {
var facing = Facing.RIGHT
var position = kotlin.run {
val x = grid[0].indexOfFirst { it == '.' }
val y = grid.indices.first { i -> grid[i][x] == '.' }
Point(x, y)
}
fun move(steps: Int) {
repeat(steps) {
val nextPosition = (position + facing.move).let { jumps[Jump(it.x, it.y, facing)] ?: it }
if (grid[nextPosition.y][nextPosition.x] != '#') {
position = nextPosition
} else {
return
}
}
}
fun rotate(direction: Char) {
facing = when (direction) {
'L' -> if (facing == Facing.RIGHT) Facing.UP else Facing.from(facing.value - 1)
'R' -> Facing.from((facing.value + 1) % Facing.values().size)
else -> error("check input")
}
}
companion object {
fun fromInput(input: List<String>): Board {
val m = input.size
val n = input.maxOf { it.length }
val xRanges = Array(m) { i ->
input[i].indexOfFirst { it != ' ' } until input[i].length
}
val yRanges = Array(n) { j ->
val min = (0 until m).indexOfFirst { i -> input[i].getOrElse(j) { ' ' } != ' ' }
val max = (0 until m).indexOfLast { i -> input[i].getOrElse(j) { ' ' } != ' ' }
min..max
}
val grid = Array(m) { CharArray(n) { ' ' } }
for (i in 0 until m) {
val line = input[i]
for (j in line.indices) {
grid[i][j] = line[j]
}
}
val jumps = buildMap {
xRanges.forEachIndexed { y, (start, end) ->
put(Jump(start - 1, y, Facing.LEFT), Point(end, y))
put(Jump(end + 1, y, Facing.RIGHT), Point(start, y))
}
yRanges.forEachIndexed { x, (start, end) ->
put(Jump(x, start - 1, Facing.UP), Point(x, end))
put(Jump(x, end + 1, Facing.DOWN), Point(x, start))
}
}
return Board(
grid = grid,
jumps = jumps
)
}
}
}
@State(Scope.Benchmark)
@Fork(1)
@Warmup(iterations = 0)
@Measurement(iterations = 10, time = 2, timeUnit = TimeUnit.SECONDS)
class Day22 {
var input: List<String> = emptyList()
private val directions = arrayOf(
Move(1, 0),
Move(0, 1),
Move(-1, 0),
Move(0, -1)
)
@Setup
fun setup() {
input = readInput("Day22")
}
@Benchmark
fun part1(): Int {
val board = Board.fromInput(input.dropLast(2))
val regex = Regex("""\d+|\w""")
val matches = regex.findAll(input.last()).map { it.value }.toList()
matches.forEachIndexed { index, value ->
if (index % 2 == 0) {
board.move(value.toInt())
} else {
board.rotate(value[0])
}
}
val (x, y) = board.position
return (y + 1) * 1_000 + (x + 1) * 4 + board.facing.value
}
@Benchmark
fun part2(): Int {
// 3D faces basis
data class FaceVector(val i: Vector3, val j: Vector3, val n: Vector3)
fun FaceVector.d2v(d: Int): Vector3 = i * directions[d].dy + j * directions[d].dx
fun FaceVector.v2d(v: Vector3): Int = (0..3).single { d -> d2v(d) == v }
data class Face(val i: Int, val j: Int)
val totalTiles = input.dropLast(2).sumOf { row -> row.count { it != ' ' } }
val faceSize = sqrt(totalTiles / 6.0).toInt()
val faces = buildSet {
input.dropLast(2).forEachIndexed { i, row ->
row.forEachIndexed { j, char ->
if (char != ' ') add(Face(i / faceSize, j / faceSize))
}
}
}
// dfs on faces to construct folding
val faceToVector = HashMap<Face, FaceVector>() // visited faces to vectors
val n2Face = HashMap<Vector3, Face>() // normals to visited faces
val faceToDirections = HashMap<Face, List<FaceVector>>() // neighbour faces in all directions
fun dfs(face: Face, faceVector: FaceVector) {
if (face in faceToVector) return
faceToVector[face] = faceVector
n2Face[faceVector.n] = face
faceToDirections[face] = List(4) { d ->
val (dj, di) = directions[d]
val fd = Face(face.i + di, face.j + dj)
val fvd = when (d) {
0 -> FaceVector(faceVector.i, faceVector.n, -faceVector.j)
1 -> FaceVector(faceVector.n, faceVector.j, -faceVector.i)
2 -> FaceVector(faceVector.i, -faceVector.n, faceVector.j)
3 -> FaceVector(-faceVector.n, faceVector.j, faceVector.i)
else -> error(d)
}
if (fd in faces) dfs(fd, fvd) // fold neighbour
fvd
}
}
val initialFace = faces.filter { it.i == 0 }.minBy { it.j } // initial face
dfs(initialFace, FaceVector(Vector3(1, 0, 0), Vector3(0, 1, 0), Vector3(0, 0, 1)))
val tiles = input.dropLast(2).map { it.toCharArray() }
val regex = Regex("""\d+|\w""")
val matches = regex.findAll(input.last()).map { it.value }.toList()
var direction = 0
var position = Point(initialFace.j * faceSize, 0)
matches.forEachIndexed { index, value ->
if (index % 2 == 0) {
for (step in 1..value.toInt()) {
var nextPosition = position + directions[direction]
var nextDirection = direction
if (nextPosition !in tiles || tiles[nextPosition] == ' ') {
val currentFace = Face(position.y / faceSize, position.x / faceSize)
val faceVector = faceToDirections.getValue(currentFace)[direction] // basis of the next face if it was connected
val nextFace = n2Face[faceVector.n]!! // next face (look up by the normal)
val actualFaceVector = faceToVector[nextFace]!! // the actual basis of the new face
nextDirection = actualFaceVector.v2d(faceVector.d2v(direction)) // direction on the new face
// compute 3D vector of the offset on the face in the original basis
val vv = faceVector.i * (nextPosition.y.mod(faceSize) + 1) + faceVector.j * (nextPosition.x.mod(faceSize) + 1)
// project offset in the new basis
fun flipNeg(s: Int) = if (s < 0) faceSize + 1 + s else s
nextPosition = Point(
nextFace.j * faceSize + flipNeg(vv * actualFaceVector.j) - 1,
nextFace.i * faceSize + flipNeg(vv * actualFaceVector.i) - 1,
)
}
when (tiles[nextPosition]) {
'.' -> {
position = nextPosition
direction = nextDirection
}
'#' -> break
else -> error("check input")
}
}
} else {
direction = when (value[0]) {
'L' -> (direction + 3) % 4
'R' -> (direction + 1) % 4
else -> error("check input")
}
}
}
return 1000 * (position.y + 1) + 4 * (position.x + 1) + direction
}
}
fun main() {
val day22 = Day22()
// test if implementation meets criteria from the description, like:
day22.input = readInput("Day22_test")
check(day22.part1() == 6032)
check(day22.part2() == 5031)
day22.input = readInput("Day22")
println(day22.part1())
println(day22.part2())
} | 0 | Kotlin | 0 | 2 | 10c3ab966f9520a2c453a2160b143e50c4c4581f | 8,879 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/main/kotlin/days/Day22.kt | TheMrMilchmann | 433,608,462 | false | {"Kotlin": 94737} | /*
* Copyright (c) 2021 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package days
import utils.*
fun main() {
data class Cuboid(
val minX: Int, val maxX: Int,
val minY: Int, val maxY: Int,
val minZ: Int, val maxZ: Int
)
data class BootStep(val cuboid: Cuboid, val state: Boolean)
val pattern = """x=(-?\d+)\.\.(-?\d+),y=(-?\d+)\.\.(-?\d+),z=(-?\d+)\.\.(-?\d+)""".toRegex()
val input = readInput().map { line ->
val (state, cuboid) = line.split(" ")
val (minX, maxX, minY, maxY, minZ, maxZ) = pattern.matchEntire(cuboid)?.destructured ?: error("Could not parse: $cuboid")
BootStep(
state = state == "on",
cuboid = Cuboid(minX.toInt(), maxX.toInt() + 1, minY.toInt(), maxY.toInt() + 1, minZ.toInt(), maxZ.toInt() + 1)
)
}
val xs = input.flatMap { listOf(it.cuboid.minX, it.cuboid.maxX) }.distinct().sorted()
val ys = input.flatMap { listOf(it.cuboid.minY, it.cuboid.maxY) }.distinct().sorted()
val zs = input.flatMap { listOf(it.cuboid.minZ, it.cuboid.maxZ) }.distinct().sorted()
val cXs = xs.withIndex().associateBy({ it.value }, { it.index })
val cYs = ys.withIndex().associateBy({ it.value }, { it.index })
val cZs = zs.withIndex().associateBy({ it.value }, { it.index })
val box = Array(xs.size) {
Array(ys.size) {
BooleanArray(zs.size)
}
}
input.forEach { step ->
for (cX in cXs[step.cuboid.minX]!! until cXs[step.cuboid.maxX]!!) {
for (cY in cYs[step.cuboid.minY]!! until cYs[step.cuboid.maxY]!!) {
for (cZ in cZs[step.cuboid.minZ]!! until cZs[step.cuboid.maxZ]!!) {
box[cX][cY][cZ] = step.state
}
}
}
}
fun part1(): Long {
var res = 0L
for (x in 0 until xs.size - 1) {
for (y in 0 until ys.size - 1) {
for (z in 0 until zs.size - 1) {
if (box[x][y][z] && -50 <= xs[x] && xs[x] <= 50 && -50 <= ys[y] && ys[y] <= 50 && -50 <= zs[z] && zs[z] <= 50)
res += (xs[x + 1] - xs[x]).toLong() * (ys[y + 1] - ys[y]) * (zs[z + 1] - zs[z])
}
}
}
return res
}
fun part2(): Long {
var res = 0L
for (x in 0 until xs.size - 1) {
for (y in 0 until ys.size - 1) {
for (z in 0 until zs.size - 1) {
if (box[x][y][z])
res += (xs[x + 1] - xs[x]).toLong() * (ys[y + 1] - ys[y]) * (zs[z + 1] - zs[z])
}
}
}
return res
}
println("Part 1: ${part1()}")
println("Part 2: ${part2()}")
} | 0 | Kotlin | 0 | 1 | dfc91afab12d6dad01de552a77fc22a83237c21d | 3,777 | AdventOfCode2021 | MIT License |
src/Day14/December14.kt | Nandi | 47,216,709 | false | null | package Day14
import java.nio.file.Files
import java.nio.file.Paths
import java.util.*
import java.util.stream.Stream
/**
* todo: visualize
*
* This year is the Reindeer Olympics! Reindeer can fly at high speeds, but must rest occasionally to recover their
* energy. Santa would like to know which of his reindeer is fastest, and so he has them race.
*
* Reindeer can only either be flying (always at their top speed) or resting (not moving at all), and always spend
* whole seconds in either state.
*
* Part 1
*
* Given the descriptions of each reindeer (in your puzzle input), after exactly 2503 seconds, what distance has the
* winning reindeer traveled?
*
* Part 2
*
* Seeing how reindeer move in bursts, Santa decides he's not pleased with the old scoring system.
*
* Instead, at the end of each second, he awards one point to the reindeer currently in the lead. (If there are
* multiple reindeer tied for the lead, they each get one point.) He keeps the traditional 2503 second time limit, of
* course, as doing otherwise would be entirely ridiculous.
*
* Again given the descriptions of each reindeer (in your puzzle input), after exactly 2503 seconds, how many points
* does the winning reindeer have?
*
* Created by Simon on 14/12/2015.
*/
enum class STATE {
RESTING, MOVING
}
data class Reindeer(val name: String, val speed: Int, val duration: Int, val rest: Int, var state: STATE = STATE.MOVING, var distance: Int = 0, var points: Int = 0) {
var restTimer = rest
var durationTimer = duration
fun updateState() {
when (state) {
STATE.RESTING -> {
restTimer--
if (restTimer == 0) {
state = STATE.MOVING
restTimer = rest
}
}
STATE.MOVING -> {
durationTimer--
if (durationTimer == 0) {
state = STATE.RESTING
durationTimer = duration
}
distance += speed
}
}
}
}
class December14 {
fun main() {
var reindeerList = arrayListOf<Reindeer>()
val lines = loadFile("src/Day14/14.dec_input.txt")
for (line in lines) {
var importantInfo = line.replace("can fly ", "")
.replace("km/s for ", "")
.replace("seconds, but then must rest for ", "")
.replace(" seconds.", "")
val (name, speed, duration, rest) = importantInfo.split(" ")
if (name !is String || speed !is String || duration !is String || rest !is String) return
reindeerList.add(Reindeer(name, speed.toInt(), duration.toInt(), rest.toInt()))
}
val byDistance = Comparator<Reindeer> { r1, r2 -> r2.distance.compareTo(r1.distance) }
val byPoints = Comparator<Reindeer> { r1, r2 -> r2.points.compareTo(r1.points) }
for (i in 1..2503) {
reindeerList.forEach { r -> r.updateState() }
reindeerList.sort(byDistance)
reindeerList.filter({ r -> r.distance.equals(reindeerList[0].distance) }).forEach { r -> r.points++ }
}
println("==== Sorted by distance ====")
reindeerList.sort(byDistance)
reindeerList.forEach { r -> println("${r.name} - ${r.distance}") }
println()
println("==== Sorted by points ====")
reindeerList.sort(byPoints)
reindeerList.forEach { r -> println("${r.name} - ${r.points}") }
}
fun loadFile(path: String): Stream<String> {
val input = Paths.get(path)
val reader = Files.newBufferedReader(input)
return reader.lines()
}
}
fun main(args: Array<String>) {
December14().main()
} | 0 | Kotlin | 0 | 0 | 34a4b4c0926b5ba7e9b32ca6eeedd530f6e95bdc | 3,771 | adventofcode | MIT License |
v2-model-extension/src/commonMain/kotlin/com/bselzer/gw2/v2/model/extension/wvw/WvwUpgrade.kt | Woody230 | 388,820,096 | false | null | package com.bselzer.gw2.v2.model.extension.wvw
import com.bselzer.gw2.v2.model.wvw.upgrade.WvwUpgrade
import com.bselzer.gw2.v2.model.wvw.upgrade.tier.WvwUpgradeTier
import kotlin.math.min
/**
* Calculates the upgrade level based on the number of [yaksDelivered] satisfying the number of [WvwUpgradeTier.yaksRequired].
*
* @param yaksDelivered the number of yaks delivered to the associated objective
* @return the level, or zero if no tiers are fulfilled
*/
fun WvwUpgrade.level(yaksDelivered: Int): Int {
val tier = tier(yaksDelivered) ?: return 0
return tiers.indexOf(tier) + 1
}
/**
* Finds the current [WvwUpgradeTier] based on the number of [yaksDelivered] satisfying the number of [WvwUpgradeTier.yaksRequired].
*
* @param yaksDelivered the number of yaks delivered to the associated objective
* @return the tier, or null if no tiers are fulfilled
*/
fun WvwUpgrade.tier(yaksDelivered: Int): WvwUpgradeTier? = tiers(yaksDelivered).lastOrNull()
/**
* Finds the fulfilled [WvwUpgradeTier]s based on the number of [yaksDelivered] satisfying the cumulative number of [WvwUpgradeTier.yaksRequired].
*
* @param yaksDelivered the number of yaks delivered to the associated objective
* @return the fulfilled upgrade tiers
*/
fun WvwUpgrade.tiers(yaksDelivered: Int): Collection<WvwUpgradeTier> {
val upgradeTiers = mutableListOf<WvwUpgradeTier>()
var yaksRequired = 0
for (tier in tiers) {
// Yaks required is for the current tier and is not cumulative so the tier order matters.
yaksRequired += tier.yaksRequired
if (yaksDelivered < yaksRequired) {
// Since the requirement is not cumulative, then all remaining tiers are also not fulfilled.
break
}
// Have enough yaks so it has been upgraded another level.
upgradeTiers.add(tier)
}
return upgradeTiers
}
/**
* Calculates the ratio of delivered yaks to the total number of yaks required. The ratio is capped by the total.
*
* @param yaksDelivered the number of yaks delivered to the associated objective
* @return the ratio represented as a pair
*/
fun WvwUpgrade.yakRatio(yaksDelivered: Int): Pair<Int, Int> {
val total = tiers.sumOf { tier -> tier.yaksRequired }
val delivered = min(yaksDelivered, total)
return Pair(delivered, total)
}
/**
* Calculates the ratio of delivered yaks to the total number of yaks required for each tier.
*
* @param yaksDelivered the number of yaks delivered to the associated objective
* @return the ratios represented as a pair
*/
fun WvwUpgrade.yakRatios(yaksDelivered: Int): Collection<Pair<Int, Int>> {
var remaining = yaksDelivered
return tiers.map { tier ->
val subtract = min(remaining, tier.yaksRequired)
remaining -= subtract
Pair(subtract, tier.yaksRequired)
}
}
/**
* Determines whether the number of yaks delivered satisfies all upgrade tiers.
*
* @param yaksDelivered the number of yaks delivered to the associated objective
* @return true if the number of [yaksDelivered] fulfills all of the [WvwUpgradeTier.yaksRequired]
*/
fun WvwUpgrade.isFullyUpgraded(yaksDelivered: Int): Boolean {
val ratio = yakRatio(yaksDelivered)
return ratio.first == ratio.second
} | 2 | Kotlin | 0 | 0 | fcd2cdfa97d78ec10e44a84e10c9b13a01f896bb | 3,251 | GW2Wrapper | Apache License 2.0 |
fd-applet-server/src/main/kotlin/io/github/haruhisa_enomoto/server/utils/Stringify.kt | haruhisa-enomoto | 628,298,470 | false | null | package io.github.haruhisa_enomoto.server.utils
import io.github.haruhisa_enomoto.backend.algebra.Indec
/**
* Returns a comparator that first compares lists by their sizes, then lexicographically
* if the sizes are equal.
*/
fun <T : Comparable<T>> getMyComparator(): Comparator<List<T>> {
return Comparator { o1, o2 ->
// Compare by list size first
val lengthCmp = o1.size.compareTo(o2.size)
if (lengthCmp != 0) return@Comparator lengthCmp
// If sizes are equal, compare elements lexicographically
o1.zip(o2) { a, b -> a.compareTo(b) }.firstOrNull { it != 0 } ?: 0
}
}
/**
* Extension function to sort a Collection<Collection<T>>.
* The function first sorts each sublist if deep.
* Then if shallow, sorts all lists by their lengths.
* If the lengths are equal, it sorts them lexicographically.
*
* @return Sorted list of lists.
*/
fun <T : Comparable<T>> Collection<Collection<T>>.mySorted(shallow: Boolean, deep : Boolean): List<List<T>> {
// Sort the elements of the original lists first
val tempList = if (deep) this.map { it.sorted() } else this.map { it.toList() }
// Apply the comparator to sort the list of lists
return if (shallow) tempList.sortedWith(getMyComparator()) else tempList
}
fun <T> Collection<Indec<T>>.toListString(sort: Boolean = true): List<String> {
return if (sort) {
this.sorted().map { it.toString() }
} else {
this.map { it.toString() }
}
}
fun <T> Collection<Collection<Indec<T>>>.toListListString(shallow: Boolean, deep: Boolean): List<List<String>> {
return this.mySorted(shallow, deep).map { it.map { indec -> indec.toString() } }
}
// toListListListString = A list of sequences of subcategories/modules
fun <T> Collection<Collection<Collection<Indec<T>>>>.toListListListString(): List<List<List<String>>> {
return this.map { it.toListListString(shallow = false, deep = true) }.sortedBy { it.size }
}
fun <T> Collection<Pair<Collection<Indec<T>>, Collection<Indec<T>>>>.toListPairListString(sort: Boolean = true): List<Pair<List<String>, List<String>>> {
if (!sort) {
return this.map { (first, second) ->
(first.toListString(false) to second.toListString(false))
}
}
val innerSortedPairs = this.map { (first, second) ->
(first.sorted() to second.sorted())
}
val sortedPairs = innerSortedPairs.sortedWith { p1, p2 ->
getMyComparator<Indec<T>>().compare(p1.first, p2.first)
}
return sortedPairs.map { (first, second) ->
(first.toListString(false) to second.toListString(false))
}
} | 0 | Kotlin | 0 | 0 | 8ec1afe14e9f0d6330d02652c1cd782a68fca5db | 2,695 | fd-applet | MIT License |
src/Day01.kt | gillyobeast | 574,413,213 | false | {"Kotlin": 27372} | import utils.appliedTo
import utils.readInput
fun main() {
fun caloriesPerElf(input: List<String>): MutableList<Int> {
val elvesCalories = mutableListOf<Int>()
var total = 0
input.forEach {
if (it.isBlank()) {
elvesCalories.add(total)
total = 0
} else {
total += it.toInt()
}
}
elvesCalories.add(total)
return elvesCalories
}
fun maxTotalCalories(input: List<String>): Int {
return caloriesPerElf(input)
.max()
}
fun totalCaloriesForTop3Elves(input: List<String>): Int {
return caloriesPerElf(input)
.sortedDescending()
.take(3)
// .also(::println)
.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
::maxTotalCalories.appliedTo(testInput, returns = 24000)
::totalCaloriesForTop3Elves.appliedTo(testInput, returns = 45000)
val input = readInput("Day01")
println("Max total calories: ${maxTotalCalories(input)}")
println("Top 3 elves' total: ${totalCaloriesForTop3Elves(input)}")
}
| 0 | Kotlin | 0 | 0 | 8cdbb20c1a544039b0e91101ec3ebd529c2b9062 | 1,213 | aoc-2022-kotlin | Apache License 2.0 |
src/main/kotlin/org/example/adventofcode/puzzle/Day07.kt | nikos-ds | 573,046,617 | false | null | package org.example.adventofcode.puzzle
import org.example.adventofcode.util.FileLoader
object Day07 {
private const val FILE_PATH = "/day-07-input.txt"
fun printSolution() {
println("- part 1: ${part1()}")
println("- part 2: ${part2()}")
}
fun part1(): Int {
val rootDirectory = parseInput()
printDir(rootDirectory, 0)
println("\n=================")
val allDirectories: Set<Directory> = collectAllDirectories(mutableSetOf(), rootDirectory)
return allDirectories.stream()
.map { it.size }
.filter { it -> it <= 100000 }
.toList()
.sum()
}
fun part2(): Int {
val totalDiskSpace = 70000000
val requiredFreeSpace = 30000000
val rootDirectory = parseInput()
val usedDiskSpace = rootDirectory.size
val needToFreeUp = usedDiskSpace + requiredFreeSpace - totalDiskSpace
val allDirectories: Set<Directory> = collectAllDirectories(mutableSetOf(), rootDirectory)
return allDirectories.stream()
.map { it.size }
.filter { it -> it >= needToFreeUp }
.sorted()
.toList()
.first()
}
fun printDir(directory: Directory, numberOfSpaces: Int) {
println("${" ".repeat(numberOfSpaces)}- ${directory.name} (dir, size=${directory.size})")
directory.directories.sortedBy { it.name }.forEach { dir -> printDir(dir, numberOfSpaces + 2) }
directory.files.sortedBy { it.name }.forEach { file -> println("${" ".repeat(numberOfSpaces + 2)}- ${file.name}, (file, size=${file.size})") }
}
fun collectAllDirectories(directories: MutableSet<Directory>, currentDirectory: Directory): Set<Directory> {
directories.add(currentDirectory)
currentDirectory.directories.forEach { dir -> collectAllDirectories(directories, dir) }
return directories
}
private fun parseInput(): Directory {
val allLines = FileLoader.loadFromFile<String>(FILE_PATH)
val goToRoot = "$ cd /"
val listItems = "$ ls"
val goUp = "$ cd .."
val goDown = """\$ cd (\w+)""".toRegex()
val directoryListing = """dir (\w+)""".toRegex()
val fileListing = """(\d+) ([a-z.]+)""".toRegex()
val rootDirectory = Directory("/", null)
var currentDirectory: Directory = rootDirectory
for (line in allLines) {
if (line == goToRoot) {
currentDirectory = rootDirectory
} else if (line == listItems) {
continue
} else if (line == goUp) {
currentDirectory = currentDirectory.parent!!
} else if (goDown.matches(line)) {
val (targetDirectoryName) = goDown.find(line)!!.destructured
currentDirectory = if (!currentDirectory.containsDirectory(targetDirectoryName)) {
val targetDirectory = Directory(targetDirectoryName, currentDirectory)
targetDirectory
} else {
currentDirectory.getChildDirectory(targetDirectoryName)!!
}
} else if (directoryListing.matches(line)) {
val (childDirectoryName) = directoryListing.find(line)!!.destructured
if (!currentDirectory.containsDirectory(childDirectoryName)) {
currentDirectory.directories.add(Directory(childDirectoryName, currentDirectory))
}
} else if (fileListing.matches(line)) {
val (fileSize, fileName) = fileListing.find(line)!!.destructured
if (!currentDirectory.containsFile(fileName)) {
currentDirectory.files.add(File(fileSize.toInt(), fileName))
incrementDirSize(currentDirectory, fileSize.toInt())
}
}
}
return rootDirectory
}
fun incrementDirSize(currentDirectory: Directory, increment: Int) {
currentDirectory.size += increment
if (currentDirectory.parent != null) {
incrementDirSize(currentDirectory.parent, increment)
}
}
class File(fileSize: Int, fileName: String) {
val size: Int
val name: String
init {
size = fileSize
name = fileName
}
}
class Directory(dirName: String, dirParent: Directory?) {
val parent: Directory?
val name: String
var size: Int = 0
var files: MutableSet<File> = HashSet()
var directories: MutableSet<Directory> = HashSet()
init {
name = dirName
parent = dirParent
}
fun containsFile(fileName: String): Boolean {
return files.stream()
.map { it -> it.name }
.toList()
.contains(fileName)
}
fun containsDirectory(directoryName: String): Boolean {
return directories.stream()
.map { it -> it.name }
.toList()
.contains(directoryName)
}
fun getChildDirectory(directoryName: String): Directory? {
if (containsDirectory(directoryName)) {
return directories.stream().filter { it -> it.name == directoryName }.findFirst().get()
}
return null
}
override fun toString(): String {
return """Directory:
| name: ${name}
| size: ${size}
| parent: ${parent?.name}
| subdirectories: ${directories.stream().map { it.name }.toList()}
| files: ${files.stream().map { it.name }.toList()}
""".trimMargin()
}
}
}
| 0 | Kotlin | 0 | 0 | 3f97096ebcd19f971653762fe29ddec1e379d09a | 5,782 | advent-of-code-2022-kotlin | MIT License |
year2022/src/cz/veleto/aoc/year2022/Day08.kt | haluzpav | 573,073,312 | false | {"Kotlin": 164348} | package cz.veleto.aoc.year2022
import cz.veleto.aoc.core.AocDay
import cz.veleto.aoc.core.Pos
import cz.veleto.aoc.core.get
import cz.veleto.aoc.core.rotateBy
class Day08(config: Config) : AocDay(config) {
private val treesInRow: Int = cachedInput.lastIndex
override fun part1(): String {
val visiblePoses = mutableSetOf<Pos>()
for (direction in Direction.entries) {
val sideStepDirection = direction.rotateBy(-1)
var rowStart: Pos? = when (direction) {
Direction.N -> treesInRow to treesInRow
Direction.E -> treesInRow to 0
Direction.S -> 0 to 0
Direction.W -> 0 to treesInRow
}
while (rowStart != null) {
var pos: Pos? = rowStart
var m = Char.MIN_VALUE
while (pos != null) {
val h = cachedInput[pos]
if (h > m) {
visiblePoses += pos
m = h
}
pos = nextInDirection(direction, pos)
}
rowStart = nextInDirection(sideStepDirection, rowStart)
}
}
return visiblePoses.count().toString()
}
override fun part2(): String {
var mv = Int.MIN_VALUE
for (bx in 0..treesInRow) {
for (by in 0..treesInRow) {
val b = bx to by
val bh = cachedInput[b]
val bv = Direction.entries.map { direction ->
var c: Pos? = nextInDirection(direction, b)
var count = 0
while (c != null) {
val ch = cachedInput[c]
count++
if (ch >= bh) break
c = nextInDirection(direction, c)
}
count
}.reduce { acc, i -> acc * i }
if (bv > mv) mv = bv
}
}
return mv.toString()
}
private fun nextInDirection(direction: Direction, current: Pos): Pos? {
val (x, y) = current
return when (direction) {
Direction.N -> (x - 1).takeUnless { it < 0 }?.let { it to y }
Direction.E -> (y + 1).takeUnless { it > treesInRow }?.let { x to it }
Direction.S -> (x + 1).takeUnless { it > treesInRow }?.let { it to y }
Direction.W -> (y - 1).takeUnless { it < 0 }?.let { x to it }
}
}
private enum class Direction {
N, E, S, W
}
}
| 0 | Kotlin | 0 | 1 | 32003edb726f7736f881edc263a85a404be6a5f0 | 2,585 | advent-of-pavel | Apache License 2.0 |
src/main/kotlin/com/github/davio/aoc/y2022/Day3.kt | Davio | 317,510,947 | false | {"Kotlin": 405939} | package com.github.davio.aoc.y2022
import com.github.davio.aoc.general.Day
import com.github.davio.aoc.general.getInputAsSequence
import kotlin.system.measureTimeMillis
fun main() {
println(Day3.getResultPart1())
measureTimeMillis {
println(Day3.getResultPart2())
}.also { println("Took $it ms") }
}
/**
* See [Advent of Code 2022 Day 3](https://adventofcode.com/2022/day/3#part2])
*/
object Day3 : Day() {
fun getResultPart1() = getInputAsSequence()
.map { line -> line.chunked(line.length / 2) }
.map { compartments ->
compartments[0].first { c -> compartments[1].contains(c) }
}.sumOf { c -> getPriority(c) }
fun getResultPart2() = getInputAsSequence()
.chunked(3)
.map { rucksacks ->
rucksacks[0].first { c -> rucksacks[1].contains(c) && rucksacks[2].contains(c) }
}.sumOf { c -> getPriority(c) }
private fun getPriority(c: Char): Int = (c.lowercaseChar().code - '`'.code) + if (c.isUpperCase()) 26 else 0
}
| 1 | Kotlin | 0 | 0 | 4fafd2b0a88f2f54aa478570301ed55f9649d8f3 | 1,024 | advent-of-code | MIT License |
advent/src/test/kotlin/org/elwaxoro/advent/y2020/Dec24.kt | elwaxoro | 328,044,882 | false | {"Kotlin": 376774} | package org.elwaxoro.advent.y2020
import org.elwaxoro.advent.PuzzleDayTester
import java.util.Locale
/**
* resource https://www.redblobgames.com/grids/hexagons/
* was SUPER helpful on this one, used the 3D coordinate system for this puzzle
*/
class Dec24 : PuzzleDayTester(24, 2020) {
override fun part1(): Any = flipYourShit().size
override fun part2(): Any = (1..100).fold(flipYourShit()) { hexes, round ->
flipAroundRightRoundLikeARecordBaby(hexes)
// .also {
// println("Day $round: ${it.size}")
// }
}.size
private fun flipYourShit(): Set<Hex> = parse().let { moveLists ->
val startingHex = Hex(0, 0, 0)
moveLists.map { moveList ->
moveList.fold(startingHex) { prevHex, move ->
prevHex.move(move)
}
}.groupBy { it }.filter { it.value.size % 2 != 0 }.keys
}
private fun flipAroundRightRoundLikeARecordBaby(flippedHexes: Set<Hex>): Set<Hex> = flippedHexes.map { hex ->
val neighbors = hex.neighbors()
val flippedNeighbors = neighbors.intersect(flippedHexes).size
val newFlippedNeighbors: List<Hex> = neighbors.filterNot { it in flippedHexes }.mapNotNull { neighbor ->
val flippedNeighborNeighbors = flippedHexes.intersect(neighbor.neighbors()).size
if (flippedNeighborNeighbors == 2) {
neighbor
} else {
null
}
}
if (flippedNeighbors == 0 || flippedNeighbors > 2) {
newFlippedNeighbors
} else {
newFlippedNeighbors.plus(hex)
}
}.flatten().toSet()
private data class Hex(val x: Int, val y: Int, val z: Int) {
fun move(dir: HexDir): Hex =
when (dir) {
HexDir.E -> Hex(x + 1, y - 1, z)
HexDir.W -> Hex(x - 1, y + 1, z)
HexDir.NE -> Hex(x + 1, y, z - 1)
HexDir.NW -> Hex(x, y + 1, z - 1)
HexDir.SE -> Hex(x, y - 1, z + 1)
HexDir.SW -> Hex(x - 1, y, z + 1)
}
fun neighbors(): List<Hex> = HexDir.values().map { move(it) }
}
private enum class HexDir { E, W, NE, NW, SE, SW }
private fun parse(): List<List<HexDir>> = load().map {
var str = it
val moves = mutableListOf<HexDir>()
while (str.isNotEmpty()) {
val move: String = if (str.first() == 's' || str.first() == 'n') {
str.substring(0, 2)
} else {
str.substring(0, 1)
}
moves.add(HexDir.valueOf(move.uppercase(Locale.getDefault())))
str = str.drop(move.length)
}
moves
}
}
| 0 | Kotlin | 4 | 0 | 1718f2d675f637b97c54631cb869165167bc713c | 2,725 | advent-of-code | MIT License |
src/main/kotlin/10/10.kt | Wrent | 225,133,563 | false | null | package `10`
import Coord
import java.lang.Math.abs
import java.lang.Math.atan2
fun main() {
val asteroids = parseAsteroids(INPUT10)
val visibleAsteroids = mutableMapOf<Coord, Set<Coord>>()
asteroids.forEach {
val visible = getVisible(it, asteroids)
visibleAsteroids.put(it, visible)
}
println("first result")
visibleAsteroids.maxBy { it.value.size }.let { println("${it?.key} ${it?.value?.size}") }
println("second result")
val base = visibleAsteroids.maxBy { it.value.size }?.key!!
val asteroidsFromBase = asteroids
.filter { it != base }
.map { AsteroidInfo(it, getDegree(base, it), getDist(base, it)) }
.groupBy { it.degree }
.mapValues { it.value.toMutableList() }
.toMutableMap()
println(removeByLaser(asteroidsFromBase, 200).let { it.x * 100 + it.y })
}
fun removeByLaser(asteroidsFromBase: MutableMap<Double, MutableList<AsteroidInfo>>, cnt: Int): Coord {
val degrees = asteroidsFromBase.keys.sorted()
var i = 0
var j = 0
while (i <= cnt) {
var degree: Double? = null
var closest: AsteroidInfo? = null
do {
degree = dgr(degrees, j)
closest = asteroidsFromBase[degree]?.minBy { it.distance }
j++
} while (closest == null)
println("Vaporizing $i asteroid: $closest")
asteroidsFromBase[degree]?.removeIf { it == closest }
i++
if (i == cnt) {
return closest.coord
}
}
throw RuntimeException()
}
fun dgr(degrees: List<Double>, i: Int): Double {
return degrees[i % degrees.size]
}
fun getVisible(asteroid: Coord, asteroids: MutableSet<Coord>): MutableSet<Coord> {
val asteroidsWithVisibility = mutableMapOf<Coord, Boolean>()
asteroids.forEach { asteroidsWithVisibility.put(it, true) }
asteroidsWithVisibility[asteroid] = false
asteroids.forEach { checked ->
if (asteroid != checked) {
asteroids.forEach { other ->
if (asteroid != other) {
if (checked != other) {
if (areOnSameLineOnSameSide(asteroid, checked, other)) {
if (isCloser(asteroid, checked, other)) {
asteroidsWithVisibility[other] = false
} else {
asteroidsWithVisibility[checked] = false
}
}
}
}
}
}
}
return asteroidsWithVisibility.filter { it.value == true }.keys.toMutableSet()
}
fun isCloser(a: Coord, b: Coord, c: Coord): Boolean {
val distA = getDist(a, b)
val distB = getDist(a, c)
return distA <= distB
}
fun getDist(a: Coord, b: Coord): Int {
return (b.x - a.x) * (b.x - a.x) + (b.y - a.y) * (b.y - a.y)
}
fun areOnSameLineOnSameSide(a: Coord, b: Coord, c: Coord): Boolean {
val sameLine = (c.y - b.y) * (b.x - a.x) == (b.y - a.y) * (c.x - b.x)
return sameLine && getDist(b, c) < getDist(a, b) + getDist(a, c)
}
private fun getDegree(a: Coord, b: Coord): Double {
val dx = a.x - b.x
val dy = -(a.y - b.y)
var inRads = atan2(dy.toDouble(), dx.toDouble())
inRads = if (inRads < 0) abs(inRads) else 2 * Math.PI - inRads
val result = Math.toDegrees(inRads) - 90.0
return if (result < 0) 360.0 + result else result
}
private fun parseAsteroids(input: String): MutableSet<Coord> {
val asteroids = mutableSetOf<Coord>()
input.split("\n").forEachIndexed { rowIndex, line ->
line.forEachIndexed { colIndex, char ->
if (char == '#') {
asteroids.add(Coord(colIndex, rowIndex))
}
}
}
return asteroids
}
data class AsteroidInfo(val coord: Coord, val degree: Double, val distance: Int)
const val INPUT10 = """##.##..#.####...#.#.####
##.###..##.#######..##..
..######.###.#.##.######
.#######.####.##.#.###.#
..#...##.#.....#####..##
#..###.#...#..###.#..#..
###..#.##.####.#..##..##
.##.##....###.#..#....#.
########..#####..#######
##..#..##.#..##.#.#.#..#
##.#.##.######.#####....
###.##...#.##...#.######
###...##.####..##..#####
##.#...#.#.....######.##
.#...####..####.##...##.
#.#########..###..#.####
#.##..###.#.######.#####
##..##.##...####.#...##.
###...###.##.####.#.##..
####.#.....###..#.####.#
##.####..##.#.##..##.#.#
#####..#...####..##..#.#
.##.##.##...###.##...###
..###.########.#.###..#."""
const val TEST101 = """.#..#
.....
#####
....#
...##"""
const val TEST102 = """......#.#.
#..#.#....
..#######.
.#.#.###..
.#..#.....
..#....#.#
#..#....#.
.##.#..###
##...#..#.
.#....####"""
const val TEST103 = """#.#...#.#.
.###....#.
.#....#...
##.#.#.#.#
....#.#.#.
.##..###.#
..#...##..
..##....##
......#...
.####.###."""
const val TEST104 = """.#..#..###
####.###.#
....###.#.
..###.##.#
##.##.#.#.
....###..#
..#.#..#.#
#..#.#.###
.##...##.#
.....#.#.."""
const val TEST105 = """.#..##.###...#######
##.############..##.
.#.######.########.#
.###.#######.####.#.
#####.##.#.##.###.##
..#####..#.#########
####################
#.####....###.#.#.##
##.#################
#####.##.###..####..
..######..##.#######
####.##.####...##..#
.#####..#.######.###
##...#.##########...
#.##########.#######
.####.#.###.###.#.##
....##.##.###..#####
.#.#.###########.###
#.#.#.#####.####.###
###.##.####.##.#..##"""
const val TEST_VAPOR = """.#....#####...#..
##...##.#####..##
##...#...#.#####.
..#.....#...###..
..#.#.....#....##""" | 0 | Kotlin | 0 | 0 | 0a783ed8b137c31cd0ce2e56e451c6777465af5d | 5,519 | advent-of-code-2019 | MIT License |
simpleCykParser/src/main/kotlin/org/michaeldadams/simpleCykParser/grammar/Grammar.kt | adamsmd | 668,129,808 | false | null | /** Types for representing a grammar. */
package org.michaeldadams.simpleCykParser.grammar
import org.michaeldadams.simpleCykParser.util.EqRegex
import org.michaeldadams.simpleCykParser.util.Generated as Gen
// ================================================================== //
// Terminals and Nonterminals
// ================================================================== //
/**
* A terminal or nonterminal in the grammar. Note that terminals and
* nonterminals have separate namespaces.
*/
sealed interface Symbol
/**
* A terminal in the grammar.
*
* @property name the name of the terminal
*/
@Gen data class Terminal(val name: String) : Symbol
/**
* A nonterminal in the grammar.
*
* @property name the name of the nonterminal
*/
@Gen data class Nonterminal(val name: String) : Symbol
// ================================================================== //
// Lexing
// ================================================================== //
/**
* A lexical rule for a terminal.
*
* @property terminal the terminal that this lexical rule is for
* @property regex the regular expression defining the syntax of the terminal
*/
@Gen data class TerminalRule(val terminal: Terminal, val regex: EqRegex)
/**
* The combined lexical rules of a language.
*
* Multiple rules for the same terminal are allowed.
*
* When multiple lexical rules match, the longest match wins. If there are
* multiple longest matches, which ever rule is earliest in [terminals] wins.
*
* @property whitespace the regular expression defining the synatx of whitespace
* and comments
* @property terminalRules the terminal rules for language
*/
@Gen data class LexRules(val whitespace: EqRegex, val terminalRules: List<TerminalRule>)
// ================================================================== //
// Parsing
// ================================================================== //
/**
* Labeled symbols in the right-hand side of a production.
*
* Note that [label] is not used by the parsing algorithm but may be useful to
* help users understand the role of different parts of a production.
*
* @property label an optional label for this element
* @property symbol optionally named symbols that this production expands to
*/
@Gen data class RhsElement(val label: String?, val symbol: Symbol)
/**
* The right-hand side of a (labeled) production.
*
* Note that [label] is not used by the parsing algorithm but is useful for
* debugging and telling one production from another.
*
* @property label an optional label for this production
* @property elements optionally named symbols that this production expands to
*/
@Gen data class Rhs(val label: String?, val elements: List<RhsElement>)
/**
* The combined parsing rules of a language.
*
* Note that this does not represent single productions explicitly. Instead
* the [productionMap] maps the left-hand sides of productions to right-hand
* sides of productions.
*
* @property start the start symbol of the language
* @property productionMap a map from a production left-hand side to the set of
* right-hand sides in productions with that left-hand side
*/
@Gen data class ParseRules(val start: Symbol, val productionMap: Map<Nonterminal, Set<Rhs>>)
// ================================================================== //
// Lexing and Parsing Together
// ================================================================== //
/**
* The lexing and parsing rules of a language.
*
* @property lexRules the lexing rules of the language
* @property parseRules the parsing rules of the language
*/
@Gen data class Grammar(val lexRules: LexRules, val parseRules: ParseRules)
| 0 | Kotlin | 0 | 0 | 23f1485bc0e56c9f6fa438053fc526066cf5a7f4 | 3,685 | simpleCykParser | MIT License |
src/main/kotlin/com/nibado/projects/advent/y2017/Day03.kt | nielsutrecht | 47,550,570 | false | null | package com.nibado.projects.advent.y2017
import com.nibado.projects.advent.Day
object Day03 : Day {
val input = 277678
override fun part1() : String {
var remainder = input
var ring = 0
while(remainder > 0) {
val size = if (ring == 0) 1 else size(ring) - size(ring - 1)
if(remainder <= size) {
break
}
remainder -= size
ring++
}
var x = ring
var y = ring
for(i in 0 .. (remainder - 1)) {
val l = i / (ring * 2)
when(l) {
0 -> y--
1 -> x--
2 -> y++
3 -> x++
}
}
return (Math.abs(x) + Math.abs(y)).toString()
}
override fun part2() : String {
val map = mutableMapOf<Point, Int?>()
var r = 0
var current = Point(0,0)
map.put(current, 1)
var count = 0
while(true) {
var points = ring(r)
current = Point(r, r)
for(p in points) {
current = current.add(p)
count++
if(!map.containsKey(current)) {
val sum = current.neighbors().map { map.getOrDefault(it,0)!! }.sum()
if(sum > input) {
return sum.toString()
} else {
map.put(current, sum)
}
}
}
r++
}
}
data class Point(val x: Int, val y: Int) {
fun add(other: Point): Point =
Point(this.x + other.x, this.y + other.y)
fun neighbors() : List<Point> = listOf(
Point(-1, -1),
Point(0, -1),
Point(1, -1),
Point(-1, 0),
Point(1, 0),
Point(-1, 1),
Point(0, 1),
Point(1, 1)
).map { this.add(it) }
}
fun ring(ring: Int) : List<Point> {
if(ring == 0) {
return listOf(Point(0, 0))
}
val size = if (ring == 0) 1 else size(ring) - size(ring - 1)
return (0 until size).map { it / (ring * 2) }.map { when(it) {
0 -> Point(0, -1)
1 -> Point(-1, 0)
2 -> Point(0, 1)
3 -> Point(1, 0)
else -> Point(0, 0)
} }.toList()
}
fun size(ring: Int) : Int {
val width = ring * 2 + 1
return width * width
}
} | 1 | Kotlin | 0 | 15 | b4221cdd75e07b2860abf6cdc27c165b979aa1c7 | 2,534 | adventofcode | MIT License |
src/main/kotlin/dev/bogwalk/batch4/Problem45.kt | bog-walk | 381,459,475 | false | null | package dev.bogwalk.batch4
import dev.bogwalk.util.maths.isHexagonalNumber
import dev.bogwalk.util.maths.isPentagonalNumber
import dev.bogwalk.util.maths.isTriangularNumber
/**
* Problem 45: Triangular, Pentagonal, & Hexagonal
*
* https://projecteuler.net/problem=45
*
* Goal: Given a & b, find all numbers below N that are both types of numbers queried (as below).
*
* Constraints: 2 <= N <= 2e14
* a < b
* a,b in {3, 5, 6} -> {triangle, pentagonal, hexagonal}
*
* Triangle Number:
*
* tN = n(n + 1) / 2
*
* Pentagonal Number:
*
* pN = n(3n - 1) / 2
*
* Hexagonal Number:
*
* hN = n(2n - 1)
*
* Some numbers can be all 3 type ->
* e.g. T_1 = P_1 = H_1 = 1
* T_285 = P_165 = H_143 = 40755
*
* e.g.: N = 10_000, a = 3, b = 5
* result = {1, 210}
* N = 100_000, a = 5, b = 6
* result = {1, 40755}
*/
class TriPentHex {
/**
* HackerRank specific implementation will never request numbers that are both triangular and
* hexagonal.
*
* Solution is optimised by generating the fastest growing number type first. Hexagonal
* numbers jump to the limit faster than the other 2, and the pentagonal number sequence
* grows faster than triangular numbers.
*
* SPEED (WORSE) 319.36ms for N = 2e14, pentagonal-hexagonal combo
*/
fun commonNumbers(n: Long, a: Int, b: Int): List<Long> {
val common = mutableListOf(1L)
var i = 2L
if (a == 3 && b == 5) {
while (true) {
val pentagonal = i * (3 * i - 1) / 2
if (pentagonal >= n) break
if (pentagonal.isTriangularNumber() != null) {
common.add(pentagonal)
}
i++
}
} else { // a == 5 && b == 6
while (true) {
val hexagonal = i * (2 * i - 1)
if (hexagonal >= n) break
if (hexagonal.isPentagonalNumber() != null) {
common.add(hexagonal)
}
i++
}
}
return common
}
/**
* For triangular-pentagonal combos, where T_x = P_y:
*
* x(x + 1) / 2 = y(3y - 1) / 2, after completing the square becomes:
*
* (6x - 1)^2 - 3(2y + 1)^2 = -2, a diophantine:
*
* 36x^2 - 12x - 12y^2 - 12y, solved for 2 integer variables:
*
* T_(x+1) = -2T_x - P_y and
*
* P_(y+1) = -3T_x - 2P_y - 1
*
* For pentagonal-hexagonal combos, where P_x = H_y:
*
* x(3x - 1) / 2 = y(2y - 1), after completing the square becomes:
*
* (6x - 1)^2 - 3(4y - 1)^2 = -2, a diophantine:
*
* 36x^2 - 12x - 48y^2 + 24y, solved for 2 integer variables:
*
* P_(x+1) = 97P_x + 112H_y - 44 and
*
* H_(y+1) = 84P_x + 97H_y - 38
*
* SPEED (BETTER) 3.7e4ns for N = 2e14, pentagonal-hexagonal combo
*/
fun commonNumbersFormula(n: Long, a: Int, b: Int): List<Long> {
val common = mutableListOf<Long>()
// P_1 = H_1 = 1
var x = 1
var y = 1
var num = 1L
if (a == 3 && b == 5) {
while (num < n) {
// negative terms signify non-integer solutions of the diophantine
if (x > 0L && y > 0L) common.add(num)
x = (-2 * x - y).also {
y = -3 * x - 2 * y - 1
}
// could insert term into either triangular or pentagonal formula
num = 1L * y * (y + 1) / 2
}
} else { // a == 5 && b == 6
while (num < n) {
if (x > 0 && y > 0) common.add(num)
x = (97 * x + 112 * y - 44).also {
y = 84 * x + 97 * y - 38
}
num = 1L * y * (2 * y - 1)
}
}
return common
}
/**
* Project Euler specific implementation that finds the next number, after {1, 40755} that is
* triangular, pentagonal, and hexagonal.
*
* All hexagonal numbers are a subset of triangular numbers made from an odd n,
* as T_(2n - 1) == H_n, based on completing the squares below:
*
* n(n + 1) / 2 = m(2m - 1)
*
* n^2 + n = 4m^2 - 2m
*
* (n + 0.5)^2 = 4(m - 0.25)^2
*
* n = 2m - 1
*
* So this solution only needs to check for hexagonal numbers that are also pentagonal.
*/
fun nextTripleType(): Long {
var next: Long = 40755
while (true) {
next++
if (
next.isHexagonalNumber() != null &&
next.isPentagonalNumber() != null
) break
}
return next
}
} | 0 | Kotlin | 0 | 0 | 62b33367e3d1e15f7ea872d151c3512f8c606ce7 | 4,826 | project-euler-kotlin | MIT License |
src/main/kotlin/de/nosswald/aoc/days/Day09.kt | 7rebux | 722,943,964 | false | {"Kotlin": 34890} | package de.nosswald.aoc.days
import de.nosswald.aoc.Day
// https://adventofcode.com/2023/day/9
object Day09 : Day<Int>(9, "Mirage Maintenance") {
private fun parseInput(input: List<String>): List<List<Int>> {
return input.map { line -> line.split(" ").map(String::toInt) }
}
private fun nextInSequence(differences: List<Int>): Int {
if (differences.sum() == 0) {
return 0
}
val next = differences.zipWithNext().map { it.second - it.first }
return differences.last() + nextInSequence(next)
}
override fun partOne(input: List<String>): Int {
return parseInput(input).sumOf(::nextInSequence)
}
override fun partTwo(input: List<String>): Int {
return parseInput(input).map(List<Int>::reversed).sumOf(::nextInSequence)
}
override val partOneTestExamples: Map<List<String>, Int> = mapOf(
listOf(
"0 3 6 9 12 15",
"1 3 6 10 15 21",
"10 13 16 21 30 45",
) to 114
)
override val partTwoTestExamples: Map<List<String>, Int> = mapOf(
listOf(
"0 3 6 9 12 15",
"1 3 6 10 15 21",
"10 13 16 21 30 45",
) to 2
)
}
| 0 | Kotlin | 0 | 1 | 398fb9873cceecb2496c79c7adf792bb41ea85d7 | 1,227 | advent-of-code-2023 | MIT License |
src/main/kotlin/se/brainleech/adventofcode/aoc2015/Aoc2015Day05.kt | fwangel | 435,571,075 | false | {"Kotlin": 150622} | package se.brainleech.adventofcode.aoc2015
import se.brainleech.adventofcode.compute
import se.brainleech.adventofcode.readLines
import se.brainleech.adventofcode.verify
class Aoc2015Day05 {
companion object {
private val NON_VOWELS = Regex("[^aeiou]")
private val DOUBLE_CHAR = Regex("([a-z])\\1")
private val NAUGHTY_COMBINATIONS = Regex("(ab|cd|pq|xy)")
private val PAIR = Regex("([a-z]{2}).*\\1")
private val SURROUNDING = Regex("([a-z]).\\1")
}
fun part1(input: List<String>): Int {
return input
.asSequence()
.filter { !it.contains(NAUGHTY_COMBINATIONS) }
.filter { it.replace(NON_VOWELS, "").length > 2 }
.filter { it.contains(DOUBLE_CHAR) }
.count()
}
fun part2(input: List<String>): Int {
return input
.asSequence()
.filter { it.contains(PAIR) }
.filter { it.contains(SURROUNDING) }
.count()
}
}
fun main() {
val solver = Aoc2015Day05()
val prefix = "aoc2015/aoc2015day05"
val testData = readLines("$prefix.test.txt")
val realData = readLines("$prefix.real.txt")
verify(3, solver.part1(testData))
compute({ solver.part1(realData) }, "$prefix.part1 = ")
verify(2, solver.part2(testData))
compute({ solver.part2(realData) }, "$prefix.part2 = ")
}
| 0 | Kotlin | 0 | 0 | 0bba96129354c124aa15e9041f7b5ad68adc662b | 1,383 | adventofcode | MIT License |
src/main/kotlin/aoc2022/Day09.kt | lukellmann | 574,273,843 | false | {"Kotlin": 175166} | package aoc2022
import AoCDay
import util.illegalInput
import kotlin.math.abs
import kotlin.math.sign
// https://adventofcode.com/2022/day/9
object Day09 : AoCDay<Int>(
title = "Rope Bridge",
part1ExampleAnswer = 13,
part1Answer = 6067,
part2ExampleAnswer = 1,
part2Answer = 2471,
) {
private data class Position(val x: Int, val y: Int)
private val STARTING_POSITION = Position(x = 0, y = 0)
private fun simulateRopeAndCountTailPositions(headMotions: String, knots: Int): Int {
val knotPositions = MutableList(size = knots) { STARTING_POSITION }
val tailPositions = hashSetOf(knotPositions.last())
headMotions
.lineSequence()
.map { motion -> motion.split(' ', limit = 2) }
.forEach { (direction, steps) ->
repeat(steps.toInt()) {
val (xh, yh) = knotPositions[0] // head
knotPositions[0] = when (direction) {
"U" -> Position(x = xh, y = yh + 1)
"D" -> Position(x = xh, y = yh - 1)
"R" -> Position(x = xh + 1, y = yh)
"L" -> Position(x = xh - 1, y = yh)
else -> illegalInput(direction)
}
for (i in 1..knotPositions.lastIndex) {
val prev = knotPositions[i - 1]
val (x, y) = knotPositions[i]
val dx = prev.x - x
val dy = prev.y - y
if (abs(dx) > 1 || abs(dy) > 1) {
knotPositions[i] = Position(x = x + dx.sign, y = y + dy.sign)
} else {
return@repeat // rest of the tail won't move either -> continue with next head motion
}
}
tailPositions.add(knotPositions.last())
}
}
return tailPositions.size
}
override fun part1(input: String) = simulateRopeAndCountTailPositions(headMotions = input, knots = 2)
override fun part2(input: String) = simulateRopeAndCountTailPositions(headMotions = input, knots = 10)
}
| 0 | Kotlin | 0 | 1 | 344c3d97896575393022c17e216afe86685a9344 | 2,229 | advent-of-code-kotlin | MIT License |
src/Day13.kt | laricchia | 434,141,174 | false | {"Kotlin": 38143} | import org.jetbrains.kotlinx.multik.api.mk
import org.jetbrains.kotlinx.multik.api.zeros
import org.jetbrains.kotlinx.multik.ndarray.data.D2Array
import org.jetbrains.kotlinx.multik.ndarray.data.get
import org.jetbrains.kotlinx.multik.ndarray.data.set
import org.jetbrains.kotlinx.multik.ndarray.operations.count
import org.jetbrains.kotlinx.multik.ndarray.operations.plus
fun firstPart13(list : List<List<Int>>, folds : List<Fold>) {
val (sizeX, sizeY) = (list.maxOf { it[0] } + 1) to (list.maxOf { it[1] } + 1)
val sheet = mk.zeros<Int>(sizeX, sizeY)
list.map {
sheet[it[0], it[1]] = 1
}
val fold = folds.first()
val firstFold = sheet.fold(fold)
println(firstFold.count { it > 0 })
}
fun secondPart13(list : List<List<Int>>, folds : List<Fold>) {
val (sizeX, sizeY) = ((folds.filter { it.axe == Axis.X }.maxOf { it.index } * 2) + 1) to ((folds.filter { it.axe == Axis.Y }.maxOf { it.index } * 2) + 1)
val sheet = mk.zeros<Int>(sizeX, sizeY)
list.map {
sheet[it[0], it[1]] = 1
}
var currentSheet = sheet
for (fold in folds) {
currentSheet = currentSheet.fold(fold)
}
val newSheet = mk.zeros<Byte>(currentSheet.shape[0], currentSheet.shape[1])
for (index in newSheet.multiIndices) {
if (currentSheet[index[0], index[1]] > 0) newSheet[index[0], index[1]] = '#'.code.toByte()
}
val trSheep = currentSheet.transpose()
for (i in trSheep.multiIndices) {
print(if (trSheep[i[0], i[1]] > 0) "███" else " ")
if (i[1] == trSheep.shape[1] - 1) print("\n")
}
}
fun main() {
val input : List<String> = readInput("Day13")
val inputDotsSize = input.indexOfFirst { it.isEmpty() }
val inputDots = input.take(inputDotsSize).map { it.split(",").map { it.toInt() } }
val instructions = input.takeLast(input.size - inputDotsSize).filterNot { it.isEmpty() }
val folds = instructions.map {
val splits = it.split("=")
Fold(if (splits[0].contains("x")) Axis.X else Axis.Y, splits[1].toInt())
}
firstPart13(inputDots, folds)
secondPart13(inputDots, folds)
}
enum class Axis { X, Y }
data class Fold(val axe : Axis, val index : Int)
fun D2Array<Int>.fold(fold : Fold) : D2Array<Int> {
val sizeX = this.shape[0]
val sizeY = this.shape[1]
when (fold.axe) {
Axis.X -> {
val firstPart = this[0 .. fold.index, 0 .. sizeY]
val secondPart = this[fold.index + 1 .. sizeX, 0 .. sizeY]
val rotatedSecond = mk.zeros<Int>(secondPart.shape[0], secondPart.shape[1])
for (i in secondPart.multiIndices) {
rotatedSecond[secondPart.shape[0] - i[0] - 1, i[1]] = secondPart[i[0], i[1]]
}
return firstPart + rotatedSecond
}
Axis.Y -> {
val yDim = (shape[1] - 1) / 2
val firstPart = this[0 .. sizeX, 0 .. yDim]
val secondPart = this[0 .. sizeX, (if (yDim == fold.index) fold.index + 1 else fold.index) .. sizeY]
val rotatedSecond = mk.zeros<Int>(secondPart.shape[0], secondPart.shape[1])
for (i in secondPart.multiIndices) {
rotatedSecond[i[0], secondPart.shape[1] - 1 - i[1]] = secondPart[i[0], i[1]]
}
return firstPart + rotatedSecond
}
}
}
| 0 | Kotlin | 0 | 0 | 7041d15fafa7256628df5c52fea2a137bdc60727 | 3,342 | Advent_of_Code_2021_Kotlin | Apache License 2.0 |
src/main/kotlin/Day02.kt | akowal | 434,506,777 | false | {"Kotlin": 30540} | fun main() {
println(Day02.solvePart1())
println(Day02.solvePart2())
}
object Day02 {
private val input = readInput("day02")
.map { it.split(" ") }
.map { (direction, distance) -> direction to distance.toInt() }
fun solvePart1(): Int {
var depth = 0
var totalDistance = 0
input.forEach { (direction, distance) ->
when (direction) {
"forward" -> totalDistance += distance
"up" -> depth -= distance
"down" -> depth += distance
}
}
return depth * totalDistance
}
fun solvePart2(): Int {
var aim = 0
var depth = 0
var totalDistance = 0
input.forEach { (direction, distance) ->
when (direction) {
"forward" -> {
totalDistance += distance
depth += aim * distance
}
"up" -> aim -= distance
"down" -> aim += distance
}
}
return depth * totalDistance
}
}
| 0 | Kotlin | 0 | 0 | 08d4a07db82d2b6bac90affb52c639d0857dacd7 | 1,094 | advent-of-kode-2021 | Creative Commons Zero v1.0 Universal |
src/main/kotlin/g1601_1700/s1626_best_team_with_no_conflicts/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1601_1700.s1626_best_team_with_no_conflicts
// #Medium #Array #Dynamic_Programming #Sorting
// #2023_06_16_Time_370_ms_(100.00%)_Space_40.5_MB_(100.00%)
class Solution {
private class Player(
val age: Int,
val score: Int
) : Comparable<Player> {
override fun compareTo(other: Player) =
if (age == other.age) {
other.score - score
} else {
other.age - age
}
}
fun bestTeamScore(scores: IntArray, ages: IntArray): Int {
val playerList = mutableListOf<Player>()
repeat(scores.size) {
playerList.add(
Player(
age = ages[it],
score = scores[it]
)
)
}
playerList.sort()
val dp = IntArray(scores.size)
var bestScore = 0
for (i in scores.indices) {
val currentPlayer = playerList[i]
dp[i] = currentPlayer.score
for (j in 0 until i) {
if (playerList[j].score >= currentPlayer.score) {
dp[i] = maxOf(dp[i], dp[j] + currentPlayer.score)
}
}
bestScore = maxOf(bestScore, dp[i])
}
return bestScore
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,295 | LeetCode-in-Kotlin | MIT License |
src/commonMain/kotlin/advent2020/day15/Day15Puzzle.kt | jakubgwozdz | 312,526,719 | false | null | package advent2020.day15
fun part1(input: String): String {
val starting = input.trim().split(',').map { it.toInt() }
return solve(starting, 2020).toString()
}
fun part2(input: String): String {
val starting = input.trim().split(',').map { it.toInt() }
return solve(starting, 30000000).toString()
}
fun solve(starting: List<Int>, turns: Int): Int {
var turn = 0
var prevNumber = 0
val map = IntArray(turns + 1)
starting.forEach { number ->
turn++
map[number] = turn
prevNumber = number
}
while (turn < turns) {
val prevTurn = map[prevNumber].let { if (it == 0) turn else it }
val number = turn - prevTurn
map[prevNumber] = turn
turn++
prevNumber = number
}
return prevNumber
}
| 0 | Kotlin | 0 | 2 | e233824109515fc4a667ad03e32de630d936838e | 799 | advent-of-code-2020 | MIT License |
src/main/kotlin/Day01.kt | zychu312 | 573,345,747 | false | {"Kotlin": 15557} | interface Caloric {
val caloricIntake: Int
}
data class Item(override val caloricIntake: Int) : Caloric
data class Elf(val id: Int, val items: List<Item>) {
val totalCalories = items.sumOf { it.caloricIntake }
}
tailrec fun parseInputToElves(input: List<String>, acc: List<Elf> = emptyList()): List<Elf> {
if (input.isEmpty()) {
return acc
}
val elf = input
.takeWhile(String::isNotBlank)
.map(String::toInt)
.map { calories -> Item(calories) }
.let { items -> Elf(id = acc.size + 1, items) }
return parseInputToElves(input.drop(elf.items.size + 1), acc + elf)
}
fun main() {
val elves = parseInputToElves(loadFile("Day01Input.txt").readLines())
val maxCaloriesInInventory = elves.maxOf { elf -> elf.totalCalories }
println("Part 1: $maxCaloriesInInventory")
val sumOfTopThreeMostCaloricInventories = elves
.map { it.totalCalories }
.sortedDescending()
.take(3)
.sum()
println("Part 2: $sumOfTopThreeMostCaloricInventories")
}
| 0 | Kotlin | 0 | 0 | 3e49f2e3aafe53ca32dea5bce4c128d16472fee3 | 1,056 | advent-of-code-kt | Apache License 2.0 |
2020/src/year2020/day11/Day11.kt | eburke56 | 436,742,568 | false | {"Kotlin": 61133} | package year2020.day11
import util.readAllLines
private fun readInput(filename: String): Array<CharArray> {
val input = readAllLines(filename)
return input.map { it.toCharArray() }.toTypedArray()
}
val getCell = { map: Array<CharArray>, row: Int, col: Int ->
if (row in map.indices && col in map[row].indices) {
map[row][col]
} else {
'.'
}
}
val countOccupied = { map: Array<CharArray> ->
var occupied = 0
for (r in map.indices) {
for (c in map[r].indices) {
if (getCell(map, r, c) == '#') {
occupied++
}
}
}
occupied
}
val dumpMap = { map: Array<CharArray> ->
println("---------------------------")
map.forEach {
println (it.joinToString(""))
}
println()
}
private fun findSteadyState1(filename: String) {
val input = readInput(filename)
val cloneArray = { map: Array<CharArray> ->
Array(map.size) { map.get(it).clone() }
}
val countAdjacentOccupied = { map: Array<CharArray>, row: Int, col: Int ->
var occupied = 0
for (r in row-1..row+1) {
for (c in col-1..col+1) {
if (r == row && c == col) continue
if (getCell(map, r, c) == '#') {
occupied++
}
}
}
occupied
}
var changed = true
var map: Array<CharArray> = cloneArray(input)
while (changed) {
//dumpMap(map)
val newMap = cloneArray(map)
changed = false
for (row in map.indices) {
for (col in map[row].indices) {
val occupied = countAdjacentOccupied(map, row, col)
var newVal = getCell(map, row, col)
if (newVal == '#') {
if (occupied >= 4) {
newVal = 'L'
changed = true
}
} else if (newVal == 'L') {
if (occupied == 0) {
newVal = '#'
changed = true
}
}
newMap[row][col] = newVal
}
}
map = newMap
}
println ("Steady: $filename -> ${countOccupied(map)}")
}
private fun findSteadyState2(filename: String) {
val input = readInput(filename)
val cloneArray = { map: Array<CharArray> ->
Array(map.size) { map.get(it).clone() }
}
val countAdjacentOccupied = { map: Array<CharArray>, row: Int, col: Int ->
var occupied = 0
var iteration = 1
val alreadySeen = Array(3) { BooleanArray(3) { false } }
alreadySeen[1][1] = true // skip the cell we're looking at
// if we've already hit a seat in every direction, we're done
while (alreadySeen.any { rc -> rc.any { cell -> !cell } }) {
val minrow = row - iteration
val maxrow = row + iteration
val mincol = col - iteration
val maxcol = col + iteration
// if the range is completely out of bounds, we're done
if (minrow !in map.indices && maxrow !in map.indices &&
mincol !in map[0].indices && maxcol !in map[0].indices) {
break
}
val rowRange = minrow..maxrow
val colRange = mincol..maxcol
for (r in rowRange step iteration) {
for (c in colRange step iteration) {
// skip the cell
if (r == row && c == col) {
continue
}
// this puts i,j in [-1,1]. could do the outer loop better but I'm lazy
val i = (r - minrow) / iteration
val j = (c - mincol) / iteration
if (i in alreadySeen.indices && j in alreadySeen[i].indices) {
// if this cell is not in bounds, we're done in that direction
if (r !in map.indices || c !in map[0].indices) {
alreadySeen[i][j] = true
}
// already tested this direction
if (alreadySeen[i][j]) {
continue
}
when (getCell(map, r, c)) {
'#' -> {
occupied++
alreadySeen[i][j] = true
}
'L' -> {
alreadySeen[i][j] = true
}
'.' -> {
}
}
}
}
}
iteration++
}
occupied
}
var changed = true
var map: Array<CharArray> = cloneArray(input)
while (changed) {
val newMap = cloneArray(map)
changed = false
for (row in map.indices) {
for (col in map[row].indices) {
val occupied = countAdjacentOccupied(map, row, col)
var newVal = getCell(map, row, col)
if (newVal == '#') {
if (occupied >= 5) {
newVal = 'L'
changed = true
}
} else if (newVal == 'L') {
if (occupied == 0) {
newVal = '#'
changed = true
}
}
newMap[row][col] = newVal
}
}
map = newMap
}
println ("Steady 2: $filename -> ${countOccupied(map)}")
}
fun main() {
findSteadyState1("test.txt")
findSteadyState1("input.txt")
findSteadyState2("test.txt")
findSteadyState2("input.txt")
}
| 0 | Kotlin | 0 | 0 | 24ae0848d3ede32c9c4d8a4bf643bf67325a718e | 5,889 | adventofcode | MIT License |
kotlin/2021/qualification-round/cheating-detection/src/main/kotlin/NotConsideringIfCheatingSolution.kts | ShreckYe | 345,946,821 | false | null | import kotlin.math.exp
import kotlin.math.ln
fun main() {
val t = readLine()!!.toInt()
val p = readLine()!!.toInt()
repeat(t, ::testCase)
}
fun testCase(ti: Int) {
val results = List(100) {
readLine()!!.map { it - '0' }
}
// simple estimation by averaging
val ss = results.map { inverseSigmoid(it.average()).coerceIn(-3.0, 3.0) }
val qs = (0 until 10000).map { j ->
inverseSigmoid(results.asSequence().map { it[j] }.average()).coerceIn(-3.0, 3.0)
}
// logarithms of player probabilities
val lnPs = (ss zip results).asSequence().map { (s, rs) ->
(rs.asSequence() zip qs.asSequence()).map { (r, q) ->
val pCorrect = sigmoid(s - q)
val p = when (r) {
1 -> pCorrect; 0 -> 1 - pCorrect; else -> throw IllegalArgumentException(r.toString())
}
ln(p)
}.sum()
}
//println(lnPs.withIndex().toList().joinToString("\n"))
val y = lnPs.withIndex()./*min*/maxByOrNull { it.value }!!.index
/*// squared deviations
val sds = (ss zip results).asSequence().map { (s, rs) ->
(rs.asSequence() zip qs.asSequence()).map { (r, q) ->
val pCorrect = sigmoid(s - q)
(pCorrect - r).squared()
}.sum()
}
//println(sds.withIndex().toList().joinToString("\n"))
val y = sds.withIndex().*//*max*//*minByOrNull { it.value }!!.index*/
println("Case #${ti + 1}: ${y + 1}")
}
fun sigmoid(x: Double) =
1 / (1 + exp(-x))
fun inverseSigmoid(y: Double) =
ln(y / (1 - y))
fun Double.squared() =
this * this | 0 | Kotlin | 1 | 1 | 743540a46ec157a6f2ddb4de806a69e5126f10ad | 1,603 | google-code-jam | MIT License |
year2015/src/main/kotlin/net/olegg/aoc/year2015/day19/Day19.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2015.day19
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.year2015.DayOf2015
/**
* See [Year 2015, Day 19](https://adventofcode.com/2015/day/19)
*/
object Day19 : DayOf2015(19) {
private val TRANSITIONS = lines
.dropLast(2)
.map { it.split(" => ") }
.map { it.first() to it.last() }
private val MOLECULE = lines.last()
private fun applyTransitions(
molecule: String,
transition: Pair<Regex, String>
): Set<String> {
val (pattern, replacement) = transition
return pattern.findAll(molecule)
.map { molecule.replaceRange(it.range, replacement) }
.toSet()
}
override fun first(): Any? {
return TRANSITIONS
.map { it.first.toRegex() to it.second }
.flatMap { applyTransitions(MOLECULE, it) }
.toSet()
.size
}
override fun second(): Any? {
val reverse = TRANSITIONS.map { it.second.toRegex() to it.first }
val molecules = mutableMapOf(MOLECULE to 0)
val queue = ArrayDeque(listOf(MOLECULE))
while ("e" !in molecules && queue.isNotEmpty()) {
val curr = queue.removeFirst()
val size = molecules.getOrDefault(curr, Int.MAX_VALUE)
val next = reverse.flatMap { applyTransitions(curr, it) }.sortedBy { it.length }.take(2) // greedy approach
queue += next.filterNot { it in molecules }
molecules += next.associateWith { (molecules.getOrDefault(it, Int.MAX_VALUE)).coerceAtMost(size + 1) }
}
return molecules.getOrDefault("e", Int.MAX_VALUE)
}
}
fun main() = SomeDay.mainify(Day19)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 1,553 | adventofcode | MIT License |
src/main/day17/Part2.kt | ollehagner | 572,141,655 | false | {"Kotlin": 80353} | package day17
import common.Grid
fun main() {
val totalIterations = 1000000000000
val jetsfile = "day17/input.txt"
val (firstOccurrence, secondOccurrence) = countPeriodicity(jetsfile)
val period = secondOccurrence - firstOccurrence
val heightAtFirstOccurrence = solve(firstOccurrence, jetsfile)
val periodHeight = solve(secondOccurrence, jetsfile) - heightAtFirstOccurrence
val totalLoops = (totalIterations - firstOccurrence) / period
val remainder = (totalIterations - firstOccurrence) % period
val firstAndReminderHeight = solve((firstOccurrence + remainder).toInt(), jetsfile)
val totalHeight = firstAndReminderHeight + (periodHeight * totalLoops)
println("Day 17 part 2. Highest point: $totalHeight")
}
fun countPeriodicity(jetsFile: String): Pair<Int, Int> {
val rocks = Rock.rockIterator()
val jets =Jet.parse(jetsFile)
var grid = Grid(Floor.start().points, "-")
val seen = mutableMapOf<State, Int>()
var iterations = 0
while(true) {
iterations++
val state = dropRock(startPositionRelativeToFloor(rocks.next(), grid.max().y), grid, jets)
state.rock.parts.forEach { grid.set(it, "#") }
val normalizedState = state.copy(floor = state.floor.normalized())
if(seen.containsKey(normalizedState)) {
return seen[normalizedState]!! to iterations
}
seen[normalizedState] = iterations
}
}
| 0 | Kotlin | 0 | 0 | 6e12af1ff2609f6ef5b1bfb2a970d0e1aec578a1 | 1,430 | aoc2022 | Apache License 2.0 |
leetcode/src/daily/Q777.kt | zhangweizhe | 387,808,774 | false | null | package daily
fun main() {
// 777. 在LR字符串中交换相邻字符
// https://leetcode.cn/problems/swap-adjacent-in-lr-string/
println(canTransform1("LXXLXRLXXL", "XLLXRXLXLX"))
}
fun canTransform(start: String, end: String): Boolean {
// 满足题意的 start 和 end,需要具备以下条件
// 1、start 和 end 长度相同
// 2、start 和 end 中,L 的数量要一致,R 的数量也要一致,且 L 和 R 在 start 和 end 中的相对顺序要一致
// 3、因为是一个 LX 替换一个 XL,即 L 会越换越靠前,所以 end 中的 L 下标,要小于等于 start 中的
// 4、因为是一个 XR 替换一个 RX,即 R 会越换越考后,所以 end 中的 R 下标,要大于等于 start 中的
if (start.length != end.length) {
return false
}
var startIndex = 0
var endIndex = 0
while (startIndex < start.length && endIndex < end.length) {
while (startIndex < start.length && start[startIndex] == 'X') {
// 跳过 x
startIndex++
}
while (endIndex < end.length && end[endIndex] == 'X') {
// 跳过 x
endIndex++
}
if (startIndex < start.length && endIndex < end.length) {
if (start[startIndex] != end[endIndex]) {
// 相对顺序不一致,一个出现了 L,一个出现了 R
return false
}
if (start[startIndex] == 'L' && end[endIndex] == 'L') {
// end 的 L 下标,要小于等于 start 的 L 下标
if (endIndex > startIndex) {
// 不满足
return false
}
}
if (start[startIndex] == 'R' && end[endIndex] == 'R') {
// end 的 R 的下标,要大于等于 start 的 R 的下标
if (endIndex < startIndex) {
// 不满足
return false
}
}
startIndex++
endIndex++
}
}
// startIndex 或者 endIndex 走到最后了
while (startIndex < start.length) {
// endIndex 走到最后了,start 剩下的应该都是 X
if (start[startIndex++] != 'X') {
return false
}
}
while (endIndex < end.length) {
// startIndex 走到最后了,end 剩下的应该都是 X
if (end[endIndex++] != 'X') {
return false
}
}
return true
}
fun canTransform1(start: String, end: String): Boolean {
if (start.length != end.length) {
return false
}
var startIndex = 0
var endIndex = 0
while (startIndex < start.length && endIndex < end.length) {
// 跳过 X
while (startIndex < start.length && start[startIndex] == 'X') {
startIndex++
}
while (endIndex < end.length && end[endIndex] == 'X') {
endIndex++
}
if (startIndex < start.length && endIndex < end.length) {
if (start[startIndex] != end[endIndex]) {
// 一个是 L,一个是 R
// 跳过 X 后,start 和 end 中,L R 出现的相对顺序不一致
return false
}
// start[startIndex] == end[endIndex],都是 L,或者都是 R
// 判断下标
if (start[startIndex] == 'L') {
// start 中 L 的下标要大于等于 end 中 L 的下标
if (startIndex < endIndex) {
return false
}
}else if (start[startIndex] == 'R') {
// start 中 L 的下标要小于等于 end 中 R 的下标
if (startIndex > endIndex) {
return false
}
}
startIndex++
endIndex++
}
}
// start 或者 end 其中一个先遍历到终点
// start 先遍历到终点
if (startIndex == start.length) {
// 那么剩下的 end 中,只能都是 X
while (endIndex < end.length) {
if (end[endIndex] != 'X') {
return false
}
endIndex++
}
}
// end 先遍历到终点
if (endIndex == end.length) {
// 那么剩下的 start 中,只能都是 X
while (startIndex < start.length) {
if (start[startIndex] != 'X') {
return false
}
startIndex++
}
}
return true
} | 0 | Kotlin | 0 | 0 | 1d213b6162dd8b065d6ca06ac961c7873c65bcdc | 4,531 | kotlin-study | MIT License |
src/main/kotlin/nl/kelpin/fleur/advent2018/Day10.kt | fdlk | 159,925,533 | false | null | package nl.kelpin.fleur.advent2018
class Day10(input: List<String>) {
data class Star(val position: Point, val velocity: Point) {
companion object {
private val starRE = Regex("""position=< ?(-?\d+), +(-?\d+)> velocity=< ?(-?\d+), +(-?\d+)>""")
fun of(notation: String): Star? = starRE.matchEntire(notation)?.destructured
?.let { (x, y, dx, dy) ->
Star(Point(x.toInt(), y.toInt()), Point(dx.toInt(), dy.toInt()))
}
}
fun atTime(n: Int = 1): Star = Star(position.plus(velocity.times(n)), velocity)
}
data class Chart(val stars: List<Star>) {
companion object {
fun of(notation: List<String>): Chart = Chart(notation.mapNotNull(Star.Companion::of))
}
private fun charFor(p: Point): Char = if (stars.any { it.position == p }) '#' else ' '
private fun xRange(): IntRange = stars.map { it.position.x }.range()
private fun yRange(): IntRange = stars.map { it.position.y }.range()
fun area(): Long = xRange().length().toLong() * yRange().length().toLong()
fun atTime(n: Int = 1): Chart = Chart(stars.map { it.atTime(n) })
override fun toString(): String = yRange().joinToString("\n") { y ->
xRange().joinToString("") { x -> charFor(Point(x, y)).toString() }
}
}
private val initialState: Chart = Chart.of(input)
fun findAlignment(steps: IntRange): Int? = steps.asSequence()
.map { it to initialState.atTime(it) }
.zipWithNext()
.find { (current: Pair<Int, Chart>, next: Pair<Int, Chart>) -> next.second.area() > current.second.area() }
?.let { (current, _) -> current }
?.also { (_: Int, chart: Chart) -> println(chart) }
?.let { (time: Int, _: Chart) -> time }
} | 0 | Kotlin | 0 | 3 | a089dbae93ee520bf7a8861c9f90731eabd6eba3 | 1,867 | advent-2018 | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MinTimeToMakeRopeColorful.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
/**
* 1578. Minimum Time to Make Rope Colorful
* @see <a href="https://leetcode.com/problems/minimum-time-to-make-rope-colorful">Source</a>
*/
fun interface MinTimeToMakeRopeColorful {
operator fun invoke(colors: String, neededTime: IntArray): Int
}
class MinTimeToMakeRopeColorfulSF : MinTimeToMakeRopeColorful {
override fun invoke(colors: String, neededTime: IntArray): Int {
var res = neededTime[0]
var maxCost = neededTime[0]
for (i in 1 until colors.length) {
if (colors[i] != colors[i - 1]) {
res -= maxCost
maxCost = 0
}
res += neededTime[i]
maxCost = maxOf(maxCost, neededTime[i])
}
return res - maxCost
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,397 | kotlab | Apache License 2.0 |
lib/src/main/kotlin/aoc/day17/Day17.kt | Denaun | 636,769,784 | false | null | package aoc.day17
fun part1(input: String): Int {
val tetris = Tetris(7, parse(input))
tetris.simulate(2022)
return tetris.towerHeight()
}
data class Coordinate(val row: Int, val column: Int) {
infix operator fun plus(other: Coordinate): Coordinate =
Coordinate(row + other.row, column + other.column)
fun move(direction: Direction) = when (direction) {
Direction.LEFT -> Coordinate(row, column - 1)
Direction.RIGHT -> Coordinate(row, column + 1)
}
fun moveDown() = Coordinate(row - 1, column)
}
class Tetris(private val width: Int, directions: List<Direction>) {
private val directions: Iterator<Direction> = loop(directions)
private val rocks: Iterator<Rock> = loop(allRocks())
private val cave: MutableList<MutableList<Boolean>> = mutableListOf()
fun towerHeight(): Int = 1 + cave.indexOfLast { it.any() }
fun simulate(numRocks: Int) {
repeat(numRocks) {
val rock = rocks.next()
val bottomLeft = simulateRock(rock)
val rockIndices = rock.indices.map(bottomLeft::plus)
reserve(rockIndices.maxOf { it.row })
rockIndices.forEach {
cave[it.row][it.column] = true
}
}
}
private fun simulateRock(rock: Rock): Coordinate {
var bottomLeft = Coordinate(towerHeight() + 3, 2)
while (true) {
tryPushing(bottomLeft, directions.next(), rock)?.also { bottomLeft = it }
tryFalling(bottomLeft, rock)?.also { bottomLeft = it } ?: return bottomLeft
}
}
private fun reserve(height: Int) {
if (cave.size > height) {
return
}
cave.addAll(List(height - cave.size + 1) { MutableList(width) { false } })
}
private fun tryFalling(bottomLeft: Coordinate, rock: Rock): Coordinate? =
bottomLeft.moveDown().takeUnless { collides(rock, it) }
private fun tryPushing(bottomLeft: Coordinate, direction: Direction, rock: Rock): Coordinate? =
bottomLeft.move(direction).takeUnless { collides(rock, it) }
private fun Rock.offseted(bottomLeft: Coordinate): List<Coordinate> =
indices.map(bottomLeft::plus)
private fun collides(rock: Rock, bottomLeft: Coordinate): Boolean =
rock.offseted(bottomLeft).any {
it.column !in 0 until width || it.row < 0 || (it.row < cave.size && cave[it.row][it.column])
}
}
fun <T> loop(values: Iterable<T>): Iterator<T> =
generateSequence { values.asSequence() }.flatten().iterator() | 0 | Kotlin | 0 | 0 | 560f6e33f8ca46e631879297fadc0bc884ac5620 | 2,545 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/day21/Day21.kt | Arch-vile | 317,641,541 | false | null | package day21
import readFile
typealias Allergen = String
typealias Ingredient = String
fun main(args: Array<String>) {
var products = readFile("./src/main/resources/day21Input.txt")
.map {
"""(.*) \(contains ([^\)]*)\)""".toRegex().find(it)!!.groupValues
}
.map {
Pair(it[1].split(" ").toSet(), it[2].split(", ").toSet())
}
val ingredientByAllergen = mutableMapOf<Allergen, Ingredient>()
do {
val allergens = products.flatMap { it.second }.toSet()
allergens
.forEach { allergen ->
println("Processing allergene $allergen")
var intersectOfAllIngredients = products
.filter { it.second.contains(allergen) }
.map { it.first }
.reduce { acc, list -> acc.intersect(list) }
println("Found ingredients $intersectOfAllIngredients")
if (intersectOfAllIngredients.size == 1) {
val ingredient = intersectOfAllIngredients.first()
println("found one $ingredient")
ingredientByAllergen.put(allergen, ingredient)
products = products
.map {
it.copy(
it.first.toMutableSet().minus(ingredient),
it.second.toMutableSet().minus(allergen))
}
}
}
} while (allergens.isNotEmpty())
// Part 1
println(
products
.map { it.first.size }
.sum())
// Part 2
println(
ingredientByAllergen
.entries
.sortedBy { it.key }
.map { it.value }
.joinToString ( "," )
)
}
| 0 | Kotlin | 0 | 0 | 12070ef9156b25f725820fc327c2e768af1167c0 | 1,534 | adventOfCode2020 | Apache License 2.0 |
leetcode2/src/leetcode/missing-number.kt | hewking | 68,515,222 | false | null | package leetcode
import java.lang.IllegalArgumentException
/**
* https://leetcode-cn.com/problems/missing-number/
* 268. 缺失数字
* @program: leetcode
* @description: ${description}
* @author: hewking
* @create: 2019-10-18 19:26
* 给定一个包含 0, 1, 2, ..., n 中 n 个数的序列,找出 0 .. n 中没有出现在序列中的那个数。
示例 1:
输入: [3,0,1]
输出: 2
示例 2:
输入: [9,6,4,2,3,5,7,0,1]
输出: 8
说明:
你的算法应具有线性时间复杂度。你能否仅使用额外常数空间来实现?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/missing-number
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
**/
object MissingNumber {
@JvmStatic
fun main(args: Array<String>) {
}
class Solution {
/**
* 思路:
* 题设区间是 [0,n]
* 先排序,n 为自然数集合。 首位数是0
* 然后判断两个数相差是否为1
*/
fun missingNumber(nums: IntArray): Int {
if (nums.isEmpty()) {
throw IllegalArgumentException()
}
nums.sort()
if (nums[0] != 0) {
return 0
}
for (i in 1 until nums.size) {
if (nums[i] - nums[i - 1] != 1) {
return nums[i] - 1
}
}
return nums.last() + 1
}
}
} | 0 | Kotlin | 0 | 0 | a00a7aeff74e6beb67483d9a8ece9c1deae0267d | 1,500 | leetcode | MIT License |
src/main/kotlin/fp/kotlin/example/chapter09/solution/9_11_TreeMonoidWithFoldable.kt | funfunStory | 101,662,895 | false | null | package fp.kotlin.example.chapter09.solution
import fp.kotlin.example.chapter09.Foldable
import fp.kotlin.example.chapter09.SumMonoid
/**
*
* 연습문제 9-11
*
* 일반 트리를 Foldable 타입클래스의 인스턴스로 만들고, ``foldLeft``, ``foldMap`` 함수의 동작을 테스트해보자.
* 이때 트리의 노드는 값 ``val value: A``와 하위 트리의 리스트인 ``val forest: FunList<Node<A>>``를 프로퍼티로 가진다.
*
* 힌트 : 후위 탐색(post-order) 로 트리를 순회한다.
*
*/
fun main() {
val node = Node(1)
val node2 = Node(1, Cons(Node(2), Nil))
val node3 = Node(1, Cons(Node(2), Cons(Node(3), Nil)))
val node4 = Node(1,
Cons(Node(2), Cons(Node(3), Cons(Node(4), Nil))))
val node5 = Node(1,
Cons(Node(2), Cons(Node(3), Cons(Node(4), Cons(Node(5), Nil)))))
val node6 =
Node(1,
Cons(Node(2, Cons(Node(6), Nil)),
Cons(Node(3),
Cons(Node(4),
Cons(Node(5), Nil)))))
val node7 =
Node(1,
Cons(Node(2, Cons(Node(6), Nil)),
Cons(Node(3, Cons(Node(7), Nil)),
Cons(Node(4, Cons(Node(8), Nil)),
Cons(Node(5, Cons(Node(9), Cons(Node(10), Nil))), Nil)))))
require(node.foldLeft(0) { acc, value -> acc + value } == 1)
require(node2.foldLeft(0) { acc, value -> acc + value } == 3)
require(node3.foldLeft(0) { acc, value -> acc + value } == 6)
require(node4.foldLeft(0) { acc, value -> acc + value } == 10)
require(node5.foldLeft(0) { acc, value -> acc + value } == 15)
require(node6.foldLeft(0) { acc, value -> acc + value } == 21)
require(node7.foldLeft(0) { acc, value -> acc + value } == 55)
require(node.foldMap({ it * 2 }, SumMonoid()) == 2)
require(node2.foldMap({ it * 2 }, SumMonoid()) == 6)
require(node3.foldMap({ it * 2 }, SumMonoid()) == 12)
require(node4.foldMap({ it * 2 }, SumMonoid()) == 20)
require(node5.foldMap({ it * 2 }, SumMonoid()) == 30)
require(node6.foldMap({ it * 2 }, SumMonoid()) == 42)
require(node7.foldMap({ it * 2 }, SumMonoid()) == 110)
}
sealed class Tree<out T> : Foldable<T>
data class Node<out T>(val value: T, val forest: FunList<Node<T>> = Nil) : Tree<T>() {
override fun <B> foldLeft(acc: B, f: (B, T) -> B): B = when (forest) {
Nil -> f(acc, value)
is Cons -> f(loop(forest, f, acc), value)
}
private tailrec fun <B> loop(list: FunList<Node<T>>, f: (B, T) -> B, acc: B): B = when (list) {
Nil -> acc
is Cons -> loop(list.tail, f, list.head.foldLeft(acc, f))
}
}
| 1 | Kotlin | 23 | 39 | bb10ea01d9f0e1b02b412305940c1bd270093cb6 | 2,663 | fp-kotlin-example | MIT License |
src/main/kotlin/oct_challenge2021/LongestCommonSubsequence.kt | yvelianyk | 405,919,452 | false | {"Kotlin": 147854, "Java": 610} | package oct_challenge2021
fun main() {
assert(longestCommonSubsequence("abcde", "ace") == 3)
assert(longestCommonSubsequence("abc", "def") == 0)
assert(longestCommonSubsequence("abc", "abc") == 2)
val res = longestCommonSubsequence("abc", "abc")
println(res)
}
fun longestCommonSubsequence(text1: String, text2: String): Int {
val memo: Array<Array<Int>> = Array(text1.length) {Array(text2.length) {-1} }
return getMax(text1, text2, 0, 0, memo)
}
private fun getMax(text1: String, text2: String, index1: Int, index2: Int, memo: Array<Array<Int>>): Int {
if (index1 == text1.length || index2 == text2.length) return 0
if (memo[index1][index2] != -1) return memo[index1][index2]
val char1: Char = text1[index1]
val char2: Char = text2[index2]
val result = when (char1) {
char2 -> {
getMax(text1, text2, index1 + 1, index2 + 1, memo) + 1
}
else -> {
val res1 = getMax(text1, text2, index1, index2 + 1, memo)
val res2 = getMax(text1, text2, index1 + 1, index2, memo)
maxOf(res1, res2)
}
}
memo[index1][index2] = result
return result
} | 0 | Kotlin | 0 | 0 | 780d6597d0f29154b3c2fb7850a8b1b8c7ee4bcd | 1,175 | leetcode-kotlin | MIT License |
DSA/kotlin-programming/happy_number.kt | atig05 | 422,574,082 | true | {"C": 65911, "Python": 42641, "C++": 37467, "Jupyter Notebook": 21486, "Solidity": 9341, "Kotlin": 7674, "HTML": 3421, "JavaScript": 2689, "Shell": 1399, "CSS": 568} | /*
kotlin program to check happy numbers
A happy number is a number, if we reach to 1 after replacing the number by the squares of the digits of the number
Following examples will help to understand better:-
Input: n = 19
Output: True
19 is Happy Number,
1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1
As we reached to 1, 19 is a Happy Number.
Input: n = 20
Output: False
20 is not a happy number
2^2 + 0^2 = 4
4^2 = 16
As we cannot reach to 1, 20 is not a happy number
*/
import java.util.*
fun squaredSum(n: Int): Int{
var sum_of_square:Int = 0
var c:Int = n
while(c!=0){
sum_of_square += c%10 * (c % 10)
c /= 10
}
return sum_of_square
}
//defining a boolean function to check whether the number is happy number or not
fun Happynumber(number: Int): Boolean {
var slow: Int
var fast: Int
fast = number
slow = fast
do {
slow = squaredSum(slow)
fast = squaredSum(squaredSum(fast))
} while (slow != fast)
return slow == 1
}
//Testing code
fun main(){
val input = Scanner(System.`in`)
println("Enter the number which you want to check")
val n = input.nextInt()
if (Happynumber(n))
println("$n is a Happy number")
else
println("$n is not a happy number")
}
/*
Enter the number which you want to check
19
19 is a Happy number
Enter the number which you want to check
20
20 is not a happy number
*/
/*
Time complexity :- O(N)
Space complexity :- O(1), which is constant
*/
| 0 | C | 0 | 0 | a13b4a72c3c13760643f0f2aa4d5dcd8bf2c79dc | 1,542 | HACKTOBERFEST-2021 | MIT License |
src/Day04.kt | gischthoge | 573,509,147 | false | {"Kotlin": 5583} | fun main() {
fun part1(input: List<String>): Int {
return input.map { pair ->
pair.split(",")
.map { range ->
val (from, to) = range.split("-").map { it.toInt() }
(from..to).toSet()
}
}.filter { (first, second) ->
val duplicates = first.intersect(second)
duplicates == first || duplicates == second
}.size
}
fun part2(input: List<String>): Int {
return input.map { pair ->
pair.split(",")
.map { range ->
val (from, to) = range.split("-").map { it.toInt() }
from..to
}
}.filter { (first, second) ->
first.intersect(second).isNotEmpty()
}.size
}
val input = readInput("Day04")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | e403f738572360d4682f9edb6006d81ce350ff9d | 903 | aock | Apache License 2.0 |
src/day1.kts | AfzalivE | 317,962,201 | false | null | println("Start")
// val input = listOf(1721, 979, 366, 299, 675, 1456)
val input = readInput("day1.txt").readLines().map { it.toInt() }
fun part1() {
var i = 0
var j = 1
var foundPair = false
while (!foundPair) {
j += 1
if (j == input.size - 2) {
i += 1
j = i + 1
}
val first = input[i]
val second = input[j]
if (sumTo2020(first, second)) {
println("Found: $first, $second")
println(first * second )
foundPair = true
}
}
}
fun part2() {
var i = 0
var j = 1
var k = j
var foundPair = false
while (!foundPair) {
k += 1
if (k == input.size - 1) {
j += 1
k = j + 1
}
if (j == input.size - 2) {
i += 1
j = i + 1
k = j + 1
}
val first = input[i]
val second = input[j]
val third = input[k]
if (sumTo2020(first, second, third)) {
println("Found: $first, $second, $third")
println(first * second * third)
foundPair = true
}
}
}
part1()
part2()
fun sumTo2020(vararg numbers: Int): Boolean {
return numbers.reduce { acc, i ->
acc + i
} == 2020
} | 0 | Kotlin | 0 | 0 | cc5998bfcaadc99e933fb80961be9a20541e105d | 1,295 | AdventOfCode2020 | Apache License 2.0 |
src/day13/Day13.kt | idle-code | 572,642,410 | false | {"Kotlin": 79612} | package day13
import logln
import logEnabled
import readInput
private const val DAY_NUMBER = 13
fun parseFile(rawInput: List<String>): List<Pair<Packet, Packet>> {
val iterator = rawInput.iterator()
val pairList = mutableListOf<Pair<Packet, Packet>>()
while (iterator.hasNext()) {
pairList.add(parseListPair(iterator))
}
return pairList
}
fun parseListPair(iterator: Iterator<String>): Pair<Packet, Packet> {
val first = parseList(iterator.next())
val second = parseList(iterator.next())
if (iterator.hasNext())
iterator.next() // Consume empty line
return Pair(first, second)
}
fun parseList(repr: String): Packet {
val tokens = tokenize(repr)
// logln("TOKENS: " + tokens.joinToString(":") { it })
val packetStack = ArrayDeque<Packet>()
for (token in tokens) {
when (token) {
"[" -> packetStack.addLast(Packet())
"]" -> {
if (packetStack.size > 1) {
val innerPacket = packetStack.removeLast()
packetStack.last().add(innerPacket)
}
}
else -> packetStack.last().add(Packet(token.toInt()))
}
}
check(packetStack.size == 1)
return packetStack.first()
}
fun tokenize(expr: String): List<String> {
val tokenList = mutableListOf<String>()
var builder = StringBuilder()
fun finishToken() {
val token = builder.toString()
if (token.isNotEmpty()) {
tokenList.add(token)
builder = StringBuilder()
}
}
for (c in expr) {
when (c) {
'[' -> tokenList.add(c.toString())
']' -> {
finishToken()
tokenList.add(c.toString())
}
in "0123456789" -> builder.append(c)
',' -> finishToken()
else -> throw IllegalArgumentException("Unknown packet symbol $c")
}
}
return tokenList
}
class Packet : Comparable<Packet> {
private var value: Int? = null
private var elements: MutableList<Packet>? = null
constructor(constant: Int) {
value = constant
}
constructor(innerPackets: List<Packet> = listOf()) {
elements = innerPackets.toMutableList()
}
override fun toString(): String {
if (value != null)
return value.toString()
return "[" + elements!!.joinToString(", ") { it.toString() } + "]"
}
fun add(packet: Packet) {
elements!!.add(packet)
}
override fun equals(other: Any?): Boolean {
if (other !is Packet)
return false
return this.compareTo(other) == 0
}
override operator fun compareTo(right: Packet): Int {
val leftValue = value
val rightValue = right.value
if (leftValue != null && rightValue != null) {
return leftValue.compareTo(rightValue)
}
val leftElements = this.elements ?: mutableListOf(this)
val rightElements = right.elements ?: mutableListOf(right)
val elementPairs = leftElements.zip(rightElements)
for (pair in elementPairs) {
if (pair.first != pair.second) {
return pair.first.compareTo(pair.second)
}
}
return leftElements.size.compareTo(rightElements.size)
}
}
fun main() {
fun part1(rawInput: List<String>): Int {
val pairList = parseFile(rawInput)
var indexSum = 0
pairList.forEachIndexed { index, (left, right) ->
// logln("")
// logln("LEFT: $left")
// logln("RIGHT: $right")
if (left < right)
indexSum += index + 1
}
return indexSum
}
fun part2(rawInput: List<String>): Int {
val pairList = parseFile(rawInput)
val firstKeyPacket = Packet(listOf(Packet(listOf(Packet(2)))))
val secondKeyPacket = Packet(listOf(Packet(listOf(Packet(6)))))
val flatList = pairList.flatMap { listOf(it.first, it.second) }
val sortedFlatList = (flatList + listOf(firstKeyPacket, secondKeyPacket)).sorted()
return (1 + sortedFlatList.indexOf(firstKeyPacket)) * (1 + sortedFlatList.indexOf(secondKeyPacket))
}
val sampleInput = readInput("sample_data", DAY_NUMBER)
val mainInput = readInput("main_data", DAY_NUMBER)
logEnabled = true
val part1SampleResult = part1(sampleInput)
println(part1SampleResult)
check(part1SampleResult == 13)
val part1MainResult = part1(mainInput)
println(part1MainResult)
check(part1MainResult == 5330)
val part2SampleResult = part2(sampleInput)
println(part2SampleResult)
check(part2SampleResult == 140)
val part2MainResult = part2(mainInput)
println(part2MainResult)
check(part2MainResult == 27648)
}
| 0 | Kotlin | 0 | 0 | 1b261c399a0a84c333cf16f1031b4b1f18b651c7 | 4,841 | advent-of-code-2022 | Apache License 2.0 |
src/com/mrxyx/algorithm/Fib.kt | Mrxyx | 366,778,189 | false | null | package com.mrxyx.algorithm
/**
* 斐波那契数列
* https://leetcode-cn.com/problems/fibonacci-number/
*/
class Fib {
/**
* 暴力递归
* @param n 入参
*/
fun fibV1(n: Int): Int {
if (n == 1 || n == 2) return 1
return fibV1(n - 1) + fibV1(n - 2)
}
/**
* 带备忘录的递归 自顶向下
*/
fun fibV2(n: Int): Int {
val mem: Array<Int> = Array(n) { 0 }
return fibV2Helper(mem, n)
}
private fun fibV2Helper(mem: Array<Int>, n: Int): Int {
if (n == 1 || n == 2) return 1
if (mem[n - 1] != 0) return mem[n - 1]
mem[n - 1] = fibV2Helper(mem, n - 1) + fibV2Helper(mem, n - 2)
return mem[n - 1]
}
/**
* 动态规划 自底向上
*/
fun fibV3(n: Int): Int {
val dp: Array<Int> = Array(n + 1) { 0 }
dp[1] = 1
dp[2] = 1
for (i in 3..n) {
dp[i] = dp[i - 1] + dp[i - 2]
}
return dp[n]
}
/**
* 动态规划 空间复杂度O(1)
*/
fun fibV4(n: Int): Int {
if (n == 1 || n == 2) return 1
var pre = 1
var curr = 1
var sum = 1
for (i in 3..n) {
sum = pre + curr
pre = curr
curr = sum
}
return sum
}
} | 0 | Kotlin | 0 | 0 | b81b357440e3458bd065017d17d6f69320b025bf | 1,317 | algorithm-test | The Unlicense |
day17/kotlin/corneil/src/main/kotlin/solution.kt | jensnerche | 317,661,818 | true | {"HTML": 2739009, "Java": 292790, "Python": 189361, "TypeScript": 172255, "Groovy": 155991, "Kotlin": 155380, "Jupyter Notebook": 116902, "Dart": 47762, "Haskell": 43633, "C++": 40222, "CSS": 35030, "Ruby": 27091, "Scala": 11409, "Dockerfile": 10370, "JavaScript": 9395, "PHP": 4152, "Go": 2838, "Shell": 2651, "Rust": 2082, "Clojure": 567, "Tcl": 46} | package com.github.corneil.aoc2019.day17
import com.github.corneil.aoc2019.common.Combinations
import com.github.corneil.aoc2019.intcode.Program
import com.github.corneil.aoc2019.intcode.ProgramState
import com.github.corneil.aoc2019.intcode.readProgram
import java.io.File
import java.io.PrintWriter
import java.io.StringWriter
import kotlin.math.abs
data class Robot(val pos: Coord, val direction: Char)
data class Coord(val x: Int, val y: Int) {
fun left() = copy(x = x - 1)
fun right() = copy(x = x + 1)
fun top() = copy(y = y - 1)
fun bottom() = copy(y = y + 1)
fun surrounds() = listOf(left(), right(), top(), bottom())
fun north(distance: Int) = copy(y = y - distance)
fun south(distance: Int) = copy(y = y + distance)
fun west(distance: Int) = copy(x = x - distance)
fun east(distance: Int) = copy(x = x + distance)
fun distance(target: Coord): Int = abs(target.x - x) + abs(target.y - y)
}
data class Movement(val movement: Char, val distance: Int) {
fun output() = if (movement.toInt() != 0) "$movement,$distance" else "$distance"
}
data class CleaningProgram(val mainRoutine: List<Char>, val subroutines: Map<Char, List<Movement>>) {
init {
require(mainRoutine.toSet() == subroutines.keys)
}
fun printToString(): String {
val sw = StringWriter()
sw.use {
PrintWriter(it).use { pw ->
val main = mainString()
pw.println("Main Routine=${main}: ${createIntCodeInput(main)}")
names().forEach { name ->
val functionString = subRoutine(name)
val functionInput = createIntCodeInput(functionString)
pw.println("Function $name: $functionString: $functionInput")
}
}
}
return sw.toString()
}
fun names() = subroutines.keys.toList().sorted()
fun mainString(): String = mainRoutine.joinToString(",")
fun subRoutine(name: Char): String =
(subroutines[name] ?: error("Expected $name in $subroutines")).joinToString(",") { it.output() }
fun movements(): List<Movement> {
return mainRoutine.flatMap { subroutines[it] ?: error("Expected $it in $subroutines") }
}
}
class Grid(val cells: MutableMap<Coord, Char> = mutableMapOf()) {
fun printToString(): String {
val sw = StringWriter()
sw.use {
PrintWriter(sw).use { pw ->
val maxY = cells.keys.maxBy { it.y }?.y ?: 0
val maxX = cells.keys.maxBy { it.x }?.x ?: 0
for (y in 0..maxY) {
for (x in 0..maxX) {
val cell = cells[Coord(x, y)] ?: ' '
pw.print(cell)
}
pw.println()
}
}
}
return sw.toString()
}
}
fun loadGrid(output: List<Long>): Grid {
val grid = Grid()
var x = 0
var y = 0
output.forEach { out ->
if (out == 10L) {
x = 0
y += 1
} else {
val coord = Coord(x, y)
x += 1
grid.cells[coord] = out.toChar()
}
}
return grid
}
fun isScaffold(c: Char) = when (c) {
'#', '^', '>', 'v', '<' -> true
else -> false
}
fun isRobot(c: Char) = when (c) {
'^', '>', 'v', '<' -> true
else -> false
}
fun isIntersection(coord: Coord, grid: Grid): Boolean {
val left = grid.cells[coord.left()] ?: ' '
val right = grid.cells[coord.right()] ?: ' '
val top = grid.cells[coord.top()] ?: ' '
val bottom = grid.cells[coord.bottom()] ?: ' '
return isScaffold(left) && isScaffold(right) && isScaffold(top) && isScaffold(bottom)
}
fun calculateAlignment(grid: Grid): Long {
val intersections = grid.cells.filter { isScaffold(it.value) && isIntersection(it.key, grid) }
return intersections.keys.map { it.x * it.y }.sum().toLong()
}
fun robotLocation(grid: Grid): Coord {
val locs = grid.cells.filter { isRobot(it.value) }
require(locs.size == 1)
return locs.keys.first()
}
fun turnLeft(direction: Char): Char {
return when (direction) {
'^' -> '<'
'>' -> '^'
'v' -> '>'
'<' -> 'v'
else -> error("Invalid direction $direction")
}
}
fun turnRight(direction: Char): Char {
return when (direction) {
'^' -> '>'
'>' -> 'v'
'v' -> '<'
'<' -> '^'
else -> error("Invalid direction $direction")
}
}
fun nextMovement(direction: Char, movement: Char): Char {
return if (movement == 'L') {
turnLeft(direction)
} else {
turnRight(direction)
}
}
fun determineMovement(robotDirection: Char, direction: Char): Char {
return when {
robotDirection == direction -> 0.toChar()
turnLeft(robotDirection) == direction -> 'L'
turnRight(robotDirection) == direction -> 'R'
else -> '*'
}
}
fun determineDirection(robot: Coord, next: Coord): Char {
return when {
robot.x == next.x && next.y > robot.y -> 'v'
robot.x == next.x && next.y < robot.y -> '^'
robot.y == next.y && next.x > robot.x -> '>'
robot.y == next.y && next.x < robot.x -> '<'
else -> error("Expect difference $robot, $next")
}
}
fun isValidDirection(robotDirection: Char, robot: Coord, next: Coord): Boolean {
val direction = determineDirection(robot, next)
return determineMovement(robotDirection, direction) != '*'
}
fun scaffoldDirection(robot: Robot, grid: Grid): Movement? {
val surrounds = robot.pos.surrounds().toSet()
val potential = grid.cells.filter {
surrounds.contains(it.key)
}.filter {
isScaffold(it.value)
}.filter {
isValidDirection(robot.direction, robot.pos, it.key)
}.toMutableMap()
val movements = potential.map {
createMovementUntilEnd(robot, it.key, grid)
}
if (movements.size > 1) {
println("Found multiple movements:$movements")
}
return movements.maxBy { it.distance }
}
fun createMovementUntilEnd(robot: Robot, next: Coord, grid: Grid): Movement {
val diffX = next.x - robot.pos.x
val diffY = next.y - robot.pos.y
var step = Coord(next.x + diffX, next.y + diffY)
while (isScaffold(grid.cells[step] ?: ' ')) {
step = step.copy(x = step.x + diffX, y = step.y + diffY)
}
val movement = determineMovement(robot.direction, determineDirection(robot.pos, next))
return Movement(movement, step.distance(next))
}
fun determineRouteInstructions(grid: Grid): List<Movement> {
val result = mutableListOf<Movement>()
val robotLocation = robotLocation(grid)
val robotDirection = grid.cells[robotLocation] ?: error("Expected robot at $robotLocation")
var robot = Robot(robotLocation, robotDirection)
do {
val direction = scaffoldDirection(robot, grid)
if (direction == null) {
println("End = $robot")
break
}
result.add(direction)
robot = walk(robot, direction)
} while (true)
return result
}
fun walk(robot: Robot, direction: Movement): Robot {
val newDirection = nextMovement(robot.direction, direction.movement)
val newLocation = when (newDirection) {
'^' -> robot.pos.north(direction.distance)
'>' -> robot.pos.east(direction.distance)
'v' -> robot.pos.south(direction.distance)
'<' -> robot.pos.west(direction.distance)
else -> error("Invalid direction $newDirection")
}
return Robot(newLocation, newDirection)
}
data class Attempt(var name: Char, val movements: List<Movement>) {
fun output() = movements.joinToString(",") { it.output() }
fun len() = output().length
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Attempt
if (movements != other.movements) return false
return true
}
override fun hashCode(): Int {
return movements.hashCode()
}
}
fun attemptMove(attempt: Attempt, movements: List<Movement>): Boolean {
if (attempt.movements.size <= movements.size) {
val compare = movements.subList(0, attempt.movements.size)
return attempt.movements == compare
}
return false
}
fun attemptRoute(sets: Set<Attempt>, movements: List<Movement>): Pair<Boolean, List<Char>> {
for (attempt in sets) {
if (attemptMove(attempt, movements)) {
if (attempt.movements.size == movements.size) {
return Pair(true, listOf(attempt.name))
}
val attemptMovements = movements.subList(attempt.movements.size, movements.lastIndex + 1)
val result = attemptRoute(sets, attemptMovements)
if (result.first) {
return Pair(true, listOf(attempt.name) + result.second)
}
}
}
return Pair(false, emptyList())
}
fun checkValidAndResults(sets: Set<Attempt>, movements: List<Movement>): Pair<Boolean, List<Attempt>> {
val attemptMap = sets.map { it.name to it }.toMap()
val result = attemptRoute(sets, movements)
return Pair(result.first, result.second.map { attemptMap[it] ?: error("Expected $it in $attemptMap") })
}
fun createIntCodeInput(functionString: String) = functionString.map { it.toLong() } + 10L
fun createCleaningProgram(instructionSet: Pair<Set<Attempt>, List<Attempt>>): CleaningProgram {
val names = instructionSet.first.map { it to it.name }.toMap()
require(instructionSet.second.all { names.keys.contains(it) })
require(names.size == names.size)
val mainRoutine = instructionSet.second.map { names[it] ?: error("Expected $it in $names") }
require(mainRoutine.toSet().size == names.size)
val subroutines = names.keys.map { it.name to it.movements }.toMap()
return CleaningProgram(mainRoutine, subroutines)
}
fun findRepeating(
totalSets: Int,
maxOutput: Int,
movements: List<Movement>
): List<CleaningProgram> {
val attempts = createAttempts(movements, maxOutput)
println("Potential Subroutines = ${attempts.size}")
val attemptArray = attempts.keys.toTypedArray()
val combinations = Combinations(totalSets, attempts.size)
val attemptSets = combinations.combinations.map { combination ->
combination.mapIndexed { index, attempt ->
attemptArray[attempt].copy(name = ('A'.toInt() + index).toChar())
}.toSet()
}
println("Testing combinations = ${attemptSets.size}")
val validCombinations = attemptSets.map {
Pair(it, checkValidAndResults(it, movements))
}.filter {
it.second.first && it.second.second.size * 2 <= maxOutput
}.map {
Pair(it.first, it.second.second)
}.sortedBy { it.second.size }
println("Valid Combindations=${validCombinations.size}")
val programs = validCombinations.map { createCleaningProgram(it) }
programs.forEachIndexed { index, cleaningProgram ->
print("Valid:$index:")
println(cleaningProgram.printToString())
require(movements == cleaningProgram.movements()) { "Expected $movements == ${cleaningProgram.movements()}" }
}
return programs
}
fun createAttempts(
movements: List<Movement>,
maxOutput: Int
): MutableMap<Attempt, Int> {
val attempts = mutableMapOf<Attempt, Int>()
for (i in movements.indices) {
for (j in (i + 2)..movements.size) {
val attempt = Attempt(0.toChar(), movements.subList(i, j))
if (attempt.len() < maxOutput) {
val count = attempts[attempt] ?: 0
attempts[attempt] = count + 1
}
}
}
return attempts
}
fun executeInstructions(program: ProgramState, cleaningProgram: CleaningProgram) {
program.setMemory(0, 2L)
program.reset()
println(cleaningProgram.printToString())
val totalInput = mutableListOf<Long>()
totalInput.addAll(createIntCodeInput(cleaningProgram.mainString()))
cleaningProgram.names().forEach { name ->
totalInput.addAll(createIntCodeInput(cleaningProgram.subRoutine(name)))
}
totalInput.addAll(createIntCodeInput("n"))
println("All Input = $totalInput")
do {
program.executeUntilInput(totalInput)
val output = program.extractOutput()
if (output.size == 1) {
println("Output=\n$output")
} else {
val str = output.joinToString("") { if (it < 256L) it.toChar().toString() else it.toString() }
println(str)
}
totalInput.clear()
} while (!program.isHalted())
}
fun main() {
val code = readProgram(File("input.txt"))
val program = Program(code).executeProgram(emptyList())
val grid = loadGrid(program.extractOutput())
println(grid.printToString())
val ap = calculateAlignment(grid)
println("Alignment Parameter = $ap")
val movements = determineRouteInstructions(grid)
val instructions = movements.joinToString(",") { it.output() }
println("Movements:$instructions")
val programs = findRepeating(3, 20, movements)
programs.forEach { cleaningProgram ->
executeInstructions(Program(code).createProgram(), cleaningProgram)
}
}
| 0 | HTML | 0 | 0 | a84c00ddbeb7f9114291125e93871d54699da887 | 13,376 | aoc-2019 | MIT License |
src/main/kotlin/graph/core/MaxWeightPathDAG.kt | yx-z | 106,589,674 | false | null | package graph.core
import util.max
// find a path in a directed acyclic graph that has max weight from s to t
// report the total weight of such path
fun <V> WeightedGraph<V, Int>.maxWeightedPath(s: Vertex<V>,
t: Vertex<V>,
checkIdentity: Boolean = true): Int {
val dp = HashMap<Vertex<V>, Int>()
val sortedVertices = topoSort()
sortedVertices.reversed().forEach { v ->
if (v == t) {
dp[v] = 0
} else {
dp[v] = Int.MIN_VALUE
getEdgesOf(v, checkIdentity).forEach { edge ->
val (_, w) = edge
dp[v] = max(dp[v]!!, (edge.weight ?: 0) + dp[w]!!)
}
}
}
return dp[s]!!
}
fun main(args: Array<String>) {
val vertices = (1..5).map { Vertex(it) }
val edges = setOf(
WeightedEdge(vertices[0], vertices[1], true, 1),
WeightedEdge(vertices[0], vertices[2], true, 4),
WeightedEdge(vertices[1], vertices[2], true, 2),
WeightedEdge(vertices[1], vertices[3], true, 5),
WeightedEdge(vertices[2], vertices[3], true, -1),
WeightedEdge(vertices[2], vertices[4], true, 3),
WeightedEdge(vertices[3], vertices[4], true, 1))
val graph = WeightedGraph(vertices, edges)
println(graph.maxWeightedPath(vertices[0], vertices[4]))
}
| 0 | Kotlin | 0 | 1 | 15494d3dba5e5aa825ffa760107d60c297fb5206 | 1,254 | AlgoKt | MIT License |
src/Day06.kt | KristianAN | 571,726,775 | false | {"Kotlin": 9011} | // Without using stdlib windowed
data class CharAndIndex(val char: Char, val index: Int)
data class Window(val windowSize: Int, val window: List<CharAndIndex?>) {
fun update(char: Char, index: Int): Window =
Window(windowSize, this.window.drop(1).plus(CharAndIndex(char, index)))
fun nonEq() = this.window.map { it?.char ?: "" }.toSet().size == windowSize && noNull()
fun len() = this.window.last()?.index?.plus(1) ?: 0
private inline fun noNull() = this.window.filterNotNull().size == windowSize
companion object {
fun new(windowSize: Int): Window = Window(windowSize, List(windowSize) { _ -> null })
}
}
fun String.uniqueWindow(windowSize: Int): Window = uniqueWindow(Window.new(windowSize), this, 0)
tailrec fun uniqueWindow(window: Window, input: String, index: Int): Window {
if (window.nonEq()) return window
return uniqueWindow(window.update(input[index], index), input, index + 1)
}
// Using stdlib windowed
fun String.findUniqueWindow(windowSize: Int, step: Int) = this.asSequence().windowed(windowSize, step).indexOfFirst {
it.toSet().size == windowSize
}.plus(windowSize)
fun main() {
fun part1(input: List<String>): Int = input.first().uniqueWindow(4).len()
fun part2(input: List<String>): Int = input.first().findUniqueWindow(14, 1)
val input = readInput("day06")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 3a3af6e99794259217bd31b3c4fd0538eb797941 | 1,405 | AoC2022Kt | Apache License 2.0 |
src/main/kotlin/adventofcode2019/Day03CrossedWires.kt | n81ur3 | 484,801,748 | false | {"Kotlin": 476844, "Java": 275} | package adventofcode2019
import kotlin.math.abs
class Day03CrossedWires
data class DistanceCoordinate(
val distance: Int,
val coordinate: Pair<Int, Int>
)
data class GravityWire(val coordinates: List<Pair<Int, Int>> = emptyList()) {
val distanceCoordinates = mutableListOf<DistanceCoordinate>()
fun buildPathFromString(input: String) {
var currentX = 0
var currentY = 0
var distance = 0
val parts = input.split(",")
parts.forEach { part ->
val dist = part.substring(1).toInt()
when (part.first()) {
'R' -> {
repeat(dist) {
distanceCoordinates.add(DistanceCoordinate(++distance, ++currentX to currentY))
}
}
'D' -> {
repeat(dist) {
distanceCoordinates.add(DistanceCoordinate(++distance, currentX to ++currentY))
}
}
'L' -> {
repeat(dist) {
distanceCoordinates.add(DistanceCoordinate(++distance, --currentX to currentY))
}
}
else -> {
repeat(dist) {
distanceCoordinates.add(DistanceCoordinate(++distance, currentX to --currentY))
}
}
}
}
}
companion object {
var currentX = 0
var currentY = 0
var path = mutableListOf<Pair<Int, Int>>()
fun fromString(input: String): GravityWire {
if (input.isBlank()) return GravityWire()
currentX = 0
currentY = 0
path = mutableListOf()
val parts = input.split(",")
parts.forEach { direction ->
move(direction.first(), direction.substring(1))
}
return GravityWire(path.toList())
}
private fun move(direction: Char, distance: String) {
val dist = distance.toInt()
when (direction) {
'R' -> {
repeat(dist) {
path.add(++currentX to currentY)
}
}
'D' -> {
repeat(dist) {
path.add(currentX to ++currentY)
}
}
'L' -> {
repeat(dist) {
path.add(--currentX to currentY)
}
}
else -> {
repeat(dist) {
path.add(currentX to --currentY)
}
}
}
}
}
}
class FuelManagementSystem(firstWireDirections: String = "", secondWireDirections: String = "") {
var firstWire: GravityWire
var secondWire: GravityWire
init {
firstWire = GravityWire.fromString(firstWireDirections)
secondWire = GravityWire.fromString(secondWireDirections)
}
fun findClosestTwistDistance(): Int {
val intersections = mutableListOf<Pair<Int, Int>>()
firstWire.coordinates.forEach { firstCoordinate ->
secondWire.coordinates.forEach { secondCoordinate ->
if (firstCoordinate == secondCoordinate) intersections.add(firstCoordinate)
}
}
val closestTwist = intersections.sortedBy { abs(it.first) + abs(it.second) }.first()
return abs(closestTwist.first) + abs(closestTwist.second)
}
fun findClosestTwistDistanceSteps(): Int {
val intersections = mutableListOf<Int>()
firstWire.distanceCoordinates.forEach { firstCoordinate ->
secondWire.distanceCoordinates.forEach { secondCoordinate ->
if (firstCoordinate.coordinate == secondCoordinate.coordinate) intersections.add(firstCoordinate.distance + secondCoordinate.distance)
}
}
return intersections.min()
}
} | 0 | Kotlin | 0 | 0 | fdc59410c717ac4876d53d8688d03b9b044c1b7e | 4,041 | kotlin-coding-challenges | MIT License |
src/main/kotlin/com/scavi/brainsqueeze/adventofcode/Day5BinaryBoarding.kt | Scavi | 68,294,098 | false | {"Java": 1449516, "Kotlin": 59149} | package com.scavi.brainsqueeze.adventofcode
class Day5BinaryBoarding {
private fun next(value: Int) = if (value % 2 == 1) (value / 2) + 1 else (value / 2)
fun solve(boardingPasses: List<String>, mySeat: Boolean = false): Int {
val seatIds = mutableListOf<Int>()
for (boardingPass in boardingPasses) {
val row = calculate(boardingPass, 127, 0, boardingPass.length - 3)
val column = calculate(boardingPass, 7, boardingPass.length - 3, boardingPass.length)
seatIds.add((row * 8) + column)
}
seatIds.sort()
if (mySeat) {
for (i in seatIds[0] until seatIds[seatIds.size - 1]) {
if (!seatIds.contains(i) && seatIds.contains(i - 1) && seatIds.contains(i + 1)) {
return i
}
}
}
return seatIds[seatIds.size - 1]
}
private fun calculate(boardingPass: String, hi: Int, from: Int, till: Int): Int {
var low = 0
var high = hi
var reminder = high
for (i in from until till) {
reminder = next(reminder)
when (boardingPass[i]) {
'F', 'L' -> high -= reminder
'B', 'R' -> low += reminder
}
}
return high
}
}
| 0 | Java | 0 | 1 | 79550cb8ce504295f762e9439e806b1acfa057c9 | 1,297 | BrainSqueeze | Apache License 2.0 |
src/Day01.kt | karlwalsh | 573,854,263 | false | {"Kotlin": 32685} | fun main() {
fun solve(input: List<Int>, n: Int): Int = input.sortedDescending().take(n).sum()
fun part1(input: List<String>): Int = solve(input.toDaySpecificInput(), 1)
fun part2(input: List<String>): Int = solve(input.toDaySpecificInput(), 3)
val input = readInput("Day01")
with(::part1) {
val exampleResult = this(example())
check(exampleResult == 24000) { "Part 1 result was $exampleResult" }
println("Part 1: ${this(input)}")
}
with(::part2) {
val exampleResult = this(example())
check(exampleResult == 45000) { "Part 2 result was $exampleResult" }
println("Part 2: ${this(input)}")
}
}
private fun List<String>.toDaySpecificInput(): List<Int> {
val puzzleInput: MutableList<Int> = mutableListOf()
var currentSum = 0
this.forEach { value ->
if (value.isBlank()) {
puzzleInput.add(currentSum)
currentSum = 0
} else {
currentSum += value.toInt()
}
}
if (currentSum > 0) puzzleInput.add(currentSum)
return puzzleInput
}
private fun example() = """
1000
2000
3000
4000
5000
6000
7000
8000
9000
10000
""".trimIndent().lines() | 0 | Kotlin | 0 | 0 | f5ff9432f1908575cd23df192a7cb1afdd507cee | 1,287 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/JewelsStones.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2020 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
/**
* You're given strings J representing the types of stones that are jewels, and S representing the stones you have.
* Each character in S is a type of stone you have. You want to know how many of the stones you have are also jewels.
* The letters in J are guaranteed distinct, and all characters in J and S are letters. Letters are case sensitive,
* so "a" is considered a different type of stone from "A".
*/
fun interface NumJewelsInStonesStrategy {
operator fun invoke(a: String, b: String): Int
}
class NumJewelsInStonesMap : NumJewelsInStonesStrategy {
override operator fun invoke(a: String, b: String): Int {
var res = 0
val setJ = hashSetOf<Char>()
for (jewel in a) {
setJ.add(jewel)
}
for (stone in b) {
if (setJ.contains(stone)) {
res++
}
}
return res
}
}
class NumJewelsInStonesRegex : NumJewelsInStonesStrategy {
override operator fun invoke(a: String, b: String): Int {
return b.replace("[^$a]".toRegex(), "").length
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,723 | kotlab | Apache License 2.0 |
src/main/kotlin/com/github/solairerove/algs4/leprosorium/sorting/MergeSort.kt | solairerove | 282,922,172 | false | {"Kotlin": 251919} | package com.github.solairerove.algs4.leprosorium.sorting
fun main() {
val items = mutableListOf(5, 6, 4, 3, 10, 9, 5, 6, 7)
print("items: $items \n")
mergeSort(items)
print("items: $items \n")
}
// O(nlog(n)) time | O(n) space
private fun mergeSort(arr: MutableList<Int>) {
val n = arr.size
val aux = MutableList(n) { i -> i }
mergeSort(arr, aux, 0, n - 1)
}
private fun mergeSort(arr: MutableList<Int>, aux: MutableList<Int>, low: Int, high: Int) {
if (high <= low) {
return
}
val mid = low + (high - low) / 2
mergeSort(arr, aux, low, mid)
mergeSort(arr, aux, mid + 1, high)
merge(arr, aux, low, mid, high)
}
private fun merge(arr: MutableList<Int>, aux: MutableList<Int>, low: Int, mid: Int, high: Int) {
var i = low
var j = mid + 1
for (k in low..high) {
aux[k] = arr[k]
}
for (k in low..high) {
when {
i > mid -> arr[k] = aux[j++]
j > high -> arr[k] = aux[i++]
aux[j] < aux[i] -> arr[k] = aux[j++]
else -> arr[k] = aux[i++]
}
}
}
| 1 | Kotlin | 0 | 3 | 64c1acb0c0d54b031e4b2e539b3bc70710137578 | 1,099 | algs4-leprosorium | MIT License |
src/main/kotlin/endredeak/aoc2022/Day08.kt | edeak | 571,891,076 | false | {"Kotlin": 44975} | package endredeak.aoc2022
fun main() {
solve("Treetop Tree House") {
data class P(val x: Int, val y: Int, val w: Int)
fun List<P>.linesOfSight(p: P, reversed: Boolean = false) =
listOf(this.filter { it.x == p.x }.sortedBy { it.x }, this.filter { it.y == p.y }.sortedBy { it.y })
.flatMap { line ->
val before = line.takeWhile { it != p }.let { if (reversed) it.reversed() else it }
val after = line.drop(before.size + 1)
listOf(before, after)
}
val input = lines
.map { it.toCharArray().map { c -> c.digitToInt() } }
.mapIndexed { y, row -> row.mapIndexed { x, w -> P(x, y, w) } }
.flatten()
part1(1711) {
input.count { p -> input.linesOfSight(p).any { it.all { t -> t.w < p.w } } }
}
part2(301392) {
input
.maxOf { p ->
input.linesOfSight(p, true)
.map { l -> l.indexOfFirst { it.w >= p.w }.let { if (it < 0) l.size else it + 1 } }
.fold(1L) { acc, i -> acc * i }
}
}
}
} | 0 | Kotlin | 0 | 0 | e0b95e35c98b15d2b479b28f8548d8c8ac457e3a | 1,205 | AdventOfCode2022 | Do What The F*ck You Want To Public License |
src/Day18.kt | kipwoker | 572,884,607 | false | null |
import kotlin.time.ExperimentalTime
import kotlin.time.measureTime
class Day18 {
data class Point(val xs: Array<Int>) {
fun isBetween(minPoint: Point, maxPoint: Point): Boolean {
return xs
.zip(minPoint.xs)
.zip(maxPoint.xs)
.all { p ->
val x = p.first.first
val min = p.first.second
val max = p.second
x in min..max
}
}
fun add(index: Int, value: Int): Point {
val new = xs.copyOf()
new[index] += value
return Point(new)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Point
if (!xs.contentEquals(other.xs)) return false
return true
}
override fun hashCode(): Int {
return xs.contentHashCode()
}
}
fun parse(input: List<String>): Set<Point> {
return input.map { line ->
val xs = line.split(',').map { it.toInt() }.toTypedArray()
Point(xs)
}.toSet()
}
fun getNeighbors(point: Point): Set<Point> {
val range = listOf(-1, 1)
return point.xs.flatMapIndexed { index, _ -> range.map { dx -> point.add(index, dx) } }.toSet()
}
fun part1(input: List<String>): String {
val points = parse(input)
var result = 0L
for (point in points) {
var coverage = 6
val neighbors = getNeighbors(point)
coverage -= neighbors.count { points.contains(it) }
result += coverage
}
return result.toString()
}
fun part2(input: List<String>): String {
val points = parse(input)
var result = 0L
val dimension = points.first().xs.size
val max = (0 until dimension).map { d -> points.maxOf { p -> p.xs[d] } }
val min = (0 until dimension).map { d -> points.minOf { p -> p.xs[d] } }
val maxPoint = Point(max.map { it + 1 }.toTypedArray())
val minPoint = Point(min.map { it - 1 }.toTypedArray())
val visited = mutableSetOf<Point>()
val q = ArrayDeque(listOf(minPoint))
while (q.isNotEmpty()) {
val point = q.removeFirst()
val neighbors = getNeighbors(point).filter { n -> n.isBetween(minPoint, maxPoint) }
for (neighbor in neighbors) {
if (neighbor in points) {
++result
} else if (neighbor !in visited) {
visited.add(neighbor)
q.addLast(neighbor)
}
}
}
return result.toString()
}
}
@OptIn(ExperimentalTime::class)
@Suppress("DuplicatedCode")
fun main() {
val solution = Day18()
val name = solution.javaClass.name
fun test() {
val expected1 = "64"
val expected2 = "58"
val testInput = readInput("${name}_test")
println("Test part 1")
assert(solution.part1(testInput), expected1)
println("> Passed")
println("Test part 2")
assert(solution.part2(testInput), expected2)
println("> Passed")
println()
println("=================================")
println()
}
fun run() {
val input = readInput(name)
val elapsed1 = measureTime {
println("Part 1: " + solution.part1(input))
}
println("Elapsed: $elapsed1")
println()
val elapsed2 = measureTime {
println("Part 2: " + solution.part2(input))
}
println("Elapsed: $elapsed2")
println()
}
test()
run()
}
| 0 | Kotlin | 0 | 0 | d8aeea88d1ab3dc4a07b2ff5b071df0715202af2 | 3,808 | aoc2022 | Apache License 2.0 |
src/main/java/com/barneyb/aoc/aoc2019/day14/SpaceStoichiometry.kt | barneyb | 553,291,150 | false | {"Kotlin": 184395, "Java": 104225, "HTML": 6307, "JavaScript": 5601, "Shell": 3219, "CSS": 1020} | package com.barneyb.aoc.aoc2019.day14
import com.barneyb.aoc.util.Solver
fun main() {
Solver.benchmark(
::parse,
{ requiredOreForFuel(it, 1) },
{ fuelFromOre(it, ONE_TRILLION) },
// { fuelFromOre2(it, ONE_TRILLION) },
)
}
internal const val ONE_TRILLION = 1_000_000_000_000
internal const val ELEMENT_ORE = "ORE"
internal const val ELEMENT_FUEL = "FUEL"
internal typealias Element = String
internal typealias Recipes = Map<Element, Reaction>
internal data class Reactant(
val quantity: Long,
val element: Element,
) {
companion object {
fun parse(str: CharSequence): Reactant {
// 1 FUEL
val idx = str.indexOf(" ")
return Reactant(
str.substring(0, idx).toLong(),
str.substring(idx + 1, str.length),
)
}
}
}
internal data class Reaction(
val ingredients: Collection<Reactant>,
val result: Reactant,
) {
companion object {
fun parse(str: CharSequence): Reaction {
// 7 A, 1 E => 1 FUEL
val idx = str.indexOf("=>")
return Reaction(
str.subSequence(0, idx)
.split(",")
.map(String::trim)
.map(Reactant::parse),
Reactant.parse(str.subSequence(idx + 3, str.length)),
)
}
}
}
internal fun parse(input: String): Recipes =
input.trim()
.lines()
.map(Reaction::parse)
.associateBy { it.result.element }
internal fun requiredOreForFuel(recipes: Recipes, neededFuel: Long): Long {
val pool = mutableMapOf<Element, Long>()
val needed = mutableMapOf(ELEMENT_FUEL to neededFuel)
while (true) {
val el = needed.keys.firstOrNull { it != ELEMENT_ORE }
?: return needed[ELEMENT_ORE]!! // done!
var toMake = needed.remove(el)!!
if (pool.containsKey(el)) {
val avail = pool.remove(el)!!
if (avail >= toMake) {
pool[el] = avail - toMake
continue
} else {
toMake -= avail
}
}
val recipe = recipes[el]!!
var copies = toMake / recipe.result.quantity
if (toMake % recipe.result.quantity != 0L) copies++
val extra = recipe.result.quantity * copies - toMake
recipe.ingredients.forEach {
needed.merge(it.element, it.quantity * copies, Long::plus)
}
pool.merge(el, extra, Long::plus)
}
}
internal fun fuelFromOre(recipes: Recipes, availOre: Long): Long {
var fuel = 1L
var ore = requiredOreForFuel(recipes, fuel)
while (true) {
val inc = (availOre - ore) * fuel / ore
if (inc == 0L) break
fuel += inc
ore = requiredOreForFuel(recipes, fuel)
}
return fuel
}
@Suppress("unused") // play, not utility
internal fun fuelFromOre2(recipes: Recipes, availOre: Long): Long {
// this is safe, since efficiency can only go UP w/ scale
var lo = availOre / requiredOreForFuel(recipes, 1)
var hi = availOre
var mid: Long
var ore: Long
while (true) {
mid = (lo + hi) / 2
if (mid == lo) break
ore = requiredOreForFuel(recipes, mid)
if (ore < availOre) lo = mid
else if (ore > availOre) hi = mid
}
return lo
}
| 0 | Kotlin | 0 | 0 | 8b5956164ff0be79a27f68ef09a9e7171cc91995 | 3,375 | aoc-2022 | MIT License |
src/main/kotlin/com/headlessideas/adventofcode/december16/PermutationPromenade.kt | Nandi | 113,094,752 | false | null | package com.headlessideas.adventofcode.december16
import com.headlessideas.adventofcode.utils.readFile
fun dance(moves: List<Move>) {
var programs = "abcdefghijklmnop".toCharArray().toMutableList()
val seen = mutableListOf<String>()
val repetitions = 1_000_000_000
for (i in 0..repetitions) {
if (seen.contains(programs.joinToString(""))) {
println("Part 2: ${seen[repetitions % i]}")
break
}
seen.add(programs.joinToString(""))
for (move in moves) {
when (move) {
is Spin -> programs = move.spin(programs)
is Exchange -> move.exchange(programs)
is Partner -> move.partner(programs)
}
}
}
println("Part 1: ${seen[1]}")
}
fun main(args: Array<String>) {
val moves = readFile("16.dec.txt").flatMap { it.split(",") }.map {
when (it.first()) {
's' -> Spin(it)
'x' -> Exchange(it)
else -> Partner(it)
}
}
dance(moves)
}
sealed class Move
class Spin(input: String) : Move() {
private val count: Int = input.substring(1).toInt()
fun spin(programs: MutableList<Char>): MutableList<Char> {
return (programs.takeLast(count) + programs.dropLast(count)).toMutableList()
}
}
class Exchange(input: String) : Move() {
private val a: Int
private val b: Int
init {
val parts = input.substring(1).split("/")
a = parts[0].toInt()
b = parts[1].toInt()
}
fun exchange(programs: MutableList<Char>) {
val tmp = programs[a]
programs[a] = programs[b]
programs[b] = tmp
}
}
class Partner(input: String) : Move() {
private val a: Char
private val b: Char
init {
val parts = input.substring(1).split("/")
a = parts[0].first()
b = parts[1].first()
}
fun partner(programs: MutableList<Char>) {
val indexA = programs.indexOf(a)
val indexB = programs.indexOf(b)
val tmp = programs[indexA]
programs[indexA] = programs[indexB]
programs[indexB] = tmp
}
} | 0 | Kotlin | 0 | 0 | 2d8f72b785cf53ff374e9322a84c001e525b9ee6 | 2,143 | adventofcode-2017 | MIT License |
src/day3/first/Solution.kt | verwoerd | 224,986,977 | false | null | package day3.first
import tools.Coordinate
import tools.manhattanDistance
import tools.manhattanOriginComparator
import tools.origin
import tools.timeSolution
import java.util.PriorityQueue
import kotlin.test.fail
fun main() = timeSolution {
val points = mutableSetOf<Coordinate>()
var last = origin
// Find all the points the first circuit go to
readLine()!!.split(",").forEach { current ->
// assumption: a circuit does not cross itself
val size = current.substring(1).toInt()
last = when (current[0]) {
'R' -> (last.x..(last.x) + size).map {
Coordinate(
it,
last.y
)
}.toCollection(points).run { Coordinate(last.x + size, last.y) }
'L' -> (last.x - size..last.x).map { Coordinate(it, last.y) }.toCollection(points).run {
Coordinate(
last.x - size,
last.y
)
}
'U' -> (last.y..(last.y) + size).map { Coordinate(last.x, it) }.toCollection(points).run {
Coordinate(
last.x,
last.y + size
)
}
'D' -> (last.y - size..last.y).map { Coordinate(last.x, it) }.toCollection(points).run {
Coordinate(
last.x,
last.y - size
)
}
else -> fail("Illegal direction $current")
}
}
points.remove(origin)
// find all the points that the second circuit cross with the first circuit
last = origin
val intersections = PriorityQueue<Coordinate>(manhattanOriginComparator)
readLine()!!.split(",").forEach { current ->
val size = current.substring(1).toInt()
last = when (current[0]) {
'R' -> (last.x..(last.x) + size).map {
Coordinate(
it,
last.y
)
}.filter { it in points }.toCollection(intersections).run { Coordinate(last.x + size, last.y) }
'L' -> (last.x - size..last.x).map {
Coordinate(
it,
last.y
)
}.filter { it in points }.toCollection(intersections).run { Coordinate(last.x - size, last.y) }
'U' -> (last.y..(last.y) + size).map {
Coordinate(
last.x,
it
)
}.filter { it in points }.toCollection(intersections).run { Coordinate(last.x, last.y + size) }
'D' -> (last.y - size..last.y).map {
Coordinate(
last.x,
it
)
}.filter { it in points }.toCollection(intersections).run { Coordinate(last.x, last.y - size) }
else -> fail("Illegal direction $current")
}
}
println(manhattanDistance(Coordinate(0, 0), intersections.peek()))
}
| 0 | Kotlin | 0 | 0 | 554377cc4cf56cdb770ba0b49ddcf2c991d5d0b7 | 2,645 | AoC2019 | MIT License |
src/main/kotlin/g0701_0800/s0749_contain_virus/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g0701_0800.s0749_contain_virus
// #Hard #Array #Depth_First_Search #Breadth_First_Search #Matrix #Simulation
// #2023_03_06_Time_201_ms_(100.00%)_Space_37.5_MB_(100.00%)
@Suppress("kotlin:S107")
class Solution {
private var m = 0
private var n = 0
private val dirs = arrayOf(intArrayOf(-1, 0), intArrayOf(1, 0), intArrayOf(0, 1), intArrayOf(0, -1))
fun containVirus(grid: Array<IntArray>): Int {
m = grid.size
n = grid[0].size
var res = 0
while (true) {
var id = 0
val visited: MutableSet<Int> = HashSet()
val islands: MutableMap<Int, MutableSet<Int>> = HashMap()
val scores: MutableMap<Int, MutableSet<Int>> = HashMap()
val walls: MutableMap<Int, Int> = HashMap()
for (i in 0 until m) {
for (j in 0 until n) {
if (grid[i][j] == 1 && !visited.contains(i * n + j)) {
dfs(i, j, visited, grid, islands, scores, walls, id++)
}
}
}
if (islands.isEmpty()) {
break
}
var maxVirus = 0
for (i in 0 until id) {
if (scores.getOrDefault(maxVirus, HashSet()).size
< scores.getOrDefault(i, HashSet()).size
) {
maxVirus = i
}
}
res += walls.getOrDefault(maxVirus, 0)
for (i in 0 until islands.size) {
for (island in islands[i]!!) {
val x = island / n
val y = island % n
if (i == maxVirus) {
grid[x][y] = -1
} else {
for (dir in dirs) {
val nx = x + dir[0]
val ny = y + dir[1]
if (nx in 0 until m && ny >= 0 && ny < n && grid[nx][ny] == 0) {
grid[nx][ny] = 1
}
}
}
}
}
}
return res
}
private fun dfs(
i: Int,
j: Int,
visited: MutableSet<Int>,
grid: Array<IntArray>,
islands: MutableMap<Int, MutableSet<Int>>,
scores: MutableMap<Int, MutableSet<Int>>,
walls: MutableMap<Int, Int>,
id: Int
) {
if (!visited.add(i * n + j)) {
return
}
islands.computeIfAbsent(id) { HashSet() }.add(i * n + j)
for (dir in dirs) {
val x = i + dir[0]
val y = j + dir[1]
if (x < 0 || x >= m || y < 0 || y >= n) {
continue
}
if (grid[x][y] == 1) {
dfs(x, y, visited, grid, islands, scores, walls, id)
}
if (grid[x][y] == 0) {
scores.computeIfAbsent(
id
) { HashSet() }.add(x * n + y)
walls[id] = walls.getOrDefault(id, 0) + 1
}
}
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 3,125 | LeetCode-in-Kotlin | MIT License |
src/algorithmsinanutshell/PrimMinSpanningTreeAlgorithm.kt | realpacific | 234,499,820 | false | null | package algorithmsinanutshell
import utils.assertArraysSame
import java.util.*
import kotlin.test.assertEquals
/**
* Prim Algorithm starts from min cost edge and then selects the next small cost edge
* while maintaining the connection with first edge.
*
* This can be modeled using [PriorityQueue] sorted using [Edge] w.r.t its weight
*/
class PrimMinSpanningTreeAlgorithm(val graph: Graph) {
private val selected = mutableSetOf<Vertex>()
private val mst = Stack<Edge>()
private val pq = PriorityQueue<Edge> { o1, o2 -> o1!!.weight!! - o2!!.weight!! }
private var isExecuted = false
private lateinit var minEdge: Graph.Edge
init {
graph.getAllNodes().forEach { startVertex ->
startVertex.edges.forEach {
if (!::minEdge.isInitialized) {
minEdge = it
} else if (minEdge.weight!! > it.weight!!) {
minEdge = it
}
}
}
}
fun execute(): PrimMinSpanningTreeAlgorithm {
runAlgorithm()
mst.forEach(::println)
isExecuted = true
return this
}
fun result(): List<Edge> {
require(isExecuted)
return mst.toList()
}
fun minCost(): Int {
require(isExecuted)
return mst.sumBy { it.weight!! }
}
private fun runAlgorithm() {
// Add the starting vertex to selected
selected.add(minEdge.startVertex)
// Put its edge on priority queue
minEdge.startVertex.edges.forEach(pq::offer)
while (pq.isNotEmpty()) {
// Since items in priority queue are sorted using edge's weight, lowest cost edge is always at the top
val edge = pq.poll()
if (selected.contains(edge.endVertex)) {
continue
} else {
mst.add(edge)
selected.add(edge.endVertex)
// Add end vertex's edges to priority queue
// This will put it as candidate to be included in mst
edge.endVertex.edges.forEach(pq::offer)
}
}
}
}
fun main() {
val graph = Graph(Relation.WEIGHTED_UNDIRECTED)
val v1 = graph.add(1)
val v2 = graph.add(2)
val v3 = graph.add(3)
val v4 = graph.add(4)
val v5 = graph.add(5)
v1.connectWith(v2, 3)
v2.connectWith(v3, 6)
v3.connectWith(v4, 5)
v4.connectWith(v1, 10)
v5.connectWith(v2, 9)
v5.connectWith(v4, 8)
val mst = PrimMinSpanningTreeAlgorithm(graph).execute()
assertEquals(22, mst.minCost())
assertArraysSame(arrayOf(3, 6, 5, 8), mst.result().map { it.weight }.toTypedArray())
} | 4 | Kotlin | 5 | 93 | 22eef528ef1bea9b9831178b64ff2f5b1f61a51f | 2,670 | algorithms | MIT License |
src/year2022/day04/Solution.kt | LewsTherinTelescope | 573,240,975 | false | {"Kotlin": 33565} | package year2022.day04
import utils.runIt
fun main() = runIt(
testInput = """
2-4,6-8
2-3,4-5
5-7,7-9
2-8,3-7
6-6,4-6
2-6,4-8
""".trimIndent(),
::part1,
testAnswerPart1 = 2,
::part2,
testAnswerPart2 = 4,
)
fun part1(input: String) = input.toAssignmentPairs().count { (a, b) -> a overlapsFully b }
fun part2(input: String) = input.toAssignmentPairs().count { (a, b) -> a overlaps b }
fun String.toAssignmentPairs() = split("\n").map { pair ->
pair.split(",")
.map {
it.split("-").let { (start, end) ->
start.toInt()..end.toInt()
}
}
.let { (a, b) -> a to b }
}
operator fun IntRange.contains(other: IntRange) = other.first in this && other.last in this
infix fun IntRange.overlaps(other: IntRange) = first in other || other.first in this
infix fun IntRange.overlapsFully(other: IntRange) = other in this || this in other
| 0 | Kotlin | 0 | 0 | ee18157a24765cb129f9fe3f2644994f61bb1365 | 861 | advent-of-code-kotlin | Do What The F*ck You Want To Public License |
advent-of-code-2022/src/test/kotlin/Day 5 Supply Stacks.kt | yuriykulikov | 159,951,728 | false | {"Kotlin": 1666784, "Rust": 33275} | import io.kotest.matchers.shouldBe
import org.junit.jupiter.api.Test
class `Day 5 Supply Stacks` {
@Test
fun silverTest() {
message(testInput) shouldBe "CMZ"
}
@Test
fun silver() {
message(loadResource("day5")) shouldBe "VRWBSFZWM"
}
@Test
fun goldTest() {
message9001(testInput) shouldBe "MCD"
}
@Test
fun gold() {
message9001(loadResource("day5")) shouldBe "RBTWJWMCF"
}
private fun message(input: String): String {
val stacks = initStacks(input)
parseMoves(input).forEach { move ->
repeat(move.howMany) {
val pop = stacks[move.from - 1].removeLast()
stacks[move.to - 1].add(pop)
}
}
return stacks.mapNotNull { it.lastOrNull() }.joinToString("")
}
private fun message9001(input: String): String {
val stacks = initStacks(input)
parseMoves(input).forEach { move ->
val from = stacks[move.from - 1]
val popped = from.takeLast(move.howMany)
repeat(move.howMany) { from.removeLast() }
stacks[move.to - 1].addAll(popped)
}
return stacks.mapNotNull { it.lastOrNull() }.joinToString("")
}
private fun parseMoves(input: String): List<Move> {
return input.split("\n\n").last().lines().map {
// move 1 from 2 to 1
val (howMany, from, to) = it.split("move ", " from ", " to ").drop(1)
Move(howMany.toInt(), from.toInt(), to.toInt())
}
}
private fun initStacks(input: String): List<MutableList<Char>> {
val stacks = (0..10).map { ArrayDeque<Char>() }.toMutableList()
input
.split("\n\n")
.first()
.lines()
.dropLast(1)
.map { line -> (1 until line.lastIndex step 4).map { index -> line[index] } }
// fill the stacks bottom-up
.reversed()
.forEach { line ->
line.forEachIndexed { index, char ->
if (char != ' ') {
stacks[index].add(char)
}
}
}
return stacks
}
data class Move(val howMany: Int, val from: Int, val to: Int)
}
private val testInput =
"""
[D]
[N] [C]
[Z] [M] [P]
1 2 3
move 1 from 2 to 1
move 3 from 1 to 3
move 2 from 2 to 1
move 1 from 1 to 2
""".trimIndent()
| 0 | Kotlin | 0 | 1 | f5efe2f0b6b09b0e41045dc7fda3a7565cb21db3 | 2,206 | advent-of-code | MIT License |
src/Day11.kt | monsterbrain | 572,819,542 | false | {"Kotlin": 42040} | import java.math.BigInteger
val OLD = -1L
class Monkey(val index: Int) {
private lateinit var op: OP
var opValue: Long? = null
var divisibleBy: Long = -1
var monkeyToThrowIfTrue = -1
var monkeyToThrowIfFalse = -1
var inspected = 0L
val items = ArrayList<Long>()
fun setItems(items: List<String>) {
this.items.addAll(items.map { it.trim().toLong() })
}
fun setOperation(s: String) {
op = when (s) {
"*" -> OP.MULTI
"+" -> OP.ADD
"-" -> OP.SUB
else -> TODO()
}
}
fun getNewWorry(item: Long): Long {
val opVal = if (opValue!! == OLD) item else opValue!!
return when (op) {
OP.ADD -> item + opVal
OP.SUB -> TODO()
OP.MULTI -> item * opVal
OP.DIV -> TODO()
}
}
fun isDivisibleBy(value: Long): Boolean {
return value % divisibleBy == 0L
}
fun addItem(newItem: Long) {
items.add(newItem)
}
}
enum class OP {
ADD,
SUB,
MULTI,
DIV
}
fun main() {
fun part1(input: List<String>): Int {
val monkeys = ArrayList<Monkey>()
for (rules in input.withIndex()) {
val monkey = Monkey(rules.index)
for (rule in rules.value.lines()) {
if (rule.contains("starting items", true)) {
val items = rule.substringAfter(": ").split(",")
println("items to add = ${items}")
monkey.setItems(items)
} else if (rule.contains("Operation")) {
val split = rule.substringAfter("= ").split(" ")
monkey.setOperation(split[1])
monkey.opValue = split.last().toLongOrNull() ?: OLD
} else if (rule.contains("Test")) {
monkey.divisibleBy = rule.split(" ").last().toLong()
} else {
if (rule.contains("true")) {
monkey.monkeyToThrowIfTrue = rule.split(" ").last().toInt()
}
if (rule.contains("false")) {
monkey.monkeyToThrowIfFalse = rule.split(" ").last().toInt()
}
}
}
monkeys.add(monkey)
}
fun oneRound() {
for (i in monkeys.indices) {
val monkey = monkeys[i]
val items = ArrayList(monkeys[i].items)
println("Monkey $i:")
for (item in items) {
monkey.inspected ++
println("inspects and item with level : $item")
var multiplied = monkey.getNewWorry(item)
println("- worry level multiplied by ${monkey.opValue} is $multiplied")
multiplied = multiplied/3
println("- gets bored div by 3 = $multiplied")
val isDivisible = monkey.isDivisibleBy(multiplied)
println("- $multiplied is ${if(isDivisible) "" else "NOT" } divisible by ${monkey.divisibleBy}")
monkey.items.remove(item)
var targetMonkey = -1
if (isDivisible) {
targetMonkey = monkey.monkeyToThrowIfTrue
monkeys[monkey.monkeyToThrowIfTrue].addItem(multiplied)
} else {
targetMonkey = monkey.monkeyToThrowIfFalse
monkeys[monkey.monkeyToThrowIfFalse].addItem(multiplied)
}
println("- item with worry $multiplied is thrown to $targetMonkey")
}
}
}
repeat(20) {
oneRound()
}
println("after 20 rounds")
for (monkey in monkeys) {
println("monkey ${monkey.index} (inspected ${monkey.inspected} times): ${monkey.items}")
}
println("monkeys.sortBy { it.inspected } = ${monkeys.sortedBy { it.inspected }.map { "${it.index}>"+it.inspected }}")
// monkey round begins
return 0
}
fun part2(input: List<String>): Int {
val monkeys = ArrayList<Monkey>()
for (rules in input.withIndex()) {
val monkey = Monkey(rules.index)
for (rule in rules.value.lines()) {
if (rule.contains("starting items", true)) {
val items = rule.substringAfter(": ").split(",")
// println("items to add = ${items}")
monkey.setItems(items)
} else if (rule.contains("Operation")) {
val split = rule.substringAfter("= ").split(" ")
monkey.setOperation(split[1])
monkey.opValue = split.last().toLongOrNull() ?: OLD
} else if (rule.contains("Test")) {
monkey.divisibleBy = rule.split(" ").last().toLong()
} else {
if (rule.contains("true")) {
monkey.monkeyToThrowIfTrue = rule.split(" ").last().toInt()
}
if (rule.contains("false")) {
monkey.monkeyToThrowIfFalse = rule.split(" ").last().toInt()
}
}
}
monkeys.add(monkey)
}
fun oneRound() {
for (i in monkeys.indices) {
val monkey = monkeys[i]
val items = ArrayList(monkeys[i].items)
println("Monkey $i:")
for (item in items) {
monkey.inspected ++
println("inspects and item with level : $item")
val multiplied = monkey.getNewWorry(item)
println("- new worry level is $multiplied")
// multiplied = multiplied/3
// println("- gets bored div by 3 = $multiplied")
val isDivisible = monkey.isDivisibleBy(multiplied)
println("- $multiplied is ${if(isDivisible) "" else "NOT" } divisible by ${monkey.divisibleBy}")
monkey.items.remove(item)
var targetMonkey = -1
if (isDivisible) {
targetMonkey = monkey.monkeyToThrowIfTrue
monkeys[monkey.monkeyToThrowIfTrue].addItem(multiplied)
} else {
targetMonkey = monkey.monkeyToThrowIfFalse
monkeys[monkey.monkeyToThrowIfFalse].addItem(multiplied)
}
println("- item with worry $multiplied is thrown to $targetMonkey")
}
}
}
repeat(20) {
oneRound()
if (it+1==1 || it+1 == 20 || it+1 == 1000 || it+1 == 2000 || it+1 == 10000) {
println("after ${it+1} rounds")
for (monkey in monkeys) {
println("monkey ${monkey.index} inspected items ${monkey.inspected} times)")
}
Long.MAX_VALUE
BigInteger.ONE
}
}
/*println("after 10000 rounds")
for (monkey in monkeys) {
println("monkey ${monkey.index} (inspected ${monkey.inspected} times): ${monkey.items}")
}*/
// println("monkeys.sortBy { it.inspected } = ${monkeys.sortedBy { it.inspected }.map { "${it.index}>"+it.inspected }}")
// monkey round begins
return 0
}
// test if implementation meets criteria from the description, like:
val testInput = readInputSepByGap("Day11_test")
// val test1Result = part1(testInput)
// check(test1Result == 0)
// val testInput2 = readInput("Day10_test2")
//val test2Result = part1(testInput2)
//check(test2Result == -1)
val input = readInputSepByGap("Day11")
// println(part1(input))
val part2testResult = part2(testInput)
//check(part2testResult == 36)
// val input = readInput("Day10")
//println(part2(input))
// val input = readInput("Day09")
//println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 3a1e8615453dd54ca7c4312417afaa45379ecf6b | 8,174 | advent-of-code-kotlin-2022-Solutions | Apache License 2.0 |
src/main/kotlin/days/day07.kt | josergdev | 573,178,933 | false | {"Kotlin": 20792} | package days
import java.nio.file.Files
import java.nio.file.Paths
fun createMapOfSizes(shellOuput: String): Map<List<String>, Int> = shellOuput
.replaceFirst("\$ ", "")
.split("\n\$ ")
.map {
when {
it.startsWith("cd") -> "cd" to listOf(it.replaceFirst("cd ", ""))
else -> "ls" to it.replaceFirst("ls\n", "").split("\n")
}
}
.let { it.scan(listOf<String>()) { acc, (command, dirOrStdout) ->
when(command) {
"cd" -> when {
dirOrStdout.first() == ".." -> acc.dropLast(1)
else -> acc + dirOrStdout.first()
}
else -> acc
}
}.zip(it)
}
.filter { (_, command) -> command.first != "cd" }
.map { (path, command) -> path to command.second }
.reversed()
.fold(mutableMapOf()) { map, (path, ls) ->
map[path] = ls.sumOf {
when {
it.startsWith("dir ") -> map[path + it.replace("dir ", "")]!!
else -> it.split(" ")[0].toInt()
}
}
map
}
fun day7part1() = createMapOfSizes(Files.readString(Paths.get("input/07.txt")))
.values
.filter { it <= 100000 }
.sum()
fun day7part2() = createMapOfSizes(Files.readString(Paths.get("input/07.txt")))
.let { it[listOf("/")]!! to it.values }
.let { (used, values) -> values.sorted().first { 70000000 - 30000000 - used + it > 0 } } | 0 | Kotlin | 0 | 0 | ea17b3f2a308618883caa7406295d80be2406260 | 1,463 | aoc-2022 | MIT License |
src/main/kotlin/com/groundsfam/advent/y2022/d22/Cube.kt | agrounds | 573,140,808 | false | {"Kotlin": 281620, "Shell": 742} | package com.groundsfam.advent.y2022.d22
import com.groundsfam.advent.points.Point
// HELPFUL FACT: Cubes are orientable! Therefore adjacent edges will _always_
// be in "opposition" when all faces are clockwise-oriented in the original map.
// No need to store orientation of edges!
// edges order:
// 0 <-> right
// 1 <-> bottom
// 2 <-> left
// 3 <-> top
data class Edge(val adjFace: Int, val adjFaceEdge: Int)
data class Face(val upperLeft: Point, val edges: List<Edge>)
private data class MutableFace(val id: Int, val upperLeft: Point, val edges: MutableList<Edge?>) {
fun toFace() = Face(upperLeft, edges.filterNotNull())
}
fun parseCube(map: List<String>): List<Face> {
val faces = findFaces(map)
// kick off process with faces that are actually adjacent on the given map
faces.forEach { face ->
val (x, y) = face.upperLeft
val adjPoints = map.sideLen.let { sl ->
listOf(Point(x + sl, y), Point(x, y + sl), Point(x - sl, y), Point(x, y - sl))
}
adjPoints.forEachIndexed { i, adjPoint ->
faces.indexOfFirst { it.upperLeft == adjPoint }.let {
if (it != -1) face.edges[i] = Edge(it, (i + 2).mod(4))
}
}
}
fun Int.prev() = (this - 1).mod(4)
fun Int.next() = (this + 1).mod(4)
// fill in edges
while (faces.any { face -> face.edges.any { it == null } }) {
faces.forEach { face ->
val frozenEdges = face.edges.toList() // we will be modifying face.edges, so loop over frozen copy
frozenEdges.forEachIndexed { edgeNum, edge ->
if (edge != null) {
// try to use adjacent face to fill in missing edges
if (face.edges[edgeNum.prev()] == null) {
faces[edge.adjFace].edges[edge.adjFaceEdge.next()]?.let { adjNextEdge ->
face.edges[edgeNum.prev()] = Edge(adjNextEdge.adjFace, adjNextEdge.adjFaceEdge.next())
}
}
if (face.edges[edgeNum.next()] == null) {
faces[edge.adjFace].edges[edge.adjFaceEdge.prev()]?.let { adjPrevEdge ->
face.edges[edgeNum.next()] = Edge(adjPrevEdge.adjFace, adjPrevEdge.adjFaceEdge.prev())
}
}
}
}
}
}
return faces.map { it.toFace() }
}
private fun findFaces(map: List<String>): List<MutableFace> {
val ret = mutableListOf<MutableFace>()
(map.indices step map.sideLen).forEach { y ->
(map[y].indices step map.sideLen).forEach { x ->
if (map[y][x] in ".#") {
val edges = mutableListOf<Edge?>().apply {
repeat(4) {
add(null)
}
}
ret.add(MutableFace(ret.size, Point(x, y), edges))
}
}
}
return ret
}
// side length of the cube
// assumption: the cube has been cut to fit in a 3s x 4s rectangle, s = sideLen
val List<String>.sideLen
get() = minOf(size, this.maxOf { it.length }) / 3
| 0 | Kotlin | 0 | 1 | c20e339e887b20ae6c209ab8360f24fb8d38bd2c | 3,164 | advent-of-code | MIT License |
kotlin/03.kt | NeonMika | 433,743,141 | false | {"Kotlin": 68645} | class Day3 : Day<List<Day3.BitString>>("03") {
// Classes
data class BitString(val str: String) : CharSequence by str {
val int: Int = str.toInt(2)
}
data class Counter(val zeros: Int = 0, val ones: Int = 0) {
/**
* Least frequent symbol, equal not defined
*/
val epsilonRate: Char
get() = if (zeros > ones) '1' else '0'
/**
* Most frequent symbol, equal not defined
*/
val gammaRate: Char
get() = if (zeros > ones) '0' else '1'
/**
* Most frequent symbol, 1 if equal
*/
val oxygenGeneratorRating: Char
get() = if (ones >= zeros) '1' else '0'
/**
* Least frequent symbol, 0 if equal
*/
val co2ScrubberRating: Char
get() = if (zeros <= ones) '0' else '1'
operator fun plus(ch: Char) = Counter(zeros + (ch == '0').int, ones + (ch == '1').int)
}
// Extension methods
fun Iterable<BitString>.counters() = fold(Array(first().length) { Counter() }.toList()) { l, x ->
l.mapIndexed { i, e -> e + x[i] }
}
fun List<BitString>.leftToRightSelection(matcher: (Char, Counter) -> Boolean): BitString {
var data = this.toList()
for (i in 0..data[0].lastIndex) {
val counters = data.counters()
data = data.filter { matcher(it[i], counters[i]) }
if (data.size == 1) {
break
}
}
return data.single()
}
val Iterable<Counter>.epsilonRate
get() = BitString(map { it.gammaRate }.joinToString(""))
val Iterable<Counter>.gammaRate
get() = BitString(map { it.epsilonRate }.joinToString(""))
// Data
override fun dataStar1(lines : List<String>) = lines.map(::BitString)
override fun dataStar2(lines : List<String>) = lines.map(::BitString)
// 1 Star
override fun star1(data: List<BitString>): Number {
val counters = data.counters()
val gammaRate = counters.gammaRate
val epsilonRate = counters.epsilonRate
return gammaRate.int * epsilonRate.int
}
// 2 Stars
override fun star2(data: List<BitString>): Number {
val oxygenGeneratorRating = data.leftToRightSelection { ch, counter -> ch == counter.oxygenGeneratorRating }
val co2ScrubberRating = data.leftToRightSelection { ch, counter -> ch == counter.co2ScrubberRating }
return oxygenGeneratorRating.int * co2ScrubberRating.int
}
}
fun main() {
Day3()()
} | 0 | Kotlin | 0 | 0 | c625d684147395fc2b347f5bc82476668da98b31 | 2,561 | advent-of-code-2021 | MIT License |
src/main/kotlin/co/csadev/advent2021/Day22.kt | gtcompscientist | 577,439,489 | false | {"Kotlin": 252918} | /**
* Copyright (c) 2021 by <NAME>
* Advent of Code 2021, Day 22
* Problem Description: http://adventofcode.com/2021/day/212
*/
package co.csadev.advent2021
import co.csadev.adventOfCode.BaseDay
import co.csadev.adventOfCode.Resources.resourceAsList
import kotlin.math.max
import kotlin.math.min
class Day22(override val input: List<String> = resourceAsList("21day22.txt")) :
BaseDay<List<String>, Long, Long> {
private val instructions = input.map {
it.split(" ", ",", "=", "..")
}.map {
CubeRule(
Cube(it[2].toInt(), it[3].toInt(), it[5].toInt(), it[6].toInt(), it[8].toInt(), it[9].toInt()),
(it[0] == "on")
)
}
private fun getReactor(part2: Boolean = false): List<Cube> {
var reactor = mutableListOf<Cube>()
var temp: MutableList<Cube>
instructions.forEachIndexed { index, rule ->
println("Running instruction #$index")
if (!part2 && rule.cube.initSpace) return@forEachIndexed
temp = reactor.flatMap { r ->
r.abjunction(rule.cube)
}.toMutableList()
if (rule.on) temp.add(rule.cube)
reactor = temp
temp = mutableListOf()
}
return reactor.toList()
}
private data class CubeRule(val cube: Cube, val on: Boolean)
private data class Cube(
val minX: Int,
val maxX: Int,
val minY: Int,
val maxY: Int,
val minZ: Int,
val maxZ: Int
) {
val initSpace = (minX < -50 || maxX > 50 || minY < -50 || maxY > 50 || minZ < -50 || maxZ > 50)
val valid = if (minX <= maxX && minY <= maxY && minZ <= maxZ) this else null
val width = maxX - minX + 1
val height = maxY - minY + 1
val depth = maxZ - minZ + 1
val volume: Long = width.toLong() * height * depth
fun intersect(a: Cube, b: Cube): Cube? {
return Cube(
max(a.minX, b.minX),
min(a.maxX, b.maxX),
max(a.minY, b.minY),
min(a.maxY, b.maxY),
max(a.minZ, b.minZ),
min(a.maxZ, b.maxZ)
).valid
}
fun abjunction(b: Cube): List<Cube> {
val i = intersect(this, b) ?: return listOf(this)
val cubes = mutableListOf<Cube>()
if (i.minX > minX) {
cubes.add(Cube(minX, i.minX - 1, minY, maxY, minZ, maxZ))
}
if (i.maxX < maxX) {
cubes.add(Cube(i.maxX + 1, maxX, minY, maxY, minZ, maxZ))
}
if (i.minY > minY) {
cubes.add(Cube(i.minX, i.maxX, minY, i.minY - 1, minZ, maxZ))
}
if (i.maxY < maxY) {
cubes.add(Cube(i.minX, i.maxX, i.maxY + 1, maxY, minZ, maxZ))
}
if (i.minZ > minZ) {
cubes.add(Cube(i.minX, i.maxX, i.minY, i.maxY, minZ, i.minZ - 1))
}
if (i.maxZ < maxZ) {
cubes.add(Cube(i.minX, i.maxX, i.minY, i.maxY, i.maxZ + 1, maxZ))
}
return cubes
}
}
override fun solvePart1() = getReactor().sumOf { it.volume }
override fun solvePart2() = getReactor(true).sumOf { it.volume }
}
| 0 | Kotlin | 0 | 1 | 43cbaac4e8b0a53e8aaae0f67dfc4395080e1383 | 3,290 | advent-of-kotlin | Apache License 2.0 |
src/main/kotlin/dp/CandySwap.kt | yx-z | 106,589,674 | false | null | package dp
import dp.Candy.*
import util.*
// suppose you are given three types of candies: A, B, C
enum class Candy(val v: Int) {
A(1), B(2), C(3);
}
// and also a row of such candies R[1..n]
// you start with one candy A in hand and traverse through the row R from 1 to n
// at each index, you may either swap your candy in hand or not
// if you don't swap the candy, your total score won't change
// if you choose to swap the candy: if the candy is the same, you earn one point
// o/w, you will lose one point (yes your score can be negative)
// find the max score you can earn after traversing R[1..n] only once
fun main(args: Array<String>) {
val R = oneArrayOf(A, B, C, C, B, A)
println(R.maxScore())
}
fun OneArray<Candy>.maxScore(): Int {
val R = this
val TYPES = Candy.values().size // # of different candies
val n = size
// dp[i, j]: max score I can earn if I am given a row R[i..n] and currently
// have a candy of type j in hand (assume 1 for A, 2 for B, 3 for C)
val dp = OneArray(n) { OneArray(TYPES) { 0 } }
// space: O(n)
// base case:
// dp[n, T] = 1 if R[n] = T
// = 0 o/w
dp[n, R[n].v] = 1
// recursive case:
// dp[i, j] = max { I swap with R[i], NOT swap with R[i] }
// = max { (if R[i] = j: 1 else: 0) + dp[i + 1, R[i]], dp[i + 1, j] }
// dependency: dp[i, j] depends on dp[i + 1, k], that is entries to the right
// eval order: decreasing i from n - 1 down to 1
for (i in n - 1 downTo 1) {
// any order for j
for (j in 1..TYPES) {
dp[i, j] = max(dp[i + 1, j], (if (R[i].v == j) 1 else 0) + dp[i + 1, R[i].v])
}
}
// time: O(n)
dp.prettyPrintTable()
// we want to know the max score, given R[1..n] and a candy of type A at first
return dp[1, 1]
} | 0 | Kotlin | 0 | 1 | 15494d3dba5e5aa825ffa760107d60c297fb5206 | 1,730 | AlgoKt | MIT License |
leetcode2/src/leetcode/SecondMiniimumNodeInABinaryTree.kt | hewking | 68,515,222 | false | null | package leetcode
import leetcode.structure.TreeNode
/**
* https://leetcode-cn.com/problems/second-minimum-node-in-a-binary-tree/
* 671. 二叉树中第二小的节点
* Created by test
* Date 2019/6/18 0:56
* Description
* 给定一个非空特殊的二叉树,每个节点都是正数,并且每个节点的子节点数量只能为 2 或 0。
* 如果一个节点有两个子节点的话,那么这个节点的值不大于它的子节点的值。
给出这样的一个二叉树,你需要输出所有节点中的第二小的值。如果第二小的值不存在的话,输出 -1 。
示例 1:
输入:
2
/ \
2 5
/ \
5 7
输出: 5
说明: 最小的值是 2 ,第二小的值是 5 。
示例 2:
输入:
2
/ \
2 2
输出: -1
说明: 最小的值是 2, 但是不存在第二小的值。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/second-minimum-node-in-a-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
object SecondMiniimumNodeInABinaryTree {
class Solution {
/**
* 思路:
* 1.因为题设子节点只有0,2两种,并且子节点大于等于父节点
* 所以有子节点的情况下,两个子节点和父节点一共三个,必有第二大的,否则就没有
* 2.根据题设可知,第一个节点是最小的,所以只需要找到第一个比第一个节点大的树就可以了
* 3.题目就变成找到第一个大于第一个节点的数
*/
fun findSecondMinimumValue(root: TreeNode?): Int {
if (root == null) return -1
return findValue(root,root?.`val`)
}
fun findValue(root: TreeNode?, value : Int) : Int{
root?:return -1
if (root.`val` > value ) return root.`val`
val l = findValue(root.left,value)
val r = findValue(root.right,value)
if (l == r && l == -1) {
return -1
}
if (l == -1) return r
if (r == -1) return l
return Math.min(l,r)
}
}
} | 0 | Kotlin | 0 | 0 | a00a7aeff74e6beb67483d9a8ece9c1deae0267d | 2,146 | leetcode | MIT License |
kotlin/128.Longest Consecutive Sequence(最长连续序列).kt | learningtheory | 141,790,045 | false | {"Python": 4025652, "C++": 1999023, "Java": 1995266, "JavaScript": 1990554, "C": 1979022, "Ruby": 1970980, "Scala": 1925110, "Kotlin": 1917691, "Go": 1898079, "Swift": 1827809, "HTML": 124958, "Shell": 7944} | /**
<p>Given an unsorted array of integers, find the length of the longest consecutive elements sequence.</p>
<p>Your algorithm should run in O(<em>n</em>) complexity.</p>
<p><strong>Example:</strong></p>
<pre>
<strong>Input:</strong> [100, 4, 200, 1, 3, 2]
<strong>Output:</strong> 4
<strong>Explanation:</strong> The longest consecutive elements sequence is <code>[1, 2, 3, 4]</code>. Therefore its length is 4.
</pre>
<p>给定一个未排序的整数数组,找出最长连续序列的长度。</p>
<p>要求算法的时间复杂度为 <em>O(n)</em>。</p>
<p><strong>示例:</strong></p>
<pre><strong>输入:</strong> [100, 4, 200, 1, 3, 2]
<strong>输出:</strong> 4
<strong>解释:</strong> 最长连续序列是 <code>[1, 2, 3, 4]。它的长度为 4。</code></pre>
<p>给定一个未排序的整数数组,找出最长连续序列的长度。</p>
<p>要求算法的时间复杂度为 <em>O(n)</em>。</p>
<p><strong>示例:</strong></p>
<pre><strong>输入:</strong> [100, 4, 200, 1, 3, 2]
<strong>输出:</strong> 4
<strong>解释:</strong> 最长连续序列是 <code>[1, 2, 3, 4]。它的长度为 4。</code></pre>
**/
class Solution {
fun longestConsecutive(nums: IntArray): Int {
}
} | 0 | Python | 1 | 3 | 6731e128be0fd3c0bdfe885c1a409ac54b929597 | 1,254 | leetcode | MIT License |
src/main/kotlin/tr/emreone/adventofcode/days/Day21.kt | EmRe-One | 433,772,813 | false | {"Kotlin": 118159} | package tr.emreone.adventofcode.days
import tr.emreone.kotlin_utils.automation.Day
import kotlin.math.max
class Day21 : Day(21, 2021, "<NAME>") {
class DeterministicDice {
var current = 0
var numberOfRolls = 0
fun roll(): Int {
numberOfRolls++
current++
if (current > 100) {
current -= 100
}
return current
}
}
class Player(val id: Int, var position: Int) {
var score = 0
fun play(dice: DeterministicDice) {
var roll = 0
repeat(3) {
roll += dice.roll()
}
position = (position + roll - 1) % 10 + 1
score += position
}
}
override fun part1(): Int {
val dice = DeterministicDice()
val pattern = """Player (\w+) starting position: (\w+)""".toRegex()
val player = mutableListOf<Player>()
for (line in inputAsList) {
val (id, position) = pattern.matchEntire(line)!!.destructured
player.add(Player(id.toInt(), position.toInt()))
}
var currentPlayer = 0
while (player.all { it.score < 1000 }) {
player[currentPlayer].play(dice)
currentPlayer = (currentPlayer + 1) % player.size
}
val loser = player.first { it.score < 1000 }
return loser.score * dice.numberOfRolls
}
val cache = mutableMapOf<List<Int>, Pair<Long, Long>>()
fun countWins(position1: Int, score1: Int, position2: Int, score2: Int): Pair<Long, Long> {
if (score1 >= 21) return Pair(1L, 0L)
if (score2 >= 21) return Pair(0L, 1L)
if (listOf(position1, score1, position2, score2) in cache) {
return cache[listOf(position1, score1, position2, score2)]!!
}
var result = Pair(0L, 0L)
for (d1 in 1..3) {
for (d2 in 1..3) {
for (d3 in 1..3) {
val newP1 = (position1 + d1 + d2 + d3 - 1) % 10 + 1
val newS1 = score1 + newP1
val wins = countWins(position2, score2, newP1, newS1)
// switched order of the player
result = result.first + wins.second to result.second + wins.first
}
}
}
cache[listOf(position1, score1, position2, score2)] = result
return result
}
override fun part2(): Long {
val pattern = """Player (\w+) starting position: (\w+)""".toRegex()
val player = mutableListOf<Player>()
for (line in inputAsList) {
val (id, position) = pattern.matchEntire(line)!!.destructured
player.add(Player(id.toInt(), position.toInt()))
}
cache.clear()
val totalWins = countWins(player[0].position, player[0].score, player[1].position, player[1].score)
return max(totalWins.first, totalWins.second)
}
}
| 0 | Kotlin | 0 | 0 | 516718bd31fbf00693752c1eabdfcf3fe2ce903c | 2,964 | advent-of-code-2021 | Apache License 2.0 |
parser-processor/src/main/kotlin/parser/Node.kt | madisp | 434,510,913 | false | {"Kotlin": 388138} | package parser
sealed class Node {
data class Split(val delim: String, val left: LeafNode, val right: Node): Node()
}
sealed class LeafNode : Node() {
data object Empty : LeafNode()
data class Field(val name: String): LeafNode()
data class Repeat(val delim: String, val field: Field): LeafNode()
}
sealed class Token {
data class Literal(val value: String): Token()
data class Expression(val contents: String): Token()
}
fun parse(pattern: String): Node {
return tree(tokenize(pattern))
}
private fun tokenize(pattern: String): List<Token> {
val tokens = mutableListOf<Token>()
var index = 0
while (index < pattern.length) {
val (token, newIndex) = readToken(pattern, index)
tokens.add(token)
index = newIndex
}
return tokens
}
private fun tree(tokens: List<Token>): Node {
if (tokens.isEmpty()) {
return LeafNode.Empty
} else if (tokens.size == 1) {
val token = tokens.single()
require (token is Token.Expression) { "Expected expression, got $token" }
return leaf(token)
} else {
val firstToken = tokens.first()
val splitOff = if (firstToken is Token.Expression) 1 else 0
val delim = tokens[splitOff]
require(delim is Token.Literal) { "Expected literal, got ${tokens[splitOff]}" }
val left = if (firstToken is Token.Expression) leaf(firstToken) else LeafNode.Empty
val right = tree(tokens.drop(splitOff + 1))
return Node.Split(delim.value, left, right)
}
}
private fun leaf(token: Token.Expression): LeafNode {
return if (token.contents.startsWith("r ")) {
val delimEnd = token.contents.indexOf('\'', 3)
val delim = token.contents.substring(3, delimEnd)
val field = token.contents.substring(delimEnd + 2)
LeafNode.Repeat(delim, LeafNode.Field(field))
} else {
LeafNode.Field(token.contents)
}
}
private val String.escaped: String get() = replace("\n", "\\n")
private fun readToken(input: String, index: Int): Pair<Token, Int> {
val part = input.substring(index)
return if (part.startsWith('{')) {
val end = part.indexOf('}')
if (end == -1) {
throw Exception("Unclosed expression starting at $index")
}
Token.Expression(part.substring(1, end).escaped) to (index + end + 1)
} else {
val end = part.indexOf('{').takeIf { it != -1 } ?: part.length
Token.Literal(part.substring(0, end).escaped) to (index + end)
}
}
| 0 | Kotlin | 0 | 1 | 3f106415eeded3abd0fb60bed64fb77b4ab87d76 | 2,379 | aoc_kotlin | MIT License |
src/main/kotlin/g2901_3000/s2909_minimum_sum_of_mountain_triplets_ii/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2901_3000.s2909_minimum_sum_of_mountain_triplets_ii
// #Medium #Array #2023_12_27_Time_463_ms_(100.00%)_Space_64.6_MB_(50.00%)
import kotlin.math.min
class Solution {
fun minimumSum(nums: IntArray): Int {
val n = nums.size
val leftSmallest = IntArray(n)
val rightSmallest = IntArray(n)
var currSmallest = nums[0]
leftSmallest[0] = -1
for (i in 1 until n) {
if (currSmallest >= nums[i]) {
leftSmallest[i] = -1
currSmallest = nums[i]
} else {
leftSmallest[i] = currSmallest
}
}
currSmallest = nums[n - 1]
rightSmallest[n - 1] = -1
for (i in n - 2 downTo 0) {
if (currSmallest >= nums[i]) {
rightSmallest[i] = -1
currSmallest = nums[i]
} else {
rightSmallest[i] = currSmallest
}
}
var ans = Int.MAX_VALUE
for (i in 0 until n) {
if (leftSmallest[i] != -1 && rightSmallest[i] != -1) {
ans = min(ans.toDouble(), (leftSmallest[i] + rightSmallest[i] + nums[i]).toDouble())
.toInt()
}
}
if (ans == Int.MAX_VALUE) {
return -1
}
return ans
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,329 | LeetCode-in-Kotlin | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.