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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
kotlin/src/katas/kotlin/leetcode/super_egg_drop/SuperEggDrop.kt | dkandalov | 2,517,870 | false | {"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221} | package katas.kotlin.leetcode.super_egg_drop
import datsok.shouldEqual
import org.junit.jupiter.api.Test
// https://leetcode.com/problems/super-egg-drop ❌
// https://www.youtube.com/watch?v=xsOCvSiSrSs
//
// You are given K eggs, and you have access to a building with N floors from 1 to N.
// Each egg is identical in function, and if an egg breaks, you cannot drop it again.
// You know that there exists a floor F with 0 <= F <= N such that any egg dropped at a floor
// higher than F will break, and any egg dropped at or below floor F will not break.
// Your goal is to know with certainty what the value of F is.
//
// Each move, you may take an egg (if you have an unbroken one) and drop it from any floor X (with 1 <= X <= N).
// What is the minimum number of moves that you need to know with certainty what F is,
// regardless of the initial value of F?
//
// Note:
// 1 <= K <= 100
// 1 <= N <= 10000
//
// Example 1:
// Input: K = 1, N = 2
// Output: 2
// Explanation:
// Drop the egg from floor 1. If it breaks, we know with certainty that F = 0.
// Otherwise, drop the egg from floor 2. If it breaks, we know with certainty that F = 1.
// If it didn't break, then we know with certainty F = 2.
// Hence, we needed 2 moves in the worst case to know what F is with certainty.
//
// Example 2:
// Input: K = 2, N = 6
// Output: 3
//
// Example 3:
// Input: K = 3, N = 14
// Output: 4
// 0 1 2
// 0 1 2 3
// 0 1 2 3 4
// 0 1 2 3 4 5
// 0 1 2 3 4 5 6
// 0 1 2 3 4 5 6 7
// 0 1 2 3 4 5 6 7 8 9
// 0 1 2 3 4 5 6 7 8 9 10 11 12
// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
fun superEggDrop(eggs: Int, floors: Int): Int {
require(eggs >= 1 && floors >= 0)
if (floors == 0) return 0
if (eggs == 1) return floors
val midFloor = when (floors) {
12 -> (floors / 2) - 1
9 -> floors / 2
else -> (floors + 1) / 2
}
val stepsBelow = superEggDrop(eggs - 1, floors = midFloor - 1) // broken egg
val stepsAbove = superEggDrop(eggs, floors = floors - midFloor) // egg didn't break
return maxOf(stepsBelow, stepsAbove) + 1
}
class Tests {
@Test fun examples() {
superEggDrop(eggs = 1, floors = 0) shouldEqual 0
superEggDrop(eggs = 1, floors = 1) shouldEqual 1
superEggDrop(eggs = 1, floors = 2) shouldEqual 2
superEggDrop(eggs = 2, floors = 2) shouldEqual 2
superEggDrop(eggs = 1, floors = 3) shouldEqual 3
superEggDrop(eggs = 2, floors = 3) shouldEqual 2
superEggDrop(eggs = 1, floors = 4) shouldEqual 4
superEggDrop(eggs = 2, floors = 4) shouldEqual 3
superEggDrop(eggs = 1, floors = 5) shouldEqual 5
superEggDrop(eggs = 2, floors = 5) shouldEqual 3
superEggDrop(eggs = 1, floors = 6) shouldEqual 6
superEggDrop(eggs = 2, floors = 6) shouldEqual 3
superEggDrop(eggs = 3, floors = 6) shouldEqual 3
superEggDrop(eggs = 2, floors = 9) shouldEqual 4
superEggDrop(eggs = 3, floors = 9) shouldEqual 4
superEggDrop(eggs = 2, floors = 12) shouldEqual 5
superEggDrop(eggs = 3, floors = 12) shouldEqual 4
superEggDrop(eggs = 2, floors = 14) shouldEqual 7
superEggDrop(eggs = 3, floors = 14) shouldEqual 4
// TODO superEggDrop(eggs = 3, floors = 25) shouldEqual 5
superEggDrop(eggs = 100, floors = 10_000) shouldEqual 14
}
} | 7 | Roff | 3 | 5 | 0f169804fae2984b1a78fc25da2d7157a8c7a7be | 3,360 | katas | The Unlicense |
compiler/fir/semantics/src/org/jetbrains/kotlin/fir/resolve/transformers/ImportUtils.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | /*
* Copyright 2010-2023 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.fir.resolve.transformers
import org.jetbrains.kotlin.fir.diagnostics.ConeDiagnostic
import org.jetbrains.kotlin.fir.resolve.diagnostics.ConeUnresolvedParentInImport
import org.jetbrains.kotlin.fir.resolve.providers.FirSymbolProvider
import org.jetbrains.kotlin.fir.symbols.impl.FirClassLikeSymbol
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.name.FqName
/**
* Compared to [resolveToPackageOrClass], does not perform the actual resolve.
*
* Instead of it, it just looks for the longest existing package name prefix in the [fqName],
* and assumes that the rest of the name (if present) is a relative class name.
*
* Given that [FqName.ROOT] package is always present in any [FirSymbolProvider],
* this function **can never fail**.
*/
fun findLongestExistingPackage(symbolProvider: FirSymbolProvider, fqName: FqName): PackageAndClass {
var currentPackage = fqName
val pathSegments = fqName.pathSegments()
var prefixSize = pathSegments.size
while (!currentPackage.isRoot && prefixSize > 0) {
if (symbolProvider.getPackage(currentPackage) != null) {
break
}
currentPackage = currentPackage.parent()
prefixSize--
}
if (currentPackage == fqName) return PackageAndClass(currentPackage, relativeClassFqName = null)
val relativeClassFqName = FqName.fromSegments((prefixSize until pathSegments.size).map { pathSegments[it].asString() })
return PackageAndClass(currentPackage, relativeClassFqName)
}
data class PackageAndClass(val packageFqName: FqName, val relativeClassFqName: FqName?)
fun resolveToPackageOrClass(symbolProvider: FirSymbolProvider, fqName: FqName): PackageResolutionResult {
val (currentPackage, relativeClassFqName) = findLongestExistingPackage(symbolProvider, fqName)
if (relativeClassFqName == null) return PackageResolutionResult.PackageOrClass(currentPackage, null, null)
val classId = ClassId(currentPackage, relativeClassFqName, isLocal = false)
return resolveToPackageOrClass(symbolProvider, classId)
}
fun resolveToPackageOrClass(symbolProvider: FirSymbolProvider, classId: ClassId): PackageResolutionResult {
val symbol = symbolProvider.getClassLikeSymbolByClassId(classId) ?: return PackageResolutionResult.Error(
ConeUnresolvedParentInImport(classId)
)
return PackageResolutionResult.PackageOrClass(classId.packageFqName, classId.relativeClassName, symbol)
}
sealed class PackageResolutionResult {
data class PackageOrClass(
val packageFqName: FqName, val relativeClassFqName: FqName?, val classSymbol: FirClassLikeSymbol<*>?
) : PackageResolutionResult()
class Error(val diagnostic: ConeDiagnostic) : PackageResolutionResult()
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 2,965 | kotlin | Apache License 2.0 |
kotlin/src/com/leetcode/31_NextPermutation.kt | programmerr47 | 248,502,040 | false | null | package com.leetcode
/**
* Possibly we can combine reverse method and fixSortedAsc
* But I'm not sure about it since 2 cycles one operation in each
* is equal to 1 cycle with two operations. So to gain some boost
* we need to have less operations than sum of what we have. And
* I'm not sure we can achieve that.
*
* Time: O(n)
*/
private class Solution31 {
fun nextPermutation(nums: IntArray) {
if (nums.size < 2) return
var num = -1
var i = nums.lastIndex
while (i >= 0 && nums[i] >= num) {
num = nums[i]
i--
}
nums.reverse(i + 1, nums.lastIndex)
if (i >= 0) nums.fixSortedAsc(i, nums.lastIndex)
}
private fun IntArray.reverse(from: Int = 0, to: Int = lastIndex) {
val mid = (to + from) shr 1
for (i in from..mid) {
switch(i, to - (i - from))
}
}
private fun IntArray.fixSortedAsc(from: Int, to: Int) {
var j = from
while (j < to && this[from] >= this[j + 1]) {
j++
}
if (j < to) switch(from, j + 1)
}
private fun IntArray.switch(index1: Int, index2: Int) {
val tmp = this[index1]
this[index1] = this[index2]
this[index2] = tmp
}
}
fun main() {
val solution = Solution31()
println(solution.solve(1, 3, 2))
println(solution.solve(1, 2, 2, 3))
println(solution.solve(3, 2, 1))
println(solution.solve(1, 2))
println(solution.solve(2, 1))
println(solution.solve(1))
println(solution.solve(4, 5, 2, 9, 1))
println(solution.solve(1, 10, 9, 8, 7, 5, 5, 2, 1, 1, 1))
}
private fun Solution31.solve(vararg nums: Int): List<Int> {
nextPermutation(nums)
return nums.toList()
} | 0 | Kotlin | 0 | 0 | 0b5fbb3143ece02bb60d7c61fea56021fcc0f069 | 1,743 | problemsolving | Apache License 2.0 |
clikt/src/commonMain/kotlin/com/github/ajalt/clikt/sources/ValueSource.kt | ajalt | 128,975,548 | false | {"Kotlin": 546659, "Shell": 1814, "Batchfile": 662} | package com.github.ajalt.clikt.sources
import com.github.ajalt.clikt.core.Context
import com.github.ajalt.clikt.parameters.options.*
interface ValueSource {
data class Invocation(val values: List<String>) {
companion object {
/** Create a list of a single Invocation with a single value */
fun just(value: Any?): List<Invocation> = listOf(value(value))
/** Create an Invocation with a single value */
fun value(value: Any?): Invocation = Invocation(listOf(value.toString()))
}
}
fun getValues(context: Context, option: Option): List<Invocation>
companion object {
/**
* Get a name for an option that can be useful as a key for a value source.
*
* The returned value is the longest option name with its prefix removed
*
* ## Examples
*
* ```
* name(option("-h", "--help")) == "help"
* name(option("/INPUT")) == "INPUT"
* name(option("--new-name", "--name")) == "new-name
* ```
*/
fun name(option: Option): String {
val longestName = option.longestName()
requireNotNull(longestName) { "Option must have a name" }
return splitOptionPrefix(longestName).second
}
/**
* Create a function that will return string keys for options.
*
* By default, keys will be equal to the value returned by [name].
*
* @param prefix A static string prepended to all keys
* @param joinSubcommands If null, keys will not include names of subcommands. If given,
* this string be used will join subcommand names to the beginning of keys. For options
* that are in a root command, this has no effect. For option in subcommands, the
* subcommand name will be joined. The root command name is never included.
* @param uppercase If true, returned keys will be entirely uppercase.
* @param replaceDashes `-` characters in option names will be replaced with this character.
*/
fun getKey(
prefix: String = "",
joinSubcommands: String? = null,
uppercase: Boolean = false,
replaceDashes: String = "-",
): (Context, Option) -> String = { context, option ->
var k = name(option).replace("-", replaceDashes)
if (joinSubcommands != null) {
k = (context.commandNameWithParents().drop(1) + k).joinToString(joinSubcommands)
}
k = k.replace("-", replaceDashes)
if (uppercase) k = k.uppercase()
prefix + k
}
/**
* Create a function that will return string keys that match the key used for environment variables.
*/
fun envvarKey(): (Context, Option) -> String = { context, option ->
val env = when (option) {
is OptionWithValues<*, *, *> -> option.envvar
else -> null
}
inferEnvvar(option.names, env, context.autoEnvvarPrefix) ?: ""
}
}
}
| 14 | Kotlin | 120 | 2,314 | 5cb5ab199947709a26754c6f8eeb73da775fac07 | 3,146 | clikt | Apache License 2.0 |
src/main/kotlin/_2022/Day25.kt | novikmisha | 572,840,526 | false | {"Kotlin": 145780} | package _2022
import readInput
import kotlin.math.pow
fun main() {
fun getNumber(char: Char): Long {
return when (char) {
'2' -> 2
'1' -> 1
'0' -> 0
'-' -> -1
'=' -> -2
else -> throw RuntimeException("unknown char")
}
}
fun toDecimal(str: String): Long {
return str.reversed()
.foldIndexed(0L) { index, acc, char -> (acc + (5.toDouble()).pow(index.toDouble()) * getNumber(char)).toLong() }
}
fun toSnafu(number: Long): String {
val snafuNumbers = "012=-"
var result = ""
var workingNumber = number
while (workingNumber != 0L) {
val mod = (workingNumber).mod(5)
result += snafuNumbers[mod]
val carriedBase = when(mod) {
3 -> 2
4 -> 1
else -> 0
}
workingNumber = (workingNumber + carriedBase) / 5
}
return result.reversed()
}
fun part1(input: List<String>): String {
val sum = input.sumOf {
toDecimal(it)
}
return toSnafu(sum)
}
fun part2(input: List<String>): Int {
return 0
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day25_test")
println(part1(testInput))
println(part2(testInput))
val input = readInput("Day25")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 0c78596d46f3a8bf977bf356019ea9940ee04c88 | 1,504 | advent-of-code | Apache License 2.0 |
2023/src/main/kotlin/de/skyrising/aoc2023/day3/solution.kt | skyrising | 317,830,992 | false | {"Kotlin": 411565} | package de.skyrising.aoc2023.day3
import de.skyrising.aoc.*
val test = TestInput("""
467..114..
...*......
..35..633.
......#...
617*......
.....+.58.
..592.....
......755.
...${'$'}.*....
.664.598..
""")
fun findNumbers(grid: CharGrid, pos: Vec2i, numbers: MutableMap<Vec2i, Int>) =
pos.eightNeighbors().mapNotNullTo(mutableSetOf()) { n ->
if (n !in grid || !grid[n].isDigit()) return@mapNotNullTo null
val start = grid[0 until n.x, n.y].indexOfLast { !it.isDigit() } + 1
numbers.getOrPut(Vec2i(start, n.y)) {
val end = grid[n.x until grid.width, n.y].indexOfFirst { !it.isDigit() } + n.x - 1
grid[start..maxOf(n.x, end), n.y].toInt()
}
}
@PuzzleName("<NAME>")
fun PuzzleInput.part1(): Any {
val grid = charGrid
val numbers = mutableMapOf<Vec2i, Int>()
grid.where { !it.isDigit() && it != '.' }.forEach { findNumbers(grid, it, numbers) }
return numbers.values.sum()
}
fun PuzzleInput.part2(): Any {
val grid = charGrid
val numbers = mutableMapOf<Vec2i, Int>()
return grid.where { it == '*' }.map { findNumbers(grid, it, numbers) }.filter { it.size == 2 }.sumOf { it.reduce(Int::times) }
}
| 0 | Kotlin | 0 | 0 | 19599c1204f6994226d31bce27d8f01440322f39 | 1,232 | aoc | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/CountGoodStrings.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import dev.shtanko.algorithms.MOD
import java.util.Arrays
/**
* 2466. Count Ways To Build Good Strings
* @see <a href="https://leetcode.com/problems/count-ways-to-build-good-strings/">Source</a>
*/
fun interface CountGoodStrings {
operator fun invoke(low: Int, high: Int, zero: Int, one: Int): Int
}
/**
* Approach 1: Dynamic Programming (Iterative)
*/
class CountGoodStringsDPRecursive : CountGoodStrings {
override operator fun invoke(low: Int, high: Int, zero: Int, one: Int): Int {
// Use dp[i] to record to number of good strings of length i.
val dp = IntArray(high + 1)
dp[0] = 1
// Iterate over each length `end`.
for (end in 1..high) {
// check if the current string can be made by append zero `0`s or one `1`s.
if (end >= zero) {
dp[end] += dp[end - zero]
}
if (end >= one) {
dp[end] += dp[end - one]
}
dp[end] %= MOD
}
// Add up the number of strings with each valid length [low ~ high].
var answer = 0
for (i in low..high) {
answer += dp[i]
answer %= MOD
}
return answer
}
}
/**
* Approach 2: Dynamic Programming (Recursive)
*/
class CountGoodStringsDPIterative : CountGoodStrings {
// Use dp[i] to record to number of good strings of length i.
private lateinit var dp: IntArray
override operator fun invoke(low: Int, high: Int, zero: Int, one: Int): Int {
dp = IntArray(high + 1)
Arrays.fill(dp, -1)
dp[0] = 1
// Add up the number of strings with each valid length [low ~ high].
var answer = 0
for (end in low..high) {
answer += dfs(end, zero, one)
answer %= MOD
}
return answer
}
// Find the number of good strings of length `end`.
private fun dfs(end: Int, zero: Int, one: Int): Int {
if (dp[end] != -1) return dp[end]
var count = 0
if (end >= one) {
count += dfs(end - one, zero, one)
}
if (end >= zero) {
count += dfs(end - zero, zero, one)
}
dp[end] = count % MOD
return dp[end]
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,891 | kotlab | Apache License 2.0 |
aoc-kotlin/src/main/kotlin/day07/Day07.kt | mahpgnaohhnim | 573,579,334 | false | {"Kotlin": 29246, "TypeScript": 1975, "Go": 1693, "Rust": 1520, "JavaScript": 123} | package day07
import java.io.File
class Day07 {
companion object {
val inputFile = File(this::class.java.getResource("input.txt")?.path.orEmpty())
fun getTotalSumSize(input: String, maxFolderSize: Int = 100000): Int {
val rootFolder = createRootFolder(input)
return sumUpByMaxSize(rootFolder, maxFolderSize)
}
fun findFolderToDelete(input: String, totalSpace: Int, freeSpaceNeeded: Int): Folder {
val rootFolder = createRootFolder(input)
val currentFreeSpace = totalSpace - rootFolder.getSize()
val spaceToFree = freeSpaceNeeded - currentFreeSpace
val possibleFolders = mutableListOf<Folder>()
this.findFoldersByMinSize(possibleFolders, rootFolder, spaceToFree)
return possibleFolders.minBy { it.getSize() }
}
fun createRootFolder(input: String): Folder {
val root = Folder(
name = "/",
folderList = mutableListOf(),
fileList = mutableListOf(),
absolutePath = "/",
parentFolder = null
)
var currentFolder: Folder = root
input.lines().forEach {
when {
it.startsWith("\$ ls") -> println(
"""
${currentFolder.absolutePath} ls
""".trimIndent()
)
it == "\$ cd .." -> currentFolder = currentFolder.parentFolder ?: currentFolder
it == "\$ cd /" -> currentFolder = root
it.startsWith("\$ cd") -> currentFolder = getChildFolder(it, currentFolder)
else -> createFolderFile(it, currentFolder)
}
}
return root
}
fun getChildFolder(command: String, currentFolder: Folder): Folder {
val targetFolderName = command.replace("\$ cd ", "")
return currentFolder.folderList.find { it.name == targetFolderName } ?: currentFolder
}
fun createFolderFile(dataInfo: String, currentFolder: Folder) {
when {
dataInfo.startsWith("dir") -> {
val dirname = dataInfo.replace("dir ", "")
val newFolder = Folder(
name = dirname,
folderList = mutableListOf(),
fileList = mutableListOf(),
absolutePath = "${currentFolder.absolutePath}$dirname/",
parentFolder = currentFolder
)
currentFolder.folderList.add(newFolder)
}
else -> {
val fileInfo = dataInfo.split(" ")
currentFolder.fileList.add(DataFile(name = fileInfo[1], size = fileInfo[0].toInt()))
}
}
}
fun sumUpByMaxSize(rootFolder: Folder, maxFolderSize: Int): Int {
val targetFolders = mutableListOf<Folder>()
findFoldersByMaxSize(targetFolders, rootFolder, maxFolderSize)
return targetFolders.sumOf { it.getSize() }
}
fun findFoldersByMaxSize(targetFolder: MutableList<Folder>, currentFolder: Folder, maxFolderSize: Int) {
if (currentFolder.getSize() <= maxFolderSize) {
targetFolder.add(currentFolder)
}
currentFolder.folderList.forEach { findFoldersByMaxSize(targetFolder, it, maxFolderSize) }
}
fun findFoldersByMinSize(targetFolder: MutableList<Folder>, currentFolder: Folder, minFolderSize: Int) {
if (currentFolder.getSize() >= minFolderSize) {
targetFolder.add(currentFolder)
}
currentFolder.folderList.forEach { findFoldersByMinSize(targetFolder, it, minFolderSize) }
}
}
}
fun main() {
val resultPart1 = Day07.getTotalSumSize(Day07.inputFile.readText())
val folderToDelete = Day07.findFolderToDelete(
input = Day07.inputFile.readText(),
totalSpace = 70000000,
freeSpaceNeeded = 30000000
)
println(
"""
resultPart1:
$resultPart1
resultPart2:
${folderToDelete.getSize()}
""".trimIndent()
)
} | 0 | Kotlin | 0 | 0 | c514152e9e2f0047514383fe536f7610a66aff70 | 4,393 | aoc-2022 | MIT License |
src/main/kotlin/aoc2021/day6.kt | sodaplayer | 434,841,315 | false | {"Kotlin": 31068} | package aoc2021
import aoc2021.utils.loadInput
import kotlin.math.roundToInt
fun main() {
val fishes = loadInput("/2021/day6")
.bufferedReader()
.readLines()
.flatMap {
it.split(",")
}
.map(String::toInt)
// Part 1 - Naive solution which works but is slow
val part1 = fishes
.chunked((300.0 / 8).roundToInt())
.parallelStream()
.map { chunk ->
generateSequence(chunk) {
it.flatMap {
if (it == 0) listOf(6, 8)
else listOf(it - 1)
}
}.take(81).last().count()
}
.reduce { a, b -> a + b }
println(part1)
val part2 = fishes
.groupBy { it }
.mapValues { (_, group) -> group.count().toLong() }
.let {
generateSequence(it, ::tick)
}
.take(257)
.last()
.map { it.value }
.sum()
print(part2)
}
fun tick(fish: Map<Int, Long>) =
mapOf(
8 to (fish[0] ?: 0L),
7 to (fish[8] ?: 0L),
6 to (fish[7] ?: 0L) + (fish[0] ?: 0L),
5 to (fish[6] ?: 0L),
4 to (fish[5] ?: 0L),
3 to (fish[4] ?: 0L),
2 to (fish[3] ?: 0L),
1 to (fish[2] ?: 0L),
0 to (fish[1] ?: 0L),
)
| 0 | Kotlin | 0 | 0 | 2d72897e1202ee816aa0e4834690a13f5ce19747 | 1,319 | aoc-kotlin | Apache License 2.0 |
src/main/kotlin/com/hj/leetcode/kotlin/problem1770/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem1770
/**
* LeetCode page: [1770. Maximum Score from Performing Multiplication Operations](https://leetcode.com/problems/maximum-score-from-performing-multiplication-operations/);
*/
class Solution {
/* Complexity:
* Time O(M^2) and Space O(M) where M is the size of multipliers;
*/
fun maximumScore(nums: IntArray, multipliers: IntArray): Int {
val maxScoreDP = getMaxScoreForEachLeftOperand(nums, multipliers)
return maxScoreDP.max()!!
}
private fun getMaxScoreForEachLeftOperand(nums: IntArray, multipliers: IntArray): IntArray {
val totalOperand = multipliers.size
val scoreContainer = createScoreContainer(totalOperand)
updateScoreContainer(scoreContainer, nums, multipliers)
return scoreContainer
}
private fun createScoreContainer(totalOperands: Int): IntArray {
val sizeIncludeZeroOperand = totalOperands + 1
return IntArray(sizeIncludeZeroOperand) { 0 }
}
private fun updateScoreContainer(
scoreContainer: IntArray,
nums: IntArray,
multipliers: IntArray
) {
val initialScore = 0
scoreContainer[0] = initialScore
val totalOperand = multipliers.size
for (operand in 1..totalOperand) {
val multiplier = getMultiplier(operand, multipliers)
updateMaxScoreOfPureLeftOperations(operand, scoreContainer, nums, multiplier)
updateMaxScoreOfCompoundOperations(operand, scoreContainer, nums, multiplier)
updateMaxScoreOfPureRightOperations(operand, scoreContainer, nums, multiplier)
}
}
private fun getMultiplier(operand: Int, multipliers: IntArray) = multipliers[operand - 1]
private fun updateMaxScoreOfPureLeftOperations(
currOperand: Int,
scoreContainer: IntArray,
nums: IntArray,
multiplier: Int
) {
val scoreOfCurrOperation = multiplier * getLeftNumber(currOperand, nums)
val maxScore = scoreContainer[currOperand - 1] + scoreOfCurrOperation
scoreContainer[currOperand] = maxScore
}
private fun getLeftNumber(leftOperand: Int, nums: IntArray) = nums[leftOperand - 1]
private fun updateMaxScoreOfCompoundOperations(
currOperand: Int,
scoreContainer: IntArray,
nums: IntArray,
multiplier: Int
) {
for (leftOperand in currOperand - 1 downTo 1) {
val rightOperand = currOperand - leftOperand
val scoreOfCurrOperationIfIsLeft = multiplier * getLeftNumber(leftOperand, nums)
val maxScoreIfCurrOperationIsLeft = scoreContainer[leftOperand - 1] + scoreOfCurrOperationIfIsLeft
val scoreOfCurrOperationIfIsRight = multiplier * getRightNumber(rightOperand, nums)
val maxScoreIfCurrOperationIsRight = scoreContainer[leftOperand] + scoreOfCurrOperationIfIsRight
val maxScore = maxOf(maxScoreIfCurrOperationIsLeft, maxScoreIfCurrOperationIsRight)
scoreContainer[leftOperand] = maxScore
}
}
private fun getRightNumber(rightOperand: Int, nums: IntArray) = nums[nums.size - rightOperand]
private fun updateMaxScoreOfPureRightOperations(
currOperand: Int,
scoreContainer: IntArray,
nums: IntArray,
multiplier: Int
) {
val scoreOfCurrOperation = multiplier * getRightNumber(currOperand, nums)
val maxScore = scoreContainer[0] + scoreOfCurrOperation
scoreContainer[0] = maxScore
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 3,537 | hj-leetcode-kotlin | Apache License 2.0 |
src/main/kotlin/Fuel.kt | alebedev | 573,733,821 | false | {"Kotlin": 82424} | fun main() = Fuel.solve()
private object Fuel {
fun solve() {
println("${fromSnafu("1=11-2")}")
println("-> ${toSnafu(12345)}")
val nums = readInput()
println("$nums")
val sum = nums.sum()
println("Sum: $sum, SNAFU: ${toSnafu(sum)}")
}
private fun readInput(): List<Long> = generateSequence(::readLine).map { fromSnafu(it) }.toList()
private fun fromSnafu(snafu: String): Long {
val ordinals = mutableListOf<Int>()
for (char in snafu.toCharArray()) {
val num = snafuChars.getOrElse(char) { throw Error("Unexpected char $char") }
if (num < 0) {
ordinals[ordinals.lastIndex] -= 1
ordinals.add(5 + num)
} else {
ordinals.add(num)
}
// println("$char $num $ordinals")
}
var result = 0L
for (ord in ordinals) {
if (result > 0) {
result *= 5
}
result += ord
}
return result
}
private fun toSnafu(snafu: Long): String {
val chars = mutableListOf<Char>()
var next = snafu
while (next > 0) {
val cur = (next % 5)
chars.add(
0,
when (cur) {
0L -> '0'
1L -> '1'
2L -> '2'
3L -> '='
4L -> '-'
else -> throw Error("!!!")
}
)
next /= 5
if (cur > 2) {
next += 1
}
}
return chars.joinToString("")
}
private val snafuChars = buildMap {
put('1', 1)
put('2', 2)
put('0', 0)
put('-', -1)
put('=', -2)
}
} | 0 | Kotlin | 0 | 0 | d6ba46bc414c6a55a1093f46a6f97510df399cd1 | 1,824 | aoc2022 | MIT License |
src/Day02.kt | erwinw | 572,913,172 | false | {"Kotlin": 87621} | @file:Suppress("MagicNumber")
private const val DAY = "02"
private const val PART1_CHECK = 15
private const val PART2_CHECK = 12
private enum class RockPaperScissors(val score: Int) {
ROCK(1),
PAPER(2),
SCISSORS(3),
;
}
private val rock = RockPaperScissors.ROCK
private val paper = RockPaperScissors.PAPER
private val scissors = RockPaperScissors.SCISSORS
const val SCORE_YOU_WIN = 6
const val SCORE_YOU_DRAW = 3
const val SCORE_YOU_LOOSE = 0
private enum class RequiredResult {
SHOULD_WIN,
SHOULD_DRAW,
SHOULD_LOOSE,
}
private val shouldWin = RequiredResult.SHOULD_WIN
private val shouldDraw = RequiredResult.SHOULD_DRAW
private val shouldLoose = RequiredResult.SHOULD_LOOSE
private val themToRPS = mapOf(
'A' to RockPaperScissors.ROCK,
'B' to RockPaperScissors.PAPER,
'C' to RockPaperScissors.SCISSORS,
)
private val usToRPS = mapOf(
'X' to RockPaperScissors.ROCK,
'Y' to RockPaperScissors.PAPER,
'Z' to RockPaperScissors.SCISSORS,
)
private val charToRequiredResult = mapOf(
'X' to shouldLoose,
'Y' to shouldDraw,
'Z' to shouldWin,
)
private val scoreGame: Map<RockPaperScissors, Map<RockPaperScissors, Int>> =
mapOf(
rock to mapOf(
rock to SCORE_YOU_DRAW,
paper to SCORE_YOU_WIN,
scissors to SCORE_YOU_LOOSE,
),
paper to mapOf(
rock to SCORE_YOU_LOOSE,
paper to SCORE_YOU_DRAW,
scissors to SCORE_YOU_WIN,
),
scissors to mapOf(
rock to SCORE_YOU_WIN,
paper to SCORE_YOU_LOOSE,
scissors to SCORE_YOU_DRAW,
),
)
private val calculateMove: Map<RockPaperScissors, Map<RequiredResult, RockPaperScissors>> =
mapOf(
rock to mapOf(
shouldLoose to scissors,
shouldDraw to rock,
shouldWin to paper,
),
paper to mapOf(
shouldLoose to rock,
shouldDraw to paper,
shouldWin to scissors,
),
scissors to mapOf(
shouldLoose to paper,
shouldDraw to scissors,
shouldWin to rock,
),
)
fun main() {
fun part1(input: List<String>) =
input.sumOf {
val them = themToRPS[it[0]]!!
val us = usToRPS[it[2]]!!
us.score + scoreGame[them]!![us]!!
}
fun part2(input: List<String>): Int =
input.sumOf {
val them = themToRPS[it[0]]!!
val required = charToRequiredResult[it[2]]!!
val us = calculateMove[them]!![required]!!
us.score + scoreGame[them]!![us]!!
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day${DAY}_test")
check(part1(testInput).also { println("Part1 test output: $it") } == PART1_CHECK)
check(part2(testInput).also { println("Part2 test output: $it") } == PART2_CHECK)
val input = readInput("Day$DAY")
println("Part1 final output: ${part1(input)}")
println("Part2 final output: ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 57cba37265a3c63dea741c187095eff24d0b5381 | 3,092 | adventofcode2022 | Apache License 2.0 |
src/Day10.kt | cagriyildirimR | 572,811,424 | false | {"Kotlin": 34697} | fun day10Part1(){
val input = readInput("Day10").map { it.split(" ") }
var cycle = 1
val l = listOf(20, 60, 100, 140, 180, 220)
var register = 1
val cs = arrayOf(0,0,0,0,0,0)
for (i in input) {
when(i.first()) {
"noop" -> {
cycle++
checking(cycle, cs, l, register)
}
"addx" -> {
cycle++
checking(cycle, cs, l, register)
register += i.last().toInt()
cycle++
checking(cycle, cs, l, register)
}
}
}
println(cs.toList())
println(cs.toList().sum())
}
fun checking(cycle: Int, cs: Array<Int>, l: List<Int>, register: Int) {
println("cyclec $cycle, register: $register")
if (cycle in l){
cs[l.indexOf(cycle)] = cycle * register
}
}
fun day10Part2(){
val input = readInput("Day10").map { it.split(" ") }
var cycle = 1
var x = 1
val result = Array(241) {"#"}
for (i in input) {
val instruction = i.first()
when(instruction) {
"noop" -> {
result[cycle] = sprite(x, cycle)
cycle++
}
"addx" -> {
result[cycle] = sprite(x, cycle)
cycle++
x += i.last().toInt()
result[cycle] = sprite(x, cycle)
cycle++
}
}
}
for (i in result.indices) {
print(result[i])
if ((i+1) % 40 == 0) println()
}
}
fun sprite(x: Int, c: Int): String {
return if (c % 40 in x-1..x+1) "#" else "."
}
//ERCREPCJ | 0 | Kotlin | 0 | 0 | 343efa0fb8ee76b7b2530269bd986e6171d8bb68 | 1,645 | AoC | Apache License 2.0 |
src/Day10.kt | ZiomaleQ | 573,349,910 | false | {"Kotlin": 49609} | import java.util.*
fun main() {
fun part1(input: List<String>): Int {
val state = mutableListOf(1)
for (line in input) {
val scan = Scanner(line)
val op = scan.next()
when (op) {
"noop" -> state.add(0)
"addx" -> {
state.add(0)
state.add(scan.nextInt())
}
}
}
var sum = 0
for (i in 20..220 step 40) {
sum += i * state.subList(0, i).sum()
}
return sum
}
fun part2(input: List<String>): String {
val state = mutableListOf(1)
for (line in input) {
val scan = Scanner(line)
val op = scan.next()
when (op) {
"noop" -> state.add(0)
"addx" -> {
state.add(0)
state.add(scan.nextInt())
}
}
}
var lines = ""
for (i in 0..220 step 40) {
var display = ""
for (cycle in i..i + 39) {
val valueAt = state.subList(0, cycle + 1).sum()
if (cycle - i == valueAt || cycle - i == valueAt + 1 || cycle - i == valueAt - 1) {
display += "*"
} else {
//For clarity
display += " "
}
}
lines += display + "\n"
}
return lines
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day10_test")
part1(testInput).also { println(it); check(it == 13140) }
val input = readInput("Day10")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | b8811a6a9c03e80224e4655013879ac8a90e69b5 | 1,767 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/days/y2022/day19/Day19.kt | jewell-lgtm | 569,792,185 | false | {"Kotlin": 161272, "Jupyter Notebook": 103410, "TypeScript": 78635, "JavaScript": 123} | package days.y2022.day19
import util.InputReader
import kotlin.math.ceil
typealias PuzzleLine = String
typealias PuzzleInput = List<PuzzleLine>
class Day19(val input: PuzzleInput) {
val bluePrints = input.map { it.toBlueprint() }
fun partOne(): Int {
val initialState = GameState.initial()
val blueprint = bluePrints.first()
return blueprint.bestStateFrom(
mutableMapOf(), GameState(
remainingMinutes = 24,
countOreRobots = 1,
ore = 0,
countClayRobots = 0,
clay = 0,
countObsidianRobots = 0,
obsidian = 0,
countGeodeRobots = 0,
geodes = 0
)
).geodes
}
}
data class GameState(
val remainingMinutes: Int = 0,
val countOreRobots: Int = 0,
val countClayRobots: Int = 0,
val countObsidianRobots: Int = 0,
val countGeodeRobots: Int = 0,
val ore: Int = 0,
val clay: Int = 0,
val obsidian: Int = 0,
val geodes: Int = 0,
) {
companion object {
fun initial() = GameState(
remainingMinutes = 24,
countOreRobots = 1,
)
}
}
sealed class RobotCost
data class OreCost(val ore: Int) : RobotCost()
data class OreClayCost(val ore: Int, val clay: Int) : RobotCost()
data class OreObsidianCost(val ore: Int, val obsidian: Int) : RobotCost()
data class Blueprint(
val id: Int,
val oreRobotCost: OreCost,
val clayRobotCost: OreCost,
val obsidianRobotCost: OreClayCost,
val geodeRobotCost: OreObsidianCost,
)
var hit = 0
var miss = 0
var i = 0
fun Blueprint.bestStateFrom(memo: MutableMap<GameState, GameState>, state: GameState): GameState {
val missBefore = miss
val result = memo.getOrPut(state) {
miss++
val possibleNextStates = state.possibleNextStates(this)
possibleNextStates.maxByOrNull { bestStateFrom(memo, it).geodes } ?: state
}
if (miss > missBefore && i++ % 10 == 0) {
println("Miss ${miss++}")
} else {
hit++
}
return result
}
fun GameState.possibleNextStates(blueprint: Blueprint): Set<GameState> {
if (remainingMinutes == 0) return emptySet()
val result = mutableSetOf<GameState>()
buyClayRobot(blueprint)?.let { result.add(it) }
buyGeodeRobot(blueprint)?.let { result.add(it) }
result.add(doNothing())
return result
}
fun GameState.doNothing(): GameState = copy(
remainingMinutes = 0,
ore = ore + (remainingMinutes * countOreRobots),
clay = clay + (remainingMinutes * countClayRobots),
obsidian = obsidian + (remainingMinutes * countObsidianRobots),
geodes = geodes + (remainingMinutes * countGeodeRobots)
)
fun OreCost.oreTurnsRequired(currentOre: Int, orePerTurn: Int): Int? {
if (orePerTurn == 0) {
if (currentOre > ore) return 0
return null
}
return ((ore - currentOre).toFloat() / orePerTurn.toFloat()).ceilToInt().coerceAtLeast(0)
}
val Blueprint.maxClayCost get() = obsidianRobotCost.clay
fun GameState.buyClayRobot(blueprint: Blueprint): GameState? {
if (blueprint.maxClayCost <= countClayRobots) return null
if (blueprint.maxClayCost <= clay) return null
val oreTurnsRequired =
blueprint.clayRobotCost.oreTurnsRequired(ore, countOreRobots + countClayRobots)
?: return null
if (oreTurnsRequired > (remainingMinutes - 2)) return null
// wait 2 minutes deciding to build the robot (+ 2 ore, - 2 minutes)
// spend 1 minute building the robot (+ 1 ore, - 1 minute)
// land on the next minute, so we can build the robot (+ 1 ore, +1 clay, - 1 minute)
return copy(
remainingMinutes = remainingMinutes - oreTurnsRequired - 2,
countClayRobots = countClayRobots + 1,
ore = ore + (countOreRobots * (oreTurnsRequired + 2)) - blueprint.clayRobotCost.ore,
clay = clay + (countClayRobots * oreTurnsRequired) + 1,
)
}
fun OreObsidianCost.oreTunsRequired(currentOre: Int, orePerTurn: Int): Int? {
if (orePerTurn == 0) {
if (currentOre > ore) return 0
return null
}
return ((ore - currentOre).toFloat() / orePerTurn.toFloat()).ceilToInt().coerceAtLeast(0)
}
fun OreObsidianCost.obsidianTurnsRequired(currentObsidian: Int, obsidianPerTurn: Int): Int? {
if (obsidianPerTurn == 0) {
if (currentObsidian > obsidian) return 0
return null
}
return ((obsidian - currentObsidian).toFloat() / obsidianPerTurn.toFloat()).ceilToInt().coerceAtLeast(0)
}
fun GameState.buyGeodeRobot(blueprint: Blueprint): GameState? {
val oreTurnsRequired =
blueprint.geodeRobotCost.oreTunsRequired(ore, countOreRobots + countClayRobots + countObsidianRobots)
?: return null
val obsidianTurnsRequired =
blueprint.geodeRobotCost.obsidianTurnsRequired(obsidian, countObsidianRobots) ?: return null
val turnsRequired = maxOf(oreTurnsRequired, obsidianTurnsRequired)
if (turnsRequired >= (remainingMinutes - 1)) return null
return copy(
remainingMinutes = remainingMinutes - turnsRequired,
countGeodeRobots = countGeodeRobots + 1,
ore = ore + (countOreRobots * turnsRequired) - blueprint.geodeRobotCost.ore,
clay = clay + (countClayRobots * turnsRequired),
obsidian = obsidian + (countObsidianRobots * turnsRequired) - blueprint.geodeRobotCost.obsidian,
geodes = geodes + (countGeodeRobots * turnsRequired),
)
}
fun Float.ceilToInt() = ceil(this).toInt()
fun Blueprint.maxOreCost() = maxOf(
oreRobotCost.ore, clayRobotCost.ore, obsidianRobotCost.ore, geodeRobotCost.ore
)
fun PuzzleLine.toBlueprint(): Blueprint {
// Blueprint 1: Each ore robot costs 4 ore. Each clay robot costs 2 ore. Each obsidian robot costs 3 ore and 14 clay. Each geode robot costs 2 ore and 7 obsidian.
// Blueprint 2: Each ore robot costs 2 ore. Each clay robot costs 3 ore. Each obsidian robot costs 3 ore and 8 clay. Each geode robot costs 3 ore and 12 obsidian
val regex =
Regex("Blueprint (\\d+): Each ore robot costs (\\d+) ore. Each clay robot costs (\\d+) ore. Each obsidian robot costs (\\d+) ore and (\\d+) clay. Each geode robot costs (\\d+) ore and (\\d+) obsidian.*")
val matchResult = regex.matchEntire(this) ?: error("Invalid blueprint line: $this")
return Blueprint(
id = matchResult.groupValues[1].toInt(),
oreRobotCost = OreCost(matchResult.groupValues[2].toInt()),
clayRobotCost = OreCost(matchResult.groupValues[3].toInt()),
obsidianRobotCost = OreClayCost(matchResult.groupValues[4].toInt(), matchResult.groupValues[5].toInt()),
geodeRobotCost = OreObsidianCost(matchResult.groupValues[6].toInt(), matchResult.groupValues[7].toInt()),
)
}
fun main() {
val year = 2022
val day = 19
val exampleInput: PuzzleInput = InputReader.getExampleLines(year, day)
val puzzleInput: PuzzleInput = InputReader.getPuzzleLines(year, day)
fun partOne(input: PuzzleInput) = Day19(input).partOne()
println("Example 1: ${partOne(exampleInput)}")
}
| 0 | Kotlin | 0 | 0 | b274e43441b4ddb163c509ed14944902c2b011ab | 7,110 | AdventOfCode | Creative Commons Zero v1.0 Universal |
src/main/kotlin/leetcode/Problem2055.kt | fredyw | 28,460,187 | false | {"Java": 1280840, "Rust": 363472, "Kotlin": 148898, "Shell": 604} | package leetcode
/**
* https://leetcode.com/problems/plates-between-candles/
*/
class Problem2055 {
fun platesBetweenCandles(s: String, queries: Array<IntArray>): IntArray {
val answer = IntArray(queries.size)
var startIndex = 0
while (startIndex < s.length && s[startIndex] != '|') {
startIndex++
}
var endIndex = s.length - 1
while (endIndex >= 0 && s[endIndex] != '|') {
endIndex--
}
if (endIndex <= startIndex) {
return answer
}
val prefixSums = IntArray(s.length)
val candles = mutableListOf<Int>()
// Keep track of the previous and next candle index positions for each plate index.
for ((index, value) in s.withIndex()) {
if (value == '*') {
prefixSums[index] = if (index - 1 < 0) 1 else prefixSums[index - 1] + 1
} else {
candles += index
prefixSums[index] = if (index - 1 < 0) 0 else prefixSums[index - 1]
}
}
data class PreviousNextCandle(val previous: Int, val next: Int)
val previousNextCandles = Array(s.length) { PreviousNextCandle(-1, -1) }
var candleIndex = 0
var index = startIndex
while (index <= endIndex) {
if (index != startIndex && s[index] == '|') {
candleIndex++
} else if (s[index] == '*') {
previousNextCandles[index] =
PreviousNextCandle(candles[candleIndex], candles[candleIndex + 1])
}
index++
}
for ((index, query) in queries.withIndex()) {
var start = query[0]
if (s[start] == '*') {
start = if (start < startIndex) {
startIndex
} else if (start > endIndex) {
endIndex
} else {
previousNextCandles[start].next
}
}
var end = query[1]
if (s[end] == '*') {
end = if (end < startIndex) {
startIndex
} else if (end > endIndex) {
endIndex
} else {
previousNextCandles[end].previous
}
}
answer[index] = if (start > end) 0 else prefixSums[end] - prefixSums[start]
}
return answer
}
}
| 0 | Java | 1 | 4 | a59d77c4fd00674426a5f4f7b9b009d9b8321d6d | 2,454 | leetcode | MIT License |
src/ch6Arrays/6.1DutchFlag.kt | codingstoic | 138,465,452 | false | {"Kotlin": 17019} | package ch6Arrays
fun main(args: Array<String>) {
solution1(arrayOf(3, 5, 4, 6, 7, 1, 2), 2).forEach {
print(it)
}
println()
solution2(arrayOf(3, 5, 4, 6, 7, 1, 2), 2).forEach {
print(it)
}
println()
solution3(arrayOf(3, 5, 4, 6, 7, 1, 2), 2).forEach {
print(it)
}
println()
solution4(arrayOf(3, 5, 4, 6, 7, 1, 2), 2).forEach {
print(it)
}
}
// running time O(n), space complexity 0(n)
fun solution1(numbers: Array<Int>, pivotPosition: Int): IntArray {
val pivot = numbers[pivotPosition]
val smallerElements = IntArray(numbers.size)
var smallerIndex = 0
val largerElements = IntArray(numbers.size)
var largerIndex = 0
val finalArray = IntArray(numbers.size)
var finalIndex = 0
numbers.forEach {
if (it < pivot) {
smallerElements[smallerIndex++] = it
}
if (it > pivot) {
largerElements[largerIndex++] = it
}
}
smallerElements.forEach {
if (it != 0) {
finalArray[finalIndex++] = it
}
}
finalArray[finalIndex++] = pivot
largerElements.forEach {
if (it != 0) {
finalArray[finalIndex++] = it
}
}
return finalArray
}
// running time O(n2), space complexity 0(1)
fun solution2(numbers: Array<Int>, pivotPosition: Int): Array<Int> {
val pivot = numbers[pivotPosition]
// first pass move all smaller elements to beginning of the array
for (i in 0..numbers.size) {
for (j in i + 1 until numbers.size) {
if (numbers[j] < pivot) {
numbers.swap(i, j)
}
}
}
//second pass move all bigger elements to the right
for (i in numbers.size-1 downTo 0) {
for (j in i - 1 downTo 0) {
if (numbers[j] > pivot) {
numbers.swap(i, j)
}
}
}
return numbers
}
// complexity running time O(n) and space complexity O(n)
fun solution3(numbers: Array<Int>, pivotPosition: Int): Array<Int> {
var leftIndex = 0
var rightIndex = numbers.size - 1
val pivot = numbers[pivotPosition]
for(i in 0 until numbers.size){
if(numbers[i] < pivot){
numbers.swap(leftIndex++, i)
}
}
for(i in numbers.size-1 downTo 0){
if(numbers[i] > pivot){
numbers.swap(rightIndex--, i)
}
}
return numbers
}
/*
The idea here is that we mark regions, smaller than pivot on the left,
then the pivot, then unclassified elements left from the result of previous swapping
then bigger elements
*/
fun solution4(numbers: Array<Int>, pivotPosition: Int): Array<Int> {
var smaller = 0
var equal = 0
val pivot = numbers[pivotPosition]
var bigger = numbers.size - 1
// while we have unclassified elements until all are classified iterate
while(equal < bigger){
when {
numbers[equal] < pivot -> numbers.swap(equal++, smaller++)
numbers[equal] > pivot -> numbers.swap(bigger--, equal)
numbers[equal] == pivot -> equal++
}
}
return numbers
}
| 0 | Kotlin | 0 | 2 | fdec1aba315405e140f605aa00a9409746cb518a | 3,154 | elements-of-programming-interviews-solutions | MIT License |
y2021/src/main/kotlin/adventofcode/y2021/Day11.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2021
import adventofcode.io.AdventSolution
import adventofcode.util.vector.Vec2
import adventofcode.util.vector.mooreNeighbors
object Day11 : AdventSolution(2021, 11, "Dumbo Octopus") {
override fun solvePartOne(input: String) =
generateSequence(parseInput(input), Grid::step).drop(1).take(100).sumOf(Grid::flashed)
override fun solvePartTwo(input: String) =
generateSequence(parseInput(input), Grid::step).map(Grid::flashed).indexOfFirst(100::equals)
private fun parseInput(input: String) = input.lines()
.flatMapIndexed { y, line ->
line.mapIndexed { x, ch -> Vec2(x, y) to Character.getNumericValue(ch) }
}
.toMap().let(::Grid)
private class Grid(val octopuses: Map<Vec2, Int>) {
fun flashed(): Int = octopuses.count { it.value == 0 }
fun step(): Grid = generateSequence(charge(), Grid::flash).first(Grid::done)
private fun charge() = Grid(octopuses.mapValues { it.value + 1 })
private fun flash() = Grid(octopuses.mapValues { (pos, v) ->
if (v in 1..9) v + pos.mooreNeighbors().count { (octopuses[it] ?: 0) > 9 }
else 0
})
private fun done() = octopuses.none { it.value > 9 }
}
}
| 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 1,260 | advent-of-code | MIT License |
src/main/kotlin/Day6.kt | maldoinc | 726,264,110 | false | {"Kotlin": 14472} | import kotlin.io.path.Path
import kotlin.io.path.readLines
import kotlin.math.ceil
import kotlin.math.floor
import kotlin.math.sqrt
fun waysToWin(time: Long, distance: Long): Long {
val x1 = 0.5 * (time - sqrt(time * time - 4.0 * distance))
val x2 = 0.5 * (time + sqrt(time * time - 4.0 * distance))
return (ceil(x2) - floor(x1)).toLong() - 1
}
fun main(args: Array<String>) {
val lines = Path(args[0])
.readLines()
.map { it.split(":").last() }
.map { it.trim() }
val nums = lines
.map { it.split(" ")
.filter(String::isNotEmpty)
.map(String::toLong) }
.toList()
val part1 =
nums
.first()
.zip(nums.last())
.map { waysToWin(time = it.first, distance = it.second) }
.fold(1L) { acc, i -> acc * i }
val part2 = lines
.map { it.replace(" ", "") }
.map { it.toLong() }
.toList()
println(part1)
println(waysToWin(part2.first(), part2.last()))
}
| 0 | Kotlin | 0 | 1 | 47a1ab8185eb6cf16bc012f20af28a4a3fef2f47 | 1,028 | advent-2023 | MIT License |
src/main/kotlin/com/hj/leetcode/kotlin/problem838/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem838
/**
* LeetCode page: [838. Push Dominoes](https://leetcode.com/problems/push-dominoes/);
*/
class Solution {
/* Complexity:
* Time O(N) and Space O(N) where N is the length of dominoes;
*/
fun pushDominoes(dominoes: String): String {
val pushed = StringBuilder(dominoes)
var leftBound = 0
loop@ for (rightBound in 1..dominoes.lastIndex) {
val fallDirection = getFallDirection(dominoes, leftBound, rightBound)
val range = leftBound..rightBound
when (fallDirection) {
FallDirection.Left -> fallToLeft(pushed, range)
FallDirection.Right -> fallToRight(pushed, range)
FallDirection.Inward -> fallInward(pushed, range)
FallDirection.Unchanged -> {}
FallDirection.Unknown -> continue@loop
}
leftBound = rightBound
}
return pushed.toString()
}
private fun getFallDirection(dominoes: String, leftBound: Int, rightBound: Int): FallDirection {
return when (dominoes[leftBound]) {
'.' -> when (dominoes[rightBound]) {
'.' -> FallDirection.Unknown
'L' -> FallDirection.Left
'R' -> FallDirection.Unchanged
else -> throw IllegalStateException()
}
'L' -> FallDirection.Unchanged
'R' -> when (dominoes[rightBound]) {
'.' -> if (rightBound == dominoes.lastIndex) FallDirection.Right else FallDirection.Unknown
'L' -> FallDirection.Inward
'R' -> FallDirection.Right
else -> throw IllegalStateException()
}
else -> throw IllegalStateException()
}
}
private enum class FallDirection { Left, Right, Inward, Unchanged, Unknown }
private fun fallToLeft(dominoes: StringBuilder, range: IntRange) {
fall(dominoes, range, 'L')
}
private fun fall(dominoes: StringBuilder, range: IntRange, directionSymbol: Char) {
for (index in range) {
dominoes[index] = directionSymbol
}
}
private fun fallToRight(dominoes: StringBuilder, range: IntRange) {
fall(dominoes, range, 'R')
}
private fun fallInward(dominoes: StringBuilder, range: IntRange) {
val width = range.last - range.first + 1
val halfWidth = width shr 1
val rangeToRight = range.first until range.first + halfWidth
fallToRight(dominoes, rangeToRight)
val rangeToLeft = range.last - halfWidth + 1..range.last
fallToLeft(dominoes, rangeToLeft)
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 2,681 | hj-leetcode-kotlin | Apache License 2.0 |
src/Day03.kt | othimar | 573,607,284 | false | {"Kotlin": 14557} | fun main(){
fun part1(input:List<String>):Int{
var priority = 0
for(bag in input){
val compSize = bag.length/2
val firstComp = bag.filterIndexed { index, _ -> index < compSize }
val secondComp = bag.filterIndexed { index, _ -> index >= compSize}
for (c in firstComp){
if(secondComp.contains(c, false)) {
priority += if (c.toString() == c.lowercase()) {
c.code - 96
} else {
c.code - 64 +26
}
break
}
}
}
return priority
}
fun part2(input:List<String>):Int{
var priority = 0
val groups = input.windowed(3, 3)
for(g in groups){
val badge = g.first().first { g[1].contains(it) and g[2].contains(it) }
priority += if (badge.toString() == badge.lowercase()) {
badge.code - 96
} else {
badge.code - 64 +26
}
}
return priority
}
check(part1(readInput("Day03_test")) == 157)
check(part2(readInput("Day03_test")) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | ff62a00123fe817773ff6248d34f606947ffad6d | 1,304 | advent-of-code-2022 | Apache License 2.0 |
2016/src/main/kotlin/com/koenv/adventofcode/Day11.kt | koesie10 | 47,333,954 | false | null | package com.koenv.adventofcode
import java.util.*
import java.util.regex.Pattern
/**
* This one is quite slow, probably due to a lot of allocations in getAdjacentStates, which allocates
* a new list for every possible state
*/
object Day11 {
fun getRequiredSteps(input: String): Int {
val types = hashSetOf<String>()
val floors = input.lines()
.filter(String::isNotBlank)
.mapIndexed { i, line ->
val lineMatcher = linePattern.matcher(line)
if (!lineMatcher.find()) {
throw IllegalArgumentException("Invalid input: `$line`")
}
if (lineMatcher.group(2) == "nothing relevant") {
return@mapIndexed listOf<FloorItem>()
}
lineMatcher.group(2).split(",").map {
val matcher = itemPattern.matcher(it.trim())
if (!matcher.find()) {
throw IllegalArgumentException("Invalid item: `$it`")
}
val type = matcher.group(2)
types.add(type)
FloorItem(i, matcher.group(4), type)
}
}
.flatten()
val pairs = arrayListOf<Pair<Int, Int>>()
floors.map { item ->
// find the beloning microchip
if (item.device == "generator") {
val microchip = floors.find {
it.element == item.element && it.device == "microchip"
}!!
pairs.add(item.floor to microchip.floor)
}
}
val startState = State(null, 0, pairs)
return findRequiredStepsBfs(startState)
}
fun findRequiredStepsBfs(startState: State): Int {
val seenStates = hashSetOf<Pair<Int, List<Pair<Int, Int>>>>()
seenStates.add(startState.elevator to startState.pairs)
var currentState = startState
val moves: Queue<State> = LinkedList<State>()
moves.add(currentState)
while (moves.isNotEmpty()) {
currentState = moves.poll()
if (isFinalMove(currentState)) {
return currentState.depth
} else {
// add all states to possible moves
getAdjacentStates(currentState, seenStates).forEach {
moves.offer(it)
seenStates.add(it.elevator to it.pairs)
}
}
}
throw IllegalStateException("No final move found")
}
private fun printTree(state: State) {
state.parent?.let { printTree(it) }
state.print()
}
private fun getAdjacentStates(currentState: State, seenStates: HashSet<Pair<Int, List<Pair<Int, Int>>>>): List<State> {
val possibleMoves = arrayListOf<State>()
currentState.pairs.forEach { pair ->
val newPairs = currentState.pairs.removeOne(pair)
// this is quite ugly, TODO: Clean it up
if (pair.first == currentState.elevator) {
possibleMoves.add(State(currentState, currentState.elevator + 1, newPairs + (pair.first + 1 to pair.second), "1"))
possibleMoves.add(State(currentState, currentState.elevator - 1, newPairs + (pair.first - 1 to pair.second), "2"))
newPairs.forEach { other ->
if (other.first == currentState.elevator) {
val newestPairs = newPairs.removeOne(other)
possibleMoves.add(State(currentState, currentState.elevator + 1, newestPairs + (pair.first + 1 to pair.second) + (other.first + 1 to other.second), "3"))
possibleMoves.add(State(currentState, currentState.elevator - 1, newestPairs + (pair.first - 1 to pair.second) + (other.first - 1 to other.second), "4"))
}
if (other.second == currentState.elevator) {
val newestPairs = newPairs.removeOne(other)
possibleMoves.add(State(currentState, currentState.elevator + 1, newestPairs + (pair.first + 1 to pair.second) + (other.first to other.second + 1), "5"))
possibleMoves.add(State(currentState, currentState.elevator - 1, newestPairs + (pair.first - 1 to pair.second) + (other.first to other.second - 1), "6"))
}
}
if (pair.second == currentState.elevator) {
possibleMoves.add(State(currentState, currentState.elevator + 1, newPairs + (pair.first + 1 to pair.second + 1), "7"))
possibleMoves.add(State(currentState, currentState.elevator - 1, newPairs + (pair.first - 1 to pair.second - 1), "8"))
}
}
if (pair.second == currentState.elevator) {
possibleMoves.add(State(currentState, currentState.elevator + 1, newPairs + (pair.first to pair.second + 1), "8"))
possibleMoves.add(State(currentState, currentState.elevator - 1, newPairs + (pair.first to pair.second - 1), "9"))
newPairs.forEach { other ->
if (other.first == currentState.elevator) {
val newestPairs = newPairs.removeOne(other)
possibleMoves.add(State(currentState, currentState.elevator + 1, newestPairs + (pair.first to pair.second + 1) + (other.first + 1 to other.second), "10"))
possibleMoves.add(State(currentState, currentState.elevator - 1, newestPairs + (pair.first to pair.second - 1) + (other.first - 1 to other.second), "11"))
}
if (other.second == currentState.elevator) {
val newestPairs = newPairs.removeOne(other)
possibleMoves.add(State(currentState, currentState.elevator + 1, newestPairs + (pair.first to pair.second + 1) + (other.first to other.second + 1), "12"))
possibleMoves.add(State(currentState, currentState.elevator - 1, newestPairs + (pair.first to pair.second - 1) + (other.first to other.second - 1), "13"))
}
}
}
}
return possibleMoves.filter { isValid(it) }.filter { !seenStates.contains(it.elevator to it.pairs) }
}
fun isFinalMove(state: State): Boolean {
return state.pairs.all { it.first == 3 && it.second == 3 } // fourth floor
}
fun isValid(state: State): Boolean {
if (state.elevator < 0 || state.elevator > 3) {
return false
}
val generators = state.pairs.mapIndexed { i, pair -> pair.first }.toSet()
return state.pairs.all {
it.first >= 0 && it.first <= 3 && it.second >= 0 && it.second <= 3 &&
(it.first == it.second || !generators.contains(it.second))
}
}
val linePattern: Pattern = Pattern.compile("The ([a-z]*) floor contains (.*).")
val itemPattern: Pattern = Pattern.compile("(and )?a ([a-z]*)(-compatible)? ([a-z]*)")
data class State(
val parent: State?,
val elevator: Int,
/**
* The first item in the pair is the generator, the second is the microchip
*/
val pairs: List<Pair<Int, Int>>,
var payload: String? = null
) {
val depth: Int
get() {
var currentParent = parent
var i = 0
while (currentParent != null) {
i++
currentParent = currentParent.parent
}
return i
}
fun print() {
println("Depth = $depth, Valid = ${isValid(this)}, Final = ${isFinalMove(this)}, Payload = $payload")
println("=".repeat(7 + pairs.size * 6))
for (i in 0..3) {
val floor = 3 - i
print("F$floor = ")
if (elevator == floor) {
print("E ")
} else {
print(". ")
}
pairs.forEachIndexed { pairIndex, pair ->
if (pair.first == floor) {
print((pairIndex + 'A'.toInt()).toChar())
print("G ")
} else {
print(". ")
}
if (pair.second == floor) {
print((pairIndex + 'A'.toInt()).toChar())
print("M ")
} else {
print(". ")
}
}
println()
}
println()
}
}
data class FloorItem(
val floor: Int,
val device: String,
val element: String
)
fun <T> Iterable<T>.removeOne(element: T): List<T> {
var found = false
return filter {
if (it == element) {
if (found) {
return@filter true
}
found = true
return@filter false
}
true
}
}
} | 0 | Kotlin | 0 | 0 | 29f3d426cfceaa131371df09785fa6598405a55f | 9,305 | AdventOfCode-Solutions-Kotlin | MIT License |
day08/src/main/kotlin/Day08.kt | bzabor | 160,240,195 | false | null | class Day08(private val input: List<String>) {
private val regex = Regex("""\D+""")
private var numList: MutableList<Int> = regex.split(input[0]).map { it.toInt() }.toMutableList()
private var sum = 0
fun part1(): Int {
process1()
return sum
}
private fun process1() {
if (numList.isNotEmpty()) {
// header info
val childCount = numList[0]
val metaDataCount = numList[1]
numList = numList.drop(2).toMutableList()
for (child in 0 until childCount) {
process1()
}
sum += numList.take(metaDataCount).sum()
numList = numList.drop(metaDataCount).toMutableList()
}
}
fun part2(): Int {
sum = 0
numList = regex.split(input[0]).map { it.toInt() }.toMutableList()
sum = process2()
return sum
}
private fun process2(): Int {
// println("NUMLIST: $numList")
var sum2 = 0
if (numList.isNotEmpty()) {
// header info
val childCount = numList[0]
val metaDataCount = numList[1]
// println("childCountL $childCount metadatacount: $metaDataCount")
numList = numList.drop(2).toMutableList()
val childSumList = mutableListOf(0)
for (child in 1..childCount) {
// println("Adding child $child to childSumList")
childSumList.add(child, process2())
}
// println("ChildsumList is: ${childSumList}")
val metaDataList = numList.take(metaDataCount)
// println("metadataList: $metaDataList")
if (childCount == 0) {
val childCountZeroSum = numList.take(metaDataCount).sum()
// println("Adding $childCountZeroSum to $sum2")
sum2 += childCountZeroSum
// println("sum2 now $sum2")
} else {
for (metaData in metaDataList) {
// println("looking for entry $metaData in childSumList $childSumList")
val foundVal = childSumList.getOrElse(metaData) { 0 }
// println("Using value of $foundVal")
sum2 += foundVal
}
}
numList = numList.drop(metaDataCount).toMutableList()
}
// println("SUM2: $sum2")
return sum2
}
class Node(val childCount: Int, val metaData: List<Int>) {
var children: MutableList<Node> = mutableListOf()
override fun toString(): String {
return "${childCount}:${children.size}:$metaData"
}
}
}
| 0 | Kotlin | 0 | 0 | 14382957d43a250886e264a01dd199c5b3e60edb | 2,689 | AdventOfCode2018 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/PalindromePartitioning.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
/**
* 131. Palindrome Partitioning
* @see <a href="https://leetcode.com/problems/palindrome-partitioning/">Source</a>
*/
fun interface PalindromePartitioning {
operator fun invoke(s: String): List<List<String>>
}
/**
* Approach 1: Backtracking
*/
class PPBacktracking : PalindromePartitioning {
override operator fun invoke(s: String): List<List<String>> {
val result: MutableList<List<String>> = ArrayList()
dfs(0, result, ArrayList(), s)
return result
}
fun dfs(start: Int, result: MutableList<List<String>>, currentList: MutableList<String>, s: String) {
if (start >= s.length) result.add(ArrayList(currentList))
for (end in start until s.length) {
if (isPalindrome(s, start, end)) {
// add current substring in the currentList
currentList.add(s.substring(start, end + 1))
dfs(end + 1, result, currentList, s)
// backtrack and remove the current substring from currentList
currentList.removeAt(currentList.size - 1)
}
}
}
private fun isPalindrome(s: String, low: Int, high: Int): Boolean {
var l = low
var h = high
while (l < h) {
if (s[l++] != s[h--]) {
return false
}
}
return true
}
}
/**
* Approach 2: Backtracking with Dynamic Programming
*/
class PPBacktrackingDP : PalindromePartitioning {
override operator fun invoke(s: String): List<List<String>> {
val len: Int = s.length
val dp = Array(len) { BooleanArray(len) }
val result: MutableList<List<String>> = ArrayList()
dfs(result, s, 0, ArrayList(), dp)
return result
}
fun dfs(
result: MutableList<List<String>>,
s: String,
start: Int,
currentList: MutableList<String>,
dp: Array<BooleanArray>,
) {
if (start >= s.length) result.add(ArrayList(currentList))
for (end in start until s.length) {
if (s[start] == s[end] && (end - start <= 2 || dp[start + 1][end - 1])) {
dp[start][end] = true
currentList.add(s.substring(start, end + 1))
dfs(result, s, end + 1, currentList, dp)
currentList.removeAt(currentList.size - 1)
}
}
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 3,014 | kotlab | Apache License 2.0 |
year2020/day18/expression/src/main/kotlin/com/curtislb/adventofcode/year2020/day18/expression/evaluate.kt | curtislb | 226,797,689 | false | {"Kotlin": 2146738} | package com.curtislb.adventofcode.year2020.day18.expression
import com.curtislb.adventofcode.common.number.productOf
/**
* TODO
*/
fun evaluate(expression: String): Long {
val results = mutableListOf<Long>()
val operators = mutableListOf('(')
for (token in expression) {
when (token) {
in '0'..'9' -> {
val number = token.digitToInt().toLong()
val lastOperator = operators.removeLast()
if (lastOperator == '(') {
results.add(number)
} else {
val lastResult = results.last()
val newResult = applyOperation(lastOperator, lastResult, number)
results[results.lastIndex] = newResult
}
}
'+', '*', '(' -> operators.add(token)
')' -> {
val lastOperator = operators.removeLast()
if (lastOperator != '(') {
val lastResult = results.removeLast()
val prevResult = results.last()
val newResult = applyOperation(lastOperator, lastResult, prevResult)
results[results.lastIndex] = newResult
}
}
}
}
return results.last()
}
/**
* TODO
*/
fun evaluateAdvanced(expression: String): Long {
var simplifiedExpression = expression
while (simplifiedExpression.contains('(')) {
simplifiedExpression = PAREN_EXPR_REGEX.replace(simplifiedExpression) { matchResult ->
val matchValue = matchResult.value
evaluateAdvanced(matchValue.substring(1 until matchValue.lastIndex)).toString()
}
}
return if (simplifiedExpression.contains('*')) {
simplifiedExpression.split('*').productOf { evaluateAdvanced(it) }
} else {
simplifiedExpression.split('+').sumOf { it.trim().toLong() }
}
}
private val PAREN_EXPR_REGEX = Regex("""\([^()]+\)""")
/**
* TODO
*/
private fun applyOperation(operator: Char, number1: Long, number2: Long): Long = when (operator) {
'+' -> number1 + number2
'*' -> number1 * number2
else -> throw IllegalArgumentException("Invalid operator: $operator")
}
| 0 | Kotlin | 1 | 1 | 6b64c9eb181fab97bc518ac78e14cd586d64499e | 2,231 | AdventOfCode | MIT License |
src/main/kotlin/day13/Departures.kt | lukasz-marek | 317,632,409 | false | {"Kotlin": 172913} | package day13
data class Bus(val id: Long)
fun Bus.departures(startingPoint: Long = 0): Sequence<Long> {
val multiplier = startingPoint / id
val seed = multiplier * id
return generateSequence(seed) { it + id }
}
data class Passenger(val arrivesAt: Long)
fun Bus.earliestDepartureFor(passenger: Passenger): Long =
departures(passenger.arrivesAt).first { it >= passenger.arrivesAt }
data class DepartureConstraint(val bus: Bus, val offset: Long)
fun DepartureConstraint.check(departure: Long): Boolean = (offset + departure) % bus.id == 0L
interface SequenceFinder {
fun find(buses: List<DepartureConstraint>): Long
}
class SequenceFinderImpl : SequenceFinder {
override fun find(buses: List<DepartureConstraint>): Long {
var sequenceStarter = Passenger(1)
var resultFound: Boolean
do {
resultFound = true
var lastValid = sequenceStarter.arrivesAt
inner@ for (bus in buses) {
val sequenceElement = bus.bus.earliestDepartureFor(sequenceStarter)
if (sequenceElement - sequenceStarter.arrivesAt != bus.offset) {
resultFound = false
val nextTimestamp = if (lastValid == sequenceStarter.arrivesAt) lastValid + 1 else lastValid
sequenceStarter = Passenger(nextTimestamp)
break@inner
}
lastValid = sequenceElement
}
} while (!resultFound)
return sequenceStarter.arrivesAt
}
}
fun Bus.departuresWithinRange(startExclusive: Long, endInclusive: Long): Sequence<Long> {
val actualStart = (startExclusive / id) * id
return generateSequence(actualStart) { it + id }.dropWhile { it < startExclusive }.takeWhile { it <= endInclusive }
}
class BacktrackingSequenceFinder : SequenceFinder {
override fun find(buses: List<DepartureConstraint>): Long {
val sortedByPeriod = buses.sortedByDescending { it.bus.id }
return searchForSequence(sortedByPeriod)
}
private fun searchForSequence(remainingConstraints: List<DepartureConstraint>): Long {
val constraintWithGreatestPeriod = remainingConstraints.first()
var timestampsSequence = constraintWithGreatestPeriod.bus.departuresWithinRange(1, Long.MAX_VALUE)
.map { it - constraintWithGreatestPeriod.offset }
for (constraint in remainingConstraints.drop(1)) {
timestampsSequence = timestampsSequence.filter { (it + constraint.offset) % constraint.bus.id == 0L }
}
return timestampsSequence.first()
}
} | 0 | Kotlin | 0 | 0 | a16e95841e9b8ff9156b54e74ace9ccf33e6f2a6 | 2,602 | aoc2020 | MIT License |
src/main/kotlin/Day12.kt | SimonMarquis | 434,880,335 | false | {"Kotlin": 38178} | class Day12(raw: List<String>) {
companion object {
val START = Cave("start")
val END = Cave("end")
}
private val input = raw.toGraph()
fun part1(): Int = input.paths(allowTwoSmalls = false).size
fun part2(): Int = input.paths(allowTwoSmalls = true).size
@JvmInline
value class Cave(private val name: String) {
private val isSmall: Boolean get() = name.all { it.isLowerCase() }
private val isBig: Boolean get() = name.all { it.isUpperCase() }
private fun List<Cave>.hasLessThanTwoSmalls() = filter { it.isSmall }.let { smalls -> smalls.none { s -> smalls.count { it == s } > 1 } }
fun isAllowedIn(path: List<Cave>, allowTwoSmalls: Boolean = false): Boolean = when {
this == START -> false
this.isBig -> true
this.isSmall -> this !in path || allowTwoSmalls && path.hasLessThanTwoSmalls()
else -> TODO()
}
}
private fun List<Cave>.isComplete() = last() == END
private fun List<String>.toGraph(): Map<Cave, Set<Cave>> = buildMap {
this@toGraph.forEach { line ->
val (src, dst) = line.split("-").map(::Cave)
put(src, this[src].orEmpty() + dst)
put(dst, this[dst].orEmpty() + src)
}
}
private fun Map<Cave, Set<Cave>>.paths(allowTwoSmalls: Boolean): List<List<Cave>> {
val paths = mutableListOf<List<Cave>>()
val acc = mutableListOf(listOf(START))
while (acc.isNotEmpty()) {
val path = acc.removeLast()
val reachableCaves = this[path.last()]?.filter { it.isAllowedIn(path, allowTwoSmalls) }.orEmpty()
val newPaths = reachableCaves.map { path + it }
val (completePaths, incompletePaths) = newPaths.partition { it.isComplete() }
acc += incompletePaths
paths += completePaths
}
return paths
}
} | 0 | Kotlin | 0 | 0 | 8fd1d7aa27f92ba352e057721af8bbb58b8a40ea | 1,917 | advent-of-code-2021 | Apache License 2.0 |
src/day16/Day16.kt | crmitchelmore | 576,065,911 | false | {"Kotlin": 115199} | package day16
import helpers.ReadFile
import java.lang.Integer.min
class Day16 {
class Node {
val name: String
var isOn = false
val rate: Int
val connections: MutableList<Node> = mutableListOf()
val shortestDistanceToNode: MutableMap<String, Int> = mutableMapOf()
val conStrings: List<String>
var best: MutableMap<Pair<Int, Set<String>>,Pair<List<String>,Int>> = mutableMapOf()
constructor(name: String, rate: Int, conStrings: List<String>) {
this.name = name
this.rate = rate
this.conStrings = conStrings
}
override fun toString(): String {
return "$name ($rate) -> ${connections.map { it.name }}"
}
}
val lines = ReadFile.named("src/day16/input.txt")
val tlines = listOf(
"Valve AA has flow rate=0; tunnels lead to valves DD, II, BB",
"Valve BB has flow rate=13; tunnels lead to valves CC, AA",
"Valve CC has flow rate=2; tunnels lead to valves DD, BB",
"Valve DD has flow rate=20; tunnels lead to valves CC, AA, EE",
"Valve EE has flow rate=3; tunnels lead to valves FF, DD",
"Valve FF has flow rate=0; tunnels lead to valves EE, GG",
"Valve GG has flow rate=0; tunnels lead to valves FF, HH",
"Valve HH has flow rate=22; tunnel leads to valve GG",
"Valve II has flow rate=0; tunnels lead to valves AA, JJ",
"Valve JJ has flow rate=21; tunnel leads to valve II",
)
var validNodesCount = 0
var validNodeNames = setOf<String>()
val nodes = mutableMapOf<String, Node>()
fun findBestDistance(baseNode: Node, node: Node, depth: Int, visited: Set<String>) {
val newVisited = visited + node.name
if (baseNode.conStrings.contains(node.name) && node.rate > 0) {
val currentBest = baseNode.shortestDistanceToNode[node.name]
if (currentBest == null || currentBest > depth) {
baseNode.shortestDistanceToNode[node.name] = depth
}
}
// If all the potential connections have already got a lower distance
var end = true
for (con in node.connections) {
if (baseNode.shortestDistanceToNode[con.name] == null || baseNode.shortestDistanceToNode[con.name]!! > depth) {
end = false
break
}
}
if (end) {
return
}
for (con in node.connections) {
if (newVisited.contains(con.name)) {
continue
}
if (con.rate > 0) {
val currentBest = baseNode.shortestDistanceToNode[con.name]
if (currentBest == null || currentBest > depth) {
baseNode.shortestDistanceToNode[con.name] = depth + 1
}
}
findBestDistance(baseNode, con, depth + 1, newVisited)
}
}
fun fp(remainingTime: Int, node: Node, currentPressure: Int, totalPressure: Int, path: List<String>) : Pair<Int, List<String>> {
var options = validNodeNames.toMutableSet()
options.removeAll(path)
if (options.isEmpty()) {
return Pair(totalPressure + remainingTime * currentPressure, path)
}
var results = mutableListOf<Pair<Int, List<String>>>()
for (option in options) {
val distance = node.shortestDistanceToNode[option]!!
val target = nodes[option]!!
if (remainingTime - distance >= 0) {
results.add(fp(
remainingTime - distance,
target,
currentPressure + target.rate,
totalPressure + currentPressure * distance,
path + option
))
} else {
results.add(Pair(totalPressure + currentPressure * remainingTime, path))
}
}
return results.maxBy { it.first }!!
}
fun singleHelper(options: Set<String>, active: Node, other: Node, otherActiveIn: Int, remainingTime: Int, totalPressure: Int, pathz: Pair<List<String>, List<String>>, isA: Boolean): List<Pair<Int, Pair<List<String>,List<String>>>> {
var results = mutableListOf<Pair<Int, Pair<List<String>,List<String>>>>()
for (option in options) {
val distance = active.shortestDistanceToNode[option]!!
var nextJump = distance
if (otherActiveIn < distance) {
nextJump = otherActiveIn
}
val target = nodes[option]!!
if (remainingTime - distance >= 0) {
// Add all of the actives travel distance to total now
results.add(fp2(
remainingTime - nextJump,
target,
other,
distance - nextJump,
otherActiveIn - nextJump,
totalPressure + (remainingTime - distance) * target.rate,
if (isA) Pair(pathz.first + option, pathz.second) else Pair(pathz.first, pathz.second + option)
))
}
}
return results
}
fun fp2(remainingTime: Int, a: Node, b: Node, aActiveIn: Int, bActiveIn: Int, totalPressure: Int, pathz: Pair<List<String>, List<String>>) : Pair<Int, Pair<List<String>, List<String>>> {
var options = validNodeNames.toMutableSet()
options.removeAll((pathz.first + pathz.second).toSet())
if (options.isEmpty() || remainingTime <= 0) {
return Pair(totalPressure, pathz)
}
// If active, then do the below
// The next step is the lowest of other active and distance
var results = mutableListOf<Pair<Int, Pair<List<String>,List<String>>>>()
if (aActiveIn > 0 && bActiveIn > 0) {
println("Ooops")
} else if (aActiveIn == 0 && bActiveIn > 0) {
results.addAll(singleHelper(options, a, b, bActiveIn, remainingTime, totalPressure, pathz, true))
} else if (bActiveIn == 0 && aActiveIn > 0) {
results.addAll(singleHelper(options, b, a, aActiveIn, remainingTime, totalPressure, pathz, false))
} else if (aActiveIn == 0 && bActiveIn == 0) {
for (optionA in options) {
for (optionB in options) {
if (optionA == optionB) {
continue
}
val distanceA = a.shortestDistanceToNode[optionA]!!
val distanceB = b.shortestDistanceToNode[optionB]!!
val nextJump = min(distanceA, distanceB)
val targetA = nodes[optionA]!!
val targetB = nodes[optionB]!!
if (remainingTime - nextJump >= 0) {
// ADD ALL ADDITIONAL PRESSURE HERE
var newTotalPressure = totalPressure
if (remainingTime - distanceA >= 0) {
newTotalPressure += (remainingTime - distanceA) * targetA.rate
}
if (remainingTime - distanceB >= 0) {
newTotalPressure += (remainingTime - distanceB) * targetB.rate
}
results.add(fp2(
remainingTime - nextJump,
targetA,
targetB,
distanceA - nextJump,
distanceB - nextJump,
newTotalPressure,
Pair(pathz.first + optionA, pathz.second + optionB)
))
}
}
}
} else {
println("Ooops")
}
if (results.isEmpty()) {
return Pair(totalPressure, pathz)
}
return results.maxBy { it.first }!!
}
fun result1() {
for (line in lines) {
val name = line.substring(6, 8)
val bits = line.drop(23).split(";")
val rate = bits[0].toInt()
val chars = if (bits[1].contains("tunnels")) 24 else 23
val constring = bits[1].drop(chars).split(", ")
val n = Node(name, rate, constring)
nodes[name] = n
}
for (node in nodes.values) {
for (con in node.conStrings) {
node.connections.add(nodes[con]!!)
}
}
validNodeNames = nodes.values.filter { it.rate > 0 }.map { it.name }.toSet()
validNodesCount = validNodeNames.count()
for (node in nodes.values) {
if (node.name == "AA" || node.rate > 0) {
for (con in node.connections) {
findBestDistance(node, con, 1, setOf(node.name))
}
}
}
nodes.values.filter { it.rate > 0 || it.name == "AA" }.forEach() {
for (k in it.shortestDistanceToNode.keys) {
// Travel time + turn on time
it.shortestDistanceToNode[k] = it.shortestDistanceToNode[k]!! + 1
}
}
println(fp2(26, nodes["AA"]!!, nodes["AA"]!!, 0,0,0, Pair(listOf("AA"),listOf("AA"))))
// A, D, Do, C, B, Bo, A, I, J, Jo, I, A, D, E, F, G, H, Ho, G, F, E, Eo, D, C, Co
//[A, D, Do, C, B, Bo, A, I, J, Jo, I, A, D, E, Eo, F, G, H, Ho, G, F, E, F]
//[A, D, Do, C, Co, D, C, D, C, B, Bo, A, I, J, Jo, I, A, D, E, Eo, F, Fo, G, Go, H, Ho, G, F, E, D, C]
// val x = findPath2(12, nodes["AA"]!!, nodes["AA"]!!, 0, 0, Pair(listOf("AA"),listOf("AA")))
//// println(x.first.map { it.drop(1) })
// println("tot: $validNodesCount")
// println(x)
}
// Pos A/B time remaining and open values
var cache: MutableMap<Pair<Set<String>, Pair<Int, Set<String>>>, Pair<Pair<List<String>, List<String>>,Int>> = mutableMapOf()
var cacheHit = 0
fun findPath2(remainingTime: Int, a: Node, b: Node, currentPressure: Int, totalPressure: Int, path2: Pair<List<String>,List<String>>): Pair<Pair<List<String>, List<String>>,Int> {
// Enter function reduce to by 1 and turn on
if (remainingTime <= 0) {
return Pair(path2, totalPressure)
}
val onValves = (path2.first + path2.second).filter() {
it.endsWith("o")
}.toSet()
if (onValves.size == validNodesCount) {
return Pair(path2, totalPressure + currentPressure * remainingTime)
}
val key = Pair(setOf(a.name, b.name), Pair(remainingTime, onValves))
if (cache[key] != null) {
cacheHit++
if (cacheHit % 100000 == 0) {
println("Cache hit: $cacheHit")
}
val extension = cache[key]!!
return Pair(Pair(path2.first + extension.first.first, path2.second + extension.first.second), totalPressure + extension.second)
}
var paths = mutableListOf<Pair<Pair<List<String>, List<String>>,Int>>()
if (a.name != b.name) {
var doA = false;
var doB = false;
if (a.rate > 0 && !onValves.contains("${a.name}o") && remainingTime >= 1) {
doA = true
val newPressure = currentPressure + a.rate
paths.addAll(b.connections.map {
findPath2(remainingTime - 1, a, it, newPressure, totalPressure + currentPressure, Pair(path2.first + "${a.name}o", path2.second + it.name))
}.toMutableList())
}
if (b.rate > 0 && !onValves.contains("${b.name}o") && remainingTime >= 1) {
doB = true
val newPressure = currentPressure + b.rate
paths.addAll(a.connections.map {
findPath2(remainingTime - 1, it, b, newPressure, totalPressure + currentPressure, Pair(path2.first + it.name, path2.second + "${b.name}o"))
}.toMutableList())
}
if (doA && doB) {
val doublePressure = currentPressure + a.rate + b.rate
paths.add(
findPath2(
remainingTime - 1,
a,
b,
doublePressure,
totalPressure + currentPressure,
Pair(path2.first + "${a.name}o", path2.second + "${b.name}o")
)
)
}
paths.addAll(a.connections.flatMap {newA ->
b.connections.map {newB ->
findPath2(remainingTime - 1, newA, newB, currentPressure, totalPressure + currentPressure, Pair(path2.first + newA.name, path2.second + newB.name))
}
}.toMutableList())
} else {
// Only 1 can switch it on, doesn't matter which
if (a.rate > 0 && !onValves.contains("${a.name}o") && remainingTime >= 1) {
val newPressure = currentPressure + a.rate
paths.addAll(b.connections.map {
findPath2(remainingTime - 1, a, it, newPressure, totalPressure + currentPressure, Pair(path2.first + "${a.name}o", path2.second + it.name))
}.toMutableList())
}
// Either move to any connection, or, if possible, turn on the valve
paths.addAll(a.connections.flatMap {newA ->
b.connections.map {newB ->
findPath2(remainingTime - 1, newA, newB, currentPressure, totalPressure + currentPressure, Pair(path2.first + newA.name, path2.second + newB.name))
}
}.toMutableList())
}
val best = paths.maxBy { it.second }!!
if (cache[key] == null) {
// Just the end bit
cache[key] = Pair(Pair(best.first.first.drop(path2.first.size), best.first.second.drop(path2.second.size)), best.second - totalPressure)
}
return best
}
fun findPath(remainingTime: Int, currentNode: Node, currentPressure: Int, totalPressure: Int, path: List<String>): Pair<List<String>,Int> {
// Enter function reduce to by 1 and turn on
if (remainingTime <= 0) {
return Pair(path, totalPressure)
}
val onValves = path.filter() {
it.endsWith("o")
}.toSet()
val key = Pair(remainingTime, onValves)
if (currentNode.best[key] != null) {
val extension = currentNode.best[key]!!
return Pair(path + extension.first, totalPressure + extension.second)
}
var paths = mutableListOf<Pair<List<String>,Int>>()
// Either move to any connection, or, if possible, turn on the valve
if (!onValves.contains("${currentNode.name}o") && remainingTime >= 1 && currentNode.rate > 0) {
val newPressure = currentPressure + currentNode.rate
paths.add(findPath(remainingTime - 1, currentNode, newPressure, totalPressure + currentPressure, path + "${currentNode.name}o"))
}
paths.addAll(currentNode.connections.map {
findPath(remainingTime - 1, it, currentPressure, totalPressure + currentPressure, path + it.name)
}.toMutableList())
val best = paths.maxBy { it.second }!!
val existingBest = currentNode.best[key]
// Can't be null here anyway
if (existingBest == null || best.second > existingBest.second ) {
// Just the end bit
currentNode.best[key] = Pair(best.first.drop(path.size), best.second - totalPressure)
}
return best
}
} | 0 | Kotlin | 0 | 0 | fd644d442b5ff0d2f05fbf6317c61ee9ce7b4470 | 15,671 | adventofcode2022 | MIT License |
kotlin/combinatorics/Permutations.kt | polydisc | 281,633,906 | true | {"Java": 540473, "Kotlin": 515759, "C++": 265630, "CMake": 571} | package combinatorics
import numeric.FFT
import optimization.Simplex
object Permutations {
fun nextPermutation(p: IntArray): Boolean {
var a = p.size - 2
while (a >= 0) {
if (p[a] < p[a + 1]) {
var b = p.size - 1
while (true) {
if (p[b] > p[a]) {
var t = p[a]
p[a] = p[b]
p[b] = t
++a
b = p.size - 1
while (a < b) {
t = p[a]
p[a] = p[b]
p[b] = t
++a
--b
}
return true
}
--b
}
}
--a
}
return false
}
fun permutationByNumber(n: Int, number: Long): IntArray {
var number = number
val fact = LongArray(n)
fact[0] = 1
for (i in 1 until n) {
fact[i] = i * fact[i - 1]
}
val p = IntArray(n)
val free = IntArray(n)
for (i in 0 until n) {
free[i] = i
}
for (i in 0 until n) {
val pos = (number / fact[n - 1 - i]).toInt()
p[i] = free[pos]
System.arraycopy(free, pos + 1, free, pos, n - 1 - pos)
number %= fact[n - 1 - i]
}
return p
}
fun numberByPermutation(p: IntArray): Long {
val n = p.size
val fact = LongArray(n)
fact[0] = 1
for (i in 1 until n) {
fact[i] = i * fact[i - 1]
}
var res: Long = 0
for (i in 0 until n) {
var a = p[i]
for (j in 0 until i) {
if (p[j] < p[i]) {
--a
}
}
res += a * fact[n - 1 - i]
}
return res
}
fun generatePermutations(p: IntArray, depth: Int) {
val n = p.size
if (depth == n) {
System.out.println(Arrays.toString(p))
return
}
for (i in 0 until n) {
if (p[i] == 0) {
p[i] = depth
generatePermutations(p, depth + 1)
p[i] = 0
}
}
}
fun nextPermutation(x: Long): Long {
val s = x and -x
val r = x + s
var ones = x xor r
ones = (ones shr 2) / s
return r or ones
}
fun decomposeIntoCycles(p: IntArray): List<List<Integer>> {
val n = p.size
val vis = BooleanArray(n)
val res: List<List<Integer>> = ArrayList()
for (i in 0 until n) {
if (vis[i]) continue
var j: Int = i
val cur: List<Integer> = ArrayList()
do {
cur.add(j)
vis[j] = true
j = p[j]
} while (j != i)
res.add(cur)
}
return res
}
// Usage example
fun main(args: Array<String?>?) {
// print all permutations method 1
generatePermutations(IntArray(2), 1)
// print all permutations method 2
val p = intArrayOf(0, 1, 2)
var cnt = 0
do {
System.out.println(Arrays.toString(p))
if (!Arrays.equals(p, permutationByNumber(p.size, numberByPermutation(p)))
|| cnt.toLong() != numberByPermutation(permutationByNumber(p.size, cnt.toLong()))
) throw RuntimeException()
++cnt
} while (nextPermutation(p))
System.out.println(5L == numberByPermutation(p))
System.out.println(Arrays.equals(intArrayOf(1, 0, 2), permutationByNumber(3, 2)))
System.out.println(13L == nextPermutation(11))
System.out.println(decomposeIntoCycles(intArrayOf(0, 2, 1, 3)))
}
}
| 1 | Java | 0 | 0 | 4566f3145be72827d72cb93abca8bfd93f1c58df | 3,939 | codelibrary | The Unlicense |
src/questions/RemoveDuplicateFromSortedArray.kt | realpacific | 234,499,820 | false | null | package questions
import algorithmdesignmanualbook.print
import kotlin.test.assertEquals
import kotlin.test.assertTrue
/**
* Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place.
* The relative order of the elements should be kept the same.
* More formally, if there are k elements after removing the duplicates,
* then the first k elements of nums should hold the final result.
* It does not matter what you leave beyond the first k elements.
* Return k after placing the final result in the first k slots of nums.
*
* [Source](https://leetcode.com/problems/remove-duplicates-from-sorted-array/submissions/)
*/
fun removeDuplicateFromSortedArray(nums: IntArray): Pair<Int, List<Int>> {
var k = 1
var isIncrementing = true
for (i in 0..nums.lastIndex) {
var j = i + 1
if (j > nums.lastIndex) {
continue
}
// Skip till you find an item that's not been swapped and is different that the current
while (j <= nums.lastIndex && (nums[i] >= nums[j])) {
j += 1
}
swap(nums, i + 1, j)
if (isIncrementing && nums[i] < nums[i + 1]) {
k++
} else {
// as soon as find a non-sorted item, then stop counting
isIncrementing = false
}
}
return k to nums.toList()
}
private fun swap(nums: IntArray, i: Int, j: Int) {
if (i > nums.lastIndex || j > nums.lastIndex) {
return
}
val temp = nums[i]
nums[i] = nums[j]
nums[j] = temp
}
fun main() {
assertTrue {
removeDuplicateFromSortedArray(intArrayOf(0, 0, 1, 1, 1, 2, 2, 3, 3, 4)).print()
.run {
validateItemsUptoNIsEqualTo(this.second.toIntArray(), this.first, intArrayOf(0, 1, 2, 3, 4))
}
}
assertTrue {
removeDuplicateFromSortedArray(intArrayOf(0, 0, 0, 0, 0, 1, 1, 1, 2, 2, 3, 3, 4)).print()
.run {
validateItemsUptoNIsEqualTo(this.second.toIntArray(), this.first, intArrayOf(0, 1, 2, 3, 4))
}
}
assertTrue {
removeDuplicateFromSortedArray(intArrayOf(1, 1, 1, 2, 2, 3, 3, 4)).print()
.run {
validateItemsUptoNIsEqualTo(this.second.toIntArray(), this.first, intArrayOf(1, 2, 3, 4))
}
}
assertTrue {
removeDuplicateFromSortedArray(intArrayOf(1)).print()
.run {
validateItemsUptoNIsEqualTo(this.second.toIntArray(), this.first, intArrayOf(1))
}
}
assertTrue {
removeDuplicateFromSortedArray(intArrayOf(4, 4, 4, 4, 4)).print()
.run {
validateItemsUptoNIsEqualTo(this.second.toIntArray(), this.first, intArrayOf(4))
}
}
assertTrue {
removeDuplicateFromSortedArray(intArrayOf(4, 4, 4, 4, 5)).print()
.run {
validateItemsUptoNIsEqualTo(this.second.toIntArray(), this.first, intArrayOf(4, 5))
}
}
assertTrue {
removeDuplicateFromSortedArray(intArrayOf(1, 1, 2)).print()
.run {
validateItemsUptoNIsEqualTo(this.second.toIntArray(), this.first, intArrayOf(1, 2))
}
}
}
private fun validateItemsUptoNIsEqualTo(nums: IntArray, n: Int, expected: IntArray): Boolean {
for (i in 0 until n) {
assertEquals(expected[i], nums[i])
}
return true
} | 4 | Kotlin | 5 | 93 | 22eef528ef1bea9b9831178b64ff2f5b1f61a51f | 3,414 | algorithms | MIT License |
examples/regression/src/main/kotlin/WeightedRegression.kt | Kotlin | 225,367,588 | false | {"Kotlin": 435270, "C": 152277, "Python": 7577} | import org.jetbrains.numkt.*
import org.jetbrains.numkt.core.KtNDArray
import org.jetbrains.numkt.core.dot
import org.jetbrains.numkt.core.ravel
import org.jetbrains.numkt.core.reshape
import org.jetbrains.numkt.linalg.Linalg
import org.jetbrains.numkt.math.*
import org.jetbrains.numkt.random.Random
import org.jetbrains.numkt.statistics.`var`
fun weight(x0: KtNDArray<Double>, x: KtNDArray<Double>, tau: Double = 5.0): KtNDArray<Double> {
var w = exp((-1) * sum((x - x0) `**` 2, axis = 1) / ((2 * tau) * (2 * tau)))
w = diag(w)
return w
}
fun weightedLeastSquares(x: KtNDArray<Double>, y: KtNDArray<Double>, weights: KtNDArray<Double>): KtNDArray<Double> =
Linalg.inv(transpose(x).dot(weights.dot(x))).dot(transpose(x).dot(weights.dot(y)))
fun weightedRegression(x: KtNDArray<Double>, y: KtNDArray<Double>, tau: Double = 5.0): KtNDArray<Double> {
val yHat = zerosLike(y)
val sh = x.shape[0]
for (i in 0 until sh) {
val w = weight(x[i..i + 1].ravel(), x, tau)
val theta = weightedLeastSquares(x, y, w)
yHat[i] = x.dot(theta)[i]
}
return yHat
}
fun r2Score(y: KtNDArray<Double>, yHat: KtNDArray<Double>) =
1.0 - sum((y - yHat) `**` 2) / `var`(y) / y.shape[0]
fun searchAccuracies(taus: KtNDArray<Double>, x: KtNDArray<Double>, y: KtNDArray<Double>): KtNDArray<Double> {
val r = arrayListOf<Double>()
for (tau in taus.flatIter()) {
r.add(r2Score(y, weightedRegression(x, y, tau = tau)))
}
return array(r)
}
fun main() {
val data = linspace<Double>(-3, 3, 1000)
val y = sin(data `**` 3 / 3)
data += Random.normal(scale = 0.1, size = *intArrayOf(1000))
val x = hstack(ones<Double>(1000).reshape(1000, 1), data.reshape(1000, 1))
val taus = linspace<Double>(0.01, 1, 10)
val accuracies = searchAccuracies(taus, x, y)
println(accuracies)
}
| 11 | Kotlin | 11 | 313 | 2f1421883c201df60c57eaa4db4c3ee74dc40413 | 1,857 | kotlin-numpy | Apache License 2.0 |
src/Day02.kt | marvingrewe | 573,069,044 | false | {"Kotlin": 6473} | import kotlin.system.measureTimeMillis
fun main() {
val day = "Day02"
fun matchUpPoints1(letter: String): Int = when (letter) {
"A X" -> 4
"B X" -> 1
"C X" -> 7
"A Y" -> 8
"B Y" -> 5
"C Y" -> 2
"A Z" -> 3
"B Z" -> 9
"C Z" -> 6
else -> error("tja")
}
fun matchUpPoints2(letter: String): Int = when (letter) {
"A X" -> 3
"B X" -> 1
"C X" -> 2
"A Y" -> 4
"B Y" -> 5
"C Y" -> 6
"A Z" -> 8
"B Z" -> 9
"C Z" -> 7
else -> error("tja")
}
fun part1(input: List<String>): Int = input.sumOf(::matchUpPoints1)
fun part2(input: List<String>): Int = input.sumOf(::matchUpPoints2)
val testInput = readInput(day + "_test")
val input = readInput(day)
var result: Any
println("Test 1 solved in ${measureTimeMillis { result = part1(testInput) }}ms with result: $result, expected: 15")
println("Test 2 solved in ${measureTimeMillis { result = part2(testInput) }}ms with result: $result, expected: 12")
println("Part 1 solved in ${measureTimeMillis { result = part1(input) }}ms with result: $result")
println("Part 2 solved in ${measureTimeMillis { result = part2(input) }}ms with result: $result")
}
| 0 | Kotlin | 0 | 0 | adec59f236b5f92cfcaf9e595fb913bf0010ac41 | 1,304 | advent-of-code-2022 | Apache License 2.0 |
src/Day02.kt | yashpalrawat | 573,264,560 | false | {"Kotlin": 12474} | enum class MOVETYPE(val value: Int) {
ROCK(1),
PAPER(2),
SCISSOR(3)
}
val mapping = mapOf(
"X" to MOVETYPE.ROCK,
"Y" to MOVETYPE.PAPER,
"Z" to MOVETYPE.SCISSOR,
"A" to MOVETYPE.ROCK,
"B" to MOVETYPE.PAPER,
"C" to MOVETYPE.SCISSOR,
)
fun findWinningPlayer(firstMove: MOVETYPE, secondMove: MOVETYPE): Int {
if (firstMove == secondMove) return 0
when(firstMove) {
MOVETYPE.ROCK -> {
return if (secondMove == MOVETYPE.PAPER) {
2
} else {
1
}
}
MOVETYPE.PAPER -> {
return if (secondMove == MOVETYPE.ROCK) {
1
} else {
2
}
}
MOVETYPE.SCISSOR -> {
return if (secondMove == MOVETYPE.PAPER) {
1
} else {
2
}
}
}
}
fun main() {
fun part1(input: List<String>): Int {
var totalScore = 0
input.forEach {
val tokens = it.split(" ")
val firstPlayerMove = mapping[tokens[0]]!!
val secondPlayerMove = mapping[tokens[1]]!!
when(findWinningPlayer(firstPlayerMove, secondPlayerMove)) {
1 -> {
totalScore += secondPlayerMove.value
}
2 -> {
totalScore += 6 + secondPlayerMove.value
}
0 -> {
totalScore += 3 + secondPlayerMove.value
}
}
}
return totalScore
}
val input = readInput("Day02")
println(part1(input))
} | 0 | Kotlin | 0 | 0 | 78a3a817709da6689b810a244b128a46a539511a | 1,672 | code-advent-2022 | Apache License 2.0 |
Kotlin/days/src/day14.kt | dukemarty | 224,307,841 | false | null | import java.io.BufferedReader
import java.io.FileReader
import java.lang.Integer.min
class ChemicalStore {
private val store = mutableListOf<Chemical>()
fun contains(name: String): Boolean {
val stored = store.firstOrNull { it.name == name }
return stored != null
}
fun getStoreSize(): Int {
return store.size
}
fun getStoredAmount(name: String): Int {
val stored = store.first { it.name == name }
return stored.amount
}
fun storeChemical(name: String, amount: Int) {
val stored = store.firstOrNull { it.name == name }
if (stored == null) {
store.add(Chemical(name, amount))
} else {
stored.amount += amount
}
}
fun retrieveChemical(name: String, maxAmount: Int): Int {
val stored = store.first { it.name == name }
val resAmount = min(stored.amount, maxAmount)
if (stored.amount < resAmount) {
throw IllegalArgumentException("amount too large")
} else if (stored.amount == resAmount) {
store.remove(stored)
} else {
stored.amount -= resAmount
}
return resAmount
}
override fun toString(): String {
return "STORE: [${store.joinToString(separator = ",") { it.toString() }}]"
}
}
data class Chemical(val description: String) {
val name: String
var amount: Int
init {
val tokens = description.trim().split(" ")
name = tokens[1]
amount = tokens[0].toInt()
}
constructor(name: String, amount: Int) : this("$amount $name")
override fun toString(): String {
return "Chemical($name, $amount)"
}
}
data class Reaction(val line: String) {
val inputs: Collection<Chemical>
val output: Chemical
init {
val parts = line.split("=>")
output = Chemical(parts[1])
inputs = parts[0].split(",").map { Chemical(it) }
}
override fun toString(): String {
return "Reaction([${inputs.joinToString(separator = ",") { "$it" }}] -> $output)"
}
}
fun main(args: Array<String>) {
println("--- Day 14: Space Stoichiometry ---");
val br = BufferedReader(FileReader("puzzle_input/day14-input1.txt"))
val reactions = br.readLines().map { Reaction(it) }
// println("Parsed reactions:\n${reactions.joinToString(separator = "\n") { "$it" }}")
day14PartOne(reactions)
day14PartTwo(reactions)
}
fun day14PartOne(reactions: List<Reaction>) {
println("\n--- Part One ---")
val required = mutableListOf(Chemical("FUEL", 1))
val store = ChemicalStore()
var oreCount = 0
while (required.any()) {
// println("#$oreCount / STORE: $store / REQ: $required")
val nextChem = required[0]
required.removeAt(0)
if (store.contains(nextChem.name)) {
val retrieved = store.retrieveChemical(nextChem.name, nextChem.amount)
nextChem.amount -= retrieved
if (nextChem.amount == 0) {
continue
}
}
val nextReaction = reactions.first { it.output.name == nextChem.name }
val times = calculateRequiredMultiplicity(nextChem, nextReaction)
for (i in nextReaction.inputs) {
if (i.name == "ORE") {
oreCount += times * i.amount
} else {
if (i.amount > 0) {
required.add(Chemical(i.name, i.amount * times))
}
}
}
if (nextReaction.output.amount * times > nextChem.amount) {
val remainder = nextReaction.output.amount * times - nextChem.amount
store.storeChemical(nextChem.name, remainder)
}
}
println("Required ORE: $oreCount")
println(" with remaining store: $store")
}
private fun calculateRequiredMultiplicity(nextChem: Chemical, nextReaction: Reaction): Int {
var times = 0
if (nextChem.amount < nextReaction.output.amount) {
times = 1
} else if (nextChem.amount == nextReaction.output.amount) {
times = 1
} else if (nextChem.amount % nextReaction.output.amount == 0) {
times = nextChem.amount / nextReaction.output.amount
} else {
times = nextChem.amount / nextReaction.output.amount + 1
}
return times
}
fun day14PartTwo(reactions: List<Reaction>) {
println("\n--- Part Two ---")
val availableOre: Long = 1000000000000
var producedFuel: Long = 0
val store = ChemicalStore()
var oreCount: Long = 0
while (oreCount < availableOre) {
val required = mutableListOf(Chemical("FUEL", 1))
while (required.any()) {
// println("#$oreCount / STORE: $store / REQ: $required")
val nextChem = required[0]
required.removeAt(0)
if (store.contains(nextChem.name)) {
val retrieved = store.retrieveChemical(nextChem.name, nextChem.amount)
nextChem.amount -= retrieved
if (nextChem.amount == 0) {
continue
}
}
val nextReaction = reactions.first { it.output.name == nextChem.name }
val times = calculateRequiredMultiplicity(nextChem, nextReaction)
for (i in nextReaction.inputs) {
if (i.name == "ORE") {
oreCount += times * i.amount
} else {
if (i.amount > 0) {
required.add(Chemical(i.name, i.amount * times))
}
}
}
if (nextReaction.output.amount * times > nextChem.amount) {
val remainder = nextReaction.output.amount * times - nextChem.amount
store.storeChemical(nextChem.name, remainder)
}
}
if (oreCount <= availableOre) {
producedFuel++
}
if (store.getStoreSize() == 0){
println("Reached empty store again with $producedFuel FUEL for $oreCount ORE")
val remainingOre = availableOre - oreCount
if (remainingOre > oreCount){
val mult = remainingOre / oreCount
oreCount += mult * oreCount
producedFuel += mult * producedFuel
println("Used to speed-up calculation with mult=$mult: $producedFuel FUEL for $oreCount ORE")
}
} else {
println("Store size: ${store.getStoreSize()}")
}
}
println("Produced fuel: $producedFuel")
println(" with remaining store: $store")
}
| 0 | Kotlin | 0 | 0 | 6af89b0440cc1d0cc3f07d5a62559aeb68e4511a | 6,602 | dukesaoc2019 | MIT License |
src/Utils.kt | hoppjan | 433,705,171 | false | {"Kotlin": 29015, "Shell": 338} |
/**
* Prints test result of a part and solution.
*/
fun <T> printTestResult(part: Int = 1, result: T, expected: T) =
println("test result $part: $result, $expected expected")
/**
* Prints result of a part.
*/
fun <T> printResult(part: Int, result: T) =
println("result part $part: $result")
/**
* Boilerplate code to run both parts on test and actual inputs.
*/
fun <I> runEverything(
day: String,
testSolution1: Int,
testSolution2: Int,
part1: (List<I>) -> Int,
part2: (List<I>) -> Int,
inputReader: InputReader<I>,
) {
// test if implementation meets criteria from the description
val testInput = inputReader.read("Day${day}_test")
// testing part 1
val testOutput1 = part1(testInput)
printTestResult(1, testOutput1, testSolution1)
check(testOutput1 == testSolution1)
// testing part 2
val testOutput2 = part2(testInput)
printTestResult(2, testOutput2, testSolution2)
check(testOutput2 == testSolution2)
// the actual input and outputs
val input = inputReader.read("Day$day")
printResult(1, part1(input))
printResult(2, part2(input))
}
/**
* Returns [IntRange] or the reversed [IntRange] if the first [Int] is bigger.
* This is necessary as descending [IntRange]s are just empty by default.
*/
infix fun Int.upTo(limit: Int) =
if (this < limit)
this..limit
else
limit..this
fun List<Int>.product() = reduce { acc, i -> acc * i }
fun <E> List<E>.containsNot(element: E) = contains(element).not()
| 0 | Kotlin | 0 | 0 | 04f10e8add373884083af2a6de91e9776f9f17b8 | 1,528 | advent-of-code-2021 | Apache License 2.0 |
src/Day08.kt | A55enz10 | 573,364,112 | false | {"Kotlin": 15119} | import java.lang.Integer.max
fun main() {
fun String.isVisibleFromSides(idx: Int): Boolean {
return this.substring(0,idx).all { it.digitToInt() < this[idx].digitToInt() }
|| this.substring(idx+1).all { it.digitToInt() < this[idx].digitToInt() }
}
fun part1(input: List<String>): Int {
var count = 0
input.forEachIndexed { i, row ->
row.forEachIndexed { j, _ ->
// borders are always visible
if (!(1..input.size-2).contains(i) || !(1..row.length-2).contains(j)) {
count++
} else {
var column = ""
input.forEach { column += it[j] }
if (row.isVisibleFromSides(j) || column.isVisibleFromSides(i)) count++
}
}
}
return count
}
fun part2(input: List<String>): Int {
var maxScore = 0
input.forEachIndexed { i, row ->
row.forEachIndexed { j, _ ->
if ((1..input.size-2).contains(i) && (1..row.length-2).contains(j)) {
// north
var northScore = 1
if (i > 0) {
for (idx in i - 1 downTo 1) {
if (input[idx][j].digitToInt() < input[i][j].digitToInt()) {
northScore++
} else {
break
}
}
}
// south
var southScore = 1
if (i < input.size - 1) {
for (idx in i + 1..input.size - 2) {
if (input[idx][j].digitToInt() < input[i][j].digitToInt()) {
southScore++
} else {
break
}
}
}
// west
var westScore = 1
if (j > 0) {
for (idx in j - 1 downTo 1) {
if (input[i][idx].digitToInt() < input[i][j].digitToInt()) {
westScore++
} else {
break
}
}
}
// east
var eastScore = 1
if (j < input[i].length - 1) {
for (idx in j + 1..input[i].length - 2) {
if (input[i][idx].digitToInt() < input[i][j].digitToInt()) {
eastScore++
} else {
break
}
}
}
val thisScore = northScore * southScore * eastScore * westScore
maxScore = max(maxScore, thisScore)
}
}
}
return maxScore
}
val input = readInput("Day08")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 8627efc194d281a0e9c328eb6e0b5f401b759c6c | 3,243 | advent-of-code-2022 | Apache License 2.0 |
src/Day08.kt | kuolemax | 573,740,719 | false | {"Kotlin": 21104} | fun main() {
fun part1(input: List<String>): Int {
val size = input.size
var result = (size - 1) * 4
val matrix = input.map { row ->
val map = row.map { it.toString().toInt() }
map
}
// col 从 2 -> size - 1 check
// row 从 2 -> size - 1 check
for ((r, row) in matrix.withIndex()) {
if (r == 0 || r == size - 1) {
continue
}
for (c in row.indices) {
if (c == 0 || c == size - 1) {
continue
}
if (checkIfMoreThanOther(r, c, size, matrix)) result++
}
}
return result
}
fun part2(input: List<String>): Int {
val size = input.size
var result = 0
val matrix = input.map { row ->
val map = row.map { it.toString().toInt() }
map
}
// col 从 2 -> size - 1 check
// row 从 2 -> size - 1 check
for ((r, row) in matrix.withIndex()) {
if (r == 0 || r == size - 1) {
continue
}
for (c in row.indices) {
if (c == 0 || c == size - 1) {
continue
}
val score = statisticalScore(r, c, size, matrix)
if (score > result) result = score
}
}
return result
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08_test")
check(part1(testInput) == 21)
check(part2(testInput) == 8)
val input = readInput("Day08")
println(part1(input))
println(part2(input))
}
fun checkIfMoreThanOther(rIndex: Int, cIndex: Int, size: Int, matrix: List<List<Int>>): Boolean {
val currentValue = matrix[rIndex][cIndex]
var result = 4
// 向左检查
var left = cIndex - 1
while (left > -1) {
if (currentValue <= matrix[rIndex][left]) {
result--
break
}
left--
}
if (result == 4) return true
// 向右检查
var right = cIndex + 1
while (right < size) {
if (currentValue <= matrix[rIndex][right]) {
result--
break
}
right++
}
if (result == 3) return true
// 向上检查
var up = rIndex - 1
while (up > -1) {
if (currentValue <= matrix[up][cIndex]) {
result--
break
}
up--
}
if (result == 2) return true
// 向下检查
var down = rIndex + 1
while (down < size) {
if (currentValue <= matrix[down][cIndex]) {
result--
break
}
down++
}
return result == 1
}
fun statisticalScore(rIndex: Int, cIndex: Int, size: Int, matrix: List<List<Int>>): Int {
val currentValue = matrix[rIndex][cIndex]
val result = mutableListOf(0, 0, 0, 0)
// 向左检查
var left = cIndex - 1
while (left > -1) {
if (currentValue <= matrix[rIndex][left]) {
result[0]++
break
}
result[0]++
left--
}
// 向右检查
var right = cIndex + 1
while (right < size) {
if (currentValue <= matrix[rIndex][right]) {
result[1]++
break
}
result[1]++
right++
}
// 向上检查
var up = rIndex - 1
while (up > -1) {
if (currentValue <= matrix[up][cIndex]) {
result[2]++
break
}
result[2]++
up--
}
// 向下检查
var down = rIndex + 1
while (down < size) {
if (currentValue <= matrix[down][cIndex]) {
result[3]++
break
}
result[3]++
down++
}
var score = 1
result.forEach { score *= it }
return score
}
| 0 | Kotlin | 0 | 0 | 3045f307e24b6ca557b84dac18197334b8a8a9bf | 3,881 | aoc2022--kotlin | Apache License 2.0 |
year2020/src/main/kotlin/net/olegg/aoc/year2020/day13/Day13.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2020.day13
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.utils.parseLongs
import net.olegg.aoc.year2020.DayOf2020
/**
* See [Year 2020, Day 13](https://adventofcode.com/2020/day/13)
*/
object Day13 : DayOf2020(13) {
override fun first(): Any? {
val (startLine, busLine) = lines
val start = startLine.toLong()
val buses = busLine.parseLongs(",")
return buses.map { it to ((start - 1) / it + 1) * it }
.minBy { it.second }
.let { it.first * (it.second - start) }
}
override fun second(): Any? {
val (_, busLine) = lines
val (nums, buses) = busLine.split(",")
.mapIndexedNotNull { index, s -> s.toBigIntegerOrNull()?.let { index.toBigInteger() to it } }
.unzip()
val mod = buses.reduce { a, b -> a * b }
val mis = buses.map { mod / it }
val revs = buses.zip(mis) { bus, mi -> mi.modInverse(bus) }
val sum = buses.zip(nums) { bus, num -> bus - (num % bus) }
.zip(mis) { acc, mi -> acc * mi }
.zip(revs) { acc, rev -> acc * rev }
.sumOf { it }
return sum % mod
}
}
fun main() = SomeDay.mainify(Day13)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 1,138 | adventofcode | MIT License |
src/test/kotlin/ch/ranil/aoc/aoc2022/Day12.kt | stravag | 572,872,641 | false | {"Kotlin": 234222} | package ch.ranil.aoc.aoc2022
import ch.ranil.aoc.AbstractDay
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals
object Day12 : AbstractDay() {
@Test
fun part1() {
assertEquals(31, compute1(testInput))
assertEquals(437, compute1(puzzleInput))
}
@Test
fun part2() {
assertEquals(29, compute2(testInput))
assertEquals(430, compute2(puzzleInput))
}
private fun compute1(input: List<String>): Int {
val relief = buildRelief(input) { diff -> diff <= 1 }
val startNode = relief.flatten().single { it.isStart }
return findShortestPaths(relief, startNode)
.single { it.isEnd }.distance
}
private fun compute2(input: List<String>): Int {
val relief = buildRelief(input) { diff -> diff >= -1 }
val endNode = relief.flatten().single { it.isEnd }
return findShortestPaths(relief, endNode)
.filter { it.isLow }
.minOf { it.distance }
}
private fun buildRelief(input: List<String>, neighborAccessible: (Int) -> Boolean): List<List<Node>> {
return input.mapIndexed { rowIdx, line ->
line.mapIndexed { colIdx, point ->
val height = point.height()
val coordinates = Coordinates(rowIdx, colIdx)
val adjacentCoordinates = coordinates.getAdjacentCoordinates()
val accessibleNeighbors = adjacentCoordinates
.mapNotNull { c -> input.get(c)?.let { c to it.height() } }
.map { (c, adjacentHeight) -> c to (adjacentHeight - height) }
.filter { (_, adjacentHeightDiff) -> neighborAccessible(adjacentHeightDiff) }
.map { it.first }
Node(point, coordinates, accessibleNeighbors)
}
}
}
private fun List<String>.get(coordinates: Coordinates): Char? {
return this.getOrNull(coordinates.rowIdx)?.getOrNull(coordinates.colIdx)
}
private fun List<List<Node>>.get(coordinates: Coordinates): Node {
return this[coordinates.rowIdx][coordinates.colIdx]
}
private fun findShortestPaths(relief: List<List<Node>>, startNode: Node): Set<Node> {
startNode.distance = 0
val unsettled = mutableSetOf(startNode)
val settled = mutableSetOf<Node>()
while (unsettled.isNotEmpty()) {
val currentNode = unsettled.minBy { it.distance }
unsettled.remove(currentNode)
currentNode.accessibleNeighbors.forEach {
val neighborNode = relief.get(it)
if (!settled.contains(neighborNode)) {
val sourceDistance = currentNode.distance
if (sourceDistance + 1 < neighborNode.distance) {
neighborNode.distance = sourceDistance + 1
}
unsettled.add(neighborNode)
}
}
settled.add(currentNode)
}
return settled
}
private fun Char.height() = (if (this == 'S') 'a' else if (this == 'E') 'z' else this).code
private data class Coordinates(val rowIdx: Int, val colIdx: Int) {
fun getAdjacentCoordinates(): List<Coordinates> {
return listOf(
Coordinates(rowIdx, colIdx - 1), // left
Coordinates(rowIdx, colIdx + 1), // right
Coordinates(rowIdx + 1, colIdx), // up
Coordinates(rowIdx - 1, colIdx), // down
)
}
}
private data class Node(
val point: Char,
val coordinates: Coordinates,
val accessibleNeighbors: List<Coordinates>,
var distance: Int = Int.MAX_VALUE,
) {
val isStart get() = point == 'S'
val isEnd get() = point == 'E'
val isLow get() = point.height() == 'a'.height()
}
}
| 0 | Kotlin | 1 | 0 | dbd25877071cbb015f8da161afb30cf1968249a8 | 3,884 | aoc | Apache License 2.0 |
src/Day06.kt | tblechmann | 574,236,696 | false | {"Kotlin": 5756} | fun main() {
fun part1(input: String, windowLength: Int = 4): Int {
var slidingWindowEnd = windowLength
var slidingWindowStart = 0
while (input
.substring(slidingWindowStart, slidingWindowEnd)
.toCharArray()
.distinct().size < windowLength) {
slidingWindowStart++
slidingWindowEnd++
}
return slidingWindowEnd
}
fun part2(input: String): Int {
return part1(input, 14)
}
// test if implementation meets criteria from the description, like:
check(part1("mjqjpqmgbljsphdztnvjfqwrcgsmlb") == 7)
check(part1("bvwbjplbgvbhsrlpgdmjqwftvncz") == 5)
check(part1("nppdvjthqldpwncqszvftbrmjlhg") == 6)
check(part1("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg") == 10)
check(part1("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw") == 11)
//check(part2(testInput) == 45000)
check(part2("mjqjpqmgbljsphdztnvjfqwrcgsmlb") == 19)
check(part2("bvwbjplbgvbhsrlpgdmjqwftvncz") == 23)
check(part2("nppdvjthqldpwncqszvftbrmjlhg") == 23)
check(part2("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg") == 29)
check(part2("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw") == 26)
val input = readInput("Day06")
println(part1(input[0]))
println(part2(input[0]))
}
| 0 | Kotlin | 0 | 0 | 4a65f6468a0cddd8081f2f0e3c1a96935438755f | 1,286 | aoc2022 | Apache License 2.0 |
src/main/kotlin/problems/Day6.kt | PedroDiogo | 432,836,814 | false | {"Kotlin": 128203} | package problems
class Day6(override val input: String) : Problem {
override val number: Int = 6
private val fishAges = input.split(",").map { i -> i.toInt() }
override fun runPartOne(): String {
return runMultipleDays(80, fishAges).toString()
}
override fun runPartTwo(): String {
return runMultipleDays(256, fishAges).toString()
}
private fun getNumberOfFishByAge(ageList: List<Int>): Array<Int> {
return ageList
.groupingBy { it }
.eachCount()
.entries
.fold(Array(9) { 0 }) { list, (age, hits) ->
list[age] = hits
list
}
}
private fun runMultipleDays(days: Int, ageList: List<Int>): Long {
var numberOfFishByAge = getNumberOfFishByAge(ageList)
.map { i -> i.toLong() }
.toTypedArray()
repeat(days) {
numberOfFishByAge = runOneDay(numberOfFishByAge)
}
return numberOfFishByAge.sum()
}
private fun runOneDay(fishByAge: Array<Long>): Array<Long> {
val first6Days = fishByAge.slice(1..6)
val day6 = fishByAge[0] + fishByAge[7]
val day7 = fishByAge[8]
val day8 = fishByAge[0]
return (first6Days + day6 + day7 + day8).toTypedArray()
}
} | 0 | Kotlin | 0 | 0 | 93363faee195d5ef90344a4fb74646d2d26176de | 1,314 | AdventOfCode2021 | MIT License |
year2023/day05/almanac/src/main/kotlin/com/curtislb/adventofcode/year2023/day05/almanac/CategoryMap.kt | curtislb | 226,797,689 | false | {"Kotlin": 2146738} | package com.curtislb.adventofcode.year2023.day05.almanac
import com.curtislb.adventofcode.common.range.overlap
import com.curtislb.adventofcode.common.range.size
/**
* A map that provides rules converting values of one category to new values of another category.
*
* @property sourceCategory The category of values that can be converted by this map.
* @property targetCategory The category of new values that are produced by this map.
* @property mappedRanges A list of pairs, where each pair `(sourceValues, targetValues)` defines a
* range of `sourceValues` that are mapped to corresponding `targetValues`.
*
* @constructor Creates a new instance of [CategoryMap] with the given [sourceCategory],
* [targetCategory], and [mappedRanges].
*/
class CategoryMap(
val sourceCategory: String,
val targetCategory: String,
private val mappedRanges: List<Pair<LongRange, LongRange>>
) {
init {
for (mappedRange in mappedRanges) {
require(mappedRange.first.size() == mappedRange.second.size()) {
"Mapped ranges must be of equal size: $mappedRanges"
}
}
}
/**
* Returns the values that result from converting the given [values] from [sourceCategory] to
* [targetCategory].
*/
fun convertValues(values: List<Long>): List<Long> {
val convertedValues = values.toMutableList()
convertedValues.forEachIndexed { index, value ->
for ((sourceRange, targetRange) in mappedRanges) {
if (value in sourceRange) {
convertedValues[index] = value + targetRange.first - sourceRange.first
break
}
}
}
return convertedValues
}
/**
* Returns the value ranges that result from converting the given value [ranges] from
* [sourceCategory] to [targetCategory].
*/
fun convertRanges(ranges: Set<LongRange>): Set<LongRange> {
val convertedRanges = mutableSetOf<LongRange>()
for (range in ranges) {
// Search for a mapped range that intersects the source range
var isMapped = false
for (mappedRange in mappedRanges) {
val newRanges = applyRangeMapping(range, mappedRange)
if (newRanges.size != 1 || newRanges[0] != range) {
convertedRanges.addAll(newRanges)
isMapped = true
break
}
}
// If no intersecting range is found, add the source range as-is
if (!isMapped) {
convertedRanges.add(range)
}
}
return convertedRanges
}
override fun toString(): String = buildString {
appendLine("$sourceCategory-to-$targetCategory map:")
for ((sourceRange, targetRange) in mappedRanges) {
appendLine("${targetRange.first} ${sourceRange.first} ${sourceRange.size()}")
}
}
/**
* Returns the value ranges that result from mapping all values in the specified [range] that
* intersect with the given [mappedRange] to their corresponding mapped values.
*/
private fun applyRangeMapping(
range: LongRange,
mappedRange: Pair<LongRange, LongRange>
): List<LongRange> {
// Find overlap between range and the mapped source range
val (sourceRange, targetRange) = mappedRange
val sourceOverlap = range overlap sourceRange
if (sourceOverlap.isEmpty()) {
return listOf(range)
}
// Create new ranges with overlapping values mapped to their destination
val targetOverlapStart = targetRange.first + (sourceOverlap.first - sourceRange.first)
val targetOverlapEnd = targetRange.last - (sourceRange.last - sourceOverlap.last)
val newRanges = listOf(
range.first..<sourceOverlap.first,
(sourceOverlap.last + 1)..range.last,
targetOverlapStart..targetOverlapEnd
)
// Remove empty ranges from the output
return newRanges.filter { !it.isEmpty() }
}
companion object {
/**
* A regex used to parse the source and target categories of a category map from its title.
*/
private val TITLE_REGEX = Regex("""(\w+)-to-(\w+) map:""")
/**
* A regex used to parse a single mapped range for a category map.
*/
private val MAPPING_REGEX = Regex("""\s*(\d+)\s+(\d+)\s+(\d+)\s*""")
/**
* Returns a [CategoryMap] with [sourceCategory], [targetCategory], and [mappedRanges] read
* from the given [lines] of text.
*
* The [lines] must have the following format:
*
* ```
* $sourceCategory-to-$targetCategory map:
* $dst1 $src1 $len1
* $dst2 $src2 $len2
* ...
* $dstN $srcN $lenN
* ```
*
* The resulting [CategoryMap] will have a list of [mappedRanges] equal to
* `Pair(srcX..<(srcX + lenX), dstX..<(dstX + lenX))` for each `X` in `1..N`.
*
* @throws IllegalArgumentException If [lines] are not formatted correctly.
*/
fun fromLines(lines: List<String>): CategoryMap {
require(lines.isNotEmpty()) { "Lines list must be non-empty" }
// Read the source and target category from the first line
val titleMatchResult = TITLE_REGEX.matchEntire(lines[0])
require(titleMatchResult != null) { "Malformed category map title: ${lines[0]}" }
val (sourceCategory, targetCategory) = titleMatchResult.destructured
// Read all mapped ranges from subsequent lines
val mappedRanges = mutableListOf<Pair<LongRange, LongRange>>()
for (index in 1..lines.lastIndex) {
val mappingMatchResult = MAPPING_REGEX.matchEntire(lines[index])
require(mappingMatchResult != null) { "Malformed mapping entry: ${lines[index]}" }
// Convert start + length representation to ranges
val (targetString, sourceString, sizeString) = mappingMatchResult.destructured
val sourceStart = sourceString.toLong()
val targetStart = targetString.toLong()
val rangeSize = sizeString.toLong()
val sourceRange = sourceStart..<(sourceStart + rangeSize)
val targetRange = targetStart..<(targetStart + rangeSize)
mappedRanges.add(sourceRange to targetRange)
}
return CategoryMap(sourceCategory, targetCategory, mappedRanges)
}
}
}
| 0 | Kotlin | 1 | 1 | 6b64c9eb181fab97bc518ac78e14cd586d64499e | 6,683 | AdventOfCode | MIT License |
src/Day04_part2.kt | abeltay | 572,984,420 | false | {"Kotlin": 91982, "Shell": 191} | fun main() {
fun part2(input: List<String>): Int {
fun hasOverlap(elf1: Pair<Int, Int>, elf2: Pair<Int, Int>): Boolean {
if (elf2.first < elf1.first) {
return hasOverlap(elf2, elf1)
}
if (elf2.first <= elf1.second) {
return true
}
return false
}
val inputLineRegex = """(\d+)-(\d+),(\d+)-(\d+)""".toRegex()
var answer = 0
for (it in input) {
val (pair11, pair12, pair21, pair22) = inputLineRegex
.matchEntire(it)
?.destructured
?: throw IllegalArgumentException("Incorrect input line $it")
val elf1 = Pair(pair11.toInt(), pair12.toInt())
val elf2 = Pair(pair21.toInt(), pair22.toInt())
if (hasOverlap(elf1, elf2)) {
answer++
}
}
return answer
}
val testInput = readInput("Day04_test")
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | a51bda36eaef85a8faa305a0441efaa745f6f399 | 1,068 | advent-of-code-2022 | Apache License 2.0 |
src/adventofcode/blueschu/y2017/day06/solution.kt | blueschu | 112,979,855 | false | null | package adventofcode.blueschu.y2017.day06
import java.io.File
import kotlin.test.assertEquals
fun input(): List<Byte> {
return File("resources/y2017/day06.txt")
.bufferedReader()
.use { it.readText() }
.trim()
.split(Regex("\\s+"))
// only 119 blocks in input, might as well save some memory by using bytes
.map { it.toByte() }
}
fun main(args: Array<String>) {
// [findAllocationLoop] has been extended to produce the solutions for both parts of the puzzle
assertEquals(AllocationLoop(2, 1), findAllocationLoop(listOf(0)))
assertEquals(AllocationLoop(5, 4), findAllocationLoop(listOf(0, 2, 7, 0)))
println("Solution: ${findAllocationLoop(input())}")
}
// for part 1
class MemoryBanks(private val memory: ByteArray) {
constructor(memoryBanks: List<Byte>) : this(memoryBanks.toByteArray())
val image get() = memory.toList()
fun reallocate() {
val largestBankIndex = mostPopulatedBankIndex()
var blockCount = memory[largestBankIndex] // blocks in the largest bank
var seekingIndex = (largestBankIndex + 1) % memory.size
memory[largestBankIndex] = 0 // empty the selected bank of all blocks
while (blockCount > 0) {
memory[seekingIndex]++
seekingIndex = (seekingIndex + 1) % memory.size
blockCount--
}
}
private fun mostPopulatedBankIndex(): Int {
var maxVal = Byte.MIN_VALUE
var maxIndex = 0
for ((index, value) in memory.withIndex()) {
if (value > maxVal) {
maxVal = value
maxIndex = index
}
}
return maxIndex
}
}
fun findAllocationLoop(initialMemoryBanks: List<Byte>): AllocationLoop {
val memory = MemoryBanks(initialMemoryBanks)
val previousStates = mutableSetOf<List<Byte>>()
var cycleCount = 0
while (true) {
cycleCount++
val currentImage = memory.run {
reallocate()
image
}
if (currentImage in previousStates) {
return AllocationLoop(cycleCount, determineLoopLength(currentImage))
}
previousStates.add(currentImage)
}
}
// added for part 2
data class AllocationLoop(val startsAfterCycles: Int, val lastsCycles: Int)
fun determineLoopLength(memoryAtLoopStart: List<Byte>): Int {
val memory = MemoryBanks(memoryAtLoopStart)
var cycleCount = 0
while (true) {
cycleCount++
val currentImage = memory.run {
reallocate()
image
}
if (currentImage == memoryAtLoopStart) {
return cycleCount
}
}
}
| 0 | Kotlin | 0 | 0 | 9f2031b91cce4fe290d86d557ebef5a6efe109ed | 2,674 | Advent-Of-Code | MIT License |
src/2023/Day14.kt | nagyjani | 572,361,168 | false | {"Kotlin": 369497} | package `2023`
import java.io.File
import java.lang.StringBuilder
import java.util.*
fun main() {
Day14().solve()
}
class Day14 {
val input1 = """
O....#....
O.OO#....#
.....##...
OO.#O....O
.O.....O#.
O.#..O.#.#
..O..#O..O
.......O..
#....###..
#OO..#....
""".trimIndent()
val input2 = """
""".trimIndent()
fun List<String>.transpose(): List<String> {
val r = List(this[0].length){ StringBuilder() }
forEachIndexed{ ix1, it1 -> it1.forEachIndexed{ ix2, it2 -> r[ix2].append(it2) } }
return r.map { it.toString() }
}
fun List<String>.reverse(): List<String> {
return map { it.reversed() }
}
fun List<String>.tilt(): List<String> {
return map { l -> l.split('#').map { chunk -> chunk.toCharArray().sortedBy { when (it) {'O' -> 0; else -> 1} }.joinToString("") }.joinToString("#")}
}
fun List<String>.fullCycle(): Pair<List<String>, Int> {
val n = tilt()
val w = n.transpose().tilt()
val s = w.transpose().reverse().tilt()
val e = s.transpose().reverse().tilt()
val n1 = e.reverse().transpose().reverse()
val load = n1.load()
return n1 to load
}
fun List<String>.load(): Int {
return map {
it.mapIndexed{ix, it ->
if (it == 'O') get(0).length - ix else 0
}.sum()
}.sum()
}
fun List<String>.print() {
val e = joinToString("\n")
print("$e\n")
}
fun solve() {
val f = File("src/2023/inputs/day14.in")
val s = Scanner(f)
// val s = Scanner(input1)
// val s = Scanner(input2)
var sum = 0
var sum1 = 0
var lineix = 0
val lines = mutableListOf<String>()
while (s.hasNextLine()) {
lineix++
val line = s.nextLine().trim()
if (line.isEmpty()) {
continue
}
lines.add(line)
}
val map0 = lines.toList().transpose()
val t = map0.fullCycle()
val m = mutableMapOf<String, Pair<Int, Int>>()
var map = map0
var periodStart = 0
var period = 0
for (i in 1 .. 10000) {
val t = map.fullCycle()
map = t.first
val k = map.joinToString("")
if (i == 98) {
println("${t.second}")
}
if (m.contains(k)) {
print("!!! $i")
period = i - m[k]!!.first
periodStart = i - period
break
} else {
m[k] = i to t.second
}
}
val e = (1000000000 - periodStart) % period + periodStart
t.first.transpose().print()
print("$e $sum $sum1 ${map0.tilt().load()}")
}
} | 0 | Kotlin | 0 | 0 | f0c61c787e4f0b83b69ed0cde3117aed3ae918a5 | 2,908 | advent-of-code | Apache License 2.0 |
src/main/kotlin/dp/maximalSquare/SolutionKt.kt | eleven-max | 441,597,605 | false | {"Java": 104251, "Kotlin": 41506} | package dp.maximalSquare
import com.evan.dynamicprogramming.Common.CommonUtil
//https://leetcode-cn.com/problems/maximal-square/
class SolutionKt {
fun maximalSquare(matrix: Array<CharArray>): Int {
val dp = Array(matrix.size) { IntArray(matrix[0].size) { 0 } }
var r = 0
//第一行
for (i in 0 until matrix[0].size) {
dp[0][i] = if ('1' == matrix[0][i]) 1 else 0
r = Math.max(r, dp[0][i])
}
CommonUtil.printMatrix(dp)
//第一列
for (i in 1 until matrix.size) {
dp[i][0] = if ('1' == matrix[i][0]) 1 else 0
r = Math.max(r, dp[i][0])
}
for (i in 1 until matrix.size) {
for (j in 1 until matrix[0].size) {
if ('0' == matrix[i][j]) {
dp[i][j] = 0
} else {
dp[i][j] = Math.min(Math.min(dp[i][j - 1], dp[i - 1][j]), dp[i - 1][j - 1]) + 1
}
r = Math.max(r, dp[i][j])
}
}
CommonUtil.printMatrix(dp)
return r
}
}
fun main() {
val matrix: Array<CharArray> = arrayOf(charArrayOf('1'), charArrayOf('0'))
val solutionKt = SolutionKt()
solutionKt.maximalSquare(matrix)
} | 0 | Java | 0 | 0 | 2e9b234b052896c6b8be07044d2b0c6812133e66 | 1,265 | Learn_Algorithm | Apache License 2.0 |
src/Day02.kt | Pixselve | 572,907,486 | false | {"Kotlin": 7404} | fun main() {
/**
* First: A for Rock, B for Paper, and C for Scissors
* Second: X for Rock, Y for Paper, and Z for Scissors
*
* A beats Z
* B beats X
* C beats Y
*
*/
fun pointPerPair(pair: Pair<Char, Char>): Int {
return when (pair.second) {
'X' -> 1 +
when (pair.first) {
'A' -> 3
'B' -> 0
'C' -> 6
else -> throw IllegalArgumentException("Invalid input")
}
'Y' -> 2 +
when (pair.first) {
'A' -> 6
'B' -> 3
'C' -> 0
else -> throw IllegalArgumentException("Invalid input")
}
'Z' -> 3 +
when (pair.first) {
'A' -> 0
'B' -> 6
'C' -> 3
else -> throw IllegalArgumentException("Invalid input")
}
else -> throw IllegalArgumentException("Invalid input")
}
}
/**
* X means you need to lose, Y means you need to end the round in a draw, and Z means you need to win.
*/
fun pointPerPairSecondRule(pair: Pair<Char, Char>): Int {
return when (pair.second) {
// X means you need to lose
'X' -> 0 +
when (pair.first) {
'A' -> 3 // A beats Z
'B' -> 1 // B beats X
'C' -> 2 // C beats Y
else -> throw IllegalArgumentException("Invalid input")
}
// Y means you need to end the round in a draw
'Y' -> 3 +
when (pair.first) {
'A' -> 1
'B' -> 2
'C' -> 3
else -> throw IllegalArgumentException("Invalid input")
}
// Z means you need to win.
'Z' -> 6 +
when (pair.first) {
'A' -> 2
'B' -> 3
'C' -> 1
else -> throw IllegalArgumentException("Invalid input")
}
else -> throw IllegalArgumentException("Invalid input")
}
}
fun part1(input: List<Pair<Char, Char>>): Int {
return input.fold(0) { acc, pair -> acc + pointPerPair(pair) }
}
fun part2(input: List<Pair<Char, Char>>): Int {
return input.fold(0) { acc, pair -> acc + pointPerPairSecondRule(pair) }
}
val testInput = readInput("Day02_test")
val parsedTestInput = testInput.map { it.split(" ") }.map { Pair(it[0].first(), it[1].first()) }
check(part1(parsedTestInput) == 15)
val input = readInput("Day02")
val parsedInput = input.map { it.split(" ") }.map { Pair(it[0].first(), it[1].first()) }
check(part1(parsedTestInput) == 15)
check(part2(parsedTestInput) == 12)
println(part1(parsedInput))
println(part2(parsedInput))
} | 0 | Kotlin | 0 | 0 | 10e14393b8b6ee3f98dfd4c37e32ad81f9952533 | 3,188 | advent-of-code-2022-kotlin | Apache License 2.0 |
2022/src/main/kotlin/org/suggs/adventofcode/Day12HillClimbing.kt | suggitpe | 321,028,552 | false | {"Kotlin": 156836} | package org.suggs.adventofcode
import org.slf4j.LoggerFactory
object Day12HillClimbing {
private val log = LoggerFactory.getLogger(this::class.java)
// ====== DEPTH FIRST
fun findShortestDepthFirstRouteToEnd(grid: List<List<Char>>): Int {
val startEnd = findStartAndEndFrom(grid)
log.debug("start=${startEnd.first} end=${startEnd.second}")
return countStepsToEndFrom(startEnd.first, grid, setOf(), 0).min()
}
private fun countStepsToEndFrom(start: CoOrdinate, grid: List<List<Char>>, visited: Set<CoOrdinate>, stepCount: Int): List<Int> {
val neighbours = findHigherNeighboursFrom(start, grid, visited).sortedByDescending { it.x }
val foo = mutableListOf<Int>()
neighbours.forEach {
foo.addAll(countStepsToEndFrom(it, grid, visited + start, stepCount + 1))
}
return when {
gridValue(start, grid) == 'E' -> listOf(stepCount) + foo
else -> foo
}
}
// ======= BREADTH FIRST
fun findShortestBreadthFirstRouteToEnd(grid: List<List<Char>>): Int {
val startEnd = findStartAndEndFrom(grid).also { log.debug("start=${it.first} end=${it.second}") }
return plotRoutesFor(setOf(startEnd.first), setOf(), grid, 0)
}
private fun plotRoutesFor(coordinates: Set<CoOrdinate>, visited: Set<CoOrdinate>, grid: List<List<Char>>, depth: Int): Int {
return when {
coordinates.isEmpty() -> throw IllegalStateException("No more routes found after step $depth")
coordinates.contains(findInGrid('E', grid)) -> depth
else ->
plotRoutesFor(coordinates.flatMap { findHigherNeighboursFrom(it, grid, visited) }.toSet(), visited union coordinates, grid, depth + 1)
}
}
private fun findHigherNeighboursFrom(start: CoOrdinate, grid: List<List<Char>>, visited: Set<CoOrdinate>): Set<CoOrdinate> {
return if (gridValue(start, grid).code == 'S'.code)
start.allNeighbours()
else
start.allNeighbours()
.filter { it.x < grid[0].size && it.y < grid.size }
.filter { gridValue(it, grid) - gridValue(start, grid) in 0..1 || (gridValue(start, grid) == 'z' && gridValue(it, grid) == 'E') }
.filterNot { visited.contains(it) }
.toSet()
}
private fun gridValue(coordinate: CoOrdinate, grid: List<List<Char>>) =
grid[coordinate.y][coordinate.x]
private fun findStartAndEndFrom(grid: List<List<Char>>): Pair<CoOrdinate, CoOrdinate> =
findInGrid('S', grid) to findInGrid('E', grid)
private fun findInGrid(char: Char, grid: List<List<Char>>): CoOrdinate {
val y = grid.indexOfFirst { it.contains(char) }
return CoOrdinate(grid[y].indexOf(char), y)
}
data class CoOrdinate(val x: Int, val y: Int) {
fun allNeighbours(): Set<CoOrdinate> {
return setOf(up(), left(), right(), down()).filterNot { it.x < 0 || it.y < 0 }.toSet()
}
private fun up() = CoOrdinate(x, y - 1)
private fun left() = CoOrdinate(x - 1, y)
private fun right() = CoOrdinate(x + 1, y)
private fun down() = CoOrdinate(x, y + 1)
override fun toString() = "($x/$y)"
}
}
| 0 | Kotlin | 0 | 0 | 9485010cc0ca6e9dff447006d3414cf1709e279e | 3,267 | advent-of-code | Apache License 2.0 |
src/me/bytebeats/algo/kt/Solution6.kt | bytebeats | 251,234,289 | false | null | package me.bytebeats.algo.kt
import kotlin.collections.ArrayList
import me.bytebeats.algs.ds.ListNode
import me.bytebeats.algs.ds.Node
import me.bytebeats.algs.ds.TreeNode
class Solution6 {
fun nextGreatestLetter(letters: CharArray, target: Char): Char {//744, O(n)
var index = -1
for (i in letters.indices) {
if (letters[i] > target) {
index = i
break
}
}
return if (index > -1) letters[index] else letters[0]
}
fun nextGreatestLetter1(letters: CharArray, target: Char): Char {//744, O(logn)
var low = 0
var high = letters.size
var mid = 0
while (low < high) {
mid = low + (high - low) / 2
if (letters[mid] <= target) low = mid + 1
else high = mid
}
return letters[low % letters.size]
}
fun isToeplitzMatrix(matrix: Array<IntArray>): Boolean {//766
if (matrix.isNotEmpty() && matrix[0].isNotEmpty()) {
for (i in matrix.indices) {
for (j in matrix[0].indices) {
if (i > 0 && j > 0 && matrix[i][j] != matrix[i - 1][j - 1]) {
return false
}
}
}
}
return true
}
private val visited = mutableMapOf<Node, Node>()
fun cloneGraph(node: Node?): Node? {//133
if (node == null) {
return null
}
if (visited.containsKey(node)) {
return visited[node]
}
val cloned = Node(node.`val`)
cloned.neighbors = ArrayList()
visited[node] = cloned
if (node.neighbors != null) {
for (neighbor in node.neighbors!!) {
cloned?.neighbors?.add(cloneGraph(neighbor))
}
}
return cloned
}
fun validWordSquare(words: List<String>): Boolean {//422
if (words.isNotEmpty()) {
val row = words.size
val column = words.map { it.length }.maxOfOrNull { it }
if (row != column) {
return false
}
for (i in 0 until row) {
if (words[i].length != row) {
val sb = StringBuilder(words[i])
for (j in 0 until row - words[i].length) {
sb.append("0")
}
}
}
}
return true
}
fun removeKdigits(num: String, k: Int): String {//402
if (num.isEmpty() || num.length <= k) {
return "0"
}
if (k <= 0) {
return num
}
var ans = StringBuilder()
ans.append(num)
var count = k
var index = -1
while (count-- > 0) {
index = -1
for (i in 0 until ans.length - 1) {
if (ans[i] > ans[i + 1]) {
index = i
break
}
}
ans.deleteCharAt(if (index == -1) ans.lastIndex else index)
}
while (ans.isNotEmpty() && ans.first() == '0') {
ans.deleteCharAt(0)
}
if (ans.isEmpty()) {
ans.append('0')
}
return ans.toString()
}
// fun maxNumber(nums1: IntArray, nums2: IntArray, k: Int): IntArray {//321
//
// }
fun monotoneIncreasingDigits(N: Int): Int {//738
val chs = N.toString().toCharArray()
var i = -1
for (j in 0 until chs.lastIndex) {
if (chs[j] > chs[j + 1]) {
i = j
break
}
}
if (i == -1) {
return N
}
while (i > 0 && chs[i] == chs[i - 1]) {
i--
}
chs[i]--
for (j in i + 1 until chs.size) {
chs[j] = '9'
}
return String(chs).toInt()
}
fun letterCasePermutation(S: String): List<String> {//784
val ans = mutableListOf<String>()
val sb = StringBuilder(S)
return ans
}
fun areSentencesSimilar(words1: Array<String>, words2: Array<String>, pairs: List<List<String>>): Boolean {//734
if (words1.size != words2.size) {
return false
}
for (i in words1.indices) {
if (words1[i] == words2[i]) {
continue
} else {
var flag = false
for (j in pairs.indices) {
if (pairs[j][0] == words1[i] && pairs[j][1] == words2[i] || pairs[j][1] == words1[i] && pairs[j][0] == words2[i]) {
flag = true
break
}
}
if (!flag) {
return false
}
}
}
return true
}
fun areSentencesSimilarTwo(words1: Array<String>, words2: Array<String>, pairs: List<List<String>>): Boolean {//737
if (words1.size != words2.size) {
return false
}
val graph = mutableMapOf<String, MutableList<String>>()
for (pair in pairs) {
for (word in pair) {
if (!graph.containsKey(word)) {
graph[word] = mutableListOf()
}
}
graph[pair[0]]?.add(pair[1])
graph[pair[1]]?.add(pair[0])
}
var word1 = ""
var word2 = ""
for (i in words1.indices) {
word1 = words1[i]
word2 = words2[i]
val stack = mutableListOf<String>()
val seen = mutableSetOf<String>()
stack.add(word1)
seen.add(word1)
search@ while (stack.isNotEmpty()) {
val word = stack.removeAt(stack.lastIndex)
if (word == word2) break@search
if (graph.containsKey(word)) {
for (similar in graph[word]!!) {
if (!seen.contains(similar)) {
stack.add(similar)
seen.add(similar)
}
}
}
if (stack.isEmpty()) {
return false
}
}
}
return true
}
fun replaceWords(dict: List<String>, sentence: String): String {//648
val words = sentence.split(" ")
val ans = StringBuilder()
for (word in words) {
val roots = dict.filter { word.length > it.length && word.startsWith(it) }
if (roots.isEmpty()) {
ans.append(word)
ans.append(" ")
} else {
ans.append(roots.sortedBy { it.length }.first())
ans.append(" ")
}
}
return ans.trim().toString()
}
fun subarraysDivByK(A: IntArray, K: Int): Int {//974
var ans = 0
val size = A.size
A[0] %= K
for (i in 1 until size) {
A[i] = (A[i] + A[i - 1]) % K
}
val count = IntArray(K)
count[0]++
for (num in A) {
count[(num % K + K) % K]++
}
for (c in count) {
ans += c * (c - 1) / 2
}
return ans
}
fun maxSubarraySumCircular(A: IntArray): Int {//918
val s = A.size
var ans = A[0]
var cur = A[0]
for (i in 1 until s) {
cur = A[i] + Math.max(cur, 0)
ans = Math.max(ans, cur)
}
val rightSums = IntArray(s)
rightSums[s - 1] = A[s - 1]
for (i in s - 2 downTo 0) {
rightSums[i] = rightSums[i + 1] + A[i]
}
val maxRight = IntArray(s)
maxRight[s - 1] = rightSums[s - 1]
for (i in s - 2 downTo 0) {
maxRight[i] = Math.max(maxRight[i + 1], rightSums[i])
}
var leftSum = 0
for (i in 0 until s - 2) {
leftSum += A[i]
ans = Math.max(ans, leftSum + maxRight[i + 2])
}
return ans
}
/**
* 连续子数组的最大值
*/
fun kadane(A: IntArray): Int {
var curVal = A[0]
var ans = A[0]
for (i in 1 until A.size) {
curVal = Math.max(A[i], curVal + A[i])
ans = Math.max(ans, curVal)
}
return ans
}
fun sumEvenAfterQueries(A: IntArray, queries: Array<IntArray>): IntArray {//985
val ans = IntArray(queries.size)
var sum = A.filter { it and 1 == 0 }.sum()
for (i in queries.indices) {
if (A[queries[i][1]] and 1 == 0) {
sum -= A[queries[i][1]]
}
A[queries[i][1]] += queries[i][0]
if (A[queries[i][1]] and 1 == 0) {
sum += A[queries[i][1]]
}
ans[i] = sum
}
return ans
}
fun isMonotonic(A: IntArray): Boolean {//896
var asd = false
var desc = false
for (i in 1 until A.size) {
if (A[i - 1] < A[i]) {
asd = true
}
if (A[i - 1] > A[i]) {
desc = true
}
if (asd && desc) {
return false
}
}
return true
}
fun countSubstrings(s: String): Int {//647
var ans = 0
for (i in s.indices) {
var j = i
while (j < s.length && s[i] == s[j]) {
ans++
j++
}
var k = i - 1
while (k > -1 && j < s.length && s[k] == s[j]) {
k--
j++
ans++
}
}
return ans
}
// fun subsetsWithDup(nums: IntArray): List<List<Int>> {//90
//
// }
/**
* K 个一组逆序链表
*1->2->3->4->5 ==> 3->2->1->4->5
* @param head
* @param k
* @return
*/
fun reverseKGroup(head: ListNode?, k: Int): ListNode? {//25
val dummy = ListNode(-1)
dummy.next = head
var pre: ListNode? = dummy
var end: ListNode? = dummy
while (end?.next != null) {
var count = 0
while (count < k && end != null) {
end = end.next
count++
}
if (end == null) break
var start = pre?.next
var next = end?.next
end?.next = null
pre?.next = reverse(start)
start?.next = next
pre = start
end = pre
}
return dummy.next
}
private fun reverse(head: ListNode?): ListNode? {
var pre: ListNode? = null
var p = head
while (p != null) {
val next = p.next
p.next = pre
pre = p
p = next
}
return pre
}
/**
* 将单链表平均分成 k 组
*/
fun splitListToParts(root: ListNode?, k: Int): Array<ListNode?> {//728
var count = 0
var p = root
while (p != null) {//计算链表长度
p = p.next
count++
}
val s = count / k//每组 s 个元素
var c = count % k//不能整除时, 余下的结点个数
val ans = Array<ListNode?>(k) { null }
p = root
for (i in 0 until k) {//k 组
ans[i] = p
var left = s
var pre = p
while (left-- > 0) {//每组分配的结点
pre = p
p = p?.next
}
if (c > 0) {//余下的结点个数, 分配到前 c 个元素
pre = p
p = p?.next
c--
}
pre?.next = null//将该组最后一个结点的引用去掉.
}
return ans
}
fun reorderList(head: ListNode?): Unit {//143
var count = 0
var p = head
while (p != null) {
count++
p = p.next
}
val half = (count + 1) / 2
var pre: ListNode? = null
p = head
var i = 0
while (i++ < half) {
pre = p
p = p?.next
}
pre?.next = null
p = reverse(p)
var q = head
while (p != null) {
val next = q?.next
q?.next = p
p = p.next
q?.next?.next = next
q = next
}
}
fun addTwoNumbers(l1: ListNode?, l2: ListNode?): ListNode? {//面试题02.05
var count1 = 0
var p = l1
while (p != null) {
count1++
p = p.next
}
var count2 = 0
var q = l2
while (q != null) {
count2++
q = q.next
}
if (count1 > count2) {
p = l1
q = l2
} else {
p = l2
q = l1
}
val head = p
var c = 0
var pre: ListNode? = null
while (p != null && q != null) {
p.`val` += q.`val` + c
c = p.`val` / 10
p.`val` %= 10
pre = p
p = p.next
q = q.next
}
while (c != 0) {
if (p != null) {
p.`val` += c
c = p.`val` / 10
p.`val` %= 10
pre = p
} else {
pre?.next = ListNode(c)
break
}
}
return head
}
fun getKthFromEnd(head: ListNode?, k: Int): ListNode? {//面试题22
var count = 0
var p = head
while (p != null) {
p = p.next
count++
}
var diff = count - k
if (diff < 0) {
return null
}
p = head
while (diff-- > -1) {
p = p?.next
}
return p
}
fun maxPower(s: String): Int {//5396
var max = 1
var ch = s[0]
var count = 1
for (i in 1 until s.length) {
if (ch == s[i]) {
count++
if (max < count) {
max = count
}
} else {
ch = s[i]
count = 1
}
}
return max
}
fun simplifiedFractions(n: Int): List<String> {//5397,1447
val ans = mutableListOf<String>()
for (i in 2..n) {
for (j in 1 until i) {
if (j == 1 || gcd(i, j) == 1) {
ans.add("$j/$i")
}
}
}
return ans
}
private fun gcd(m: Int, n: Int): Int {
var j = m
var k = n
var rem = 0
while (k != 0) {
rem = j % k
j = k
k = rem
}
return j
}
var count = 0
fun goodNodes(root: TreeNode?): Int {//5398, 1448
count = 0
goodNodes(root, 0, true)
return count
}
private fun goodNodes(root: TreeNode?, max: Int, isRoot: Boolean) {
if (root == null) {
return
}
if (isRoot) {
count++
goodNodes(root.left, root.`val`, false)
goodNodes(root.right, root.`val`, false)
} else {
if (root.`val` >= max) {
count++
}
val newMax = Math.max(root.`val`, max)
goodNodes(root.left, newMax, false)
goodNodes(root.right, newMax, false)
}
}
var ans = "0"
fun largestNumber(cost: IntArray, target: Int): String {//5399
ans = "0"
val map = sortedMapOf<Int, Int>()
for (i in 8 downTo 0) {
if (!map.containsValue(cost[i])) {
map[i] = cost[i]
}
}
largestNumber(map.entries.reversed(), target, StringBuilder())
return ans
}
private fun largestNumber(cost: List<MutableMap.MutableEntry<Int, Int>>, target: Int, sb: StringBuilder) {
if (target < 0) {
return
} else if (target == 0) {
if (ans.length < sb.length) {
ans = sb.toString()
} else if (ans.length == sb.length) {
if (ans < sb.toString()) {
ans = sb.toString()
}
}
} else {
cost.forEach {
if (it.value <= target) {
val newSb = StringBuilder(sb)
newSb.append(it.key + 1)
largestNumber(cost, target - it.value, newSb)
}
}
}
}
fun busyStudent(startTime: IntArray, endTime: IntArray, queryTime: Int): Int {//5412, 1450
var count = 0
for (i in startTime.indices) {
if (queryTime in startTime[i]..endTime[i]) {
count++
}
}
return count
}
fun arrangeWords(text: String): String {//5413, 1451
val ans = StringBuilder()
val words = text.split(" ").sortedBy { it.length }
for (i in words.indices) {
if (i == 0) {
val sb = StringBuilder(words[i])
sb[0] = sb[0].toUpperCase()
ans.append(sb)
} else {
ans.append(" ")
if (words[i][0].isUpperCase()) {
ans.append(words[i].toLowerCase())
} else {
ans.append(words[i])
}
}
}
return ans.toString()
}
fun peopleIndexes(favoriteCompanies: List<List<String>>): List<Int> {//5414, 1452
var set = mutableSetOf<Int>()
for (i in 0 until favoriteCompanies.lastIndex) {
for (j in i + 1 until favoriteCompanies.size) {
if (favoriteCompanies[i].size > favoriteCompanies[j].size
&& contains(favoriteCompanies[i], favoriteCompanies[j])
) {
set.add(j)
} else if (favoriteCompanies[i].size < favoriteCompanies[j].size
&& contains(favoriteCompanies[j], favoriteCompanies[i])
) {
set.add(i)
}
}
}
val ans = mutableListOf<Int>()
for (i in favoriteCompanies.indices) {
ans.add(i)
}
ans.removeAll(set)
return ans
}
private fun contains(long: List<String>, short: List<String>): Boolean {
for (i in short.indices) {
if (!long.contains(short[i])) {
return false
}
}
return true
}
fun canFinish(numCourses: Int, prerequisites: Array<IntArray>): Boolean {//207
val inDegrees = IntArray(numCourses)
val graph = mutableMapOf<Int, MutableList<Int>>()
for (prerequisite in prerequisites) {
inDegrees[prerequisite[0]]++
if (graph.containsKey(prerequisite[1])) {
graph[prerequisite[1]]?.add(prerequisite[0])
} else {
val dependencies = mutableListOf<Int>()
dependencies.add(prerequisite[0])
graph[prerequisite[1]] = dependencies
}
}
val q = mutableListOf<Int>()
for (i in 0 until numCourses) {
if (inDegrees[i] == 0) q.add(i)
}
while (q.isNotEmpty()) {
val cur = q.removeAt(0)
graph[cur]?.apply {
for (i in 0 until size) {
inDegrees[this[i]]--
if (inDegrees[this[i]] == 0) {
q.add(this[i])
}
}
}
}
for (i in 0 until numCourses) {
if (inDegrees[i] != 0) return false
}
return true
}
fun findOrder(numCourses: Int, prerequisites: Array<IntArray>): IntArray {//210
val inDegrees = IntArray(numCourses) { 0 }
val graph = mutableMapOf<Int, MutableList<Int>>()
for (prerequisite in prerequisites) {
inDegrees[prerequisite[0]]++
if (graph.containsKey(prerequisite[1])) {
graph[prerequisite[1]]?.add(prerequisite[0])
} else {
val dependencies = mutableListOf<Int>()
dependencies.add(prerequisite[0])
graph[prerequisite[1]] = dependencies
}
}
val ans = mutableListOf<Int>()
val q = mutableListOf<Int>()//used as queue
for (i in 0 until numCourses) {
if (inDegrees[i] == 0) q.add(i)
}
while (q.isNotEmpty()) {
val cur = q.removeAt(0)
ans.add(cur)
graph[cur]?.apply {
for (i in 0 until size) {
inDegrees[this[i]]--
if (inDegrees[this[i]] == 0) {
q.add(this[i])
}
}
}
}
return if (ans.size == numCourses) ans.toIntArray() else IntArray(0)
}
fun findAnagrams(s: String, p: String): List<Int> {//438
val ans = mutableListOf<Int>()
if (s.isNotEmpty() && s.length >= p.length) {
val pChs = IntArray(26) { 0 }
for (element in p) {
pChs[element - 'a']++
}
val sChs = IntArray(26) { 0 }
for (i in 0 until p.lastIndex) {
sChs[s[i] - 'a']++
}
for (i in p.lastIndex until s.length) {
sChs[s[i] - 'a']++
if (isEqual(pChs, sChs)) {
ans.add(i - p.length + 1)
}
sChs[s[i - p.length + 1] - 'a']--
}
}
return ans
}
private fun isEqual(s: IntArray, p: IntArray): Boolean {
for (i in s.indices) {
if (s[i] != p[i]) {
return false
}
}
return true
}
fun uncommonFromSentences(A: String, B: String): Array<String> {//884
val amap = mutableMapOf<String, Int>()
A.split(" ").forEach { amap.compute(it) { _, v -> if (v == null) 1 else v + 1 } }
val bmap = mutableMapOf<String, Int>()
B.split(" ").forEach { bmap.compute(it) { _, v -> if (v == null) 1 else v + 1 } }
val ans = mutableListOf<String>()
amap.entries.filter { it.value == 1 }.map { it.key }.forEach {
if (!bmap.containsKey(it)) {
ans.add(it)
}
}
bmap.entries.filter { it.value == 1 }.map { it.key }.forEach {
if (!amap.containsKey(it)) {
ans.add(it)
}
}
return ans.toTypedArray()
}
fun distributeCandies(candies: IntArray): Int {//575
val set = mutableSetOf<Int>()
val size = candies.size
for (i in 0 until size) {
set.add(candies[i])
if (set.size >= size / 2) {
return size / 2
}
}
return set.size
}
fun multiply(A: Array<IntArray>, B: Array<IntArray>): Array<IntArray> {//311
val rowA = A.size
val columnA = A[0].size
val rowB = B.size
val columnB = B[0].size
val ans = Array(rowA) { IntArray(columnB) }
for (i in 0 until rowA) {
for (j in 0 until columnB) {
for (k in 0 until rowB) {
ans[i][j] += A[i][k] * B[k][j]
}
}
}
return ans
}
fun numSubarrayProductLessThanK(nums: IntArray, k: Int): Int {//713
var ans = 0
if (nums.isNotEmpty() && k > 1) {//if k <= 1 return 0
var product = 1
var left = 0
for (right in nums.indices) {
product *= nums[right]
while (product >= k) product /= nums[left++]//essence!
ans += right - left + 1
}
}
return ans
}
fun twoSumLessThanK(A: IntArray, K: Int): Int {//1099
var sum = -1
if (A.size > 1) {
A.sort()
var i = 0
var j = A.lastIndex
var tmp = 0
while (i < j) {
tmp = A[i] + A[j]
if (tmp >= K) {
j--
} else {
if (tmp > sum) {
sum = tmp
}
i++
}
}
}
return sum
}
fun maxSubArrayLen(nums: IntArray, k: Int): Int {//325, prefix sum hashmap
var ans = 0
val preSums = mutableMapOf<Int, Int>()
preSums[0] = -1
var sum = 0
for (i in nums.indices) {
sum += nums[i]
if (preSums.containsKey(sum - k)) {
ans = Math.max(ans, i - preSums[sum - k]!!)
}
if (!preSums.containsKey(sum)) {
preSums[sum] = i
}
}
return ans
}
fun checkInclusion(s1: String, s2: String): Boolean {//567
if (s1.length > s2.length) {
return false
}
val ch1 = CharArray(26)
for (c in s1) {
ch1[c - 'a']++
}
val ch2 = CharArray(26)
for (i in 0 until s1.lastIndex) {
ch2[s2[i] - 'a']++
}
for (i in s1.lastIndex until s2.length) {
ch2[s2[i] - 'a']++
var flag = false
for (j in 0 until 26) {
if (ch1[j] != ch2[j]) {
flag = true
break
}
}
if (!flag) {
return true
}
ch2[s2[i - s1.length + 1] - 'a']--
}
return false
}
fun validPalindrome(s: String): Boolean {//680
var i = 0
var j = s.lastIndex
while (i < j) {
if (s[i] == s[j]) {
i++
j--
} else {
return validPalindrome(s, i + 1, j) || validPalindrome(s, i, j - 1)
}
}
return true
}
private fun validPalindrome(s: String, left: Int, right: Int): Boolean {//680
var i = left
var j = right
while (i < j) {
if (s[i] == s[j]) {
i++
j--
} else {
return false
}
}
return true
}
fun countSquares(matrix: Array<IntArray>): Int {//1277
var ans = 0
if (matrix.isNotEmpty()) {
val f = Array(matrix.size) { IntArray(matrix[0].size) { 0 } }
for (i in matrix.indices) {
for (j in matrix[0].indices) {
if (i == 0 || j == 0) {
f[i][j] = matrix[i][j]
} else if (matrix[i][j] == 0) {
f[i][j] = 0
} else {
f[i][j] = Math.min(Math.min(f[i][j - 1], f[i - 1][j]), f[i - 1][j - 1]) + 1
}
ans += f[i][j]
}
}
}
return ans
}
fun findLongestSubarray(array: Array<String>): Array<String> {//面试题17.05
var s = 0
var e = 0
var ans = 0
var count = 0
val size = array.size
val memo = IntArray((size shr 1) + 1) { -2 }
memo[size] = -1
for (i in array.indices) {
count += if (array[i][0].isLetter()) 1 else -1
if (memo[count + size] > -2) {
if (i - memo[count + size] > ans) {
s = memo[count + size] + 1
e = i + 1
ans = i - memo[count + size]
}
} else {
memo[count + size] = i
}
}
return array.copyOfRange(s, e)
}
fun frequencySort(s: String): String {//451
val map = sortedMapOf<Char, Int>()
for (c in s) {
map.compute(c) { _, v -> if (v == null) 1 else v + 1 }
}
val ans = StringBuilder()
map.entries.sortedByDescending { it.value }.map {
var k = it.value
while (k-- > 0) {
ans.append(it.key)
}
}
return ans.toString()
}
fun trailingZeroes(n: Int): Int {//面试题16.05
var ans = 0
var k = n
while (k > 1) {
k /= 5
ans++
}
return ans
}
fun findNumberIn2DArray(matrix: Array<IntArray>, target: Int): Boolean {// 面试题04
if (matrix.isNotEmpty() && matrix[0].isNotEmpty()) {
var i = 0
var j = matrix[0].lastIndex
while (i < matrix.size && j > -1) {
if (matrix[i][j] < target) {
i++
} else if (matrix[i][j] > target) {
j--
} else {
return true
}
}
}
return false
}
fun replaceSpace(s: String): String {//面试题05
val ans = StringBuilder()
for (c in s) {
if (c == ' ') {
ans.append("%20")
} else {
ans.append(c)
}
}
return ans.toString()
}
fun numWays(n: Int): Int {//面试题10-II
val MOD = 1_000_000_007
var pre = 1
var ans = 1
var tmp = 0
var k = n
while (k-- > 1) {
tmp = (pre + ans) % MOD
pre = ans
ans = tmp
}
return ans
}
fun minArray(numbers: IntArray): Int {//面试题11
var left = 0
var right = numbers.lastIndex
var mid = 0
while (left < right) {
mid = left + (right - left) / 2
if (numbers[mid] < numbers[right]) {
right = mid
} else if (numbers[mid] > numbers[right]) {
left = mid + 1
} else {
right--
}
}
return numbers[left]
}
fun firstUniqChar(s: String): Char {//面试题50
val map = mutableMapOf<Char, Int>()
for (c in s) {
map.compute(c) { _, v -> if (v == null) 1 else v + 1 }
}
val chs = map.entries.filter { it.value == 1 }.map { it.key }
if (chs.isNotEmpty()) {
for (i in s.indices) {
if (chs.contains(s[i])) {
return s[i]
}
}
}
return ' '
}
fun missingNumber(nums: IntArray): Int {//面试题53-II
var ans = 0
val size = nums.size
ans = ans xor size
for (i in nums.indices) {
ans = ans xor i
ans = ans xor nums[i]
}
return ans
}
fun printNumbers(n: Int): IntArray {//面试题17
var size = 1
for (i in 0 until n) {
size *= 10
}
val ans = IntArray(size - 1)
for (i in 0 until size - 1) {
ans[i] = i + 1
}
return ans
}
fun twoSum(nums: IntArray, target: Int): IntArray {//面试题57
val ans = IntArray(2) { -1 }
var i = 0
var j = nums.lastIndex
while (i < j) {
if (nums[i] + nums[j] > target) {
j--
} else if (nums[i] + nums[j] < target) {
i++
} else {
ans[0] = nums[i]
ans[1] = nums[j]
break
}
}
return ans
}
fun search(nums: IntArray, target: Int): Int {//面试题53 - I
var i = 0
var j = nums.lastIndex
var mid = 0
while (i <= j) {
mid = i + (j - i) / 2
if (nums[mid] > target) {
j = mid - 1
} else if (nums[mid] < target) {
i = mid + 1
} else {
i = mid
j = mid
while (i > 0 && nums[i] == nums[i - 1]) {
i--
}
while (j < nums.lastIndex && nums[j] == nums[j + 1]) {
j++
}
return j - i + 1
}
}
return 0
}
fun arrangeCoins(n: Int): Int {//441
var left = n
var rows = 1
var ans = 0
while (left >= rows) {
left -= rows
rows++
ans++
}
return ans
}
fun dayOfYear(date: String): Int {//1154
val year = date.split("-")[0]
val firstDate = "$year-01-01"
return daysOfDate(date) - daysOfDate(firstDate) + 1
}
private fun daysOfDate(date: String): Int {//Zeller formula
val arr = date.split("-")
var day = arr[2].toInt()
var month = arr[1].toInt()
var year = arr[0].toInt()
if (month <= 2) {
month += 10
year--
} else {
month -= 2
}
return day + month * 30 + (3 * month - 1) / 5 + 365 * year + year / 4 - year / 100 + year / 400
}
fun getHint(secret: String, guess: String): String {//299
var bulls = 0
var cows = 0
val bucket = IntArray(10) { 0 }
for (i in secret.indices) {
if (guess[i] == secret[i]) {
bulls++
} else {
bucket[secret[i] - '0'] += 1
bucket[guess[i] - '0'] -= 1
}
}
for (i in bucket) {
if (i > 0) {
cows += i
}
}
cows = secret.length - cows - bulls
return "${bulls}A${cows}B"
}
fun convertInteger(A: Int, B: Int): Int {//面试题05.06
var a = A
var b = B
var ans = 0
while (a != 0 || b != 0) {
if (a and 1 != b and 1) {
ans++
}
a = a ushr 1
b = b ushr 1
}
return ans
}
fun convertInteger1(A: Int, B: Int): Int {//面试题05.06
var ans = 0
var n = A xor B
while (n != 0) {
n = n and (n - 1)
ans++
}
return ans
}
fun isPrefixOfWord(sentence: String, searchWord: String): Int {//5416, 1455
val words = sentence.split(" ")
for (i in words.indices) {
if (words[i].startsWith(searchWord)) {
return i + 1
}
}
return -1
}
fun maxVowels(s: String, k: Int): Int {//5417
val vowels = setOf('a', 'e', 'i', 'o', 'u')
var ans = 0
var count = 0
for (i in 0 until k - 1) {
if (s[i] in vowels) {
count++
}
}
for (i in k - 1 until s.length) {
if (s[i] in vowels) {
count++
}
ans = Math.max(ans, count)
if (s[i - k + 1] in vowels) {
count--
}
}
return ans
}
var paths = 0
fun pseudoPalindromicPaths(root: TreeNode?): Int {//5418
paths = 0
pseudoPalindromicPaths(root, mutableListOf())
return paths
}
private fun pseudoPalindromicPaths(root: TreeNode?, list: MutableList<Int>) {
if (root == null) {
return
}
if (root.left == null && root.right == null) {
list.add(root.`val`)
if (containsPalindromic(list)) {
paths++
}
} else {
if (root.left != null) {
val left = mutableListOf<Int>()
left.addAll(list)
left.add(root.`val`)
pseudoPalindromicPaths(root.left, left)
}
if (root.right != null) {
val right = mutableListOf<Int>()
right.addAll(list)
right.add(root.`val`)
pseudoPalindromicPaths(root.right, right)
}
}
}
private fun containsPalindromic(list: MutableList<Int>): Boolean {
return list.groupBy { it }.entries.filter { it.value.size and 1 == 1 }.size <= 1
}
fun findMedianSortedArrays(nums1: IntArray, nums2: IntArray): Double {//4
val totalSize = nums1.size + nums2.size
if (totalSize and 1 == 1) {
return getKthElement(nums1, nums2, totalSize / 2 + 1).toDouble()
} else {
val mid1 = totalSize / 2 - 1
val mid2 = totalSize / 2
return (getKthElement(nums1, nums2, mid1 + 1) + getKthElement(nums1, nums2, mid2 + 1)) / 2.0
}
}
private fun getKthElement(nums1: IntArray, nums2: IntArray, K: Int): Int {
/* 主要思路:要找到第 k (k>1) 小的元素,那么就取 pivot1 = nums1[k/2-1] 和 pivot2 = nums2[k/2-1] 进行比较
* 这里的 "/" 表示整除
* nums1 中小于等于 pivot1 的元素有 nums1[0 .. k/2-2] 共计 k/2-1 个
* nums2 中小于等于 pivot2 的元素有 nums2[0 .. k/2-2] 共计 k/2-1 个
* 取 pivot = min(pivot1, pivot2),两个数组中小于等于 pivot 的元素共计不会超过 (k/2-1) + (k/2-1) <= k-2 个
* 这样 pivot 本身最大也只能是第 k-1 小的元素
* 如果 pivot = pivot1,那么 nums1[0 .. k/2-1] 都不可能是第 k 小的元素。把这些元素全部 "删除",剩下的作为新的 nums1 数组
* 如果 pivot = pivot2,那么 nums2[0 .. k/2-1] 都不可能是第 k 小的元素。把这些元素全部 "删除",剩下的作为新的 nums2 数组
* 由于我们 "删除" 了一些元素(这些元素都比第 k 小的元素要小),因此需要修改 k 的值,减去删除的数的个数
*/
val size1 = nums1.size
val size2 = nums2.size
var i1 = 0
var i2 = 0
var kth = 0
var k = K
while (true) {
if (i1 == size1) {
return nums2[i2 + k - 1]
}
if (i2 == size2) {
return nums1[i1 + k - 1]
}
if (k == 1) {
return Math.min(nums1[i1], nums2[i2])
}
val half = k / 2
val newI1 = Math.min(i1 + half, size1) - 1
val newI2 = Math.min(i2 + half, size2) - 1
if (nums1[newI1] <= nums2[newI2]) {
k -= (newI1 - i1 + 1)
i1 = newI1 + 1
} else {
k -= (newI2 - i2 + 1)
i2 = newI2 + 1
}
}
return 0
}
fun validWordAbbreviation(word: String, abbr: String): Boolean {//408
if (word == abbr) {
return true
}
if (word.length < abbr.length || abbr.startsWith('0')) {
return false
}
var i = 0
var j = 0
while (i < word.length && j < abbr.length) {
if (abbr[j].isLetter()) {
if (word[i] != abbr[j]) {
return false
} else {
i++
j++
}
} else {
var k = j + 1
while (k < abbr.length && abbr[k].isDigit()) {
k++
}
val sub = abbr.substring(j, k)
val count = sub.toInt()
if (sub.length != count.toString().length) {
return false
}
i += count
j = k
}
}
return i == word.length && j == abbr.length
}
fun detectCapitalUse(word: String): Boolean {//520
var upper = 0
var lower = 0
for (ch in word) {
if (ch.isLowerCase()) {
lower++
} else {
upper++
}
}
if (upper == 0 || lower == 0) {
return true
} else {
if (upper == word.length) {
return true
} else if (upper >= 2) {
return lower == 0
} else if (upper == 1) {
return word[0].isUpperCase()
} else {
return true
}
}
}
} | 0 | Kotlin | 0 | 1 | 7cf372d9acb3274003bb782c51d608e5db6fa743 | 40,233 | Algorithms | MIT License |
src/net/sheltem/aoc/y2023/Day11.kt | jtheegarten | 572,901,679 | false | {"Kotlin": 178521} | package net.sheltem.aoc.y2023
import net.sheltem.common.PositionInt
import net.sheltem.common.manhattan
suspend fun main() {
Day11().run()
}
class Day11 : Day<Long>(374, 82000210) {
override suspend fun part1(input: List<String>): Long = input.toUniverseMap(1).pairUp().sumOf { it.first manhattan it.second }
override suspend fun part2(input: List<String>): Long = input.toUniverseMap(999_999).pairUp().sumOf { it.first manhattan it.second }
}
private fun List<PositionInt>.pairUp(): List<Pair<PositionInt, PositionInt>> {
val visited = mutableListOf<PositionInt>()
val result = mutableListOf<Pair<PositionInt, PositionInt>>()
for (i in indices) {
visited.add(this[i])
this.filterNot { visited.contains(it) }
.map {
this[i] to it
}.let(result::addAll)
}
return result
}
private fun List<String>.toUniverseMap(expand: Int): List<PositionInt> {
val galaxies = this.flatMapIndexed { y, s ->
s.mapIndexedNotNull { x, char ->
if (char == '#') x to y else null
}
}
val xRange = galaxies.minOf { it.first }..galaxies.maxOf { it.first }
val yRange = galaxies.minOf{ it.second }..galaxies.maxOf { it.second }
val emptyX = xRange - galaxies.map { it.first }.toSet()
val emptyY = yRange - galaxies.map { it.second }.toSet()
return galaxies.map {galaxy ->
val offsetX = emptyX.count { it < galaxy.first } * expand
val offsetY = emptyY.count { it < galaxy.second } * expand
(galaxy.first + offsetX) to (galaxy.second + offsetY)
}
}
| 0 | Kotlin | 0 | 0 | ac280f156c284c23565fba5810483dd1cd8a931f | 1,603 | aoc | Apache License 2.0 |
string-similarity/src/commonMain/kotlin/com/aallam/similarity/NormalizedLevenshtein.kt | aallam | 597,692,521 | false | null | package com.aallam.similarity
import kotlin.math.max
/**
* This distance is computed as levenshtein distance divided by the length of the longest string.
* The resulting value is always in the interval 0 to 1.
*
* [Levenshtein Distance](https://en.wikipedia.org/wiki/Levenshtein_distance)
*/
public class NormalizedLevenshtein {
/**
* Levenshtein distance metric implementation.
*/
private val levenshtein = Levenshtein()
/**
* This distance is computed as levenshtein distance divided by the length of the longest string.
* The resulting value is always in the interval 0 to 1.
*
* Compute distance as Levenshtein(s1, s2) / max(|s1|, |s2|).
*
* @param first left hand side string to compare.
* @param second right hand side string to compare.
* @return the computed normalized Levenshtein distance.
*/
public fun distance(first: CharSequence, second: CharSequence): Double {
val maxLength = max(first.length, second.length)
if (maxLength == 0) return 0.0
return levenshtein.distance(first, second) / maxLength.toDouble()
}
/**
* Compute the similarity between two string.
* Corresponds to 1.0 - normalized distance.
*
* @param lhs left hand side string to compare.
* @param rhs right hand side string to compare.
* @return the computer similarity
*/
public fun similarity(lhs: CharSequence, rhs: CharSequence): Double {
return 1.0 - distance(lhs, rhs)
}
}
| 0 | Kotlin | 0 | 1 | 40cd4eb7543b776c283147e05d12bb840202b6f7 | 1,522 | string-similarity-kotlin | MIT License |
src/main/kotlin/sschr15/aocsolutions/Day17.kt | sschr15 | 317,887,086 | false | {"Kotlin": 184127, "TeX": 2614, "Python": 446} | package sschr15.aocsolutions
import sschr15.aocsolutions.util.*
/**
* AOC 2023 [Day 17](https://adventofcode.com/2023/day/17)
* Challenge: How do you best fuel all those metal crucibles, anyway?
*/
object Day17 : Challenge {
@ReflectivelyUsed
override fun solve() = challenge(2023, 17) {
// test()
val grid: Grid<Int>
val start = Point.origin
val end: Point
part1 {
grid = inputLines.map { it.map(Char::digitToInt) }.toGrid()
end = Point(grid.width - 1, grid.height - 1)
val result = dijkstra(
Triple(start, Direction.East as Direction, 0),
{ (pt, dir, count) ->
if (count > 3 || pt !in grid) emptyList() else listOf(
Triple(dir.mod(pt), dir, count + 1),
Triple(dir.turnRight().mod(pt), dir.turnRight(), 1),
Triple(dir.turnLeft().mod(pt), dir.turnLeft(), 1)
)
},
{ (pt, _, count) -> if (count > 3 || pt !in grid) 2 pow 24 else grid[pt] }
)
result.filterKeys { (pt, _, _) -> pt == end }.values.min()
}
part2 {
val result = dijkstra(
Triple(start, Direction.North as Direction, 0),
{ (pt, dir, cumulativeCost) ->
val list = mutableListOf<Triple<Point, Direction, Int>>()
val left = dir.turnLeft()
val right = dir.turnRight()
var leftSide = pt
var leftSum = -grid[pt] // offset for adding the current point
var rightSide = pt
var rightSum = -grid[pt]
repeat(4) {
leftSum += if (leftSide in grid) grid[leftSide] else 0 // fail silently
leftSide = left.mod(leftSide)
rightSum += if (rightSide in grid) grid[rightSide] else 0
rightSide = right.mod(rightSide)
}
repeat(7) {
if (leftSide in grid) {
leftSum += grid[leftSide]
list.add(Triple(leftSide, left, leftSum))
leftSide = left.mod(leftSide)
}
if (rightSide in grid) {
rightSum += grid[rightSide]
list.add(Triple(rightSide, right, rightSum))
rightSide = right.mod(rightSide)
}
}
list
},
{ (_, _, cumulativeCost) -> cumulativeCost }
)
result.filterKeys { (pt, _, _) -> pt == end }.values.min()
}
}
@JvmStatic
fun main(args: Array<String>) = println("Time: ${solve()}")
}
| 0 | Kotlin | 0 | 0 | e483b02037ae5f025fc34367cb477fabe54a6578 | 2,948 | advent-of-code | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/DiagonalMatrixSort.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import java.util.Arrays
import java.util.PriorityQueue
import kotlin.math.min
/**
* 1329. Sort the Matrix Diagonally
* @see <a href="https://leetcode.com/problems/sort-the-matrix-diagonally/">Source</a>
*/
fun interface DiagonalMatrixSort {
fun diagonalSort(mat: Array<IntArray>): Array<IntArray>
}
/**
* Straight Forward
*/
class DiagonalMatrixSortSF : DiagonalMatrixSort {
override fun diagonalSort(mat: Array<IntArray>): Array<IntArray> {
val m: Int = mat.size
val n: Int = mat[0].size
var r = m - 1
var c = 0
while (r >= 0) {
fillMatrix(mat, m, n, r, c)
r--
}
r = 0
c = 1
while (c < n - 1) {
fillMatrix(mat, m, n, r, c)
c++
}
return mat
}
private fun fillMatrix(mat: Array<IntArray>, m: Int, n: Int, r: Int, c: Int) {
val arr: MutableList<Int> = ArrayList()
var i = 0
while (r + i < m && c + i < n) {
arr.add(mat[r + i][c + i])
i++
}
i = 0
arr.sort()
while (r + i < m && c + i < n) {
mat[r + i][c + i] = arr[i]
i++
}
}
}
class DiagonalMatrixSortSFArray : DiagonalMatrixSort {
override fun diagonalSort(mat: Array<IntArray>): Array<IntArray> {
val n: Int = mat.size
val m: Int = mat[0].size
for (i in 0 until n) {
val arr = IntArray(min(n - i, m))
var j = 0
var k = i
while (k < n && j < m) {
arr[j] = mat[k][j]
k++
j++
}
Arrays.sort(arr)
j = 0
k = i
while (k < n && j < m) {
mat[k][j] = arr[j]
k++
j++
}
}
for (j in 1 until m) {
val arr = IntArray(min(n, m - j))
var i = 0
var k = j
while (k < m && i < n) {
arr[i] = mat[i][k]
k++
i++
}
arr.sort()
i = 0
k = j
while (k < m && i < n) {
mat[i][k] = arr[i]
k++
i++
}
}
return mat
}
}
class DiagonalMatrixSortMap : DiagonalMatrixSort {
override fun diagonalSort(mat: Array<IntArray>): Array<IntArray> {
val m: Int = mat.size
val n: Int = mat[0].size
val d: HashMap<Int, PriorityQueue<Int>> = HashMap()
for (i in 0 until m) {
for (j in 0 until n) {
d.putIfAbsent(i - j, PriorityQueue())
d[i - j]?.add(mat[i][j])
}
}
for (i in 0 until m) {
for (j in 0 until n) {
d[i - j]?.let {
mat[i][j] = it.poll()
}
}
}
return mat
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 3,592 | kotlab | Apache License 2.0 |
src/Day3/Day3.kt | tomashavlicek | 571,148,715 | false | {"Kotlin": 23780} | package Day3
import readInput
fun main() {
val priority = CharRange('a', 'z').plus(CharRange('A', 'Z'))
fun part1(input: List<String>): Int {
return input
.map { rucksack: String ->
val half = rucksack.length / 2
listOf(rucksack.take(half).toSet(), rucksack.takeLast(half).toSet())
}.sumOf {
priority.indexOf(it.first().intersect(it.last()).first()) + 1
}
}
fun part2(input: List<String>): Int {
return input
.map { it.toSet() }
.windowed(size = 3, step = 3)
.sumOf {
val shared = it[0].intersect(it[1]).intersect(it[2]).first()
priority.indexOf(shared) + 1
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day3/Day3_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day3/Day3")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 899d30e241070903fe6ef8c4bf03dbe678310267 | 1,051 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/day3/Day3.kt | jakubgwozdz | 571,298,326 | false | {"Kotlin": 85100} | package day3
import execute
import readAllText
import wtf
fun part1(input: String) = input.lineSequence().filter(String::isNotBlank)
.map { it.chunked(it.length / 2).map(String::toSet) }
.map { (p1, p2) -> p1.first { it in p2 } }
.sumOf(::priority)
fun part2(input: String) = input.lineSequence().filter(String::isNotBlank)
.chunked(3).map { it.map(String::toSet) }
.map { (p1, p2, p3) -> p1.first { it in p2 && it in p3 } }
.sumOf(::priority)
private fun priority(c: Char) = when {
c.isLowerCase() -> c - 'a' + 1
c.isUpperCase() -> c - 'A' + 27
else -> wtf(c)
}
fun main() {
val input = readAllText("local/day3_input.txt")
val test = """
vJrwpWtwJgWrhcsFMMfFFhFp
jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL
PmmdzqPrVvPwwTWBwg
wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn
ttgJtRGJQctTZtZT
CrZsJsPPZsGzwwsLwLmpwMDw
""".trimIndent()
execute(::part1, test, 157)
execute(::part1, input)
execute(::part2, test, 70)
execute(::part2, input)
}
| 0 | Kotlin | 0 | 0 | 7589942906f9f524018c130b0be8976c824c4c2a | 1,028 | advent-of-code-2022 | MIT License |
src/main/kotlin/g0801_0900/s0834_sum_of_distances_in_tree/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g0801_0900.s0834_sum_of_distances_in_tree
// #Hard #Dynamic_Programming #Depth_First_Search #Tree #Graph
// #2023_03_27_Time_746_ms_(100.00%)_Space_65.9_MB_(100.00%)
class Solution {
private var n = 0
private lateinit var count: IntArray
private lateinit var answer: IntArray
private lateinit var graph: Array<MutableList<Int>?>
private fun postorder(node: Int, parent: Int) {
for (child in graph[node]!!) {
if (child != parent) {
postorder(child, node)
count[node] += count[child]
answer[node] += answer[child] + count[child]
}
}
}
private fun preorder(node: Int, parent: Int) {
for (child in graph[node]!!) {
if (child != parent) {
answer[child] = answer[node] - count[child] + n - count[child]
preorder(child, node)
}
}
}
fun sumOfDistancesInTree(n: Int, edges: Array<IntArray>): IntArray {
this.n = n
count = IntArray(n)
answer = IntArray(n)
graph = arrayOfNulls(n)
count.fill(1)
for (i in 0 until n) {
graph[i] = ArrayList()
}
for (edge in edges) {
graph[edge[0]]?.add(edge[1])
graph[edge[1]]?.add(edge[0])
}
postorder(0, -1)
preorder(0, -1)
return answer
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,410 | LeetCode-in-Kotlin | MIT License |
src/main/aoc2018/Day18.kt | nibarius | 154,152,607 | false | {"Kotlin": 963896} | package aoc2018
import Grid
import Pos
class Day18(input: List<String>) {
private var area = Grid.parse(input)
private fun nextState(area: Grid, pos: Pos): Char {
val trees = area.numNeighboursWithValue(pos, '|', true)
val yards = area.numNeighboursWithValue(pos, '#', true)
return when (area[pos]) {
'.' -> if (trees >= 3) '|' else '.'
'|' -> if (yards >= 3) '#' else '|'
'#' -> if (yards >= 1 && trees >= 1) '#' else '.'
else -> throw RuntimeException("Unknown character: ${area[pos]}")
}
}
/**
* Tries to find a loop within the given amount of interations. If
* a loop is found the first entry in the pair is the loop length and
* the second the scores or the loop. If no loop is found the second
* entry in the pair is a list containing only the score of the last iteration
*/
private fun findLoop(maxIterations: Int): Pair<Int, List<Int>> {
val scores = mutableListOf<Int>() // index 0 is score for minute 1
val seen = mutableMapOf<Int, Int>() // hashcode to minute seen last
var current = area
var next = area.copy()
var tmp: Grid
for (minute in 1..maxIterations) {
current.keys.forEach { pos -> next[pos] = nextState(current, pos) }
tmp = current
current = next
next = tmp
val hash = current.hashCode()
if (seen.containsKey(hash)) { // loop found
return seen[hash]!! to scores.drop(seen[hash]!! - 1)
}
seen[hash] = minute
scores.add(getScore(current))
}
return -1 to scores.takeLast(1)
}
private fun getScore(area: Grid) = area.count('#') * area.count('|')
fun solvePart1(): Int {
return findLoop(10).second.single()
}
fun solvePart2(): Int {
val target = 1000000000
val (start, loop) = findLoop(target)
val index = (target - start) % loop.size
return loop[index]
}
} | 0 | Kotlin | 0 | 6 | f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22 | 2,060 | aoc | MIT License |
src/main/kotlin/se/saidaspen/aoc/aoc2022/Day25.kt | saidaspen | 354,930,478 | false | {"Kotlin": 301372, "CSS": 530} | package se.saidaspen.aoc.aoc2022
import se.saidaspen.aoc.util.*
fun main() = Day25.run()
object Day25 : Day(2022, 25) {
override fun part1() = dec2Snafu(input.lines().map { snafu2Dec(it) }.sumOf { it })
override fun part2() = ""
private fun dec2Snafu(dec: Long): String {
var left = dec
var snafu = ""
while (left > 0) {
val curr = left % 5
val (digit, chr) = when (curr) {
0L -> P(0L, '0')
1L -> P(1L, '1')
2L -> P(2L, '2')
3L -> P(-2L, '=')
4L -> P(-1L, '-')
else -> throw RuntimeException("Unsupported")
}
snafu += chr
left -= digit
left /= 5
}
return snafu.reversed()
}
private fun snafu2Dec(snafu: String): Long {
return snafu.e()
.reversed()
.foldIndexed(0L){ i, acc, elem ->
val digit = when(elem) {
'=' -> -2
'-' -> -1
'0' -> 0
'1' -> 1
'2' -> 2
else -> throw RuntimeException("Unsupported")
}
acc + digit * 5L.pow(i)
}
}
}
| 0 | Kotlin | 0 | 1 | be120257fbce5eda9b51d3d7b63b121824c6e877 | 1,283 | adventofkotlin | MIT License |
kotlin/src/com/daily/algothrim/leetcode/PivotIndex.kt | idisfkj | 291,855,545 | false | null | package com.daily.algothrim.leetcode
/**
* 724. 寻找数组的中心索引
*
* 给定一个整数类型的数组 nums,请编写一个能够返回数组 “中心索引” 的方法。
*
* 我们是这样定义数组 中心索引 的:数组中心索引的左侧所有元素相加的和等于右侧所有元素相加的和。
*
* 如果数组不存在中心索引,那么我们应该返回 -1。如果数组有多个中心索引,那么我们应该返回最靠近左边的那一个。
* */
class PivotIndex {
companion object {
@JvmStatic
fun main(args: Array<String>) {
println(PivotIndex().solution(intArrayOf(
1, 7, 3, 6, 5, 6
)))
println(PivotIndex().solution(intArrayOf(
1, 2, 3
)))
println(PivotIndex().solution(intArrayOf(
-1, -1, -1, -1, -1, -1
)))
}
}
// 输入:
// nums = [1, 7, 3, 6, 5, 6]
// 输出:3
// 解释:
// 索引 3 (nums[3] = 6) 的左侧数之和 (1 + 7 + 3 = 11),与右侧数之和 (5 + 6 = 11) 相等。
// 同时, 3 也是第一个符合要求的中心索引。
fun solution(nums: IntArray): Int {
var totalSum = 0
var subSum = 0
for (item in nums) {
totalSum += item
}
nums.forEachIndexed { index, item ->
if (subSum * 2 + item == totalSum) {
return index
}
subSum += item
}
return -1
}
} | 0 | Kotlin | 9 | 59 | 9de2b21d3bcd41cd03f0f7dd19136db93824a0fa | 1,557 | daily_algorithm | Apache License 2.0 |
src/main/kotlin/dev/bogwalk/batch5/Problem54.kt | bog-walk | 381,459,475 | false | null | package dev.bogwalk.batch5
/**
* Problem 54: Poker Hands
*
* https://projecteuler.net/problem=54
*
* Goal: Determine the winner when presented with 2 poker hands, based on the rules detailed
* below and assuming that all cards are valid and a winner is possible.
*
* Constraints: None
*
* Poker Hand Rankings: From lowest to highest ->
* [High Cards, One Pair, Two Pairs, Three of a kind, Straight, Flush, Full House, Four of a
* kind, Straight Flush, Royal Flush]
*
* If both hands have the same ranked hand, the rank made up of the highest value wins. If both
* ranks tie, then the highest value of the next highest rank is assessed until the only rank
* left to assess is the high card rank.
*
* e.g.: hand 1 = "5H 6H 2S KS 3D" -> High card King
* hand 2 = "5D JD 7H JS 8H" -> One pair Joker
* winner = player 2
*
* hand 1 = "AH AC AS 7S 7C" -> Full house 3 Aces, One pair 7
* hand 2 = "AS 3S 3D AD AH" -> Full house 3 Aces, One pair 3
* winner = player 1
*/
class PokerHands {
/**
* Compares lists representing all possible ranks for both hands, in reverse order, as this
* allows higher ranking possibilities to be compared first. If a rank has equal values, the
* next highest rank possibility will be compared. If comparison comes down to individual
* high cards, they have already been returned in reverse order by the helper function.
*
* @return 1 if [hand1] is the winner; otherwise, 2.
*/
fun pokerHandWinner(hand1: List<String>, hand2: List<String>): Int {
val hand1Ranks = rankHand(hand1)
val hand2Ranks = rankHand(hand2)
for (i in 9 downTo 1) {
val h1 = hand1Ranks[i]
val h2 = hand2Ranks[i]
if (h1.isEmpty() && h2.isEmpty()) continue
if (h1.isEmpty()) return 2
if (h2.isEmpty()) return 1
if (h1.single() == h2.single()) continue
return if (h1.single() < h2.single()) 2 else 1
}
for (j in hand1Ranks[0].indices) {
if (hand1Ranks[0][j] == hand2Ranks[0][j]) continue
return if (hand1Ranks[0][j] < hand2Ranks[0][j]) 2 else 1
}
return 0 // will not be reached
}
/**
* Rank a five card hand based on the order detailed in the problem description.
*
* All existing ranks are presented as their highest relevant card to allow potential ties
* between hands to be broken without needing to re-rank them.
*
* e.g.
* ["4C", "4D", "4S", "9S", "9D"] is presented as:
*
* [[], [9], [], [4], [], [], [4], [], [], []], which, when evaluated from RtL means the
* hand has Full House with 3 Fours, then 3 Fours, then 2 Nines.
*
* ["3D", "6D", "7H", "QD", "QS"] is presented as:
*
* [[7, 6, 3], [12], [], [], [], [], [], [], [], []], which, when evaluated from
* RtL means the hand has 2 Queens, then High card 7, then 6, then 3.
*/
private fun rankHand(hand: List<String>): List<List<Int>> {
// nested list to allow multiple high cards
val ranks = MutableList(10) { emptyList<Int>() }
val count = normaliseCount(hand.map(String::first))
val uniqueSuits = hand.map { it[1] }.toSet().size
var streak = 0
var pair = 0
var triple = 0
// move backwards to sort high cards in reverse
for (i in 14 downTo 2) {
when (count[i]) {
0 -> { // no cards of value i
streak = 0
continue
}
4 -> ranks[7] = listOf(i) // 4 of a kind
3 -> { // 3 of a kind
ranks[3] = listOf(i)
triple = i
}
2 -> { // 1 pair, at minimum
if (pair > 0) { // 2 pair
// give the 2 pair ranking the higher value pair
ranks[1] = listOf(
maxOf(i, ranks[1].single())
)
ranks[2] = listOf(
minOf(i, ranks[1].single())
)
} else {
ranks[1] = listOf(i)
pair = i
}
}
1 -> ranks[0] += listOf(i) // high card
}
streak++
if (streak == 5 || streak == 4 && i == 2 && count[1] > 0) { // straight
// low Ace straight has high card 5
ranks[4] = if (streak == 4) {
// ensure 14 not at front of high card list since Ace is low in this case
ranks[0] = ranks[0].drop(1) + listOf(14)
listOf(5)
} else {
listOf(i + 4)
}
if (uniqueSuits == 1) { // straight flush
ranks[8] = if (streak == 4) {
// low Ace straight flush has high card 5
listOf(5)
} else {
listOf(i + 4)
}
// royal flush
if (i == 10) ranks[9] = listOf(14)
}
break // no further cards if streak achieved
}
}
// give the full house ranking the higher 3 of a kind value
if (triple > 0 && pair > 0) ranks[6] = listOf(triple)
// give flush ranking the highest card value, unless it's a low Ace straight flush
if (uniqueSuits == 1) {
ranks[5] = ranks[8].ifEmpty {
listOf(ranks[0].maxOrNull()!!)
}
}
return ranks
}
/**
* Normalises card values to range from 1 to 14 & counts the amount of each card in the hand.
* Note that Ace cards are counted as both high & low.
*
* @return list of card counts with card value == index. e.g. [0, 0, 0, 0, 0, 2, 1, 1, 0, 0,
* 0, 0, 0, 1, 0] represents a hand with 2 fives, 1 six, 1 seven, and 1 King.
*/
private fun normaliseCount(values: List<Char>): List<Int> {
val nonNums = listOf('T', 'J', 'Q', 'K', 'A')
val count = MutableList(15) { 0 }
for (value in values) {
val num = if (value < ':') value.code - 48 else 10 + nonNums.indexOf(value)
count[num]++
if (num == 14) count[1]++ //count Ace as a high or low card
}
return count
}
} | 0 | Kotlin | 0 | 0 | 62b33367e3d1e15f7ea872d151c3512f8c606ce7 | 6,552 | project-euler-kotlin | MIT License |
2017/src/fifteen/DiskDefragmentationChallenge.kt | Mattias1 | 116,139,424 | false | null | package fifteen
class DiskDefragmentationChallenge {
fun usedSquares(salt: String): Int {
val diskGrid = getDiskGrid(salt)
return diskGrid.sumBy { it.count { it } }
}
private fun getDiskGrid(salt: String): List<List<Boolean>> {
return (0..127).map {
knotHash(salt + '-' + it.toString()).flatMap { toBitList(it) }
}
}
private fun toBitList(n: Int): List<Boolean> =
(7 downTo 0).map { (n shr it) % 2 == 1 }
fun regionCount(salt: String): Int {
val diskGrid = getDiskGrid(salt)
val regionGrid = buildIntDiskGrid(128)
var region = 0
diskGrid.forEachIndexed { x, diskList ->
diskList.forEachIndexed { y, _ ->
if (isUnknownRegion(x, y, diskGrid, regionGrid)) {
region++
floodFill(diskGrid, regionGrid, x, y, region)
}
}
}
return region
}
private fun buildIntDiskGrid(size: Int): List<MutableList<Int>> =
List(size, { MutableList(size, { 0 }) })
private fun floodFill(diskGrid: List<List<Boolean>>, regionGrid: List<MutableList<Int>>, x: Int, y: Int, region: Int) {
regionGrid[x][y] = region
borders(x, y)
.filter { isUnknownRegion(it, diskGrid, regionGrid) }
.forEach { floodFill(diskGrid, regionGrid, it.first, it.second, region) }
}
private fun borders(x: Int, y: Int): List<Pair<Int, Int>> {
return listOf(-1, 1)
.flatMap { listOf(Pair(x + it, y), Pair(x, y + it)) }
.filter { it.first in 0..127 && it.second in 0..127 }
}
private fun isUnknownRegion(p: Pair<Int, Int>, diskGrid: List<List<Boolean>>, regionGrid: List<List<Int>>): Boolean =
isUnknownRegion(p.first, p.second, diskGrid, regionGrid)
private fun isUnknownRegion(x: Int, y: Int, diskGrid: List<List<Boolean>>, regionGrid: List<List<Int>>): Boolean =
diskGrid[x][y] && regionGrid[x][y] == 0
/*
* I totally stole this one from Ruud. Sorry.
* I made my knot hash version in Python because at that point in time I didn't have access to the computer that I use for Kotlin.
*/
private fun knotHash(input: String): List<Int> {
val lengths = input.map { it.toInt() } + listOf(17, 31, 73, 47, 23)
val rounds = (1..64).flatMap { lengths }
val sparseHash = knot(rounds)
return sparseHash.chunked(16) { it.reduce(Int::xor) }
}
private fun knot(lengths: List<Int>): List<Int> {
val initial = (0..255).toList()
val list = lengths.foldIndexed(initial) { skip, list, length ->
val knot = list.drop(length) + list.take(length).reversed()
knot.rotateLeft(skip)
}
// Undo all previous rotations
val rotation = lengths.withIndex()
.sumBy { (i, l) -> i + l } % list.size
return list.rotateLeft(list.size - rotation)
}
private fun List<Int>.rotateLeft(n: Int) = drop(n % size) + take(n % size)
} | 0 | Kotlin | 0 | 0 | 6bcd889c6652681e243d493363eef1c2e57d35ef | 3,172 | advent-of-code | MIT License |
src/main/kotlin/com/dvdmunckhof/aoc/event2020/Day04.kt | dvdmunckhof | 318,829,531 | false | {"Kotlin": 195848, "PowerShell": 1266} | package com.dvdmunckhof.aoc.event2020
class Day04(input: String) {
private val fieldNames = listOf("byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid")
private val entries = input.split("\n\n").map(this::splitEntry)
fun solvePart1(): Int {
return entries.count {
val list = fieldNames.toMutableList()
list.removeAll(it.keys)
list.isEmpty()
}
}
fun solvePart2(): Int {
return entries.count { fields ->
val list = fieldNames.toMutableList()
list.removeAll(fields.keys)
if (list.isNotEmpty()) {
return@count false
}
fields.all { (name, value) -> validateField(name, value) }
}
}
private fun splitEntry(entry: String): Map<String, String> {
return entry.split(' ', '\n').associate {
val colonIndex = it.indexOf(':')
it.substring(0, colonIndex) to it.substring(colonIndex + 1)
}
}
private fun validateField(name: String, value: String): Boolean {
return when (name) {
"byr" -> {
val year = value.toInt()
year in 1920..2002
}
"iyr" -> {
val year = value.toInt()
year in 2010..2020
}
"eyr" -> {
val year = value.toInt()
year in 2020..2030
}
"hgt" -> {
val regex = Regex("^(\\d+)(cm|in)$")
val result = regex.find(value)
if (result == null) {
false
} else {
val size = result.groupValues[1].toInt()
val unit = result.groupValues[2]
if (unit == "cm") {
size in 150..193
} else {
size in 59..76
}
}
}
"hcl" -> {
value.matches(Regex("^#[0-9a-z]{6}$"))
}
"ecl" -> {
"amb blu brn gry grn hzl oth".contains(value)
}
"pid" -> {
value.matches(Regex("^\\d{9}$"))
}
else -> true
}
}
}
| 0 | Kotlin | 0 | 0 | 025090211886c8520faa44b33460015b96578159 | 2,283 | advent-of-code | Apache License 2.0 |
src/main/java/com/booknara/problem/twopointers/LongestMountainInArrayKt.kt | booknara | 226,968,158 | false | {"Java": 1128390, "Kotlin": 177761} | package com.booknara.problem.twopointers
/**
* 845. Longest Mountain in Array (Medium)
* https://leetcode.com/problems/longest-mountain-in-array/
*/
class LongestMountainInArrayKt {
// T:O(n), S:O(1)
fun longestMountain(A: IntArray): Int {
// input check
if (A.size <= 2) return 0
var res = 0
var i = 1
while (i < A.size - 1) {
var left = i - 1
var right = i + 1
if (A[left] >= A[i] || A[i] <= A[right]) {
i = right
continue
}
while ((left >= 0 && A[left] < A[left + 1]) || (right < A.size && A[right - 1] > A[right])) {
if (left >= 0 && A[left] < A[left + 1]) {
left--
}
if (right < A.size && A[right - 1] > A[right]) {
right++
}
}
res = Math.max(res, (right - 1) - (left + 1) + 1)
i = right
}
return res
}
}
/*
[2,1,4,7,3,2,5]
1. find the peek point
2. the prev and next neighbor should be smaller than the peek
3. move the prev and next pointers
4. get the longest mountain
5. move the peek point by adding the right point
*/ | 0 | Java | 1 | 1 | 04dcf500ee9789cf10c488a25647f25359b37a53 | 1,237 | playground | MIT License |
src/main/kotlin/days/Day13.kt | TheMrMilchmann | 571,779,671 | false | {"Kotlin": 56525} | /*
* Copyright (c) 2022 <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 ParserState(val src: String, var offset: Int)
fun parse(state: ParserState): Day13Node {
if (state.src[state.offset] == '[') {
state.offset++
val elements = buildList {
if (state.src[state.offset] != ']') {
add(parse(state))
}
while (state.src[state.offset++] == ',') {
add(parse(state))
}
}
return Day13List(elements)
} else {
var element = state.src.drop(state.offset).takeWhile { it.isWhitespace() || it.isDigit() }
state.offset += element.length
element = element.trim()
return Day13Int(element.toInt())
}
}
val data = readInput().filter(String::isNotBlank).map { parse(ParserState(it, 0)) }
fun part1(): Int =
data.chunked(2) { (a, b) -> a to b }.withIndex().filter { (_, pair) -> pair.first < pair.second }.sumOf { (index, _) -> index + 1 }
fun part2(): Int {
val divider2 = Day13List(Day13List(listOf(Day13Int(2))))
val divider6 = Day13List(Day13List(listOf(Day13Int(6))))
return buildList {
addAll(data)
add(divider2)
add(divider6)
}
.also { println(it.indexOf(divider2)) }
.sortedWith(Day13Node::compareTo)
.withIndex()
.map { (i, packet) -> if (packet == divider2 || packet == divider6) i + 1 else 1 }
.reduce(Int::times)
}
println("Part 1: ${part1()}")
println("Part 2: ${part2()}")
}
private operator fun Day13Node.compareTo(other: Day13Node): Int {
return if (this is Day13Int && other is Day13Int) {
this.value.compareTo(other.value)
} else {
val a = (this as? Day13List)?.elements ?: listOf(this)
val b = (other as? Day13List)?.elements ?: listOf(other)
a.compareTo(b)
}
}
private operator fun List<Day13Node>.compareTo(other: List<Day13Node>): Int {
val thisItr = iterator()
val otherItr = other.iterator()
while (thisItr.hasNext()) {
if (!otherItr.hasNext()) return 1
val a = thisItr.next()
val b = otherItr.next()
val res = a.compareTo(b)
if (res != 0) return res
}
return if (otherItr.hasNext()) -1 else 0
}
private sealed class Day13Node
private data class Day13Int(
val value: Int
) : Day13Node()
private data class Day13List(
val elements: List<Day13Node>
) : Day13Node(), List<Day13Node> by elements | 0 | Kotlin | 0 | 1 | 2e01ab62e44d965a626198127699720563ed934b | 3,722 | AdventOfCode2022 | MIT License |
src/Day08.kt | amelentev | 573,120,350 | false | {"Kotlin": 87839} | import java.math.BigInteger
fun main() {
val input = readInput("Day08")
val instructions = input[0]
val map = input.drop(2).associate {
val key = it.substringBefore(' ')
val left = it.substringAfter('(').substringBefore(',')
val right = it.substringAfter(", ").substringBefore(')')
key to (left to right)
}
fun next(s: String, i: Int): String {
return if (instructions[i % instructions.length] == 'L') {
map[s]!!.first
} else {
map[s]!!.second
}
}
run {
var cur = "AAA"
var res = 0
while (cur != "ZZZ") {
cur = next(cur, res)
res ++
}
println(res)
}
run {
fun find(s0: String, i0: Int): Pair<Int, String> {
var i = i0
var s = s0
do {
s = next(s, i)
i++
} while (!s.endsWith('Z'))
return i to s
}
val starts = map.keys.filter { it.endsWith('A') }
for (s0 in starts) {
print(s0)
var (s1, i1) = s0 to 0
for (i in 0..3) {
val next = find(s1, i1)
s1 = next.second
print("\t${next.first - i1}\t$s1")
i1 = next.first
}
println()
}
val cycles = starts.map { find(it, 0).first }
val lcm = cycles.fold(BigInteger.ONE) { acc, x ->
acc * x.toBigInteger() / acc.gcd(x.toBigInteger())
}
println(lcm)
}
} | 0 | Kotlin | 0 | 0 | a137d895472379f0f8cdea136f62c106e28747d5 | 1,574 | advent-of-code-kotlin | Apache License 2.0 |
src/day08/Solution.kt | abhabongse | 576,594,038 | false | {"Kotlin": 63915} | /* Solution to Day 8: Treetop Tree House
* https://adventofcode.com/2022/day/8
*/
package day08
import utils.Grid
import java.io.File
import kotlin.math.max
fun main() {
val fileName =
// "day08_sample.txt"
"day08_input.txt"
val forest = readInput(fileName)
// Part 1: visible trees from outside the grid
forest.populateViewingBlockHeight()
val p1VisibleTrees = forest.iterator().count { tree -> tree.visibleFromOneDirection }
println("Part 1: $p1VisibleTrees")
// Part 2: tree with the best scenic score
forest.populateViewingDistance()
val p2BestScenicScore = forest.iterator().maxOf { tree -> tree.scenicScore }
println("Part 2: $p2BestScenicScore")
}
/**
* Reads and parses input data according to the problem statement.
*/
fun readInput(fileName: String): Grid<Tree> {
val data = File("inputs", fileName)
.readLines()
.map { line -> line.trim().map { Tree(it.digitToInt()) }.toList() }
return Grid(data)
}
/**
* Populates the viewing block height data for each tree in all four directions.
*/
@OptIn(ExperimentalStdlibApi::class)
fun Grid<Tree>.populateViewingBlockHeight() {
for (r in 0..<this.numRows) {
var maxFromWest = -1 // maintains max height starting from west
for (c in 0..<this.numCols) {
this[r, c].viewingBlockHeight.west = maxFromWest
maxFromWest = max(maxFromWest, this[r, c].height)
}
var maxFromEast = -1 // maintains max height starting from east
for (c in (0..<this.numCols).reversed()) {
this[r, c].viewingBlockHeight.east = maxFromEast
maxFromEast = max(maxFromEast, this[r, c].height)
}
}
for (c in 0..<this.numCols) {
var maxFromNorth = -1 // maintains max height starting from north
for (r in 0..<this.numRows) {
this[r, c].viewingBlockHeight.north = maxFromNorth
maxFromNorth = max(maxFromNorth, this[r, c].height)
}
var maxFromSouth = -1 // maintains max height starting from south
for (r in (0..<this.numRows).reversed()) {
this[r, c].viewingBlockHeight.south = maxFromSouth
maxFromSouth = max(maxFromSouth, this[r, c].height)
}
}
}
/**
* Populates the viewing distance data for each tree in all four directions.
*
* Implementation Details:
* e.g. indexForMaxHeight\[h] = the most recent index whose height is at least h
* (initialized to the index indicating the edge of the forest)
*/
@OptIn(ExperimentalStdlibApi::class)
fun Grid<Tree>.populateViewingDistance() {
for (r in 0..<this.numRows) {
run { // Looking westward
val indexForMaxHeight = (0..9).map { 0 }.toCollection(ArrayList())
for (c in 0..<this.numCols) {
val height = this[r, c].height
this[r, c].viewingDistance.west = c - indexForMaxHeight[height]
(0..height).forEach { indexForMaxHeight[it] = c }
}
}
run { // Looking eastward
val indexForMaxHeight = (0..9).map { this.numCols - 1 }.toCollection(ArrayList())
for (c in (0..<this.numCols).reversed()) {
val height = this[r, c].height
this[r, c].viewingDistance.east = indexForMaxHeight[height] - c
(0..height).forEach { indexForMaxHeight[it] = c }
}
}
}
for (c in 0..<this.numCols) {
run { // Looking northward
val indexForMaxHeight = (0..9).map { 0 }.toCollection(ArrayList())
for (r in 0..<this.numRows) {
val height = this[r, c].height
this[r, c].viewingDistance.north = r - indexForMaxHeight[height]
(0..height).forEach { indexForMaxHeight[it] = r }
}
}
run { // Looking southward
val indexForMaxHeight = (0..9).map { this.numRows - 1 }.toCollection(ArrayList())
for (r in (0..<this.numRows).reversed()) {
val height = this[r, c].height
this[r, c].viewingDistance.south = indexForMaxHeight[height] - r
(0..height).forEach { indexForMaxHeight[it] = r }
}
}
}
}
| 0 | Kotlin | 0 | 0 | 8a0aaa3b3c8974f7dab1e0ad4874cd3c38fe12eb | 4,241 | aoc2022-kotlin | Apache License 2.0 |
src/Lesson7StacksAndQueues/Fish.kt | slobodanantonijevic | 557,942,075 | false | {"Kotlin": 50634} |
import java.util.Stack
/**
* 100/100
* @param A
* @param B
* @return
*/
fun solution(A: IntArray, B: IntArray): Int {
// main idea: use "stack" to store the fishes with B[i]==1
// that is, "push" the downstream fishes into "stack"
// note: "push" the Size of the downstream fish
val downstream: Stack<Int> = Stack<Int>()
var alive = A.size
for (i in A.indices) {
// case 1; for the fish going to downstrem
// push the fish to "stack", so we can keep them from the "last" one
if (B[i] == 1) {
downstream.push(A[i]) // push the size of the downstream fish
}
// case 2: for the fish going upstream
// check if there is any fish going to downstream
if (B[i] == 0) {
while (!downstream.isEmpty()) {
// if the downstream fish is bigger (eat the upstream fish)
if (downstream.peek() > A[i]) {
alive--
break // the upstream fish is eaten (ending)
} else if (downstream.peek() < A[i]) { // if the downstream fish is smaller (eat the downstream fish)
alive--
downstream.pop() // the downstream fish is eaten (not ending)
}
}
}
}
return alive
}
/**
* You are given two non-empty arrays A and B consisting of N integers. Arrays A and B represent N voracious fish in a river, ordered downstream along the flow of the river.
*
* The fish are numbered from 0 to N − 1. If P and Q are two fish and P < Q, then fish P is initially upstream of fish Q. Initially, each fish has a unique position.
*
* Fish number P is represented by A[P] and B[P]. Array A contains the sizes of the fish. All its elements are unique. Array B contains the directions of the fish. It contains only 0s and/or 1s, where:
*
* 0 represents a fish flowing upstream,
* 1 represents a fish flowing downstream.
* If two fish move in opposite directions and there are no other (living) fish between them, they will eventually meet each other. Then only one fish can stay alive − the larger fish eats the smaller one. More precisely, we say that two fish P and Q meet each other when P < Q, B[P] = 1 and B[Q] = 0, and there are no living fish between them. After they meet:
*
* If A[P] > A[Q] then P eats Q, and P will still be flowing downstream,
* If A[Q] > A[P] then Q eats P, and Q will still be flowing upstream.
* We assume that all the fish are flowing at the same speed. That is, fish moving in the same direction never meet. The goal is to calculate the number of fish that will stay alive.
*
* For example, consider arrays A and B such that:
*
* A[0] = 4 B[0] = 0
* A[1] = 3 B[1] = 1
* A[2] = 2 B[2] = 0
* A[3] = 1 B[3] = 0
* A[4] = 5 B[4] = 0
* Initially all the fish are alive and all except fish number 1 are moving upstream. Fish number 1 meets fish number 2 and eats it, then it meets fish number 3 and eats it too. Finally, it meets fish number 4 and is eaten by it. The remaining two fish, number 0 and 4, never meet and therefore stay alive.
*
* Write a function:
*
* class Solution { public int solution(int[] A, int[] B); }
*
* that, given two non-empty arrays A and B consisting of N integers, returns the number of fish that will stay alive.
*
* For example, given the arrays shown above, the function should return 2, as explained above.
*
* Write an efficient algorithm for the following assumptions:
*
* N is an integer within the range [1..100,000];
* each element of array A is an integer within the range [0..1,000,000,000];
* each element of array B is an integer that can have one of the following values: 0, 1;
* the elements of A are all distinct.
*/ | 0 | Kotlin | 0 | 0 | 155cf983b1f06550e99c8e13c5e6015a7e7ffb0f | 3,789 | Codility-Kotlin | Apache License 2.0 |
src/main/kotlin/year2023/Day01.kt | forketyfork | 572,832,465 | false | {"Kotlin": 142196} | package year2023
class Day01 {
companion object {
val digits = (0..9).associateBy { it.toString() }
val words = listOf("one", "two", "three", "four", "five", "six", "seven", "eight", "nine")
.withIndex().associate { (idx, word) -> word to idx + 1 }
val digitsAndWords = digits + words
}
fun part1(input: String): Int = solveForDigitMap(input, digits)
fun part2(input: String): Int = solveForDigitMap(input, digitsAndWords)
private fun solveForDigitMap(input: String, digitMap: Map<String, Int>): Int = input.lines()
.filter { it.isNotBlank() }
.sumOf { line ->
val (_, firstDigit) = line.findAnyOf(digitMap.keys)!!
val (_, lastDigit) = line.findLastAnyOf(digitMap.keys)!!
"${digitMap[firstDigit]}${digitMap[lastDigit]}".toInt()
}
}
| 0 | Kotlin | 0 | 0 | 5c5e6304b1758e04a119716b8de50a7525668112 | 854 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/com/ginsberg/advent2019/Day22.kt | tginsberg | 222,116,116 | false | null | /*
* Copyright (c) 2019 by <NAME>
*/
/**
* Advent of Code 2019, Day 22 - Slam Shuffle
* Problem Description: http://adventofcode.com/2019/day/22
* Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2019/day22/
*/
package com.ginsberg.advent2019
import java.math.BigInteger
import java.math.BigInteger.ONE
import java.math.BigInteger.ZERO
import kotlin.math.absoluteValue
class Day22(private val input: List<String>) {
fun solvePart1(): Int =
followInstructions().indexOf(2019)
fun solvePart2(): BigInteger =
modularArithmeticVersion(2020.toBigInteger())
private fun modularArithmeticVersion(find: BigInteger): BigInteger {
val memory = arrayOf(ONE, ZERO)
input.reversed().forEach { instruction ->
when {
"cut" in instruction ->
memory[1] += instruction.getBigInteger()
"increment" in instruction ->
instruction.getBigInteger().modPow(NUMBER_OF_CARDS - TWO, NUMBER_OF_CARDS).also {
memory[0] *= it
memory[1] *= it
}
"stack" in instruction -> {
memory[0] = memory[0].negate()
memory[1] = (memory[1].inc()).negate()
}
}
memory[0] %= NUMBER_OF_CARDS
memory[1] %= NUMBER_OF_CARDS
}
val power = memory[0].modPow(SHUFFLES, NUMBER_OF_CARDS)
return ((power * find) + ((memory[1] * (power + NUMBER_OF_CARDS.dec())) * ((memory[0].dec()).modPow(NUMBER_OF_CARDS - TWO, NUMBER_OF_CARDS)))).mod(NUMBER_OF_CARDS)
}
private fun followInstructions(): List<Int> =
input.fold(createDeck()) { deck, instruction ->
when {
"cut" in instruction -> deck.cut(instruction.getInt())
"increment" in instruction -> deck.deal(instruction.getInt())
"stack" in instruction -> deck.reversed()
else -> throw IllegalArgumentException("Invalid instruction: $instruction")
}
}
private fun createDeck(length: Int = 10_007): List<Int> =
List(length) { it }
private fun List<Int>.cut(n: Int): List<Int> =
when {
n > 0 -> this.drop(n) + this.take(n)
n < 0 -> this.takeLast(n.absoluteValue) + this.dropLast(n.absoluteValue)
else -> this
}
private fun List<Int>.deal(increment: Int): List<Int> {
val newDeck = this.toMutableList()
var place = 0
this.forEach { card ->
newDeck[place] = card
place += increment
place %= this.size
}
return newDeck
}
private fun String.getInt(): Int =
this.split(" ").last().toInt()
private fun String.getBigInteger(): BigInteger =
this.split(" ").last().toBigInteger()
companion object {
val NUMBER_OF_CARDS = 119315717514047.toBigInteger()
val SHUFFLES = 101741582076661.toBigInteger()
val TWO = 2.toBigInteger()
}
}
| 0 | Kotlin | 2 | 23 | a83e2ecdb6057af509d1704ebd9f86a8e4206a55 | 3,096 | advent-2019-kotlin | Apache License 2.0 |
kotlin/combinatorics/Combinations.kt | polydisc | 281,633,906 | true | {"Java": 540473, "Kotlin": 515759, "C++": 265630, "CMake": 571} | package combinatorics
import java.util.Arrays
// https://en.wikipedia.org/wiki/Combination
object Combinations {
fun nextCombination(comb: IntArray, n: Int): Boolean {
val k = comb.size
var i = k - 1
while (i >= 0) {
if (comb[i] < n - k + i) {
++comb[i]
while (++i < k) {
comb[i] = comb[i - 1] + 1
}
return true
}
i--
}
return false
}
fun combinationByNumber(n: Int, k: Int, number: Long): IntArray {
var number = number
val c = IntArray(k)
var cnt = n
for (i in 0 until k) {
var j = 1
while (true) {
val am = binomial((cnt - j).toLong(), (k - 1 - i).toLong())
if (number < am) break
number -= am
++j
}
c[i] = if (i > 0) c[i - 1] + j else j - 1
cnt -= j
}
return c
}
fun numberByCombination(c: IntArray, n: Int): Long {
val k = c.size
var res: Long = 0
var prev = -1
for (i in 0 until k) {
for (j in prev + 1 until c[i]) {
res += binomial((n - 1 - j).toLong(), (k - 1 - i).toLong())
}
prev = c[i]
}
return res
}
fun binomial(n: Long, k: Long): Long {
var k = k
k = Math.min(k, n - k)
var res: Long = 1
for (i in 0 until k) {
res = res * (n - i) / (i + 1)
}
return res
}
fun nextCombinationWithRepeats(p: IntArray, n: Int): Boolean {
val k = p.size
var i = k - 1
while (i >= 0) {
if (p[i] < n - 1) {
++p[i]
while (++i < k) {
p[i] = p[i - 1]
}
return true
}
i--
}
return false
}
// Usage example
fun main(args: Array<String?>?) {
var p = intArrayOf(0, 1)
System.out.println(!nextCombination(p, 2))
System.out.println(Arrays.equals(intArrayOf(0, 1), p))
p = IntArray(2)
System.out.println(nextCombinationWithRepeats(p, 2))
System.out.println(Arrays.equals(intArrayOf(0, 1), p))
System.out.println(nextCombinationWithRepeats(p, 2))
System.out.println(Arrays.equals(intArrayOf(1, 1), p))
System.out.println(!nextCombinationWithRepeats(p, 2))
System.out.println(78L == numberByCombination(intArrayOf(1, 2, 3, 6, 8), 9))
System.out.println(Arrays.toString(combinationByNumber(9, 5, 78)))
p = IntArray(3)
do {
System.out.println(Arrays.toString(p))
} while (nextCombinationWithRepeats(p, 3))
}
}
| 1 | Java | 0 | 0 | 4566f3145be72827d72cb93abca8bfd93f1c58df | 2,823 | codelibrary | The Unlicense |
src/Day02.kt | luix | 573,258,926 | false | {"Kotlin": 7897, "Java": 232} | fun main() {
fun part1(input: List<String>): Int {
var max = 0
var sum = 0
input.forEach {
if (it == "") {
max = if (sum > max) sum else max
sum = 0
} else {
sum += it.toInt()
}
}
return max
}
fun part2(input: List<String>): Int {
val items = mutableListOf<Int>()
var sum = 0
input.forEach {
if (it == "") {
items.add(sum)
sum = 0
} else {
sum += it.toInt()
}
}
println(items)
items.sort()
items.reverse()
println(items)
return (items[0] + items[1] + items[2])
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 8e9b605950049cc9a0dced9c7ba99e1e2458e53e | 1,047 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/day10.kt | gautemo | 433,582,833 | false | {"Kotlin": 91784} | import shared.getLines
private val invalidRightParantheses = Regex("""[\[<{]\)""")
private val invalidRightSquareBracket = Regex("""[(<{]]""")
private val invalidRightSquirlyBracket = Regex("""[\[<(]}""")
private val invalidRightCrocodile = Regex("""[\[({]>""")
fun totalSyntaxScore(lines: List<String>): Int{
var rightParantheses = 0
var rightSquareBracket = 0
var rightSquirlyBracket = 0
var rightCrocodile = 0
for(line in lines){
val codeLeft = removeMatches(line)
rightParantheses += invalidRightParantheses.findAll(codeLeft).count()
rightSquareBracket += invalidRightSquareBracket.findAll(codeLeft).count()
rightSquirlyBracket += invalidRightSquirlyBracket.findAll(codeLeft).count()
rightCrocodile += invalidRightCrocodile.findAll(codeLeft).count()
}
return rightParantheses * 3 + rightSquareBracket * 57 + rightSquirlyBracket * 1197 + rightCrocodile * 25137
}
private fun invalid(code: String): Boolean{
val codeLeft = removeMatches(code)
return invalidRightParantheses.containsMatchIn(codeLeft) ||
invalidRightSquareBracket.containsMatchIn(codeLeft) ||
invalidRightSquirlyBracket.containsMatchIn(codeLeft) ||
invalidRightCrocodile.containsMatchIn(codeLeft)
}
fun autocompleteScore(lines: List<String>): Long{
val scores = lines.filter { !invalid(it) }.map { completeScore(it) }.sorted()
return scores[scores.size/2]
}
private fun completeScore(code: String): Long{
val score = mapOf(
Pair(')', 1),
Pair(']', 2),
Pair('}', 3),
Pair('>', 4),
)
val complete = complete(code)
val added = complete.replace(code, "")
return added.fold(0){ sum, c -> sum * 5 + score[c]!! }
}
private fun complete(code: String): String{
if(removeMatches(code).isEmpty()) return code
if(!invalid("$code)")) return complete("$code)")
if(!invalid("$code]")) return complete("$code]")
if(!invalid("$code}")) return complete("$code}")
if(!invalid("$code>")) return complete("$code>")
throw Exception("Should be valid symbol inserted before this")
}
private fun removeMatches(code: String): String{
val changed = popMatch(code)
return if(changed == code) code else removeMatches(changed)
}
private fun popMatch(code: String) = code.replace(Regex("""\(\)|\[]|<>|\{}"""), "")
fun main(){
val lines = getLines("day10.txt")
val task1 = totalSyntaxScore(lines)
println(task1)
val task2 = autocompleteScore(lines)
println(task2)
}
| 0 | Kotlin | 0 | 0 | c50d872601ba52474fcf9451a78e3e1bcfa476f7 | 2,534 | AdventOfCode2021 | MIT License |
solver/src/commonMain/kotlin/org/hildan/sudoku/solver/techniques/NakedTuples.kt | joffrey-bion | 9,559,943 | false | {"Kotlin": 51198, "HTML": 187} | package org.hildan.sudoku.solver.techniques
import org.hildan.sudoku.model.*
/**
* Trivially sets the digit of a cell when only one candidate remains for that cell.
*/
object NakedSingles : Technique {
override fun attemptOn(grid: Grid): List<NakedSinglesStep> {
val actions = grid.emptyCells.asSequence()
.filter { it.candidates.size == 1 }
.map { cell -> Action.PlaceDigit(cell.candidates.single(), cell.index) }
.toList()
return if (actions.isEmpty()) emptyList() else listOf(NakedSinglesStep(actions))
}
}
data class NakedSinglesStep(
override val actions: List<Action.PlaceDigit>,
): Step {
override val techniqueName: String = "Naked Singles"
override val description: String = "The cells ${cellRefs(actions.map { it.cellIndex })} only have 1 candidate " +
"left. We can therefore place the corresponding digits."
}
object NakedPairs : NakedTuples("Naked Pairs", tupleSize = 2)
object NakedTriples : NakedTuples("Naked Triples", tupleSize = 3)
object NakedQuads : NakedTuples("Naked Quads", tupleSize = 4)
/**
* Naked tuples are groups of N candidates that are the only ones present in N different cells of a unit.
* When this happens, those N candidates must all be in those N cells and thus cannot be in the rest of the unit, so
* they can be removed from the candidates of the other cells of the unit.
*/
open class NakedTuples(
private val techniqueName: String,
private val tupleSize: Int,
) : Technique {
override fun attemptOn(grid: Grid): List<NakedTupleStep> {
val nakedTuples = mutableListOf<NakedTupleStep>()
grid.units.forEach { unit ->
val emptyCells = unit.cells.filter { it.isEmpty }
val cellsByTuple = emptyCells.groupByPotentialNakedTuple()
cellsByTuple.forEach { (tuple, nakedCells) ->
if (nakedCells.size == tupleSize) {
// Exactly N cells with the same naked tuple of N candidates in the unit
// Those N candidates must all be in those N cells and can be removed from other cells in the unit
val removals = tupleCandidatesRemovalActions(
unitCells = emptyCells,
cellsWithNakedTuple = nakedCells,
tupleCandidates = tuple,
)
if (removals.isNotEmpty()) {
nakedTuples.add(NakedTupleStep(techniqueName, unit.id, tuple, nakedCells.mapToIndices(), removals))
}
}
}
}
return nakedTuples
}
private fun List<Cell>.groupByPotentialNakedTuple(): Map<Set<Int>, Set<Cell>> {
val allCandidates = flatMapTo(HashSet()) { it.candidates }
val potentialTuples = allCandidates.allTuplesOfSize(tupleSize)
return potentialTuples.associateWith { tuple ->
// we consider all cells whose candidates are a subset of the tuple (or all of it)
filterTo(HashSet()) { cell -> tuple.containsAll(cell.candidates) }
}
}
private fun tupleCandidatesRemovalActions(
unitCells: List<Cell>,
cellsWithNakedTuple: Set<Cell>,
tupleCandidates: Set<Digit>,
): List<Action.RemoveCandidate> = buildList {
for (cell in unitCells) {
if (cell !in cellsWithNakedTuple) {
val candidatesToRemove = cell.candidates intersect tupleCandidates
addAll(candidatesToRemove.map { Action.RemoveCandidate(it, cell.index) })
}
}
}
}
data class NakedTupleStep(
override val techniqueName: String,
val unit: UnitId,
val tuple: Set<Digit>,
val cells: Set<CellIndex>,
override val actions: List<Action.RemoveCandidate>,
): Step {
override val description: String = "The ${tuple.size} digits $tuple are the only ones to appear in exactly " +
"${tuple.size} cells (${cellRefs(cells)}) in $unit. All of those digits must therefore be in those cells, and" +
" cannot be in any other cell of $unit."
}
| 0 | Kotlin | 0 | 0 | 441fbb345afe89b28df9fe589944f40dbaccaec5 | 4,112 | sudoku-solver | MIT License |
src/main/kotlin/d15/d15.kt | LaurentJeanpierre1 | 573,454,829 | false | {"Kotlin": 118105} | package d15
import readInput
import java.util.Scanner
import kotlin.math.abs
fun part1(input: List<String>, row : Long): Int {
val ranges = mutableListOf<LongRange>()
val beacons = mutableSetOf<LongRange>()
for (line in input) {
val scan = Scanner(line)
scan.useDelimiter("[=,:]")
assert(scan.next() == "Sensor at x")
val xS = scan.nextLong()
assert(scan.next() == " y")
val yS = scan.nextLong()
assert(scan.next() == " closest beacon is at x")
val xB = scan.nextLong()
assert(scan.next() == " y")
val yB = scan.nextLong()
if (yB == row) {
beacons.add(xB..xB)
}
val dist = abs(xS - xB) + abs(yS - yB)
//println("($xS, $yS) -> ($xB, $yB) : dist = $dist")
val dy = abs(row - yS)
if (dy <= dist) {
val minX = xS - (dist - dy)
val maxX = xS + (dist - dy)
//println(“Sensor covers row $row from $minX to $maxX")
val rowRange = mutableListOf(minX..maxX)
for (range in ranges) {
val ite = rowRange.listIterator()
while (ite.hasNext()) {
val r = ite.next()
if (r.start < range.start) {
if (r.endInclusive < range.first) {
// no intersect
} else {
val nr = r.start until range.first
ite.set(nr)
}
if (r.endInclusive > range.endInclusive) {
ite.add(range.endInclusive + 1..r.endInclusive)
}
} else if (r.start <= range.endInclusive) {
val nr = range.endInclusive + 1..r.endInclusive
ite.set(nr)
} else {
// no intersect
}
}
}
for (range in rowRange)
if (!range.isEmpty())
ranges.add(range)
}
}
println(ranges)
println(beacons)
return ranges.sumOf { it.count() } - beacons.size
}
fun part2(input: List<String>): Long {
for (row in 0L..4000000L) {
val ranges = mutableListOf<LongRange>()
val beacons = mutableSetOf<LongRange>()
for (line in input) {
val scan = Scanner(line)
scan.useDelimiter("[=,:]")
assert(scan.next() == "Sensor at x")
val xS = scan.nextLong()
assert(scan.next() == " y")
val yS = scan.nextLong()
assert(scan.next() == " closest beacon is at x")
val xB = scan.nextLong()
assert(scan.next() == " y")
val yB = scan.nextLong()
if (yB == row) {
beacons.add(xB..xB)
}
val dist = abs(xS - xB) + abs(yS - yB)
val dy = abs(row - yS)
if (dy <= dist) {
var minX = xS - (dist - dy)
var maxX = xS + (dist - dy)
if (minX < 0) minX = 0
if (maxX > 4000000) maxX = 4000000
val rowRange = mutableListOf(minX..maxX)
for (range in ranges) {
val ite = rowRange.listIterator()
while (ite.hasNext()) {
val r = ite.next()
if (r.start < range.start) {
if (r.endInclusive < range.first) {
// no intersect
} else {
val nr = r.start until range.first
ite.set(nr)
}
if (r.endInclusive > range.endInclusive) {
ite.add(range.endInclusive + 1..r.endInclusive)
}
} else if (r.start <= range.endInclusive) {
val nr = range.endInclusive + 1..r.endInclusive
ite.set(nr)
} else {
// no intersect
}
}
}
for (range in rowRange)
if (!range.isEmpty())
ranges.add(range)
}
}
ranges.sortWith { i1, i2 -> i1.start.compareTo(i2.start) }
for ((r1, r2) in ranges.windowed(2))
if (r1.endInclusive != r2.start-1)
return row + 4000000 * (r1.endInclusive+1)
println("not in $row")
}
return -1
}
fun main() {
//val input = readInput("d15/test"); val row = 10L
val input = readInput("d15/input1"); val row = 2000000L
//println(part1(input, row))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 5cf6b2142df6082ddd7d94f2dbde037f1fe0508f | 5,121 | aoc2022 | Creative Commons Zero v1.0 Universal |
src/main/kotlin/me/peckb/aoc/_2019/calendar/day18/Day18.kt | peckb1 | 433,943,215 | false | {"Kotlin": 956135} | package me.peckb.aoc._2019.calendar.day18
import arrow.core.mapNotNull
import me.peckb.aoc._2019.calendar.day18.Day18.Section.*
import me.peckb.aoc._2019.calendar.day18.Day18.Section.Source.*
import javax.inject.Inject
import me.peckb.aoc.generators.InputGenerator.InputGeneratorFactory
typealias Distance = Int
class Day18 @Inject constructor(
private val generatorFactory: InputGeneratorFactory,
) {
fun partOne(filename: String) = generatorFactory.forFile(filename).read { input ->
val inputList = input.toList()
val caves = createCaves(inputList)
val paths = createPaths(caves)
solve(paths)
}
fun partTwo(filename: String) = generatorFactory.forFile(filename).read { input ->
val inputList = input.toList()
val caves = createCaves(inputList).toMutableMap()
val (robotX, robotY) = caves.entries.first { it.value is Robot }.key
// put in the walls
listOf(
Area(robotX, robotY),
Area(robotX + 1, robotY),
Area(robotX - 1, robotY),
Area(robotX, robotY + 1),
Area(robotX, robotY - 1),
).forEach { caves[it] = Wall }
// make four new robots for each section
listOf(
Area(robotX + 1, robotY + 1),
Area(robotX + 1, robotY - 1),
Area(robotX - 1, robotY + 1),
Area(robotX - 1, robotY - 1),
).forEachIndexed { index, area -> caves[area] = Robot(index) }
val paths = createPaths(caves)
solve(paths)
}
private fun createCaves(input: List<String>): Map<Area, Section> {
val caves = mutableMapOf<Area, Section>()
var bots = 0
input.forEachIndexed { y, line ->
line.forEachIndexed { x, data ->
val area = Area(x, y)
when (data) {
in 'A'..'Z' -> caves[area] = Door(Character.toLowerCase(data))
in 'a'..'z' -> caves[area] = Key(data)
'@' -> caves[area] = Robot(bots++)
'.' -> caves[area] = Empty
'#' -> caves[area] = Wall
}
}
}
return caves
}
private fun createPaths(caves: Map<Area, Section>): Map<Source, Map<Key, Route>> {
val sourceLocations = caves.mapNotNull { (_, a) -> if (a is Source) a else null }
val paths = mutableMapOf<Source, Map<Key, Route>>()
sourceLocations.forEach { (area, source) ->
val result = mutableMapOf<Key, Route>()
val doorsByArea = mutableMapOf(area to emptySet<Door>())
val caveDijkstra = CaveDijkstra(caves, result, doorsByArea, area)
caveDijkstra.solve(area)
paths[source] = result
}
return paths
}
private fun solve(paths: Map<Source, Map<Key, Route>>): Int {
val allKeys: Set<Key> = paths.keys.mapNotNullTo(mutableSetOf()) { (it as? Key) }
val searchDijkstra = SearchDijkstra(allKeys, paths)
val sources = paths.keys.filterIsInstance<Robot>()
val startArea = SearchArea(sources, emptySet())
val solutions = searchDijkstra.solve(startArea)
return solutions
.filter { (searchArea, _) -> searchArea.foundKeys.containsAll(allKeys) }
.minOf { it.value }
}
data class Area(val x: Int, val y: Int)
data class Route(val distance: Distance, val doorsBlocking: Set<Door>)
sealed class Section {
sealed class Source : Section() {
data class Robot(val id: Int) : Source()
data class Key(val id: Char) : Source()
}
data class Door(val id: Char) : Section() { val key: Key = Key(id.lowercaseChar()) }
data object Empty : Section()
data object Wall : Section()
}
}
| 0 | Kotlin | 1 | 3 | 2625719b657eb22c83af95abfb25eb275dbfee6a | 3,461 | advent-of-code | MIT License |
src/main/kotlin/summarisation/Summarise.kt | rock3125 | 138,799,834 | false | {"Kotlin": 30711, "Java": 939, "Shell": 774} | package summarisation
import summarisation.parser.Sentence
import summarisation.parser.StanfordParser
import summarisation.parser.Token
import summarisation.parser.Undesirables
import java.util.*
import kotlin.collections.ArrayList
import kotlin.math.ln
import kotlin.math.sqrt
/**
* Extractive Summarization of text - simple algorithm that scores texts
* based on position in story, numbers, proper nouns, thematic relationships between title and sentences,
* cosine relationships between sentences, and themes based on frequencies
*
*/
class Summarise {
private val undesirables = Undesirables() // stop word detector
private val parser = StanfordParser() // stanford parser for tagging and sentence boundary detection
init {
parser.init()
}
/**
* perform a text summarization - assumes first line of book is the "title" (And will add a full stop to this line)
*
* @param text the text to summary
* @param topN the top scoring item count to return
* @param sortBySentenceAfterTopN resort by story order after topN have been cut-off
* @return if valid a top list of n sentences
*/
fun summarize(text: String, topN: Int, sortBySentenceAfterTopN: Boolean): ArrayList<Sentence> {
if (topN > 0) {
val result = preProcessText(text)
if (result != null) {
val sentenceScoreList = scoreSentences(result)
return SummariseSentenceScore.getTopN(result.originalSentenceList, sentenceScoreList, topN,
sortBySentenceAfterTopN)
}
}
return ArrayList()
}
/**
* pre-process all the text - return a summary of the word frequencies and the parsed text itself
*
* @param text the text to process
* @return the pre processing results for this text
*/
private fun preProcessText(_text: String): SummarisePreProcessResult? {
// split the title "cleverly"
var text = _text
val parts = text.split("\n")
val sb = StringBuilder()
var counter = 0
for (part in parts) {
sb.append(part)
if (counter == 0) {
sb.append(".")
}
sb.append("\n")
counter += 1
}
text = sb.toString()
val sentenceList = parser.parse(text)
val frequencyMap = HashMap<String, Int>()
val finalSentenceList = ArrayList<Sentence>()
var longestSentence = 0
for (sentence in sentenceList) {
val newTokenList = ArrayList<Token>()
for (token in sentence.tokenList) {
if (!undesirables.contains(token.lemma.toLowerCase())) {
newTokenList.add(token)
}
}
if (newTokenList.isNotEmpty()) {
for (t in newTokenList) {
val lemma = t.lemma.toLowerCase()
if (!frequencyMap.containsKey(lemma)) {
frequencyMap[lemma] = 1
} else {
frequencyMap[lemma] = frequencyMap[lemma]!! + 1
}
}
}
// allow empty sentences to make tokenized match original
finalSentenceList.add(Sentence(newTokenList))
if (newTokenList.size > longestSentence) {
longestSentence = newTokenList.size
}
}
if (finalSentenceList.isNotEmpty()) {
val title = finalSentenceList[0].tokenList
return SummarisePreProcessResult(sentenceList, finalSentenceList, frequencyMap, longestSentence, title)
}
return null
}
/**
* given the processed results (parsed data) - apply the scoring algorithms across all sentences
*
* @param results the pre-processing results ready to be processed
* @return a list of scores, one for each sentence - additive between the different algorithms applied,
* the highest score is assumed to be the most relevant / representative sentence
*/
private fun scoreSentences(results: SummarisePreProcessResult?): ArrayList<Float> {
if (results == null)
return ArrayList()
val sentenceList = results.tokenizedSentenceList
val title = results.title
val longestSentence = results.longestSentence
val wordCount = results.wordCount
val resultMap = HashMap<Int, Float>()
for (i in sentenceList.indices)
resultMap[i] = 0.0f
val titleFeatures = getTitleFeatures(sentenceList, title)
for (i in sentenceList.indices)
resultMap[i] = resultMap[i]!! + titleFeatures[i]
val sentenceLength = getSentenceLengthFeatures(sentenceList, longestSentence)
for (i in sentenceList.indices)
resultMap[i] = resultMap[i]!! + sentenceLength[i]
val tfifs = getTfIsf(sentenceList, wordCount)
for (i in sentenceList.indices)
resultMap.put(i, resultMap[i]!! + tfifs[i])
val sentencePos = getSentencePositionRating(sentenceList, sentenceList.size / 4)
for (i in sentenceList.indices)
resultMap.put(i, resultMap[i]!! + sentencePos[i])
// O(n2) - very expensive to run
// List<Float> sentenceSim = getSentenceSimilarity(sentenceList);
// for (int i = 0; i < sentenceList.size(); i++)
// resultMap.put(i, resultMap[i]!! + sentenceSim.get(i));
val properNouns = getProperNounFeatures(sentenceList)
for (i in sentenceList.indices)
resultMap.put(i, resultMap[i]!! + properNouns[i])
val thematicWords = getThematicFeatures(sentenceList, wordCount, 10)
for (i in sentenceList.indices)
resultMap.put(i, resultMap[i]!! + thematicWords[i])
val numericData = getNumericalFeatures(sentenceList)
for (i in sentenceList.indices)
resultMap.put(i, resultMap[i]!! + numericData[i])
val sentenceRatingList = ArrayList<Float>()
for (i in sentenceList.indices)
sentenceRatingList.add(resultMap[i]!!)
return sentenceRatingList
}
/**
* return a score for each sentence vis a vie title scoring
* @param sentenceList the list of sentences to check
* @param title the title's tokens
* @return a list of floats, one for each sentence on how it scores
*/
private fun getTitleFeatures(sentenceList: List<Sentence>, title: List<Token>): List<Float> {
// setup a faster lookup
val titleLookup = HashSet<String>()
for (token in title) {
titleLookup.add(token.lemma.toLowerCase())
}
val sentenceTitleFeatures = ArrayList<Float>()
for (sentence in sentenceList) {
var count = 0.0f
if (title.isNotEmpty()) {
for (token in sentence.tokenList) {
if (titleLookup.contains(token.lemma.toLowerCase())) {
count += 1.0f
}
}
}
sentenceTitleFeatures.add(count / title.size.toFloat())
}
return sentenceTitleFeatures
}
/**
* return a list of how the sentences correspond to the longest sentence from [0.0, 1.0]
* @param sentenceList the list of sentences to check
* @param longestSentence the size of the longest sentence
* @return a list of scores for each sentence one
*/
private fun getSentenceLengthFeatures(sentenceList: List<Sentence>, longestSentence: Int): List<Float> {
val sentenceLengthFeatures = ArrayList<Float>()
val longestS = longestSentence.toFloat()
for (sentence in sentenceList) {
if (longestS > 0.0f) {
sentenceLengthFeatures.add(sentence.tokenList.size.toFloat() / longestS)
} else {
sentenceLengthFeatures.add(0.0f)
}
}
return sentenceLengthFeatures
}
/**
* return a count of the number of sentences to token appears in
* @param sentenceList the set of sentences
* @param token the token to check
* @return the count of the number of sentences token appears in
*/
private fun getWordSentenceCount(sentenceList: List<Sentence>, token: Token, cache: HashMap<String, Int>): Int {
if (cache.containsKey(token.lemma.toLowerCase())) {
return cache[token.lemma.toLowerCase()]!!
} else {
var numSentences = 0
for (sentence in sentenceList) {
for (t in sentence.tokenList) {
if (t.lemma.compareTo(token.lemma, ignoreCase = true) == 0) {
numSentences += 1
break
}
}
}
cache[token.lemma.toLowerCase()] = numSentences
return numSentences
}
}
/**
* return a value for each sentence on how it scores with the term/frequency - inverse sentence frequency
* @param sentenceList the sentences to score
* @param wordCount the frequency map of all words
* @return the scores for the sentences
*/
private fun getTfIsf(sentenceList: List<Sentence>, wordCount: HashMap<String, Int>): List<Float> {
val sentenceFeatures = ArrayList<Float>()
val cache = HashMap<String, Int>()
var largest = 0.0f
for (sentence in sentenceList) {
var w = 0.0
for (token in sentence.tokenList) {
val n = getWordSentenceCount(sentenceList, token, cache).toDouble()
w += wordCount[token.lemma.toLowerCase()]!!.toDouble() * ln(sentenceList.size.toDouble() / n)
}
sentenceFeatures.add(w.toFloat())
if (w > largest) {
largest = w.toFloat()
}
}
return normalize(sentenceFeatures, largest)
}
/**
* normalize list if largest > 0.0 using largest
* @param list the list to normalize
* @param largest the normalization max value
* @return a new list or the old list if largest == 0.0
*/
private fun normalize(list: List<Float>, largest: Float): List<Float> {
if (largest > 0.0f) {
val finalSentenceFeatures = ArrayList<Float>()
for (value in list) {
finalSentenceFeatures.add(value / largest)
}
return finalSentenceFeatures
}
return list
}
/**
* rank the numToRank sentence with a score decending from 1.0 to 0.0
* @param sentenceList the list of sentences
* @param numToRank how many to "rank" (default was 5)
* @return the list of features for these sentences
*/
private fun getSentencePositionRating(sentenceList: List<Sentence>, numToRank: Int): List<Float> {
val sentenceFeatures = ArrayList<Float>()
var n = numToRank.toFloat()
for (sentence in sentenceList) {
if (n > 0.0f) {
sentenceFeatures.add(n / numToRank)
n -= 1.0f
} else {
sentenceFeatures.add(0.0f)
}
}
return sentenceFeatures
}
/**
* map a sentence into frequency items
* @param sentence the sentence to map
* @return the words and their frequencies
*/
private fun map(sentence: Sentence): Map<String, Int> {
val result = HashMap<String, Int>()
for (token in sentence.tokenList) {
val lemma = token.lemma.toLowerCase()
if (!result.containsKey(lemma)) {
result[lemma] = 1
} else {
result[lemma] = result[lemma]!! + 1
}
}
return result
}
/**
* perform a frequency cosine map between s1 and s2
* @param s1 sentence set 1 of words with frequencies
* @param s2 sentence set 2 of words with frequencies
* @return the cosine similarity between s1 and s2
*/
private fun getCosine(s1: Map<String, Int>, s2: Map<String, Int>): Float {
var numerator = 0.0f
for (key1 in s1.keys) {
if (s2.containsKey(key1)) {
numerator += s1[key1]!! * s2[key1]!!
}
}
var sum1 = 0.0f
for (v1 in s1.values) {
sum1 += v1 * v1
}
var sum2 = 0.0f
for (v2 in s2.values) {
sum2 += v2 * v2
}
val denominator = (sqrt(sum1) + sqrt(sum2))
return if (denominator > 0.0f) {
numerator / denominator
} else 0.0f
}
/**
* this is a cosine similarity measurement between sentences among each other
* O(n2) - careful
*
* @param sentenceList the list of sentences to apply the algorithm to
* @return a list of values identifying similarities between other sentences overall
*/
private fun getSentenceSimilarity(sentenceList: List<Sentence>): List<Float> {
val sentenceFeatures = ArrayList<Float>()
var maxS = 0.0f
for (i in sentenceList.indices) {
var s = 0.0f
for (j in sentenceList.indices) {
if (i != j) {
s += getCosine(map(sentenceList[i]), map(sentenceList[j]))
}
}
sentenceFeatures.add(s)
if (s > maxS) {
maxS = s
}
}
// normalize?
return normalize(sentenceFeatures, maxS)
}
/**
* get frequencies for the proper nouns in each sentence
* @param sentenceList the sentences to check
* @return a list of proper noun weightings
*/
private fun getProperNounFeatures(sentenceList: List<Sentence>): List<Float> {
val sentenceFeatures = ArrayList<Float>()
for (sentence in sentenceList) {
var count = 0.0f
for (token in sentence.tokenList) {
if (token.tag.compareTo("NNP", ignoreCase = true) == 0 || token.tag.compareTo("NNPS", ignoreCase = true) == 0) {
count += 1.0f
}
}
if (sentence.tokenList.isNotEmpty()) {
sentenceFeatures.add(count / sentence.tokenList.size)
} else {
sentenceFeatures.add(0.0f)
}
}
return sentenceFeatures
}
/**
* get thematic (i.e. high frequency) features judgements for sentences
* @param sentenceList the sentences to consider
* @param wordCount the existing frequency map of all items
* @param top the top-n items to score on (a count)
* @return a list of values for each sentence
*/
private fun getThematicFeatures(sentenceList: List<Sentence>, wordCount: HashMap<String, Int>, top: Int): List<Float> {
// grab the top x thematic words
val thematicWords = HashSet(SummaryFrequencyWord.getTopN(wordCount, top))
var maxCount = 0.0f
val sentenceFeatures = ArrayList<Float>()
for (sentence in sentenceList) {
var count = 0.0f
for (token in sentence.tokenList) {
if (thematicWords.contains(token.lemma.toLowerCase())) {
count += 1.0f
}
}
sentenceFeatures.add(count)
if (count > maxCount) {
maxCount = count
}
}
return normalize(sentenceFeatures, maxCount)
}
// helper: is str a number (1231244) but not a float
private fun isNumber(str: String): Boolean {
if (str.trim().isNotEmpty()) {
val data = str.toCharArray()
for (ch in data) {
if (ch !in '0'..'9') {
return false
}
}
return true
}
return false
}
/**
* get sentences that have numbers in them
* @param sentenceList the list
* @return a feature set for this sentence
*/
private fun getNumericalFeatures(sentenceList: List<Sentence>): List<Float> {
val sentenceFeatures = ArrayList<Float>()
for (sentence in sentenceList) {
var count = 0.0f
for (token in sentence.tokenList) {
if (isNumber(token.lemma)) {
count += 1.0f
}
}
if (sentence.tokenList.isNotEmpty()) {
sentenceFeatures.add(count)
} else {
sentenceFeatures.add(0.0f)
}
}
return sentenceFeatures
}
}
| 0 | Kotlin | 0 | 4 | 24d8916dbecde35eaeb760eb4307ca32a4ecb768 | 16,681 | ExtractiveSummarisation | MIT License |
BestFit/src/Main.kt | nepinney | 218,421,434 | false | {"Kotlin": 2566} | import java.util.*
import kotlin.collections.ArrayList
import kotlin.math.ceil
import kotlin.random.Random
fun generatePackages() =
sequence {
val i = 100
while (true) yield((i*Random.nextFloat()).toInt())
}
fun generateBins() =
sequence {
var i = 0
while (true) yield(Bin(i++))
}
fun packBins (packages: Sequence<Int>, bins: Sequence<Bin>, numOfPackages: Int): MutableList<Bin> {
val storageContainer: MutableList<Bin> = ArrayList()
val iterPacks = packages.iterator()
val iterBins = bins.iterator()
var pack = iterPacks.next()
var bin = iterBins.next()
val total = ArrayList<Int>()
for (i in 0 until numOfPackages) {
when (i){
0 -> {
bin.addToBin(pack) //add pack to bin
storageContainer.add(bin) //add bin to storageContainer
}
else -> {
val least = storageContainer.filter{ it.availableSpace >= pack }.map{ it.availableSpace - pack}.sortedDescending()
if (least.isNotEmpty()) {
val best = storageContainer.filter { (it.availableSpace - pack) == least[least.lastIndex] }
storageContainer[(best[0].binNumber)].addToBin(pack)
} else {
val aBin = iterBins.next()
aBin.addToBin(pack)
storageContainer.add(aBin)
}
}
}
print("$pack ")
total.add(pack)
pack = iterPacks.next()
}
println()
val totalOfItems = total.reduce{ acc, d -> acc + d }
println("Total room required: $totalOfItems ")
println("Will need at least ${(totalOfItems/100)+1} bins.\n")
return storageContainer
}
fun main() {
/* val reader = Scanner(System.`in`)
print("How many items do you have?")
val numItems = reader.nextInt()*/
val packs = generatePackages()
val bins = generateBins()
val loadedContainers = packBins(packs, bins, 100)
loadedContainers.forEach { println("Bin ${it.binNumber} Rem space: ${it.availableSpace} ${it.items}") }
}
| 0 | Kotlin | 0 | 0 | 2404ae78a0af3c4771bd06685e66cf087226195f | 2,208 | Best-Fit-Bin-Packing | The Unlicense |
src/Day06.kt | jalex19100 | 574,686,993 | false | {"Kotlin": 19795} | fun main() {
fun allUnique(string: String): Boolean {
val setOfChars = string.toSet().distinct()
// println("$string <=> $setOfChars: ${string.length == setOfChars.size}")
return (string.length == setOfChars.size)
}
fun part1(input: String, markerSize: Int = 4): Int {
var index = markerSize
while (index < input.length) {
if (allUnique(input.substring(index - markerSize, index))) return index
index++
}
return -1
}
fun part2(input: String): Int {
return part1(input, 14)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day06_test")
testInput.forEach { line ->
println("$line ${part1(line)}")
println("$line ${part2(line)}")
}
val input = readInput("Day06")
input.forEach { line ->
println("$input ${part1(line)}")
println("$input ${part2(line)}")
}
}
| 0 | Kotlin | 0 | 0 | a50639447a2ef3f6fc9548f0d89cc643266c1b74 | 979 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/day06/Day06.kt | zypus | 573,178,215 | false | {"Kotlin": 33417, "Shell": 3190} | package day06
import AoCTask
// https://adventofcode.com/2022/day/6
fun Sequence<Char>.charactersReadToFindSequenceOfDistinctSize(size: Int): Int {
val index = this
.windowed(size, step = 1)
.indexOfFirst {
it.toSet().size == size
}
return index + size
}
fun part1(input: List<String>): Int {
val result = input
.first()
.asSequence()
.charactersReadToFindSequenceOfDistinctSize(4)
return result
}
fun part2(input: List<String>): Int {
val result = input
.first()
.asSequence()
.charactersReadToFindSequenceOfDistinctSize(14)
return result
}
fun main() = AoCTask("day06").run {
// test if implementation meets criteria from the description, like:
check(part1(testInput) == 7)
check(part1(readTestInput(2)) == 5)
check(part1(readTestInput(3)) == 6)
check(part1(readTestInput(4)) == 10)
check(part1(readTestInput(5)) == 11)
check(part2(testInput) == 19)
check(part2(readTestInput(2)) == 23)
check(part2(readTestInput(3)) == 23)
check(part2(readTestInput(4)) == 29)
check(part2(readTestInput(5)) == 26)
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f37ed8e9ff028e736e4c205aef5ddace4dc73bfc | 1,214 | aoc-2022 | Apache License 2.0 |
src/day3/main.kt | rafagalan | 573,145,902 | false | {"Kotlin": 5674} | package day3
import readInput
fun Char.toPriority(): Int {
if(this.isLowerCase())
return this.code - 96
return this.code - 38
}
fun <A> setIntersect(a: Set<A>, b: Set<A>) = a.intersect(b)
fun main() {
fun part1(input: List<String>) = input.sumOf {
it.windowed(it.length/2, it.length/2).let { (firstHalf, secondHalf) ->
firstHalf.toSet().intersect(secondHalf.toSet()).let { commonTypes ->
commonTypes.sumOf(Char::toPriority)
}
}
}
fun part2(input: List<String>) = input.windowed(3, 3) { elfGroup ->
elfGroup.map(String::toSet).reduce(::setIntersect).toList()[0].toPriority()
}.sum()
val testInput = readInput("day3/test_input")
check(part1(testInput) == 157)
val realInput = readInput("day3/input")
println(part1(realInput))
val testInput2 = readInput("day3/test_input")
check(part2(testInput2) == 70)
val realInput2 = readInput("day3/input")
println(part2(realInput2))
} | 0 | Kotlin | 0 | 0 | 8e7d3f25fe52a4153479adb56c5924b50f6c0be9 | 1,033 | AdventOfCode2022 | Apache License 2.0 |
src/day04/Day04.kt | TimberBro | 567,240,136 | false | {"Kotlin": 11186} | package day04
import utils.readInput
import kotlin.streams.toList
fun main() {
fun separatePassports(input: List<String>): List<List<String>> {
val passportsList = ArrayList<List<String>>()
var passport = ArrayList<String>()
val iterator = input.listIterator()
while (iterator.hasNext()) {
val line = iterator.next()
if (line.isNotEmpty()) {
passport.add(line)
} else if (line.isEmpty()) {
passportsList.add(passport)
passport = ArrayList()
}
}
passportsList.add(passport)
return passportsList
}
fun part1Valid(passport: Map<String, String>): Boolean {
if (passport.size == 8 || (passport.size == 7 && !passport.contains("cid"))) {
return true
}
return false
}
fun byrValid(byr: String): Boolean {
val intValue = byr.toInt()
if (intValue in 1920..2002) {
return true
}
return false
}
fun iyrValid(iyr: String): Boolean {
val intValue = iyr.toInt()
if (intValue in 2010..2020) {
return true
}
return false
}
fun eyrValid(eyr: String): Boolean {
val intValue = eyr.toInt()
if (intValue in 2020..2030) {
return true
}
return false
}
fun hgtValid(hgt: String): Boolean {
val valuePattern = "((\\d{3}cm)|(\\d{2}in))"
val splitPattern = "((?=cm)|(?=in))"
if (hgt.matches(valuePattern.toRegex())) {
val strings = hgt.split(splitPattern.toRegex())
when (strings[1]) {
"cm" -> return (strings[0].toInt() >= 150 || strings[0].toInt() <= 193)
"in" -> return (strings[0].toInt() >= 59 || strings[0].toInt() <= 76)
}
return false
}
return false
}
fun hclValid(hcl: String): Boolean {
val pattern = "(#[\\da-f]{6})"
return hcl.matches(pattern.toRegex())
}
fun eclValid(ecl: String): Boolean {
val pattern = "((amb)|(blu)|(brn)|(gry)|(grn)|(hzl)|(oth))"
return ecl.matches(pattern.toRegex())
}
fun pidValid(pid: String): Boolean {
// this works, but need to understand it fully
val pattern = "(?<!\\d)(\\d{9})(?!\\d)"
return pid.matches(pattern.toRegex())
}
// chain all validation functions
fun validPassport(passport: Map<String, String>): Boolean {
return passport["byr"]?.let { byrValid(it) } ?: false &&
passport["iyr"]?.let { iyrValid(it) } ?: false &&
passport["eyr"]?.let { eyrValid(it) } ?: false &&
passport["hgt"]?.let { hgtValid(it) } ?: false &&
passport["hcl"]?.let { hclValid(it) } ?: false &&
passport["ecl"]?.let { eclValid(it) } ?: false &&
passport["pid"]?.let { pidValid(it) } ?: false
}
fun part1(input: List<String>): Int {
var result = 0
val passportsList = separatePassports(input)
for (passport in passportsList) {
val parsedFields = passport.stream()
.map { it.split(" ") }
.flatMap { it.stream() }
.map { it.split(":") }
.map { it[0] to it[1] }
.toList().filterNotNull().toMap()
if (part1Valid(parsedFields)) {
result++
}
}
return result
}
fun part2(input: List<String>): Int {
var result = 0
val passportsList = separatePassports(input)
for (passport in passportsList) {
val parsedFields = passport.stream()
.map { it.split(" ") }
.flatMap { it.stream() }
.map { it.split(":") }
.map { it[0] to it[1] }
.toList().filterNotNull().toMap()
if (validPassport(parsedFields)) {
result++
}
}
return result
}
val testInput = readInput("day04/Day04_test")
check(part1(testInput) == 2)
val invalidPassports = readInput("day04/InvalidPassports")
check(part2(invalidPassports) == 0)
val validPassports = readInput("day04/ValidPassports")
check(part2(validPassports) == 4)
val input = readInput("day04/Day04")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 1959383d2f422cc565560eefb1ed4f05bb87a386 | 4,603 | aoc2020 | Apache License 2.0 |
src/day04/Day04.kt | cmargonis | 573,161,233 | false | {"Kotlin": 15730} | package day04
import readInput
private const val DIRECTORY = "./day04"
fun main() {
fun IntRange.contains(other: IntRange): Boolean = first <= other.first && last >= other.last
/**
* Converts e.g. 22-34 to a [IntRange]
*/
fun textToRange(rawRange: String): IntRange = rawRange
.split("-")
.map { it.toInt() }
.zipWithNext { a, b -> a..b }
.first()
fun groupToRanges(it: String) = it.split(",").map { range -> textToRange(range) }
fun part1(input: List<String>): Int = input.map {
groupToRanges(it)
.zipWithNext { a: IntRange, b: IntRange -> a.contains(b) or b.contains(a) }
.first()
}.count { it }
fun part2(input: List<String>): Int = input.map {
groupToRanges(it)
.zipWithNext { a: IntRange, b: IntRange -> a.intersect(b).isNotEmpty() }
.first()
}.count { it }
val input = readInput("${DIRECTORY}/Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | bd243c61bf8aae81daf9e50b2117450c4f39e18c | 1,012 | kotlin-advent-2022 | Apache License 2.0 |
gcj/y2020/qual/d.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package gcj.y2020.qual
private fun solve(n: Int, period: Int = 10) {
val a = IntArray(n)
var iter = 0
fun ask(index: Int): Int {
iter++
println(index + 1)
return readInt()
}
val first = IntArray(2) { -1 }
val negated = IntArray(2) { -1 }
fun fetchNegated(d: Int) {
negated[d] = if (first[d] == -1) 0 else ask(first[d]) xor a[first[d]]
}
for (i in 0 until n / 2) {
val j = n - 1 - i
a[i] = ask(i); a[j] = ask(j)
val d = a[i] xor a[j]
if (first[d] == -1) {
first[d] = i
negated[d] = 0
}
if (negated[d] == -1) fetchNegated(d)
a[i] = a[i] xor negated[d]; a[j] = a[j] xor negated[d]
val needed = if (-1 in negated) 3 else 2
if (iter + needed > period) {
while (iter < period) ask(0)
iter = 0
negated.fill(-1)
}
}
repeat(2) { fetchNegated(it) }
val flipped = negated[0] xor negated[1]
val ans = List(n) { a[if (flipped == 0) it else (n - 1 - it)] xor negated[0] }
println(ans.joinToString(""))
}
fun main() {
val (tests, n) = readInts()
repeat(tests) {
solve(n)
assert(readLn() == "Y")
}
}
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 1,234 | competitions | The Unlicense |
src/main/kotlin/org/gmd/service/alg/ELOMemberRatingAlgorithm.kt | akustik | 184,784,065 | false | null | package org.gmd.service.alg
import org.gmd.model.Evolution
import org.gmd.model.Game
import org.gmd.model.Score
import org.springframework.stereotype.Component
@Component
open class ELOMemberRatingAlgorithm : MemberRatingAlgorithm {
companion object {
fun probabilityOfWinForBRating(ratingA: Double, ratingB: Double): Double {
return 1.0 * 1.0 / (1 + 1.0 *
Math.pow(10.0, 1.0 * (ratingA - ratingB) / 400))
}
}
private fun removeGamesNotAffectingELO(games: List<Game>): List<Game> {
return games.filter { game -> game.parties.size > 1 && game.parties.map { p -> p.score }.distinct().count() > 1}
}
override fun rate(games: List<Game>): List<Score> {
val ratedPlayers = mutableMapOf<String, List<Pair<Double, Long>>>()
val gamesToRate = removeGamesNotAffectingELO(games).sortedBy { game -> game.timestamp }
ratePlayersInGame(ratedPlayers, gamesToRate)
return ratedPlayers.map { rating ->
Score(rating.key, Math.round(rating.value.last().first).toInt(), rating.value.size - 1)
}
}
override fun evolution(games: List<Game>): List<Evolution> {
val ratedPlayers = mutableMapOf<String, List<Pair<Double, Long>>>()
val gamesToRate = removeGamesNotAffectingELO(games).sortedBy { game -> game.timestamp }
ratePlayersInGame(ratedPlayers, gamesToRate)
return ratedPlayers.map { rating ->
Evolution(rating.key, rating.value.map { v -> Pair(Math.round(v.first).toInt(), v.second) })
}
}
class RatedMember(val name: String, val score: Int, val rating: List<Pair<Double, Long>>)
private tailrec fun ratePlayersInGame(ratings: MutableMap<String, List<Pair<Double, Long>>>, games: List<Game>): MutableMap<String, List<Pair<Double, Long>>> {
return when {
games.isNotEmpty() -> {
val firstGame = games.first()
val currentStatus = firstGame.parties.flatMap { party ->
party.members.map { member ->
RatedMember(member.name, party.score, ratings.getOrDefault(member.name, listOf(Pair(1200.0, 0L))))
}
}
currentStatus.forEach { member ->
run {
val differentScoreDeltas = currentStatus.filter { m ->
m.score != member.score
}.map { m ->
eloRatingDeltaForA(member, m)
}
val newRating = member.rating.last().first + differentScoreDeltas.sum() / differentScoreDeltas.size
ratings.put(member.name, member.rating + Pair(newRating, firstGame.timestamp!!))
}
}
return ratePlayersInGame(ratings, games.drop(1))
}
else -> ratings
}
}
private fun eloRatingDeltaForA(a: RatedMember, b: RatedMember, k: Int = 30): Double {
return if (a.score > b.score) {
k * probabilityOfWinForB(a, b)
} else {
k * (probabilityOfWinForB(a, b) - 1)
}
}
private fun probabilityOfWinForB(a: RatedMember, b: RatedMember): Double {
val ratingA = a.rating.last().first
val ratingB = b.rating.last().first
return probabilityOfWinForBRating(ratingA, ratingB)
}
}
| 9 | Kotlin | 3 | 4 | 07184b0ea0889b22c78b46f710818187d36b1af7 | 3,439 | topscores | MIT License |
src/main/kotlin/dev/phiber/aoc2022/day4/Solution.kt | rsttst | 572,967,557 | false | {"Kotlin": 7688} | package dev.phiber.aoc2022.day4
import dev.phiber.aoc2022.readAllLinesUntilEmpty
fun parseRange(rangeStr: String) : IntRange {
val (rangeStartStr, rangeEndStr) = rangeStr.split("-", limit = 2)
return rangeStartStr.toInt()..rangeEndStr.toInt()
}
infix fun IntRange.fullyContains(other: IntRange) : Boolean = this.first <= other.first && this.last >= other.last
infix fun IntRange.intersects(other: IntRange) : Boolean = this.first <= other.last && this.last >= other.first
fun main() {
val lines: List<String> = readAllLinesUntilEmpty()
val sectionRangePairs: List<Pair<IntRange, IntRange>> = lines
.map { line -> line.split(",", limit = 2) }
.map { (sectionRangeStr1, sectionRangeStr2) -> parseRange(sectionRangeStr1) to parseRange(sectionRangeStr2) }
val sectionFullContainmentCount: Int = sectionRangePairs.count { (sectionRange1, sectionRange2) ->
sectionRange1 fullyContains sectionRange2 || sectionRange2 fullyContains sectionRange1
}
val sectionIntersectionCount: Int = sectionRangePairs.count { (sectionRange1, sectionRange2) ->
sectionRange1 intersects sectionRange2
}
println("Task 1: $sectionFullContainmentCount")
println("Task 2: $sectionIntersectionCount")
}
| 0 | Kotlin | 0 | 0 | 2155029ebcee4727cd0af75543d9f6f6ab2b8995 | 1,254 | advent-of-code-2022 | Apache License 2.0 |
src/day_14/kotlin/Day14.kt | Nxllpointer | 573,051,992 | false | {"Kotlin": 41751} | import kotlin.math.sign
// AOC Day 14
const val rockCharacter = '#'
const val sandCharacter = '.'
const val airCharacter = ' '
const val printCave = false
typealias Cave = Array<CharArray>
fun Cave.print() = forEach { println(it.joinToString(" ")) }.also { println() }
operator fun Cave.get(point: Vector2D) = this[point.y][point.x]
operator fun Cave.set(point: Vector2D, char: Char) {
this[point.y][point.x] = char
}
val sandMovesPriorityOrdered = listOf(Vector2D(0, 1), Vector2D(-1, 1), Vector2D(1, 1))
fun Cave.simulateFallingSand(startPosition: Vector2D): Vector2D {
var currentPosition = startPosition
var isResting = false
while (!isResting) {
sandMovesPriorityOrdered
.map { currentPosition + it }
.filter { it.y in 0..this.lastIndex && it.x in 0..this[0].lastIndex }
.filter { this[it] == airCharacter }
.apply {
if (none()) isResting = true
else currentPosition = first()
}
}
return currentPosition
}
fun part1(cave: Cave, sandSourcePoint: Vector2D) {
var sandUnits = 0
while (true) {
val sandRestingPoint = cave.simulateFallingSand(sandSourcePoint)
if (sandRestingPoint.y == cave.lastIndex - 1) break
sandUnits++
cave[sandRestingPoint] = sandCharacter
}
if (printCave) cave.print()
println("Part 1: The first unit of sand falls into the abyss after $sandUnits sand units have come to rest")
}
fun part2(cave: Cave, sandSourcePoint: Vector2D) {
var sandUnits = 0
while (true) {
val sandRestingPoint = cave.simulateFallingSand(sandSourcePoint)
sandUnits++
cave[sandRestingPoint] = sandCharacter
if (sandRestingPoint == sandSourcePoint) break
}
if (printCave) cave.print()
println("Part 2: $sandUnits sand untis have to come to rest for the source to be blocked")
}
fun String.toPoint() = this.split(",").mapToInt().run { Vector2D(first(), last()) }
fun Cave.deepCopy(): Cave = map { it.toList().toCharArray() }.toTypedArray()
val pointRegex = "\\d+,\\d+".toRegex()
fun main() {
val (cave, sandSourcePoint) = getAOCInput { rawInput ->
val points = pointRegex.findAll(rawInput).map { it.value.toPoint() }
var minX = points.minOf { it.x }
var maxX = points.maxOf { it.x }
val minY = 0 // Sand level
var maxY = points.maxOf { it.y }
val floorHeight = maxY + 2
maxY = floorHeight
minX -= floorHeight
maxX += floorHeight
fun Vector2D.asNormalized() = Vector2D(x - minX, y - minY)
val cave: Cave = Array(maxY - minY + 1) { CharArray(maxX - minX + 1) { airCharacter } }
val sandSourcePoint = Vector2D(500, 0).asNormalized()
cave[sandSourcePoint] = 'S'
val floorPath = Vector2D(minX, floorHeight).asNormalized() to Vector2D(maxX, floorHeight).asNormalized()
val paths = rawInput.trim().lines()
.flatMap { line ->
line
.split(" -> ")
.map { it.toPoint().asNormalized() }
.zipWithNext()
}
.plus(floorPath)
paths.forEach { (start, end) ->
var currentPos = start
val signX = (end.x - start.x).sign
val signY = (end.y - start.y).sign
while (currentPos.x != end.x) {
cave[currentPos] = rockCharacter
currentPos += Vector2D(signX, 0)
cave[currentPos] = rockCharacter
}
while (currentPos.y != end.y) {
cave[currentPos] = rockCharacter
currentPos += Vector2D(0, signY)
cave[currentPos] = rockCharacter
}
}
cave to sandSourcePoint
}
part1(cave.deepCopy(), sandSourcePoint)
part2(cave.deepCopy(), sandSourcePoint)
}
| 0 | Kotlin | 0 | 0 | b6d7ef06de41ad01a8d64ef19ca7ca2610754151 | 3,912 | AdventOfCode2022 | MIT License |
src/day02/Day02.kt | jimsaidov | 572,881,855 | false | {"Kotlin": 10629} | package day02
class Day02(private val input: List<String>) {
private val DRAW = 3
private val WIN = 6
private val points = mapOf('X' to 1, 'Y' to 2, 'Z' to 3)
private val drawPoints = mapOf("A X" to 4, "B Y" to 5, "C Z" to 6)
private val lossPoints = mapOf("A Z" to 3, "B X" to 1, "C Y" to 2)
fun part1(): Int {
var totalScore = 0
input.forEach {
totalScore += when (it) {
in lossPoints -> lossPoints.getValue(it)
in drawPoints -> drawPoints.getValue(it)
else -> points.getValue(it[2]) + WIN
}
}
return totalScore
}
private val complementLoss = mapOf('A' to 'Z', 'B' to 'X', 'C' to 'Y')
private val complementDraw = mapOf('A' to 'X', 'B' to 'Y', 'C' to 'Z')
private val complementWin = mapOf('A' to 'Y', 'B' to 'Z', 'C' to 'X')
fun part2(): Int {
var totalScore = 0
input.forEach{
totalScore += when(it[2]){
'X' -> points.getValue(complementLoss.getValue(it[0]))
'Y' -> points.getValue(complementDraw.getValue(it[0])) + DRAW
else -> points.getValue(complementWin.getValue(it[0])) + WIN
}
}
return totalScore
}
}
fun main() {
check(Day02(InputReader.testFileAsList("02")).part1() == 15)
println(Day02(InputReader.asList("02")).part1())
check(Day02(InputReader.testFileAsList("02")).part2() == 12)
println(Day02(InputReader.asList("02")).part2())
} | 0 | Kotlin | 0 | 0 | d4eb926b57460d4ba4acced14658f211e1ccc12c | 1,525 | aoc2022 | Apache License 2.0 |
kotlin/14.kt | NeonMika | 433,743,141 | false | {"Kotlin": 68645} | class Day14 : Day<Day14.Replacements>("14") {
data class Replacements(val template: String, val mappings: Map<String, String>)
override fun dataStar1(lines: List<String>) =
Replacements(lines.first(), lines.drop(1).associate { it.strings("->").let { it[0] to it[1] } })
override fun dataStar2(lines: List<String>) = dataStar1(lines)
fun Map<String, Long>.next(data: Replacements) =
this.entries
.flatMap { (pair, v) ->
listOf(
(pair[0] + data.mappings[pair]!!) to v,
(data.mappings[pair]!! + pair[1]) to v
)
}
.groupingBy { it.first }
.fold(0L) { sum, (_, v) -> sum + v }
fun Map<String, Long>.charCounts(data: Replacements) =
this.entries
.groupingBy { it.key[0] }
.fold(0L) { sum, (_, v) -> sum + v }
.toMutableMap()
.also { it[data.template.last()] = 1 + (it[data.template.last()] ?: 0) }
override fun star1(data: Replacements): Any {
var pairCounts = data.template.windowed(2).groupingBy { it }.eachCount().mapValues { (_, v) -> v.toLong() }
repeat(10) {
pairCounts = pairCounts.next(data)
}
return pairCounts.charCounts(data).values.sorted().let { it.last() - it.first() }
}
override fun star2(data: Replacements): Any {
var pairCounts = data.template.windowed(2).groupingBy { it }.eachCount().mapValues { (_, v) -> v.toLong() }
repeat(40) {
pairCounts = pairCounts.next(data)
}
return pairCounts.charCounts(data).values.sorted().let { it.last() - it.first() }
}
}
fun main() {
Day14()()
} | 0 | Kotlin | 0 | 0 | c625d684147395fc2b347f5bc82476668da98b31 | 1,722 | advent-of-code-2021 | MIT License |
src/Day08_part2.kt | rosyish | 573,297,490 | false | {"Kotlin": 51693} | import kotlin.math.max
private data class Score(var left: Int, var right: Int, var up: Int, var down: Int) {
override fun toString() = "$left, $right, $up, $down"
}
fun main() {
val lines = readInput("Day08_input")
val rows = lines.size
val cols = lines[0].length
val input = Array(rows) { i -> Array(cols) { j -> lines[i][j] - '0'} }
val scores = Array(rows) { Array(cols) { Score(0,0,0,0) } }
for (i in 0 until rows) {
for (j in 0 until cols) {
scores[i][j].left = j - 0
scores[i][j].right = cols - 1 - j
scores[i][j].up = i - 0
scores[i][j].down = rows - 1 - i
for (k in j-1 downTo 0) {
val onMyLeft = input[i][k]
if (onMyLeft >= input[i][j]) {
scores[i][j].left = j - k
break
}
}
for (k in j+1 until cols) {
val onMyRight = input[i][k]
if (onMyRight >= input[i][j]) {
scores[i][j].right = k - j
break
}
}
for (k in i-1 downTo 0) {
val above = input[k][j]
if (above >= input[i][j]) {
scores[i][j].up = i-k
break
}
}
for (k in i+1 until rows) {
val below = input[k][j]
if (below >= input[i][j]) {
scores[i][j].down = k-i
break
}
}
}
}
var maxValue = 0;
for (i in 0 until rows) {
for (j in 0 until cols) {
val s = scores[i][j].left * scores[i][j].right * scores[i][j].up * scores[i][j].down
maxValue = max(maxValue, s)
}
}
println(maxValue)
} | 0 | Kotlin | 0 | 2 | 43560f3e6a814bfd52ebadb939594290cd43549f | 1,847 | aoc-2022 | Apache License 2.0 |
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[剑指 Offer 53 - II]0~n-1中缺失的数字.kt | maoqitian | 175,940,000 | false | {"Kotlin": 354268, "Java": 297740, "C++": 634} | //一个长度为n-1的递增排序数组中的所有数字都是唯一的,并且每个数字都在范围0~n-1之内。在范围0~n-1内的n个数字中有且只有一个数字不在该数组中,请找出
//这个数字。
//
//
//
// 示例 1:
//
// 输入: [0,1,3]
//输出: 2
//
//
// 示例 2:
//
// 输入: [0,1,2,3,4,5,6,7,9]
//输出: 8
//
//
//
// 限制:
//
// 1 <= 数组长度 <= 10000
// Related Topics 数组 二分查找
// 👍 90 👎 0
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
fun missingNumber(nums: IntArray): Int {
//方法一 等差数列 (1+n)*n/2
val len = nums.size
var alltotal = (len+1)*len/2
var total = 0
for (i in 0 until len){
total += nums[i]
}
return alltotal - total
//方法二 二分查找 和前一题类似
var left = 0
var right = nums.size-1
while (left <= right){
val mid = left + (right - left)/2
//如果 index 和数组对应数字相等 说明前面都排列正确无漏,往后找
if(nums[mid] == mid) left = mid+1
else right = mid-1 //否则不对齐则漏数在当前位置前面
}
return left
}
}
//leetcode submit region end(Prohibit modification and deletion)
| 0 | Kotlin | 0 | 1 | 8a85996352a88bb9a8a6a2712dce3eac2e1c3463 | 1,357 | MyLeetCode | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/NetworkDelayTime.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import java.util.LinkedList
import java.util.PriorityQueue
import java.util.Queue
import kotlin.math.max
/**
* 743. Network Delay Time
* @see <a href="https://leetcode.com/problems/network-delay-time/">Source</a>
*/
fun interface NetworkDelayTime {
operator fun invoke(times: Array<IntArray>, n: Int, k: Int): Int
}
class NetworkDelayTimeDFS : NetworkDelayTime {
override operator fun invoke(times: Array<IntArray>, n: Int, k: Int): Int {
// Build the adjacency list
for (time in times) {
val source = time[0]
val dest = time[1]
val travelTime = time[2]
adj.putIfAbsent(source, ArrayList())
adj[source]?.add(Pair(travelTime, dest))
}
// Sort the edges connecting to every node
for (node in adj.keys) {
adj[node]?.let { it.sortWith { a, b -> a.first - b.second } }
}
val signalReceivedAt = IntArray(n + 1) { Int.MAX_VALUE }
dfs(signalReceivedAt, k, 0)
var answer = Int.MIN_VALUE
for (node in 1..n) {
answer = max(answer, signalReceivedAt[node])
}
// Integer.MAX_VALUE signifies at least one node is unreachable
return if (answer == Int.MAX_VALUE) -1 else answer
}
// Adjacency list
private val adj: MutableMap<Int, MutableList<Pair<Int, Int>>> = HashMap()
private fun dfs(signalReceivedAt: IntArray, currNode: Int, currTime: Int) {
// If the current time is greater than or equal to the fastest signal received
// Then no need to iterate over adjacent nodes
if (currTime >= signalReceivedAt[currNode]) {
return
}
// Fastest signal time for currNode so far
signalReceivedAt[currNode] = currTime
if (!adj.containsKey(currNode)) {
return
}
// Broadcast the signal to adjacent nodes
val pairs = adj[currNode] ?: return
for (edge in pairs) {
val (travelTime, neighborNode) = edge
// currTime + time : time when signal reaches neighborNode
dfs(signalReceivedAt, neighborNode, currTime + travelTime)
}
}
}
class NetworkDelayTimeBFS : NetworkDelayTime {
override operator fun invoke(times: Array<IntArray>, n: Int, k: Int): Int {
// Build the adjacency list
for (time in times) {
val source = time[0]
val dest = time[1]
val travelTime = time[2]
adj.putIfAbsent(source, ArrayList())
adj[source]?.add(Pair(travelTime, dest))
}
val signalReceivedAt = IntArray(n + 1) { Int.MAX_VALUE }
bfs(signalReceivedAt, k)
var answer = Int.MIN_VALUE
for (i in 1..n) {
answer = max(answer, signalReceivedAt[i])
}
// INT_MAX signifies at least one node is unreachable
return if (answer == Int.MAX_VALUE) -1 else answer
}
// Adjacency list
var adj: MutableMap<Int, MutableList<Pair<Int, Int>>> = HashMap()
private fun bfs(signalReceivedAt: IntArray, sourceNode: Int) {
val q: Queue<Int> = LinkedList()
q.add(sourceNode)
// Time for starting node is 0
signalReceivedAt[sourceNode] = 0
while (q.isNotEmpty()) {
val currNode: Int = q.remove()
if (!adj.containsKey(currNode)) {
continue
}
// Broadcast the signal to adjacent nodes
val pairs = adj[currNode] ?: return
for (edge in pairs) {
val (travelTime, neighborNode) = edge
// Fastest signal time for neighborNode so far
// signalReceivedAt[currNode] + time :
// time when signal reaches neighborNode
val arrivalTime = signalReceivedAt[currNode] + travelTime
if (signalReceivedAt[neighborNode] > arrivalTime) {
signalReceivedAt[neighborNode] = arrivalTime
q.add(neighborNode)
}
}
}
}
}
class NetworkDelayTimeDijkstra : NetworkDelayTime {
data class GraphNode(val id: Int, val neighbors: MutableList<GraphNode> = mutableListOf())
override operator fun invoke(times: Array<IntArray>, n: Int, k: Int): Int {
val graph = (1..n).associateWith { GraphNode(it) }
val weight = mutableMapOf<Pair<Int, Int>, Int>()
val distance = mutableMapOf<Int, Int>()
times.forEach { time ->
graph[time[1]]?.let { graph[time[0]]?.neighbors?.add(it) }
weight[Pair(time[0], time[1])] = time[2]
}
dijkstra(graph, weight, distance, k)
return distance.map { it.value }.maxOf { it }.takeIf { it != Int.MAX_VALUE } ?: -1
}
private fun dijkstra(
graph: Map<Int, GraphNode>,
weight: Map<Pair<Int, Int>, Int>,
distance: MutableMap<Int, Int>,
sourceId: Int,
) {
initializeSingleSource(graph, distance, sourceId)
val minHeap = PriorityQueue<GraphNode> { o1, o2 -> (distance[o1.id] ?: 0) - (distance[o2.id] ?: 0) }
minHeap.offer(graph[sourceId]!!)
while (minHeap.isNotEmpty()) {
val node = minHeap.poll()
node.neighbors.forEach { graphNode ->
val newDist = (distance[node.id] ?: 0) + (weight[Pair(node.id, graphNode.id)] ?: 0)
val safeDist = distance[graphNode.id] ?: 0
if (safeDist > newDist) {
distance[graphNode.id] = newDist
graph[graphNode.id]?.let { minHeap.offer(it) }
}
}
}
}
private fun initializeSingleSource(graph: Map<Int, GraphNode>, distance: MutableMap<Int, Int>, sourceId: Int) {
graph.map { it.key }.forEach { distance[it] = Int.MAX_VALUE }
distance[sourceId] = 0
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 6,523 | kotlab | Apache License 2.0 |
src/Day10.kt | slawa4s | 573,050,411 | false | {"Kotlin": 20679} | data class Command(val command: String, val value: Int?)
const val ADDX = "addx"
const val NOOP = "noop"
val mapOfTimeOfCommand = mapOf(
ADDX to 2,
NOOP to 1
)
fun main() {
fun isCycleCounted(cycle: Int): Boolean = (cycle - 20) % 40 == 0
fun prepareInput(input: List<String>): List<Command> = input.map {
val split = it.split(" ")
Command(split[0], if (split.size > 1) Integer.parseInt(split[1]) else null)
}
fun part1(commands: List<Command>): Int {
var sumOfCountedCycles = 0
var cycle = 0
var x = 1
for (command in commands) {
val needCycles = mapOfTimeOfCommand[command.command]!!
for (executionTime in 0 until needCycles) {
cycle += 1
if (isCycleCounted(cycle)) sumOfCountedCycles += x * cycle
}
if (command.command == ADDX) x += command.value!!
}
return sumOfCountedCycles
}
val preparedInput = prepareInput(readInput("Day10"))
println(part1(preparedInput))
}
| 0 | Kotlin | 0 | 0 | cd8bbbb3a710dc542c2832959a6a03a0d2516866 | 1,053 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/aoc2023/Day10.kt | Ceridan | 725,711,266 | false | {"Kotlin": 110767, "Shell": 1955} | package aoc2023
class Day10 {
fun part1(input: String): Int {
val (start, grid) = parseInput(input)
val loop = findLoop(start, grid)
return loop.size / 2
}
fun part2(input: String): Int {
val (start, grid) = parseInput(input)
val loop = findLoop(start, grid)
val (newGridPoints, newLoopPoints) = expandPoints(input, loop)
val outside = newLoopPoints.toMutableSet()
val deque = ArrayDeque(listOf(-1 to -1))
while (deque.isNotEmpty()) {
val (y, x) = deque.removeFirst()
if ((y to x) in outside) continue
if ((y to x) !in newGridPoints) continue
outside.add(y to x)
deque.add(y - 1 to x)
deque.add(y + 1 to x)
deque.add(y to x - 1)
deque.add(y to x + 1)
}
return newGridPoints.subtract(outside)
.count { it.y % 2 == 0 && it.x % 2 == 0 }
}
private fun findLoop(start: Pipe, grid: Map<Point, Pipe>): Set<Pipe> {
val loop = mutableSetOf(start)
var prevPoint = start.selfPoint
var nextPoint = start.outPoint
while (nextPoint != start.selfPoint) {
grid[nextPoint]!!.let {
loop.add(it)
nextPoint = it.getOutPoint(prevPoint)
prevPoint = it.selfPoint
}
}
return loop
}
private fun expandPoints(input: String, loop: Set<Pipe>): Pair<Set<Point>, Set<Point>> {
val newGridPoints = mutableSetOf<Point>()
val newLoopPoints = mutableSetOf<Point>()
val lines = input.split('\n')
val rows = lines.size
val cols = lines[0].length
for (y in -1..rows * 2) {
for (x in -1..cols * 2) {
newGridPoints.add(y to x)
}
}
for (pipe in loop) {
val (y, x) = pipe.selfPoint
val newY = y * 2
val newX = x * 2
newGridPoints.add(newY to newX)
newLoopPoints.add(newY to newX)
if (pipe.type in setOf('|', 'L', 'J')) {
newGridPoints.add(newY - 1 to newX)
newLoopPoints.add(newY - 1 to newX)
}
if (pipe.type in setOf('|', '7', 'F')) {
newGridPoints.add(newY + 1 to newX)
newLoopPoints.add(newY + 1 to newX)
}
if (pipe.type in setOf('-', 'J', '7')) {
newGridPoints.add(newY to newX - 1)
newLoopPoints.add(newY to newX - 1)
}
if (pipe.type in setOf('-', 'L', 'F')) {
newGridPoints.add(newY to newX + 1)
newLoopPoints.add(newY to newX + 1)
}
}
return newGridPoints to newLoopPoints
}
private fun parseInput(input: String): Pair<Pipe, Map<Point, Pipe>> {
var startPoint: Point = -1 to -1
val grid = mutableMapOf<Point, Pipe>()
val lines = input.split('\n')
for (y in lines.indices) {
val chars = lines[y].toCharArray()
for (x in chars.indices) {
val Point = y to x
grid[Point] = parsePipe(Point, chars[x])
if (chars[x] == 'S') {
startPoint = Point
}
}
}
val startPipe = parseStart(startPoint, grid)
grid[startPoint] = startPipe
return startPipe to grid
}
private fun parseStart(Point: Point, grid: Map<Point, Pipe>): Pipe {
val (y, x) = Point
val possibleTypes = mutableSetOf('|', '-', 'L', 'J', '7', 'F')
grid[y to x - 1].let {
if (it == null || (Point != it.inPoint && Point != it.outPoint)) {
possibleTypes.removeAll(listOf('-', 'J', '7'))
}
}
grid[y to x + 1].let {
if (it == null || (Point != it.inPoint && Point != it.outPoint)) {
possibleTypes.removeAll(listOf('-', 'L', 'F'))
}
}
grid[y - 1 to x].let {
if (it == null || (Point != it.inPoint && Point != it.outPoint)) {
possibleTypes.removeAll(listOf('|', 'L', 'J'))
}
}
grid[y + 1 to x].let {
if (it == null || (Point != it.inPoint && Point != it.outPoint)) {
possibleTypes.removeAll(listOf('|', '7', 'F'))
}
}
if (possibleTypes.size > 1) throw IllegalArgumentException("Multiple start pipe options")
return parsePipe(Point, possibleTypes.first())
}
private fun parsePipe(Point: Point, type: Char): Pipe {
val (y, x) = Point
return when (type) {
'|' -> Pipe(type, Point, y + 1 to x, y - 1 to x)
'-' -> Pipe(type, Point, y to x - 1, y to x + 1)
'L' -> Pipe(type, Point, y - 1 to x, y to x + 1)
'J' -> Pipe(type, Point, y - 1 to x, y to x - 1)
'7' -> Pipe(type, Point, y + 1 to x, y to x - 1)
'F' -> Pipe(type, Point, y + 1 to x, y to x + 1)
else -> Pipe(type, Point, y to x, y to x)
}
}
data class Pipe(val type: Char, val selfPoint: Point, val inPoint: Point, val outPoint: Point) {
fun getOutPoint(inPoint: Point) = when (inPoint) {
this.inPoint -> outPoint
outPoint -> this.inPoint
else -> throw IllegalArgumentException("Pipe is not connected to $inPoint")
}
}
}
fun main() {
val day10 = Day10()
val input = readInputAsString("day10.txt")
println("10, part 1: ${day10.part1(input)}")
println("10, part 2: ${day10.part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 18b97d650f4a90219bd6a81a8cf4d445d56ea9e8 | 5,675 | advent-of-code-2023 | MIT License |
src/main/de/ddkfm/Day3.kt | DDKFM | 433,861,159 | false | {"Kotlin": 13522} | package de.ddkfm
class Day3 : DayInterface<List<String>, Int> {
override fun part1(input: List<String>): Int {
val maxLength = input.maxOf { it.length }
val rates = (0 until maxLength).map { i ->
var recognizableChars = input.map { it[i] }
val mostCommonBit = getMostCommonBits(recognizableChars)
val leastCommonBit = getLeastCommonBits(recognizableChars)
return@map mostCommonBit to leastCommonBit
}
val gamma = rates.joinToString(separator = "") { it.first.toString() }.toInt(2)
val epsilon = rates.joinToString(separator = "") { it.second.toString() }.toInt(2)
return gamma * epsilon
}
override fun part2(input: List<String>): Int {
var remaining = input.toMutableList()
var i = 0;
while(remaining.size > 1) {
var recognizableChars = remaining.map { it[i] }
val mostCommonBit = getMostCommonBits(recognizableChars)
remaining = remaining.filter { it[i] == mostCommonBit }.toMutableList()
i++
}
val oxygenRating = remaining.first().toInt(2)
remaining = input.toMutableList()
i = 0;
while(remaining.size > 1) {
var recognizableChars = remaining.map { it[i] }
val lestCommonBit = getLeastCommonBits(recognizableChars)
remaining = remaining.filter { it[i] == lestCommonBit }.toMutableList()
i++
}
val co2Rating = remaining.first().toInt(2)
return co2Rating * oxygenRating
}
private fun getMostCommonBits(chars : List<Char>) : Char {
return when {
chars.filter { it == '1' }.size >= chars.filter { it == '0' }.size -> '1'
else -> '0'
}
}
private fun getLeastCommonBits(chars : List<Char>) : Char {
return when {
chars.filter { it == '1' }.size >= chars.filter { it == '0' }.size -> '0'
else -> '1'
}
}
} | 0 | Kotlin | 0 | 0 | 6e147b526414ab5d11732dc32c18ad760f97ff59 | 1,997 | AdventOfCode21 | MIT License |
src/com/github/frozengenis/day4/Puzzle.kt | FrozenSync | 159,988,833 | false | null | package com.github.frozengenis.day4
import java.io.File
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.util.*
fun main() {
val guards = File("""src\com\github\frozengenis\day4\input.txt""")
.let(::parseInputToLogs)
.let(::applyLogsToGuards)
val guardMostSlept = guards.maxBy(Guard::totalTimeAsleep)
val guardMostSleptOnSameMinute = guards.maxBy { it.maxFrequencyAsleepOnSameMinute ?: -1 }
StringBuilder("Advent of Code 2018 - Day 4").appendln().appendln()
.appendln("Answer part 1: ${guardMostSlept?.let(::calculateAnswer)} \t by $guardMostSlept")
.appendln("Answer part 2: ${guardMostSleptOnSameMinute?.let(::calculateAnswer)} \t by $guardMostSleptOnSameMinute")
.let(::print)
}
private fun parseInputToLogs(input: File): List<Log> {
val scanner = Scanner(input)
val result = mutableListOf<Log>()
while (scanner.hasNext()) {
scanner.nextLine()
.let(::parseToLog)
.let(result::add)
}
return result.sortedBy { it.timestamp }
}
private fun parseToLog(input: String): Log {
val scanner = Scanner(input).useDelimiter("""[\[\]]""")
val timestamp = scanner.next()
val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")
val time = LocalDateTime.parse(timestamp, formatter)
val action = scanner.nextLine()
return when {
action.contains("begins shift") -> ShiftLog(time, action.filter { it.isDigit() }.toInt())
action.contains("falls asleep") -> SleepLog(time)
action.contains("wakes up") -> WakeUpLog(time)
else -> throw IllegalArgumentException("Invalid input log")
}
}
private fun applyLogsToGuards(logs: List<Log>): List<Guard> {
var guardAtShift: Guard? = null
val guardsById = mutableMapOf<Int, Guard>()
logs.forEach { log ->
when (log) {
is ShiftLog -> guardAtShift = guardsById.getOrPut(log.guardId) { Guard(log.guardId) }
is SleepLog -> guardAtShift?.sleepAt(log.timestamp) ?: throw IllegalArgumentException("Invalid input: a sleep log cannot appear before a shift log")
is WakeUpLog -> guardAtShift?.wakeUpAt(log.timestamp) ?: throw IllegalArgumentException("Invalid input: a wake up log cannot appear before a shift log")
}
}
return guardsById.values.toList()
}
private fun calculateAnswer(guard: Guard) = guard.minuteMostAsleep?.times(guard.id)
| 0 | Kotlin | 0 | 0 | ec1e3472990a36b4d2a2270705253c679bee7618 | 2,449 | advent-of-code-2018 | The Unlicense |
app/src/main/java/com/betulnecanli/kotlindatastructuresalgorithms/CodingPatterns/ModifiedBinarySearch.kt | betulnecanli | 568,477,911 | false | {"Kotlin": 167849} | /*
Use this technique to search a sorted set of elements efficiently.
The "Modified Binary Search" coding pattern is a variation of the standard binary search,
often used to find specific elements or conditions in a sorted array that doesn't necessarily have a straightforward match.
*/
//1. Ceiling of a Number
fun searchCeilingOfNumber(arr: IntArray, key: Int): Int {
if (key > arr.last()) {
return -1 // No ceiling exists as the key is greater than the largest element
}
var start = 0
var end = arr.size - 1
while (start <= end) {
val mid = start + (end - start) / 2
if (arr[mid] == key) {
return mid // Found an exact match
}
if (key < arr[mid]) {
end = mid - 1
} else {
start = mid + 1
}
}
return start // 'start' is the index of the ceiling of the key
}
fun main() {
val arr = intArrayOf(4, 6, 10)
val key = 6
val ceilingIndex = searchCeilingOfNumber(arr, key)
val ceiling = if (ceilingIndex != -1) arr[ceilingIndex] else -1
println("Ceiling of $key: $ceiling")
}
//2. Bitonic Array Maximum
fun findBitonicArrayMax(arr: IntArray): Int {
var start = 0
var end = arr.size - 1
while (start < end) {
val mid = start + (end - start) / 2
if (arr[mid] > arr[mid + 1]) {
// We are in the descending part of the bitonic array
end = mid
} else {
// We are in the ascending part of the bitonic array
start = mid + 1
}
}
// 'start' is the index of the maximum element in the bitonic array
return arr[start]
}
fun main() {
val arr = intArrayOf(1, 3, 8, 12, 4, 2)
val maxElement = findBitonicArrayMax(arr)
println("Maximum Element in the Bitonic Array: $maxElement")
}
/*
Ceiling of a Number:
The searchCeilingOfNumber function finds the smallest number in the array that is greater than or equal to the given key.
If the key is greater than the largest element in the array, it returns -1.
Bitonic Array Maximum:
The findBitonicArrayMax function finds the maximum element in a bitonic array.
A bitonic array is one that starts monotonically increasing and then monotonically decreases.
*/
| 2 | Kotlin | 2 | 40 | 70a4a311f0c57928a32d7b4d795f98db3bdbeb02 | 2,257 | Kotlin-Data-Structures-Algorithms | Apache License 2.0 |
advent-of-code2016/src/main/kotlin/day05/Advent5.kt | REDNBLACK | 128,669,137 | false | null | package day05
import toHex
import toMD5
/**
--- Day 5: How About a Nice Game of Chess? ---
You are faced with a security door designed by Easter Bunny engineers that seem to have acquired most of their security knowledge by watching hacking movies.
The eight-character password for the door is generated one character at a time by finding the MD5 hash of some Door ID (your puzzle input) and an increasing integer index (starting with 0).
A hash indicates the next character in the password if its hexadecimal representation starts with five zeroes. If it does, the sixth character in the hash is the next character of the password.
For example, if the Door ID is abc:
The first index which produces a hash that starts with five zeroes is 3231929, which we find by hashing abc3231929; the sixth character of the hash, and thus the first character of the password, is 1.
5017308 produces the next interesting hash, which starts with 000008f82..., so the second character of the password is 8.
The third time a hash starts with five zeroes is for abc5278568, discovering the character f.
In this example, after continuing this search a total of eight times, the password is <PASSWORD>.
Given the actual Door ID, what is the password?
--- Part Two ---
As the door slides open, you are presented with a second door that uses a slightly more inspired security mechanism. Clearly unimpressed by the last version (in what movie is the password decrypted in order?!), the Easter Bunny engineers have worked out a better solution.
Instead of simply filling in the password from left to right, the hash now also indicates the position within the password to fill. You still look for hashes that begin with five zeroes; however, now, the sixth character represents the position (0-7), and the seventh character is the character to put in that position.
A hash result of 000001f means that f is the second character in the password. Use only the first result for each position, and ignore invalid positions.
For example, if the Door ID is abc:
The first interesting hash is from abc3231929, which produces 0000015...; so, 5 goes in position 1: _5______.
In the previous method, 5017308 produced an interesting hash; however, it is ignored, because it specifies an invalid position (8).
The second interesting hash is at index 5357525, which produces 000004e...; so, e goes in position 4: _5__e___.
You almost choke on your popcorn as the final character falls into place, producing the password <PASSWORD>.
Given the actual Door ID and this new method, what is the password? Be extra proud of your solution if it uses a cinematic "decrypting" animation.
*/
fun main(args: Array<String>) {
val algorithm1 = { hash: String, array: CharArray ->
val prefix = "0".repeat(5)
if (hash.startsWith(prefix)) {
val pos = array.indexOfFirst { it == Char.MIN_SURROGATE }
array[pos] = hash[5]
}
array
}
println(findPassword("abc", algorithm1, 8) == "<PASSWORD>")
println(findPassword("<PASSWORD>", algorithm1, 8))
val algorithm2 = { hash: String, array: CharArray ->
val prefix = "0".repeat(5)
if (hash.startsWith(prefix)) {
val pos = try { hash[5].toString().toInt() } catch (e: Exception) { Int.MAX_VALUE }
if (pos < array.size && array[pos] == Char.MIN_SURROGATE) array[pos] = hash[6]
}
array
}
println(findPassword("abc", algorithm2, 8) == "<PASSWORD>")
println(findPassword("<PASSWORD>", algorithm2, 8))
}
fun findPassword(input: String, algorithm: (String, CharArray) -> CharArray, length: Int): String {
val array = Char.MIN_SURROGATE.toString().repeat(length).toCharArray()
tailrec fun find(i: Int, array: CharArray): CharArray {
if (!array.contains(Char.MIN_SURROGATE)) return array
val hash = (input + i).toMD5().toHex()
return find(i + 1, algorithm(hash, array))
}
return find(0, array).joinToString("").toLowerCase()
}
| 0 | Kotlin | 0 | 0 | e282d1f0fd0b973e4b701c8c2af1dbf4f4a149c7 | 4,006 | courses | MIT License |
src/Day05.kt | emanguy | 573,113,840 | false | {"Kotlin": 17921} | import java.util.Stack
data class Instruction(
val quantity: Int,
val sourceIdx: Int,
val destinationIdx: Int,
)
data class ParsedInput(
val stacks: MutableList<Stack<Char>>,
val instructions: List<Instruction>
)
fun MutableList<Stack<Char>>.addCrate(stackIdx: Int, value: Char) {
while (this.size <= stackIdx) {
this.add(Stack())
}
this[stackIdx].push(value)
}
fun main() {
fun parseInput(inputs: List<String>): ParsedInput {
val lineIterator = inputs.iterator()
val stackLines = mutableListOf<String>()
// Read the contents of the stacks
var currentLine = lineIterator.next()
do {
stackLines += currentLine
currentLine = lineIterator.next()
} while (currentLine != "")
// Drop the stack "titles"
stackLines.removeLast()
// Reverse the input & build the stacks
val stacks = mutableListOf<Stack<Char>>()
for (stackInput in stackLines.reversed()) {
var workingInput = stackInput
var stackIndex = 0
while (workingInput.isNotEmpty()) {
// If the first character of the string is a bracket we have a value for the stack
if (workingInput[0] == '[') {
// The second character is our letter, so push that onto a stack
stacks.addCrate(stackIndex, workingInput[1])
}
// If possible, truncate the first 4 letters to move on to the next crate
workingInput = if (workingInput.length > 3) {
workingInput.substring(4)
} else { // Otherwise there should be no additional crates, and we can set the input string blank
""
}
stackIndex++
}
}
// Parse the instructions
val instructionRegex = """^move (\d+) from (\d+) to (\d+)$""".toRegex()
val instructions = mutableListOf<Instruction>()
// The iterator should only have the instructions left
for (instructionLine in lineIterator) {
val parsedString = instructionRegex.matchEntire(instructionLine)
?: throw IllegalArgumentException("Got a bad instruction: $instructionLine")
val (_, quantity, source, destination) = parsedString.groupValues
instructions += Instruction(
quantity.toInt(),
source.toInt() - 1, // We want 0 indexed
destination.toInt() - 1,
)
}
return ParsedInput(stacks, instructions)
}
fun topsOfStacks(stacks: List<Stack<Char>>) = stacks
.filter { it.isNotEmpty() }
.map { it.peek() }
.fold("") { finalString, currentChar -> finalString + currentChar }
fun part1(inputs: List<String>): String {
val (stacks, instructions) = parseInput(inputs)
for (instruction in instructions) {
var amountToMove = instruction.quantity
while (amountToMove > 0 && stacks[instruction.sourceIdx].isNotEmpty()) {
stacks[instruction.destinationIdx].push(stacks[instruction.sourceIdx].pop())
amountToMove--
}
}
return topsOfStacks(stacks)
}
fun part2(inputs: List<String>): String {
val (stacks, instructions) = parseInput(inputs)
for (instruction in instructions) {
var amountToMove = instruction.quantity
val bufferStack = Stack<Char>()
while (amountToMove > 0 && stacks[instruction.sourceIdx].isNotEmpty()) {
bufferStack.push(stacks[instruction.sourceIdx].pop())
amountToMove--
}
while (bufferStack.isNotEmpty()) {
stacks[instruction.destinationIdx].push(bufferStack.pop())
}
}
return topsOfStacks(stacks)
}
// Verify the sample input works
val inputs = readInput("Day05_test")
check(part1(inputs) == "CMZ")
check(part2(inputs) == "MCD")
val finalInputs = readInput("Day05")
println(part1(finalInputs))
println(part2(finalInputs))
}
| 0 | Kotlin | 0 | 1 | 211e213ec306acc0978f5490524e8abafbd739f3 | 4,202 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/de/startat/aoc2023/Day6.kt | Arondc | 727,396,875 | false | {"Kotlin": 194620} | package de.startat.aoc2023
import kotlin.math.sqrt
data class Race(val raceTime:Long, val bestDistance : Long)
class Day6 {
fun star1(){
var numberOfResults = 1
numberOfResults *= simulateRace(Race(46,214))
numberOfResults *= simulateRace(Race(80,1177))
numberOfResults *= simulateRace(Race(78,1402))
numberOfResults *= simulateRace(Race(66,1024))
println("Die Lösung für Stern 1 ist $numberOfResults")
}
fun star2(){
val numberOfResults = simulateRace(Race(46807866,214117714021024))
println("Die Lösung für Stern 2 ist $numberOfResults")
}
private fun simulateRace(race : Race): Int {
val loadingTimes = findLowestAndHighestLoadingTime(race)
var corrector = 0 //I count one possibility too much if the right border is exactly at a value without fractional part
if(loadingTimes.second.toInt().toDouble().equals(loadingTimes.second)){
corrector = 1
}
val possibilities = loadingTimes.second.toInt() - loadingTimes.first.toInt() - corrector
println("Es gibt $possibilities Möglichkeiten den Rekord zu brechen für $race")
return possibilities
}
private fun findLowestAndHighestLoadingTime(race: Race): Pair<Double, Double> {
val a : Double = (-1).toDouble()
val b : Double = race.raceTime.toDouble()
val c : Double = (-1*race.bestDistance).toDouble()
val x1 = (-b+ sqrt(b*b - 4*a*c))/(2*a)
val x2 = (-b- sqrt(b*b - 4*a*c))/(2*a)
return Pair(x1,x2)
}
}
val day6testInput = """
Time: 7 15 30
Distance: 9 40 200
""".trimIndent()
val day6input = """
Time: 46 80 78 66
Distance: 214 1177 1402 1024
""".trimIndent() | 0 | Kotlin | 0 | 0 | 660d1a5733dd533aff822f0e10166282b8e4bed9 | 1,786 | AOC2023 | Creative Commons Zero v1.0 Universal |
src/main/kotlin/day05/AlmanacMap.kt | limelier | 725,979,709 | false | {"Kotlin": 48112} | package day05
import day05.Domain.Companion.domain
import day05.Interval.Companion.startInterval
import kotlin.math.sign
internal class AlmanacMap(
entries: List<Entry>
) {
private val entries = entries.sortedBy { it.source.lower }
internal class Entry(
destinationStart: Long,
sourceStart: Long,
length: Long,
) {
val source = sourceStart.startInterval(length)
private val delta = destinationStart - sourceStart
/** Check if the source range contains the key */
operator fun contains(key: Long): Boolean = key in source
/** Returns the destination of the key, assuming the source range contains it */
fun apply(key: Long): Long =
if (this.contains(key)) {
key + delta
} else {
throw IllegalArgumentException("Cannot transform key outside of source range")
}
/** Returns the portion of the destination range covered by the transformation of the input, if any */
fun apply(input: Interval): Interval? = source.intersection(input)?.moved(delta)
override fun toString(): String = "$source -> $delta"
}
/**
* Find the index of the first entry that could be applied to an interval starting with [lower], or `null` if none
* apply
*/
private fun firstFeasibleEntry(lower: Long): Int? {
val idx = entries.binarySearch { entry ->
if (lower in entry) {
0
} else {
(entry.source.lower - lower).sign
}
}
if (idx >= 0) {
return idx
}
val insertionPoint = -idx - 1
return if (insertionPoint in entries.indices) {
insertionPoint
} else {
null
}
}
fun apply(input: Long): Long {
val entryIdx = firstFeasibleEntry(input)
if (entryIdx != null && entries[entryIdx].contains(input)) {
return entries[entryIdx].apply(input)
}
return input
}
/**
* Generate all intervals created by applying the map's entries to the [interval], as well as remaining
* sub-intervals that do not have a matching entry
*/
fun apply(interval: Interval): List<Interval> {
val firstEntryIdx = firstFeasibleEntry(interval.lower) ?: return listOf(interval)
val results = mutableListOf<Interval>()
var remaining = interval
var entryIdx = firstEntryIdx
while (entryIdx in entries.indices) {
val entry = entries[entryIdx]
// if the entry applies
if (remaining.intersection(entry.source) != null) {
// add part before source interval without modifying it
if (remaining.lower < entry.source.lower) {
results += Interval(remaining.lower..<entry.source.lower)
}
results += entry.apply(remaining)!!
if (remaining.upper <= entry.source.upper) {
// nothing left to handle, results are done
return results
}
// remove handled parts from remaining
remaining = Interval(entry.source.upper + 1..remaining.upper)
}
entryIdx++
}
// add in leftover unhandled part without modifying it
results += remaining
return results
}
fun apply(inputDomain: Domain): Domain =
inputDomain.intervals
.flatMap { apply(it) }
.domain()
} | 0 | Kotlin | 0 | 0 | 0edcde7c96440b0a59e23ec25677f44ae2cfd20c | 3,589 | advent-of-code-2023-kotlin | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.