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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/main/java/nerd/tuxmobil/fahrplan/congress/repositories/SessionsTransformer.kt | johnjohndoe | 12,616,092 | true | null | package nerd.tuxmobil.fahrplan.congress.repositories
import androidx.annotation.VisibleForTesting
import nerd.tuxmobil.fahrplan.congress.models.RoomData
import nerd.tuxmobil.fahrplan.congress.models.ScheduleData
import nerd.tuxmobil.fahrplan.congress.models.Session
class SessionsTransformer @VisibleForTesting constructor(
private val roomProvider: RoomProvider
) {
companion object {
fun createSessionsTransformer(): SessionsTransformer {
val roomProvider = object : RoomProvider {
override val prioritizedRooms: List<String> = listOf(
"Saal 1",
"Saal 2",
"Saal G",
"Saal 6",
"Saal 17",
"Lounge"
)
override val deprioritizedRooms: List<String> = emptyList()
}
return SessionsTransformer(roomProvider)
}
}
/**
* Transforms the given [sessions] for the given [dayIndex] into a [ScheduleData] object.
*
* Apart from the [dayIndex] it contains a list of room names and their associated sessions
* (sorted by [Session.dateUTC]). Rooms names are added in a defined order: room names of
* prioritized rooms first, then all other room names in the order defined by the given session.
* After adding room names the original order [Session.roomIndex] is no longer of interest.
*/
fun transformSessions(dayIndex: Int, sessions: List<Session>): ScheduleData {
// Pre-populate the map with prioritized rooms
val roomMap = roomProvider.prioritizedRooms
.associateWith { mutableListOf<Session>() }
.toMutableMap()
val sortedSessions = sessions.sortedBy { it.roomIndex }
for (session in sortedSessions) {
val sessionsInRoom = roomMap.getOrPut(session.room) { mutableListOf() }
sessionsInRoom.add(session)
}
val roomDataList = roomMap.mapNotNull { (roomName, sessions) ->
if (sessions.isEmpty()) {
// Drop prioritized rooms without sessions
null
} else {
RoomData(
roomName = roomName,
sessions = sessions.sortedBy { it.dateUTC }.toList()
)
}
}.sortWithDeprioritizedRooms(roomProvider.deprioritizedRooms)
return ScheduleData(dayIndex, roomDataList)
}
}
interface RoomProvider {
val prioritizedRooms: List<String>
val deprioritizedRooms: List<String>
}
/**
* Moves all [RoomData] items with a room name contained in [deprioritizedRooms] to the end of the list.
* The order of room names in the [deprioritizedRooms] list is applied to the receiving list.
*/
private fun List<RoomData>.sortWithDeprioritizedRooms(deprioritizedRooms: List<String>): List<RoomData> {
if (deprioritizedRooms.isEmpty()) {
return this
}
val (tail, head) = partition { deprioritizedRooms.contains(it.roomName) }
val sortedTail = deprioritizedRooms.mapNotNull { room ->
tail.firstOrNull { room == it.roomName }
}
return head + sortedTail
}
| 0 | Kotlin | 3 | 21 | 081e90400c2e9f6c0445197b654efb904cc8f3ed | 3,193 | CampFahrplan | Apache License 2.0 |
maxsubarray/src/main/kotlin/com/felipecsl/Main.kt | felipecsl | 94,643,403 | false | null | package com.felipecsl
// https://www.hackerrank.com/challenges/maxsubarray
fun main(args: Array<String>) {
val totalArrays = readLine()!!.trim().toInt()
val arrays = (0 until totalArrays).map {
readLine() // arr length, unused
readInputLine()
}
arrays.forEach {
println("${maxContiguousSubArray(it)} ${maxNonContiguousSubArray(it)}")
}
}
fun maxContiguousSubArray(arr: List<Int>): Int {
var maxEndingHere = 0
var maxSoFar = Int.MIN_VALUE
arr.forEach { x ->
maxEndingHere = Math.max(x, maxEndingHere + x)
maxSoFar = Math.max(maxSoFar, maxEndingHere)
}
return maxSoFar
}
fun maxNonContiguousSubArray(arr: List<Int>) =
if (arr.any { it > 0 })
arr.filter { it > 0 }.sum()
else
arr.max()
private fun readInputLine() =
readLine()!!.trim().split(' ').map(String::toInt)
| 0 | Kotlin | 0 | 3 | a4c07dd1531aae23d67ff52284b6fcca17b6c37c | 832 | hackerrank | MIT License |
utility/bases/src/main/java/com/shamlou/bases/dataStructure/RadixTree.kt | keivanshamlu | 453,712,116 | false | {"Kotlin": 140153} | package com.shamlou.bases.dataStructure
import java.util.*
/**
* (In the following comparisons, it is assumed that the keys are of length k
* and the data structure contains n members.)
*/
class RadixTree<T>(private val root: Node<T> = Node(false)) {
/**
* checks whether tree is empty or not
*/
fun isEmpty(): Boolean = root.edges.isEmpty()
/**
* compare two strings and will return first index which two strings differ
*/
private fun getFirstMismatchLetter(word: String, edgeWord: String): Int {
for (i in 1 until word.length.coerceAtMost(edgeWord.length)) {
if (word[i] != edgeWord[i]) return i
}
return NO_MISMATCH
}
/**
* get list of objects and will insert them all into radix tree
*/
fun insertAll(items : List<Item<T>>){
items.map { insert(it) }
}
/**
* get an object and will insert it to radix tree
*/
fun insert(item: Item<T>) {
var current = root
var currIndex = 0
//Iterative approach
while (currIndex < item.label.length) {
val transitionChar = item.label.lowercase()[currIndex]
val curEdge = current.getTransition(transitionChar)
//Updated version of the input word
val currStr = item.label.lowercase().substring(currIndex)
//There is no associated edge with the first character of the current string
//so simply add the rest of the string and finish
if (curEdge == null) {
current.addEdge(transitionChar,Edge(currStr, Node(true, item)))
break
}
var splitIndex = getFirstMismatchLetter(currStr, curEdge.label)
if (splitIndex == NO_MISMATCH) {
//The edge and leftover string are the same length
//so finish and update the next node as a word node
if (currStr.length == curEdge.label.length) {
curEdge.next.isLeaf = true
curEdge.next.item = item
break
} else if (currStr.length < curEdge.label.length) {
//The leftover word is a prefix to the edge string, so split
val suffix = curEdge.label.substring(currStr.length)
curEdge.label = currStr
val newNext = Node<T>(true, item)
val afterNewNext = curEdge.next
curEdge.next = newNext
newNext.addEdge(suffix, afterNewNext)
break
} else {
//There is leftover string after a perfect match
splitIndex = curEdge.label.length
}
} else {
//The leftover string and edge string differed, so split at point
val suffix = curEdge.label.substring(splitIndex)
curEdge.label = curEdge.label.substring(0, splitIndex)
val prevNext = curEdge.next
curEdge.next = Node(false)
curEdge.next.addEdge(suffix, prevNext)
}
//Traverse the tree
current = curEdge.next
currIndex += splitIndex
}
}
/**
* searches for a prefix in radix tree
* first of all search for particular node and then calls [getAllChildren]
* and it will get all children of that node which is found data
*/
fun search(word: String): List<T> {
if(word.isEmpty())return emptyList()
var current = root
var currIndex = 0
while (currIndex < word.length) {
val transitionChar = word.lowercase()[currIndex]
val edge = current.getTransition(transitionChar) ?: kotlin.run {
return listOf()
}
currIndex += edge.label.length
current = edge.next
}
return current.getAllChildren(word.lowercase())
}
companion object {
private const val NO_MISMATCH = -1
}
}
/**
* represents edges of a node, containts the lable
* of edge and the node the edge is referring to
*/
class Edge<T>(var label: String, var next: Node<T>)
/**
* holds item and the key that radix tree works with
*/
class Item<T>(var label: String, var item: T)
/**
* represents node of the radix tree, contains group
* of edges that are hold a tree map so it's sorted
* alphanumeric all the time so whenever we call [getAllChildren]
* we get a list of <T> which is in alphanumeric order
*/
class Node<T>(var isLeaf: Boolean, var item: Item<T>? = null) {
// i used TreeMap so it can keep everything sorted
var edges: TreeMap<Char, Edge<T>> = TreeMap()
/**
* get the edge that a Char is referring in treemap
*/
fun getTransition(transitionChar: Char): Edge<T>? {
return edges[transitionChar]
}
/**
* adds a edge in edges treemap
*/
fun addEdge(label: String, next: Node<T>) {
edges[label[0]] = Edge(label, next)
}
/**
* adds a edge in edges treemap
*/
fun addEdge(char : Char , edge: Edge<T>){
edges[char] = edge
}
/**
* gets a node in radix tree and the prefix text of that node
* recursively calls itself until it reaches leaves and then
* it will add them to a list
*/
fun getAllChildren(tillNow: String): List<T> {
val list = mutableListOf<T>()
if (isLeaf && item?.label?.lowercase()?.startsWith(tillNow) == true && item?.item != null) {
item?.item?.let { return listOf(it) }
}
edges.map {
if (it.value.next.isLeaf) list.add(it.value.next.item!!.item)
else list.addAll(
it.value.next.getAllChildren(
StringBuilder()
.append(tillNow)
.append(it.value.label)
.toString()
)
)
}
return list
}
} | 0 | Kotlin | 0 | 0 | 631b1d7bd0997d985866f42e25db4f1cc4e11297 | 6,034 | All-cities | Apache License 2.0 |
src/main/kotlin/year2021/day-14.kt | ppichler94 | 653,105,004 | false | {"Kotlin": 182859} | package year2021
import lib.aoc.Day
import lib.aoc.Part
import lib.memoize
fun main() {
Day(14, 2021, PartA14(), PartB14()).run()
}
open class PartA14(private val steps: Long = 10) : Part() {
private data class Counter(val data: MutableMap<Char, Long>) {
constructor(text: String) : this(mutableMapOf()) {
text.forEach { addOrSet(it, 1) }
}
fun update(counter: Counter) {
counter.data.forEach { (k, v) -> addOrSet(k, v) }
}
private fun addOrSet(k: Char, v: Long) {
val myValue = data[k]
if (myValue != null) {
data[k] = myValue + v
} else {
data[k] = v
}
}
}
private lateinit var template: String
private lateinit var rules: Map<String, String>
private lateinit var countMemoized: (String, Long) -> Counter
override fun parse(text: String) {
val (templateText, rulesText) = text.split("\n\n")
template = templateText
rules = rulesText.split("\n").map { it.split(" -> ") }.associate { it[0] to it[1] }
}
override fun compute(): String {
countMemoized = { pair: String, step: Long -> count(pair, step) }.memoize()
val counter = Counter(template)
template.windowed(2).forEach {
counter.update(countMemoized(it, 0L))
}
return (counter.data.values.max() - counter.data.values.min()).toString()
}
private fun count(pair: String, step: Long): Counter {
if (step == steps || pair !in rules.keys) {
return Counter("")
}
val insertion = rules.getValue(pair)
val counter = Counter(insertion)
counter.update(countMemoized(pair[0] + insertion, step + 1))
counter.update(countMemoized(insertion + pair[1], step + 1))
return counter
}
override val exampleAnswer: String
get() = "1588"
}
class PartB14 : PartA14(40) {
override val exampleAnswer: String
get() = "2188189693529"
}
| 0 | Kotlin | 0 | 0 | 49dc6eb7aa2a68c45c716587427353567d7ea313 | 2,114 | Advent-Of-Code-Kotlin | MIT License |
aoc_2023/src/main/kotlin/problems/day11/Galaxies.kt | Cavitedev | 725,682,393 | false | {"Kotlin": 228779} | package problems.day11
import kotlin.math.abs
class Galaxies(lines: List<String>) {
val galaxiesList: List<Galaxy>
init {
val galaxiesMut = mutableListOf<Galaxy>()
for (i in lines.indices) {
val line = lines[i]
for (j in line.indices) {
val char = line[j]
if (char == '#') {
galaxiesMut.add(Galaxy(i, j))
}
}
}
this.galaxiesList = galaxiesMut
}
fun expand(times: Int) {
val iSorted = this.galaxiesList.sortedBy { it.i }
var lastI = iSorted.first().i
var expandAmount = 0
for (galaxy in iSorted.drop(1)) {
val dif = galaxy.i - lastI
if (dif > 1)
expandAmount += ((dif - 1) * times)
lastI = galaxy.i
galaxy.i += expandAmount
}
val jSorted = this.galaxiesList.sortedBy { it.j }
var lastJ = jSorted.first().j
expandAmount = 0
for (galaxy in jSorted.drop(1)) {
val dif = galaxy.j - lastJ
if (dif > 1)
expandAmount += (dif - 1) * times
lastJ = galaxy.j
galaxy.j += expandAmount
}
}
fun sumDistances(): Long {
return this.galaxiesList.foldIndexed(0L) { index, acc, galaxy ->
acc + this.galaxiesList.drop(index + 1).fold(0L) { acc2, galaxy2 ->
acc2 + abs(galaxy.i - galaxy2.i) + abs(galaxy.j - galaxy2.j)
}
}
}
} | 0 | Kotlin | 0 | 1 | aa7af2d5aa0eb30df4563c513956ed41f18791d5 | 1,543 | advent-of-code-2023 | MIT License |
src/main/kotlin/solving/Solver.kt | marrow16 | 426,714,749 | false | {"Kotlin": 41948} | package solving
import Puzzle
import words.Word
import java.util.*
import java.util.concurrent.atomic.AtomicLong
class Solver(private val puzzle: Puzzle) {
private val explored = AtomicLong()
private val solutions: MutableList<Solution> = ArrayList()
private var beginWord: Word = puzzle.startWord
private var endWord: Word = puzzle.finalWord
private var reversed = false
private var maximumLadderLength: Int = -1
private lateinit var endDistances: WordDistanceMap
fun solve(maxLadderLength: Int): List<Solution> {
explored.set(0)
solutions.clear()
maximumLadderLength = maxLadderLength
if (maximumLadderLength < 1) {
// won't find any solutions with ladder of length 0!...
return solutions
}
beginWord = puzzle.startWord
endWord = puzzle.finalWord
reversed = false
// check for short-circuits...
when (beginWord - endWord) {
0 -> {
// same word - so there's only one solution...
solutions.add(Solution(beginWord))
return solutions
}
1 -> {
// the two words are only one letter different...
solutions.add(Solution(beginWord, endWord))
when (maximumLadderLength) {
2 ->
// maximum ladder is 2 so we already have the only answer...
return solutions
3 -> {
shortCircuitLadderLength3()
return solutions
}
}
}
2 -> if (maximumLadderLength == 3) {
shortCircuitLadderLength3()
return solutions
}
}
// begin with the word that has the least number of linked words...
// (this reduces the number of pointless solution candidates explored!)
reversed = beginWord.linkedWords.size > endWord.linkedWords.size
if (reversed) {
beginWord = puzzle.finalWord
endWord = puzzle.startWord
}
endDistances = WordDistanceMap(endWord, maximumLadderLength - 1)
beginWord.linkedWords
.parallelStream()
.filter{ linkedWord -> endDistances.reachable(linkedWord, maximumLadderLength)}
.map { linkedWord -> CandidateSolution(this, beginWord, linkedWord) }
.forEach(this::solve)
return solutions
}
private fun solve(candidate: CandidateSolution) {
val lastWord: Word = candidate.ladder.last()
if (lastWord == endWord) {
foundSolution(candidate)
} else if (candidate.ladder.size < maximumLadderLength) {
lastWord.linkedWords
.parallelStream()
.filter { linkedWord -> !candidate.seenWords.contains(linkedWord) }
.filter { linkedWord -> endDistances.reachable(linkedWord, maximumLadderLength, candidate.ladder.size) }
.map { linkedWord -> CandidateSolution(candidate, linkedWord) }
.forEach(this::solve)
}
}
private fun shortCircuitLadderLength3() {
// we can determine solutions by convergence of the two linked word sets...
val startLinkedWords: MutableSet<Word> = HashSet(beginWord.linkedWords)
startLinkedWords.retainAll(endWord.linkedWords)
for (intermediateWord in startLinkedWords) {
solutions.add(Solution(beginWord, intermediateWord, endWord))
}
}
@Synchronized
private fun foundSolution(candidate: CandidateSolution) {
val solution = Solution(candidate, reversed)
solutions.add(solution)
}
@Synchronized
fun incrementExplored() {
explored.incrementAndGet()
}
val exploredCount: Long get() = explored.get()
} | 0 | Kotlin | 0 | 2 | b5c0db038b5d1e58e4710a8189e9205c49741010 | 3,903 | KotlinWordLadder | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/LastStoneWeight.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2020 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import java.util.PriorityQueue
fun interface LastStoneWeight {
operator fun invoke(arr: IntArray): Int
}
class LastStoneWeightSort : LastStoneWeight {
override operator fun invoke(arr: IntArray): Int {
return arr.lastStoneWeight()
}
private fun IntArray.lastStoneWeight(): Int {
sort()
for (i in size - 1 downTo 1) {
this[i - 1] = this[i] - this[i - 1]
sort()
}
return if (this.isEmpty()) 1 else first()
}
}
class LastStoneWeightQueue : LastStoneWeight {
override operator fun invoke(arr: IntArray): Int {
val pq = PriorityQueue<Int> { c, d -> d - c }
for (stone in arr) {
pq.offer(stone)
}
while (pq.size > 1) {
pq.offer(pq.poll() - pq.poll())
}
return if (arr.isEmpty()) 1 else pq.poll()
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,504 | kotlab | Apache License 2.0 |
2015/src/main/kotlin/com/koenv/adventofcode/Day6.kt | koesie10 | 47,333,954 | false | null | package com.koenv.adventofcode
class Day6Part1(val width: Int, val height: Int) {
val grid: Array<Array<Int>>
val numberOfLightsInOnState: Int
get() = grid.sumBy {
it.sum()
}
val numberOfLightsInOffState: Int
get() = width * height - numberOfLightsInOnState
init {
this.grid = Array(width, { Array(height, { STATE_OFF }) }) // Initialize an array of int[width][height] with all states set to 0
}
fun setStateForAll(newState: Int) {
grid.forEachIndexed { x, row ->
row.forEachIndexed { y, column ->
grid[x][y]= newState
}
}
}
fun parseCommand(input: String) {
val matchResult = COMMAND_REGEX.find(input) ?: throw IllegalArgumentException("Not a valid command: $input")
val command = matchResult.groups[1]!!.value
val startX = matchResult.groups[2]!!.value.toInt()
val startY = matchResult.groups[3]!!.value.toInt()
val endX = matchResult.groups[4]!!.value.toInt()
val endY = matchResult.groups[5]!!.value.toInt()
val operator = getOperatorForCommand(command)
for (x in startX..endX) {
for (y in startY..endY) {
grid[x][y] = operator(grid[x][y])
}
}
}
fun parseCommands(input: String) {
return input.lines().forEach {
parseCommand(it)
}
}
private fun getOperatorForCommand(command: String): (Int) -> Int {
when (command) {
"turn on" -> return {
STATE_ON
}
"turn off" -> return {
STATE_OFF
}
"toggle" -> return {
if (it == STATE_OFF) STATE_ON else STATE_OFF
}
}
throw IllegalArgumentException("Invalid command: $command")
}
companion object {
const val STATE_OFF = 0
const val STATE_ON = 1
val COMMAND_REGEX = "(turn on|toggle|turn off)\\s(\\d+),(\\d+)\\sthrough\\s(\\d+),(\\d+)".toRegex()
}
}
class Day6Part2(val width: Int, val height: Int) {
val grid: Array<Array<Int>>
val totalBrightness: Int
get() = grid.sumBy {
it.sum()
}
init {
this.grid = Array(width, { Array(height, { DEFAULT_BRIGHTNESS }) }) // Initialize an array of int[width][height] with all states set to 0
}
fun setStateForAll(newState: Int) {
grid.forEachIndexed { x, row ->
row.forEachIndexed { y, column ->
grid[x][y]= newState
}
}
}
fun parseCommand(input: String) {
val matchResult = COMMAND_REGEX.find(input) ?: throw IllegalArgumentException("Not a valid command: $input")
val command = matchResult.groups[1]!!.value
val startX = matchResult.groups[2]!!.value.toInt()
val startY = matchResult.groups[3]!!.value.toInt()
val endX = matchResult.groups[4]!!.value.toInt()
val endY = matchResult.groups[5]!!.value.toInt()
val operator = getOperatorForCommand(command)
for (x in startX..endX) {
for (y in startY..endY) {
grid[x][y] = operator(grid[x][y])
}
}
}
fun parseCommands(input: String) {
return input.lines().forEach {
parseCommand(it)
}
}
private fun getOperatorForCommand(command: String): (Int) -> Int {
when (command) {
"turn on" -> return {
it + 1
}
"turn off" -> return {
if (it > 0) it - 1 else it
}
"toggle" -> return {
it + 2
}
}
throw IllegalArgumentException("Invalid command: $command")
}
companion object {
const val DEFAULT_BRIGHTNESS = 0
val COMMAND_REGEX = "(turn on|toggle|turn off)\\s(\\d+),(\\d+)\\sthrough\\s(\\d+),(\\d+)".toRegex()
}
} | 0 | Kotlin | 0 | 0 | 29f3d426cfceaa131371df09785fa6598405a55f | 3,972 | AdventOfCode-Solutions-Kotlin | MIT License |
kotlin/src/com/s13g/aoc/aoc2023/Day13.kt | shaeberling | 50,704,971 | false | {"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245} | package com.s13g.aoc.aoc2023
import com.s13g.aoc.Result
import com.s13g.aoc.Solver
import com.s13g.aoc.resultFrom
/**
* --- Day 13: Point of Incidence ---
* https://adventofcode.com/2023/day/13
*/
class Day13 : Solver {
override fun solve(lines: List<String>): Result {
val inputs = mutableListOf(mutableListOf<String>())
for (line in lines) {
if (line.isBlank()) inputs.add(mutableListOf())
else inputs.last().add(line)
}
return resultFrom(solve(inputs), solve(inputs, true))
}
private fun solve(inputs: List<List<String>>, part2: Boolean = false) =
inputs.sumOf { getMirrorRow(it, part2) * 100 } +
inputs.sumOf { getMirrorRow(rotate90(it), part2) }
private fun getMirrorRow(input: List<String>, part2: Boolean): Int {
for (i in 0..input.lastIndex - 1) {
if (isValidMirrorPoint(i, input, part2)) return i + 1
}
return 0
}
private fun isValidMirrorPoint(
p: Int,
input: List<String>,
part2: Boolean
): Boolean {
var r0 = p
var r1 = p + 1
var diffs = 0
while (r0 >= 0 && r1 <= input.lastIndex) {
diffs += input[r0].numDiff(input[r1])
r0--
r1++
}
return if (!part2) diffs == 0 else diffs == 1
}
private fun rotate90(input: List<String>) =
input[0].indices.map { col -> input.map { it[col] }.joinToString("") }
private fun String.numDiff(other: String) =
mapIndexed { i, ch -> ch != other[i] }.count { it }
} | 0 | Kotlin | 1 | 2 | 7e5806f288e87d26cd22eca44e5c695faf62a0d7 | 1,456 | euler | Apache License 2.0 |
src/main/kotlin/com/jacobhyphenated/day24/Day24.kt | jacobhyphenated | 572,119,677 | false | {"Kotlin": 157591} | package com.jacobhyphenated.day24
import com.jacobhyphenated.Day
import java.io.File
import kotlin.math.pow
// Planet of Discord
class Day24: Day<List<List<Boolean>>> {
override fun getInput(): List<List<Boolean>> {
return parseInputGrid(
this.javaClass.classLoader.getResource("day24/input.txt")!!
.readText()
)
}
/**
* Bugs appear in a 5x5 grid.
* * Bugs die unless there is exactly 1 bug adjacent (no diagonals)
* * Empty spaces become bugs if there are 1 or 2 adjacent bugs
* * All updates occur simultaneously each "minute"
*
* Find the first time a 5x5 grid layout matches any previous grid layout.
*
* The biodiversity rating is based on numbering the grid from left to right, top to bottom
* (spaces in the 5x5 grid are 0 - 24).
* Each space increases the biodiversity score by a power of 2 (1,2,4,8,16...)
*
* Sum the biodiversity score of each space containing a bug
*/
override fun part1(input: List<List<Boolean>>): Number {
val previousStates = mutableSetOf<List<List<Boolean>>>()
var currentState = input
while (true) {
val nextState = mutableListOf<List<Boolean>>()
for (row in currentState.indices) {
val nextRow = mutableListOf<Boolean>()
for (col in currentState[row].indices) {
val adjacentCount = findAdjacent(row, col, currentState).count { it }
if (currentState[row][col]) {
nextRow.add(adjacentCount == 1)
} else {
nextRow.add(adjacentCount == 1 || adjacentCount == 2)
}
}
nextState.add(nextRow)
}
currentState = nextState
if (!previousStates.add(nextState)) {
break
}
}
// calculate biodiversity score
return currentState.mapIndexed { r, row ->
row.mapIndexed { c, bug ->
if (bug) { 2.0.pow(c + r * 5).toInt() } else { 0 }
}.sum()
}.sum()
}
/**
* The bugs exist in an infinitely recursive grid.
* In each grid, the middle space (row = 2, col = 2) is a new grid.
* The depth of the recursion goes forever, but only the starting grid (depth 0) has bugs
*
* Spaces along the outside of the grid are adjacent to the outer grid interior spaces
* ex - 0,3 is a adjacent to (0,2), (0,4) (1,3) and outer grid (1,2)
*
* Spaces adjacent to the interior grid are also adjacent ot each interior grid space that borders is
* ex - 2,1 is adjacent to (1,1), (2,0), (3,1) and outer grid: (0,0),(1,0),(2,0),(3,0),(4,0)
*
* Find how many bugs exist after 200 minutes
*/
override fun part2(input: List<List<Boolean>>): Number {
return bugsAfterMinutes(input, 200)
}
fun bugsAfterMinutes(input: List<List<Boolean>>, minutes: Int): Int {
var depthMap = mutableMapOf<Int, List<List<Boolean>>>()
depthMap[0] = input
repeat(minutes) {
val nextDepthMap = mutableMapOf<Int, List<List<Boolean>>>()
for (depth in depthMap.keys.min() - 1 .. depthMap.keys.max() + 1) {
// map this grid at depth to the next grid at the same depth
val nextGrid = getGridAtDepth(depthMap, depth)
.mapIndexed { r, row ->
row.mapIndexed { c, isBug ->
val adjacentCount = findAdjacentDepth(r,c, depth, depthMap).count { it }
// this is not a real space, since it represents an interior grid
if (r == 2 && c == 2) {
false
}
else if (isBug) {
adjacentCount == 1
} else {
adjacentCount == 1 || adjacentCount == 2
}
}
}
nextDepthMap[depth] = nextGrid
}
depthMap = nextDepthMap
}
return depthMap.values.sumOf { grid ->
grid.sumOf { row -> row.count { it } }
}
}
/**
* Find adjacent spaces in a flat 5x5 grid
*/
private fun findAdjacent(row: Int, col: Int, grid: List<List<Boolean>>): List<Boolean> {
val result = mutableListOf<Boolean>()
for (r in (row - 1).coerceAtLeast(0) .. (row + 1).coerceAtMost(grid.size - 1)) {
if (r == row) {
continue
}
result.add(grid[r][col])
}
for (c in (col - 1).coerceAtLeast(0) .. (col + 1).coerceAtMost(grid[row].size - 1)) {
if (c == col) {
continue
}
result.add(grid[row][c])
}
return result
}
/**
* Find adjacent spaces in the recursive grid
*/
private fun findAdjacentDepth(row: Int, col: Int, depth: Int, depthMap: Map<Int, List<List<Boolean>>>): List<Boolean> {
val result = mutableListOf<Boolean>()
for (r in (row-1)..(row+1)) {
if (r == row) {
continue
}
if (r < 0) {
result.add(getGridAtDepth(depthMap, depth + 1)[1][2])
}
else if (r == 2 && col == 2) {
val innerGrid = getGridAtDepth(depthMap, depth - 1)
if (row == 1){
result.addAll(innerGrid[0])
} else {
result.addAll(innerGrid[4])
}
}
else if (r > 4) {
result.add(getGridAtDepth(depthMap, depth + 1)[3][2])
}
else {
result.add(getGridAtDepth(depthMap, depth)[r][col])
}
}
for (c in (col-1)..(col+1)) {
if (c == col) {
continue
}
if (c < 0) {
result.add(getGridAtDepth(depthMap, depth+1)[2][1])
}
else if (row == 2 && c == 2) {
val innerGrid = getGridAtDepth(depthMap, depth - 1)
if (col == 1) {
result.addAll((0..4).map { innerGrid[it][0] })
} else {
result.addAll((0..4).map { innerGrid[it][4] })
}
}
else if (c > 4) {
result.add(getGridAtDepth(depthMap, depth + 1)[2][3])
}
else {
result.add(getGridAtDepth(depthMap, depth)[row][c])
}
}
return result
}
private fun getGridAtDepth(depthMap: Map<Int, List<List<Boolean>>>, depth: Int): List<List<Boolean>> {
return depthMap[depth] ?: List(5) { List(5) { false} }
}
fun parseInputGrid(input: String): List<List<Boolean>> {
return input.lines()
.map { it.toCharArray().map { c -> c == '#' } }
}
} | 0 | Kotlin | 0 | 0 | 1a0b9cb6e9a11750c5b3b5a9e6b3d63649bf78e4 | 7,099 | advent2019 | The Unlicense |
project-kotlin-js/src/main/kotlin/Solver.kt | PoorLazyCoder | 454,526,909 | false | null | class Solver(
private var g: List<String>, var y1: List<String>, var y2: List<String>, var y3: List<String>,
private var gray: String
) {
fun solve(): List<List<String>> {
var words = getAllDicWords().toList()
if (g.joinToString("").trim().isEmpty()) g = listOf()
if (y1.joinToString("").trim().isEmpty()) y1 = listOf()
if (y2.joinToString("").trim().isEmpty()) y2 = listOf()
if (y3.joinToString("").trim().isEmpty()) y3 = listOf()
gray = gray.trim()
if (g.isNotEmpty()) {
words = words.filter { w ->
(w[0] == g[0] || g[0] == "") &&
(w[1] == g[1] || g[1] == "") &&
(w[2] == g[2] || g[2] == "") &&
(w[3] == g[3] || g[3] == "") &&
(w[4] == g[4] || g[4] == "")
}
}
if (y1.isNotEmpty()) {
words = filterOutYellow(y1, words)
}
if (y2.isNotEmpty()) {
words = filterOutYellow(y2, words)
}
if (y3.isNotEmpty()) {
words = filterOutYellow(y3, words)
}
if (gray.isNotEmpty()) {
// letters remove from gray
var removeWs = mutableListOf<String>().apply {
addAll(g)
addAll(y1)
addAll(y2)
addAll(y3)
forEach { gray = gray.replace(it, "") }
}
words = words.filter { w ->
w.none { gray.contains(it) }
}
}
return words
}
fun filterOutYellow(y: List<String>, words: List<List<String>>) = run {
words.filter { w ->
((w[0] != y[0]) &&
(w[1] != y[1]) &&
(w[2] != y[2]) &&
(w[3] != y[3]) &&
(w[4] != y[4]))
}.filter { w ->
val wordSt: String = w.joinToString("")
y.all {
wordSt.contains(it)
}
}
}
companion object {
private var dicWords: List<List<String>> = listOf()
private fun getAllDicWords(): List<List<String>> {
if (dicWords.isEmpty()) {
var tempDicWords = mutableListOf<List<String>>()
var tempWords = mutableListOf<String>()
tempWords.addAll(dicWords1)
tempWords.addAll(dicWords2)
tempWords.addAll(dicWords3)
tempWords.forEach {
val w = it.split("").toMutableList()
w.removeFirst()
w.removeLast()
tempDicWords.add(w)
}
dicWords = tempDicWords.toList()
}
return dicWords
}
}
} | 0 | Kotlin | 1 | 1 | 4a92e313d38dde60c11c14764825071e4c0a07ea | 2,835 | Wordle-Helper-Kotlin-JS | MIT License |
aoc21/day_15/main.kt | viktormalik | 436,281,279 | false | {"Rust": 227300, "Go": 86273, "OCaml": 82410, "Kotlin": 78968, "Makefile": 13967, "Roff": 9981, "Shell": 2796} | import pathutils.Pos
import pathutils.fourNeighs
import pathutils.shortest
import java.io.File
fun neighs(pos: Pos, cave: Array<IntArray>): List<Pos> =
fourNeighs(pos, 0, cave.size - 1, 0, cave[0].size - 1)
fun dstFun(@Suppress("UNUSED_PARAMETER") from: Pos, to: Pos, cave: Array<IntArray>): Int =
cave[to.x][to.y]
fun main() {
val cave = File("input").readLines().map {
it.map(Character::getNumericValue).toIntArray()
}.toTypedArray()
val firstDest = Pos(cave.size - 1, cave[0].size - 1)
val first = shortest(Pos(0, 0), firstDest, cave, ::neighs, ::dstFun)!!.dst
println("First: $first")
val largeCave = Array(cave.size * 5) { IntArray(cave[0].size * 5) }
for (x in 0 until cave.size) {
for (i in 0 until 5) {
for (y in 0 until cave[x].size) {
for (j in 0 until 5) {
largeCave[cave.size * i + x][cave[x].size * j + y] =
(cave[x][y] + i + j).let { if (it >= 10) (it % 10) + 1 else it }
}
}
}
}
val secondDest = Pos(largeCave.size - 1, largeCave[0].size - 1)
val second = shortest(Pos(0, 0), secondDest, largeCave, ::neighs, ::dstFun)!!.dst
println("Second: $second")
}
| 0 | Rust | 1 | 0 | f47ef85393d395710ce113708117fd33082bab30 | 1,251 | advent-of-code | MIT License |
year2021/src/main/kotlin/net/olegg/aoc/year2021/day11/Day11.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2021.day11
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.utils.Directions.Companion.NEXT_8
import net.olegg.aoc.utils.Vector2D
import net.olegg.aoc.utils.fit
import net.olegg.aoc.utils.get
import net.olegg.aoc.utils.set
import net.olegg.aoc.year2021.DayOf2021
/**
* See [Year 2021, Day 11](https://adventofcode.com/2021/day/11)
*/
object Day11 : DayOf2021(11) {
override fun first(): Any? {
val start = lines.map { line -> line.map { it.digitToInt() } }
val (_, result) = (0..<100).fold(start to 0) { (field, flash), _ ->
val new = field.map { line ->
line.map { it + 1 }.toMutableList()
}
val toFlash = new.flatMapIndexed { y, line ->
line.mapIndexedNotNull { x, value ->
Vector2D(x, y).takeIf { value > 9 }
}
}
val flashed = mutableSetOf<Vector2D>()
val queue = ArrayDeque(toFlash)
while (queue.isNotEmpty()) {
val curr = queue.removeFirst()
if (curr !in flashed) {
flashed += curr
NEXT_8.map { curr + it.step }
.filter { it !in flashed }
.filter { new.fit(it) }
.forEach { new[it] = new[it]!! + 1 }
queue += NEXT_8.map { curr + it.step }
.filter { new.fit(it) }
.filter { new[it]!! > 9 }
}
}
flashed.forEach { new[it] = 0 }
return@fold new.map { it.toList() } to flash + flashed.size
}
return result
}
override fun second(): Any? {
val start = lines.map { line -> line.map { it.digitToInt() } }
val allSize = start.flatten().size
return generateSequence(1) { it + 1 }
.scan(Triple(start, 0, 0)) { (field, _, _), step ->
val new = field.map { line ->
line.map { it + 1 }.toMutableList()
}
val toFlash = new.flatMapIndexed { y, line ->
line.mapIndexedNotNull { x, value ->
Vector2D(x, y).takeIf { value > 9 }
}
}
val flashed = mutableSetOf<Vector2D>()
val queue = ArrayDeque(toFlash)
while (queue.isNotEmpty()) {
val curr = queue.removeFirst()
if (curr !in flashed) {
flashed += curr
NEXT_8.map { curr + it.step }
.filter { it !in flashed }
.filter { new.fit(it) }
.forEach { new[it] = new[it]!! + 1 }
queue += NEXT_8.map { curr + it.step }
.filter { new.fit(it) }
.filter { new[it]!! > 9 }
}
}
flashed.forEach { new[it] = 0 }
return@scan Triple(new.map { it.toList() }, flashed.size, step)
}
.first { it.second == allSize }
.third
}
}
fun main() = SomeDay.mainify(Day11)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 2,755 | adventofcode | MIT License |
src/chapter2/problem7/solution2.kts | neelkamath | 395,940,983 | false | null | /*
Question:
Intersection: Given two (singly) linked lists, determine if the two lists intersect. Return the intersecting node. Note
that the intersection is defined based on reference, not value. That is, if the kth node of the first linked list is the
exact same node (by reference) as the jth node of the second linked list, then they are intersecting.
Answer:
Using no additional data structures.
*/
class LinkedListNode<T>(var data: T, var next: LinkedListNode<T>? = null) {
/** Returns either the intersecting node or `null` if there's no intersection. */
fun findIntersection(node: LinkedListNode<T>): LinkedListNode<T>? {
val thisLength = readLength()
val otherLength = node.readLength()
var thisNode: LinkedListNode<T>? = this
var otherNode: LinkedListNode<T>? = node
if (thisLength < otherLength) repeat(otherLength.minus(thisLength).toInt()) { otherNode = otherNode!!.next }
else repeat(thisLength.minus(otherLength).toInt()) { thisNode = thisNode!!.next }
while (thisNode != null) {
if (thisNode == otherNode) return thisNode
thisNode = thisNode!!.next
otherNode = otherNode!!.next
}
return null
}
private fun readLength(): UInt {
var length = 1U
var node = this
while (node.next != null) {
node = node.next!!
++length
}
return length
}
override fun toString(): String {
val builder = StringBuilder()
var node: LinkedListNode<T>? = this
while (node != null) {
if (!builder.isEmpty()) builder.append("->")
builder.append(node!!.data)
node = node!!.next
}
builder.insert(0, "[")
builder.append("]")
return builder.toString()
}
}
fun <T> printIntersection(list1: LinkedListNode<T>, list2: LinkedListNode<T>): Unit =
println("List 1: $list1\nList 2: $list2\nIntersection: ${list1.findIntersection(list2)?.data}")
run {
val list1 = LinkedListNode(
1,
)
val list2 = LinkedListNode(
1,
)
printIntersection(list1, list2)
}
run {
val list1 = LinkedListNode(
1,
LinkedListNode(
2,
),
)
val list2 = LinkedListNode(
1,
LinkedListNode(
2,
LinkedListNode(
3,
),
),
)
printIntersection(list1, list2)
}
run {
val intersectingNode = LinkedListNode(
2,
LinkedListNode(
3,
),
)
val list1 = LinkedListNode(
1,
intersectingNode,
)
val list2 = LinkedListNode(
1,
intersectingNode,
)
printIntersection(list1, list2)
}
run {
val intersectingNode = LinkedListNode(
2,
LinkedListNode(
3,
),
)
val list1 = LinkedListNode(
100,
LinkedListNode(
200,
LinkedListNode(
300,
intersectingNode,
),
),
)
val list2 = LinkedListNode(
1,
intersectingNode,
)
printIntersection(list1, list2)
}
| 0 | Kotlin | 0 | 0 | 4421a061e5bf032368b3f7a4cee924e65b43f690 | 3,204 | ctci-practice | MIT License |
src/main/kotlin/days/Day4.kt | butnotstupid | 433,717,137 | false | {"Kotlin": 55124} | package days
class Day4 : Day(4) {
override fun partOne(): Any {
val numberSeq = inputList[0].split(",").map { it.toLong() }
val boards = inputList.drop(1).chunked(6).map { block ->
block.drop(1).map { line ->
line.split(" ").filter { it.isNotEmpty() }.map { it.toLong() }
}.let { numbers ->
Board(numbers)
}
}
numberSeq.forEachIndexed { numberIndex, number ->
boards.forEachIndexed { boardIndex, board ->
board.mark(number)
if (board.isWon()) {
println("Board #$boardIndex won on turn #$numberIndex = $number")
return board.winScore(number)
}
}
}
return "No answer found"
}
override fun partTwo(): Any {
val numberSeq = inputList[0].split(",").map { it.toLong() }
val boards = inputList.drop(1).chunked(6).map { block ->
block.drop(1).map { line ->
line.split(" ").filter { it.isNotEmpty() }.map { it.toLong() }
}.let { numbers ->
Board(numbers)
}
}
var boardsLeft = boards.size
numberSeq.forEachIndexed { numberIndex, number ->
boards.forEachIndexed { boardIndex, board ->
if (!board.isWon()){
board.mark(number)
if (board.isWon()) {
boardsLeft -= 1
if (boardsLeft == 0) {
println("Board #$boardIndex was last to win on turn #$numberIndex = $number")
return board.winScore(number)
}
}
}
}
}
return "No answer found"
}
data class Board(private val numbers: List<List<Long>>) {
private val size = 5
private val marked = Array(5) { Array(5) { false } }
private var won = false
fun mark(number: Long) {
for (i in 0 until size) {
for (j in 0 until size) {
if (numbers[i][j] == number) marked[i][j] = true
}
}
}
fun isWon(): Boolean {
if (won) return won
for (i in 0 until size) {
var rowAll = true
for (j in 0 until size) {
rowAll = rowAll && marked[i][j]
}
if (rowAll) {
won = true
return won
}
}
for (j in 0 until size) {
var columnAll = true
for (i in 0 until size) {
columnAll = columnAll && marked[i][j]
}
if (columnAll) {
won = true
return won
}
}
return won
}
fun winScore(lastCalled: Long): Long {
var unmarkedSum = 0L
for (i in 0 until size) {
for (j in 0 until size) {
unmarkedSum += if (!marked[i][j]) numbers[i][j] else 0
}
}
return lastCalled * unmarkedSum
}
}
}
| 0 | Kotlin | 0 | 0 | a06eaaff7e7c33df58157d8f29236675f9aa7b64 | 3,308 | aoc-2021 | Creative Commons Zero v1.0 Universal |
src/main/kotlin/com/groundsfam/advent/y2022/d03/Day03.kt | agrounds | 573,140,808 | false | {"Kotlin": 281620, "Shell": 742} | package com.groundsfam.advent.y2022.d03
import com.groundsfam.advent.DATAPATH
import com.groundsfam.advent.timed
import kotlin.io.path.div
import kotlin.io.path.useLines
fun priority(item: Char): Int =
if (item in 'a'..'z') {
item - 'a' + 1
} else { // it's between 'A' and 'Z'
item - 'A' + 27
}
fun commonItem(rucksack: String): Char {
val first = rucksack.substring(0, rucksack.length / 2)
val second = rucksack.substring(rucksack.length / 2, rucksack.length)
val common = first.toSet() intersect second.toSet()
assert(common.size == 1) { "Found more/less than one common item: $common" }
return common.toList()[0]
}
fun badgeItem(group: List<String>): Char =
group
.map { it.toSet() }
.reduce { a, b -> a intersect b }
.also { assert(it.size == 1) { "Expected only one common character, but got $it" } }
.let { it.toList()[0] }
fun main() = timed {
val rucksacks = (DATAPATH / "2022/day03.txt").useLines { lines ->
lines.toList()
}
rucksacks
.sumOf { priority(commonItem(it)) }
.also { println("Priority sum = $it") }
rucksacks
.chunked(3)
.onEach { assert(it.size == 3) { "Groups should all be size 3, but got $it" } }
.sumOf { priority(badgeItem(it)) }
.also { println("Badge sum = $it") }
} | 0 | Kotlin | 0 | 1 | c20e339e887b20ae6c209ab8360f24fb8d38bd2c | 1,362 | advent-of-code | MIT License |
src/Day11.kt | realpacific | 573,561,400 | false | {"Kotlin": 59236} | class Monkey(val id: Int, operation: String, test: String) {
private val itemsInHand = mutableListOf<Long>()
var inspectionCount = 0
private set
private lateinit var throwToFn: (Boolean) -> Int
val divisibleBy by lazy {
val testRegex = Regex("Test: divisible by (\\d+)").find(test)!!
testRegex.groupValues[1].toLong()
}
fun catchItem(item: Long) {
itemsInHand.add(item)
}
fun throwItem(item: Long) {
itemsInHand.remove(item)
}
fun currentItems() = ArrayList(itemsInHand)
private val operationRegex by lazy {
Regex("Operation: new = old ([+|-|*|/]) (\\d+)").find(operation)
?: Regex("Operation: new = old ([+|-|*|/]) old").find(operation)!!
}
fun calculateThrow(item: Long, mapper: (Long) -> Long): Pair<Long, Int> {
inspectionCount++
val worryLevel = mapper(calculateWorryLevel(item))
val throwTo = throwToFn(test(worryLevel))
return worryLevel to throwTo
}
fun setThrowTo(cases: List<String>) {
val ifTrueRegex = Regex("If true: throw to monkey (\\d+)").find(cases[0])!!
val ifFalseRegex = Regex("If false: throw to monkey (\\d+)").find(cases[1])!!
throwToFn = {
if (it) ifTrueRegex.groupValues[1].toInt()
else ifFalseRegex.groupValues[1].toInt()
}
}
private fun calculateWorryLevel(value: Long): Long {
val operator = operationRegex.groupValues[1]
val operand = operationRegex.groupValues.getOrNull(2)?.toLongOrNull() ?: value
return when (operator) {
"*" -> value.times(operand)
"+" -> value.plus(operand)
"-" -> value.minus(operand)
"/" -> value.div(operand)
else -> TODO()
}
}
private fun test(value: Long): Boolean {
return value.mod(divisibleBy) == 0L
}
companion object {
fun build(input: List<String>): Monkey {
val regex = Regex("Monkey (\\d):").find(input[0])!!
val monkeyId = regex.groupValues[1].toInt()
val monkey = Monkey(monkeyId, operation = input[2], test = input[3])
monkey.setThrowTo(input.slice(4..5))
monkey.itemsInHand.addAll(extractAllDigits(input[1]))
return monkey
}
private fun extractAllDigits(input: String) = input.split(" ")
.map { it.replace(",", "") }
.filter { it.toLongOrNull() != null }
.map { it.toLong() }.toMutableList()
}
}
fun main() {
fun calculateMonkeyBusiness(monkeys: List<Monkey>): Long {
val topTwoInspectionCount = monkeys.map { it.inspectionCount }.sortedDescending().slice(0..1)
return (topTwoInspectionCount[0]).toLong().times(topTwoInspectionCount[1].toLong())
}
fun buildMonkeys(input: List<String>): List<Monkey> {
val monkeys = ArrayList<Monkey>(input.size / 7)
input.chunked(7).forEach { data ->
val monkey = Monkey.build(data)
monkeys.add(monkey)
}
return monkeys
}
fun part1(input: List<String>): Long {
val monkeys = buildMonkeys(input)
repeat(20) { round ->
monkeys.forEach { monkey ->
val currentItem = monkey.currentItems()
for (item in currentItem) {
val (worryLevel, throwTo) = monkey.calculateThrow(item) {
it.div((3).toLong())
}
monkey.throwItem(item)
monkeys[throwTo].catchItem(worryLevel)
}
}
}
monkeys.forEach { monkey ->
println("Monkey ${monkey.id} inspected items ${monkey.inspectionCount} times.")
}
return calculateMonkeyBusiness(monkeys)
}
fun part2(input: List<String>): Long {
val monkeys = buildMonkeys(input)
val modulo = monkeys.map(Monkey::divisibleBy).fold(1L) { acc, current -> acc.times(current) }
repeat(10000) {
monkeys.forEach { monkey ->
val currentItem = monkey.currentItems()
for (item in currentItem) {
val (worryLevel, throwTo) = monkey.calculateThrow(item) {
it.mod(modulo)
}
monkey.throwItem(item)
monkeys[throwTo].catchItem(worryLevel)
}
}
}
monkeys.forEach { monkey ->
println("Monkey ${monkey.id} inspected items ${monkey.inspectionCount} times.")
}
return calculateMonkeyBusiness(monkeys)
}
run {
val input = readInput("Day11")
println(part1(input))
println(part2(input))
}
}
| 0 | Kotlin | 0 | 0 | f365d78d381ac3d864cc402c6eb9c0017ce76b8d | 4,780 | advent-of-code-2022 | Apache License 2.0 |
src/test/kotlin/ch/ranil/aoc/aoc2023/Day01.kt | stravag | 572,872,641 | false | {"Kotlin": 234222} | package ch.ranil.aoc.aoc2023
import ch.ranil.aoc.AbstractDay
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals
class Day01 : AbstractDay() {
@Test
fun part1() {
assertEquals(142, compute1(testInput))
assertEquals(55488, compute1(puzzleInput))
}
@Test
fun part2Dummy() {
assertEquals(83, "eightwothree".convertNumberStrings())
assertEquals(42, "4nineeightseven2".convertNumberStrings())
}
@Test
fun part2() {
assertEquals(281, compute2(test2Input))
assertEquals(55614, compute2(puzzleInput))
}
private fun compute1(input: List<String>): Int {
return input.sumOf { line ->
val numbersInLine = line.toCharArray().filter { it.isDigit() }
"${numbersInLine.first()}${numbersInLine.last()}".toInt()
}
}
private fun compute2(input: List<String>): Int {
return input.sumOf { line ->
val convertedLine = line.convertNumberStrings()
convertedLine
}
}
private fun String.convertNumberStrings(): Int {
val line = this
val map = mapOf(
"one" to 1,
"two" to 2,
"three" to 3,
"four" to 4,
"five" to 5,
"six" to 6,
"seven" to 7,
"eight" to 8,
"nine" to 9,
"1" to 1,
"2" to 2,
"3" to 3,
"4" to 4,
"5" to 5,
"6" to 6,
"7" to 7,
"8" to 8,
"9" to 9,
)
val numbers = map.flatMap { (numberStr, number) ->
setOf(
line.indexOf(numberStr) to number,
line.lastIndexOf(numberStr) to number,
).filter { it.first >= 0 }
}.sortedBy { it.first }.map { it.second }
return numbers.first() * 10 + numbers.last()
}
} | 0 | Kotlin | 1 | 0 | dbd25877071cbb015f8da161afb30cf1968249a8 | 1,916 | aoc | Apache License 2.0 |
src/Day13.kt | coolcut69 | 572,865,721 | false | {"Kotlin": 36853} | import com.beust.klaxon.JsonArray
import com.beust.klaxon.Parser.Companion.default
private val JSON_PARSER = default()
fun main() {
fun part1(inputs: List<String>): Int {
var sum = 0
repeat((inputs.size + 1) / 3) { index ->
val x = index * 3
val left = inputs[x + 0]
val right = inputs[x + 1]
println("$left vs $right")
val packet1 = JSON_PARSER.parse(StringBuilder(left)) as JsonArray<*>
val packet2 = JSON_PARSER.parse(StringBuilder(right)) as JsonArray<*>
sum += if (packet1 compareTo packet2 < 0) index + 1 else 0
}
return sum
}
fun part2(input: List<String>): Int {
return 0
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day13_test")
check(part1(testInput) == 13)
// check(part2(testInput) == 0)
val input = readInput("Day13")
println(part1(input))
check(part1(input) == 6070)
// println(part2(input))
// check(part2(input) == 0)
}
private infix fun Any.compareTo(other: Any): Int {
if (this.toString().toIntOrNull() != null && other.toString().toIntOrNull() != null) {
return this.toString().toInt().compareTo(other.toString().toInt())
}
if (this is JsonArray<*> || other is JsonArray<*>) {
// Wrap in list if single element
val newThis = if (this is JsonArray<*>) this else JsonArray(this)
val newOther = if (other is JsonArray<*>) other else JsonArray(other)
for (i in newThis.indices) {
if (i in newOther.indices) {
val comparison = newThis[i]!! compareTo newOther[i]!!
if (comparison == 0) {
continue
}
return comparison
} else {
return 1 // Left side is longer
}
}
return if (newThis.size == newOther.size) 0 else -1 // Equal size or right side is longer
}
return 0
}
| 0 | Kotlin | 0 | 0 | 031301607c2e1c21a6d4658b1e96685c4135fd44 | 2,043 | aoc-2022-in-kotlin | Apache License 2.0 |
forth/src/main/kotlin/Forth.kt | 3mtee | 98,672,009 | false | null | class Forth {
companion object {
private val OPS: Map<String, (List<Int>) -> List<Int>> = mapOf(
"+" to {
require(it.size >= 2) { "tsk-tsk-tsk" }
it.dropLast(2) + it.takeLast(2).sum()
},
"-" to {
require(it.size >= 2) { "tsk-tsk-tsk" }
it.dropLast(2) + it.takeLast(2).reduce { acc, i -> acc - i }
},
"*" to {
require(it.size >= 2) { "tsk-tsk-tsk" }
it.dropLast(2) + it.takeLast(2).reduce { acc, i -> acc * i }
},
"/" to {
require(it.size >= 2 && it[1] != 0) { "tsk-tsk-tsk" }
it.dropLast(2) + it.takeLast(2).reduce { acc, i -> acc / i }
},
"dup" to {
require(it.isNotEmpty()) { "tsk-tsk-tsk" }
it + it.last()
},
"drop" to {
require(it.isNotEmpty()) { "tsk-tsk-tsk" }
it.dropLast(1)
},
"swap" to {
require(it.size >= 2) { "tsk-tsk-tsk" }
val sub = it.takeLast(2)
it.dropLast(2) + sub.last() + sub[0]
},
"over" to {
require(it.size >= 2) { "tsk-tsk-tsk" }
it + it[it.size - 2]
}
)
}
fun evaluate(vararg line: String) = processReplacements(line.asList())
.fold(listOf<List<Int>>()) { acc, s -> acc + listOf(evaluateLine(s)) }
.flatMap { it.toList() }
private fun processReplacements(lines: List<String>): List<String> {
val replacements = mutableMapOf<String, String>()
return lines.mapNotNull {
val line = it.lowercase()
if (line.matches(Regex(":.*;"))) {
updateReplacementsMap(line, replacements)
null
} else {
prepareLine(line, replacements)
}
}
}
private fun updateReplacementsMap(
line: String,
replacements: MutableMap<String, String>
) {
val commandDefinition = line.substring(1, line.length - 2).trim()
val spaceIndex = commandDefinition.indexOf(" ")
val key = commandDefinition.substring(0, spaceIndex)
require(key.toDoubleOrNull() == null) { "You can't redefine a number" }
val value = commandDefinition.substring(spaceIndex + 1)
replacements[key] = prepareLine(value, replacements)
}
private fun prepareLine(line: String, replacements: MutableMap<String, String>) = line.split(" ")
.map { token ->
if (replacements.containsKey(token)) {
replacements[token]
} else {
token
}
}
.joinToString(" ")
private fun evaluateLine(line: String): List<Int> {
return line.lowercase().split(" ")
.fold(listOf()) { acc, c ->
when {
c.toIntOrNull() != null -> acc + c.toInt()
c in OPS.keys -> OPS[c]!!.invoke(acc)
else -> throw IllegalArgumentException("Incorrect input")
}
}
}
}
| 0 | Kotlin | 0 | 0 | 6e3eb88cf58d7f01af2236e8d4727f3cd5840065 | 3,220 | exercism-kotlin | Apache License 2.0 |
src/day12/Day12.kt | ZsemberiDaniel | 159,921,870 | false | null | package day12
import RunnablePuzzleSolver
import java.lang.StringBuilder
class Day12 : RunnablePuzzleSolver {
lateinit var initialState: CharArray
lateinit var transitions: Map<String, Char>
override fun readInput1(lines: Array<String>) {
initialState = lines[0].substring(15).toCharArray()
val transitionPairs = lines.sliceArray(2 until lines.size).map {
val line = it.split(" => ")
line[0] to line[1][0]
}.filter { it.first[2] != it.second }.toTypedArray()
transitions = mapOf(*transitionPairs)
}
override fun readInput2(lines: Array<String>) { }
override fun solvePart1(): String {
return getSumsForGenerationsUntil(20)[19].toString()
}
override fun solvePart2(): String {
val generationCount = 50000000000L
val sums = getSumsForGenerationsUntil(200)
val differences = (1 until sums.size).map { sums[it] - sums[it - 1] }
// we go through the differences searching for a starting point from which point on they repeat
var firstSameDiff: Int? = null
for (i in 0 until differences.size - 3) {
if (differences[i] == differences[i + 1] && differences[i + 1] == differences[i + 2]) {
firstSameDiff = i
break
}
}
if (firstSameDiff == null) {
return "Couldn't find the sum. Maybe increase the generation count!"
}
// we add the numbers till the repetition and then repeat the difference x times till we get to the last
// generation we need
return (sums[firstSameDiff] + differences[firstSameDiff + 1] * (generationCount - firstSameDiff)).toString()
}
private fun getSumsForGenerationsUntil(lastGeneration: Int): Array<Int> {
val generationSums = Array(lastGeneration + 1) { 0 }
val plantsArraySize = 2000
// the 0th plant is plantsArraySize / 2
val plants = CharArray(plantsArraySize) { '.' }
var firstPlant = plantsArraySize / 2
var lastPlant = firstPlant + initialState.size - 1
// we copy the initial state
for (i in 0 until initialState.size)
plants[plantsArraySize / 2 + i] = initialState[i]
// what plants to 'flip' (.->#,#->.) after each generation
val flipPlants = mutableListOf<Int>()
for (generationAt in 1..lastGeneration) {
var newFirstPlant = firstPlant
var newLastPlant = lastPlant
// stores the string of the current plant's 2 neighbours
val currentString = StringBuilder()
for (i in firstPlant - 5 until firstPlant) // we init it with th string before the first plant
currentString.append(plants[i])
// we check for each plant whether it can transition to something else
for (plantId in firstPlant - 2..lastPlant + 2) {
// we update the string
currentString.deleteCharAt(0)
currentString.append(plants[plantId + 2])
// this plant flips it's state
val transition = transitions[currentString.toString()]
if (transition != null) {
if (plantId < newFirstPlant) newFirstPlant = plantId
if (plantId > newLastPlant) newLastPlant = plantId
flipPlants.add(plantId)
}
}
// updating where the first and last plants are
firstPlant = newFirstPlant
lastPlant = newLastPlant
// we flip the plants we need to flip
for (plantId in flipPlants) {
plants[plantId] = if (plants[plantId] == '.') { '#' } else { '.' }
// we can't calculate sum based on previous generation if it is the first generation
if (generationAt != 1) {
// we subtract if we flipped to .
generationSums[generationAt] += if (plants[plantId] == '.') {
- plantId + plantsArraySize / 2
} else { // we add if we flipped to #
plantId - plantsArraySize / 2
}
}
}
flipPlants.clear()
// we need to calculate it by summing in the first generation
if (generationAt == 1)
generationSums[generationAt] = (firstPlant..lastPlant).filter { plants[it] == '#' }.map { it - plantsArraySize / 2 }.sum()
else // we can rely on previous generations in generations 2 and above
generationSums[generationAt] += generationSums[generationAt - 1]
}
return generationSums
}
}
| 0 | Kotlin | 0 | 0 | bf34b93aff7f2561f25fa6bd60b7c2c2356b16ed | 4,756 | adventOfCode2018 | MIT License |
src/main/kotlin/com/marcdenning/adventofcode/day12/Day12b.kt | marcdenning | 317,730,735 | false | {"Kotlin": 87536} | package com.marcdenning.adventofcode.day12
import java.io.File
import kotlin.math.abs
fun main(args: Array<String>) {
var ship = Ship(
Coordinates(0, 0, 90),
Coordinates(10, 1, 0)
)
File(args[0]).readLines().map { parseInstruction(it) }
.forEach { ship = moveShipToWaypoint(ship, it) }
println("Manhattan distance: ${abs(ship.shipCoordinates.x) + abs(ship.shipCoordinates.y)}")
}
fun moveShipToWaypoint(ship: Ship, instruction: Pair<Char, Int>): Ship {
return when (instruction.first) {
FORWARD -> {
val xMovement = instruction.second * ship.waypointCoordinates.x
val yMovement = instruction.second * ship.waypointCoordinates.y
Ship(Coordinates(
ship.shipCoordinates.x + xMovement,
ship.shipCoordinates.y + yMovement,
ship.shipCoordinates.orientation
), Coordinates(
ship.waypointCoordinates.x,
ship.waypointCoordinates.y,
ship.waypointCoordinates.orientation
))
}
NORTH -> Ship(
Coordinates(ship.shipCoordinates.x, ship.shipCoordinates.y, ship.shipCoordinates.orientation),
Coordinates(ship.waypointCoordinates.x, ship.waypointCoordinates.y + instruction.second, ship.waypointCoordinates.orientation)
)
SOUTH -> Ship(
Coordinates(ship.shipCoordinates.x, ship.shipCoordinates.y, ship.shipCoordinates.orientation),
Coordinates(ship.waypointCoordinates.x, ship.waypointCoordinates.y - instruction.second, ship.waypointCoordinates.orientation)
)
EAST -> Ship(
Coordinates(ship.shipCoordinates.x, ship.shipCoordinates.y, ship.shipCoordinates.orientation),
Coordinates(ship.waypointCoordinates.x + instruction.second, ship.waypointCoordinates.y, ship.waypointCoordinates.orientation)
)
WEST -> Ship(
Coordinates(ship.shipCoordinates.x, ship.shipCoordinates.y, ship.shipCoordinates.orientation),
Coordinates(ship.waypointCoordinates.x - instruction.second, ship.waypointCoordinates.y, ship.waypointCoordinates.orientation)
)
LEFT -> when (instruction.second) {
90 -> rotateWaypointLeft(ship)
180 -> rotateWaypointLeft(rotateWaypointLeft(ship))
270 -> rotateWaypointLeft(rotateWaypointLeft(rotateWaypointLeft(ship)))
else -> throw Exception()
}
RIGHT -> when (instruction.second) {
90 -> rotateWaypointRight(ship)
180 -> rotateWaypointRight(rotateWaypointRight(ship))
270 -> rotateWaypointRight(rotateWaypointRight(rotateWaypointRight(ship)))
else -> throw Exception()
}
else -> throw Exception()
}
}
fun rotateWaypointLeft(ship: Ship) = Ship(
Coordinates(ship.shipCoordinates.x, ship.shipCoordinates.y, ship.shipCoordinates.orientation),
Coordinates(-ship.waypointCoordinates.y, ship.waypointCoordinates.x, ship.waypointCoordinates.orientation)
)
fun rotateWaypointRight(ship: Ship) = Ship(
Coordinates(ship.shipCoordinates.x, ship.shipCoordinates.y, ship.shipCoordinates.orientation),
Coordinates(ship.waypointCoordinates.y, -ship.waypointCoordinates.x, ship.waypointCoordinates.orientation)
)
data class Ship(
val shipCoordinates: Coordinates,
val waypointCoordinates: Coordinates
)
| 0 | Kotlin | 0 | 0 | b227acb3876726e5eed3dcdbf6c73475cc86cbc1 | 3,429 | advent-of-code-2020 | MIT License |
src/main/kotlin/day25.kt | gautemo | 433,582,833 | false | {"Kotlin": 91784} | import shared.Point
import shared.XYMap
import shared.getText
fun cucumbersStopsAt(input: String): Int{
val bottom = CucumbersMap(input)
return bottom.waitForCucumbersToStop()
}
open class CucumberSpace
data class Cucumber(val eastDir: Boolean) : CucumberSpace(){
fun next(current: Point, width: Int, height: Int): Point {
return if(eastDir){
val x = if(current.x+1 == width) 0 else current.x+1
Point(x, current.y)
}else{
val y = if(current.y+1 == height) 0 else current.y+1
Point(current.x, y)
}
}
}
class CucumbersMap(input: String): XYMap<CucumberSpace>(input.lines(), { c: Char -> if(c == '.') CucumberSpace() else Cucumber(c == '>') }) {
private fun step(): Boolean{
val movedEast = moveCucumbers(true)
val movedSouth = moveCucumbers(false)
return movedEast || movedSouth
}
private fun moveCucumbers(east: Boolean): Boolean{
val movingCucumbers = allPoints().map{ Pair(it, getValue(it)) }.filter {
if(it.second !is Cucumber || (it.second as Cucumber).eastDir != east) return@filter false
val canMove = getValue((it.second as Cucumber).next(it.first, width, height)) !is Cucumber
canMove
}
if(movingCucumbers.isNotEmpty()){
movingCucumbers.filterIsInstance<Pair<Point,Cucumber>>().forEach {
setValue(it.first, CucumberSpace())
setValue(it.second.next(it.first, width, height), it.second)
}
return true
}
return false
}
fun waitForCucumbersToStop(): Int{
var steps = 1
while(step()){
steps++
}
return steps
}
}
fun main(){
val input = getText("day25.txt")
val result = cucumbersStopsAt(input)
println(result)
} | 0 | Kotlin | 0 | 0 | c50d872601ba52474fcf9451a78e3e1bcfa476f7 | 1,855 | AdventOfCode2021 | MIT License |
src/Day03.kt | thiyagu06 | 572,818,472 | false | {"Kotlin": 17748} | import java.io.File
fun main() {
fun parseInput(file: String): List<String> {
return File(file).readLines()
}
fun Char.priority(): Int {
return when (this) {
in 'a'..'z' -> this - 'a' + 1
in 'A'..'Z' -> this - 'A' + 27
else -> 0
}
}
fun part1(): Int {
val lines = parseInput("input/day03a.txt")
return lines.sumOf { it ->
val a = it.substring(0, it.length / 2)
val b = it.substring(it.length / 2)
a.first { it in b }.priority()
}.printIt()
}
fun part2(): Int {
val lines = parseInput("input/day03b.txt")
return lines.chunked(3).sumOf { values ->
val (a, b, c) = values
a.first { it in b && it in c }.priority()
}
}
// test if implementation meets criteria from the description, like:
check(part1() == 7875)
check(part2() == 2479)
}
| 0 | Kotlin | 0 | 0 | 55a7acdd25f1a101be5547e15e6c1512481c4e21 | 951 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/nl/kelpin/fleur/advent2018/Day06.kt | fdlk | 159,925,533 | false | null | package nl.kelpin.fleur.advent2018
class Day06(input: List<String>) {
val points: List<Point> = input.map { Point(it) }
val xRange: IntRange = points.map { it.x }.range()
val yRange: IntRange = points.map { it.y }.range()
private val pointsWithInfiniteArea: Set<Point> =
rectangle().filter(::isOnTheEdge).mapNotNull(::closestPoint).toSet()
fun closestPoint(p: Point): Point? {
val (a, b) = points.sortedBy { it.distanceTo(p) }
return if (a.distanceTo(p) == b.distanceTo(p)) null else a
}
fun totalDistance(p: Point): Int = points.sumBy { it.distanceTo(p) }
private fun rectangle(): Iterable<Point> = xRange.flatMap { x -> yRange.map { y -> Point(x, y) } }
private fun isOnTheEdge(p: Point): Boolean =
p.x == xRange.start || p.x == xRange.endInclusive || p.y == yRange.start || p.y == yRange.endInclusive
fun part1(): Int? = rectangle()
.mapNotNull(::closestPoint)
.filterNot(pointsWithInfiniteArea::contains)
.mostFrequent()
.occurrence
fun part2(threshold: Int): Int = rectangle()
.map(::totalDistance)
.count { it < threshold }
} | 0 | Kotlin | 0 | 3 | a089dbae93ee520bf7a8861c9f90731eabd6eba3 | 1,191 | advent-2018 | MIT License |
year2017/src/main/kotlin/net/olegg/aoc/year2017/day25/Day25.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2017.day25
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.year2017.DayOf2017
/**
* See [Year 2017, Day 25](https://adventofcode.com/2017/day/25)
*/
object Day25 : DayOf2017(25) {
private val HEADER_PATTERN = (
"Begin in state ([A-Z]+)\\.\\n" +
"Perform a diagnostic checksum after ([0-9]+) steps\\."
).toRegex()
private val STATE_PATTERN = "In state ([A-Z]+):".toRegex()
private val ACTION_PATTERN = (
"If the current value is ([0-9]+)[^-]+" +
"- Write the value ([0-9]+)[^-]+" +
"- Move one slot to the ([a-z]+)[^-]+" +
"- Continue with state ([A-Z]+)\\."
).toRegex()
override fun first(): Any? {
val sections = data.split("\n\n")
val (initialState, iterations) = HEADER_PATTERN.find(sections[0])?.destructured ?: error("Unable to parse")
val states = sections
.drop(1)
.map { section ->
State(
name = STATE_PATTERN.find(section)?.destructured?.component1() ?: "A",
actions = ACTION_PATTERN
.findAll(section, section.indexOf("\n"))
.map { match ->
val (value, write, shift, state) = match.destructured
value.toInt() to Action(write.toInt(), if (shift == "left") -1 else 1, state)
}
.toMap(),
)
}
.associateBy { it.name }
val tape = mutableMapOf<Int, Int>()
(0..<iterations.toInt())
.fold(initialState to 0) { (state, shift), _ ->
states[state]
?.actions
?.get(tape[shift] ?: 0)
?.also { action -> tape[shift] = action.write }
?.let { action -> action.state to shift + action.shift }
?: (state to shift)
}
return tape.values.sum()
}
data class State(
val name: String,
val actions: Map<Int, Action>
)
data class Action(
val write: Int,
val shift: Int,
val state: String
)
}
fun main() = SomeDay.mainify(Day25)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 1,968 | adventofcode | MIT License |
src/Day01.kt | Riari | 574,587,661 | false | {"Kotlin": 83546, "Python": 1054} | fun main() {
// Processes input into a list of total calories per elf in descending order
fun processInput(input: List<String>): List<Int> {
val elves = mutableListOf<Int>()
var total = 0
input.forEach {
val calories = it.toIntOrNull()
if (calories == null) {
elves.add(total)
total = 0
} else {
total += calories.toInt()
}
}
elves.add(total)
elves.sortDescending()
return elves
}
fun part1(input: List<Int>): Int {
return input[0]
}
fun part2(input: List<Int>): Int {
return input.slice(0..2).sum()
}
val testInput = processInput(readInput("Day01_test"))
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = processInput(readInput("Day01"))
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 8eecfb5c0c160e26f3ef0e277e48cb7fe86c903d | 939 | aoc-2022 | Apache License 2.0 |
src/Day04.kt | mborromeo | 571,999,097 | false | {"Kotlin": 10600} | fun main() {
fun sectionsData(it: String): List<Int> {
return it.split(",").map{
it.split("-").map {
it.toInt()
}
}.flatten()
}
fun part1(input: List<String>): Int {
return input.count {
val (a, b, c, d) = sectionsData(it)
(a <= c && b >= d) || (c <= a && d >= b)
}
}
fun part2(input: List<String>): Int {
return input.count {
val (a, b, c, d) = sectionsData(it)
a <= d && b >= c
}
}
val inputData = readInput("Day04_input")
println("Part 1: " + part1(inputData))
println("Part 2: " + part2(inputData))
}
| 0 | Kotlin | 0 | 0 | d01860ecaff005aaf8e1e4ba3777a325a84c557c | 680 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/g1401_1500/s1438_longest_continuous_subarray_with_absolute_diff_less_than_or_equal_to_limit/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1401_1500.s1438_longest_continuous_subarray_with_absolute_diff_less_than_or_equal_to_limit
// #Medium #Array #Heap_Priority_Queue #Sliding_Window #Ordered_Set #Queue #Monotonic_Queue
// #2023_06_07_Time_479_ms_(75.00%)_Space_50.3_MB_(100.00%)
import java.util.ArrayDeque
class Solution {
fun longestSubarray(nums: IntArray, limit: Int): Int {
val maxQ = ArrayDeque<Int>()
val minQ = ArrayDeque<Int>()
var best = 0
var left = 0
for (right in nums.indices) {
while (maxQ.isNotEmpty() && nums[right] > nums[maxQ.peekLast()]) {
maxQ.removeLast()
}
maxQ.offerLast(right)
while (minQ.isNotEmpty() && nums[right] < nums[minQ.peekLast()]) {
minQ.removeLast()
}
minQ.offerLast(right)
while (nums[maxQ.peekFirst()] - nums[minQ.peekFirst()] > limit) {
if (maxQ.peekFirst() == left) {
maxQ.removeFirst()
}
if (minQ.peekFirst() == left) {
minQ.removeFirst()
}
left++
}
best = Math.max(best, right - left + 1)
}
return best
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,250 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/CountBinarySubstrings.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import kotlin.math.min
/**
* Count Binary Substrings
* @see <a href="https://leetcode.com/problems/count-binary-substrings">Source</a>
*/
fun interface CountBinarySubstrings {
operator fun invoke(s: String): Int
}
/**
* Approach #1: Group By Character
* Time Complexity: O(N)
* Space Complexity: O(N)
*/
class GroupByCharacter : CountBinarySubstrings {
override operator fun invoke(s: String): Int {
val groups = IntArray(s.length)
var t = 0
groups[0] = 1
for (i in 1 until s.length) {
if (s[i - 1] != s[i]) {
groups[++t] = 1
} else {
groups[t]++
}
}
var ans = 0
for (i in 1..t) {
ans += min(groups[i - 1], groups[i])
}
return ans
}
}
/**
* Approach #2: Linear Scan
* Time Complexity: O(N)
* Space Complexity: O(1)
*/
class CBSLinearScan : CountBinarySubstrings {
override operator fun invoke(s: String): Int {
var ans = 0
var prev = 0
var cur = 1
for (i in 1 until s.length) {
if (s[i - 1] != s[i]) {
ans += min(prev, cur)
prev = cur
cur = 1
} else {
cur++
}
}
return ans + min(prev, cur)
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,971 | kotlab | Apache License 2.0 |
src/day5/result.kt | davidcurrie | 437,645,413 | false | {"Kotlin": 37294} | package day5
import java.io.File
import kotlin.math.absoluteValue
import kotlin.math.max
import kotlin.math.sign
data class Line(val x1: Int, val y1: Int, val x2: Int, val y2: Int)
fun main() {
val input = File("src/day5/input.txt").readLines()
val regex = Regex("([0-9]*),([0-9]*) -> ([0-9]*),([0-9]*)")
val lines = input.map { regex.matchEntire(it)!!.destructured.toList().map { it.toInt() } }
.map { Line(it[0], it[1], it[2], it[3]) }
val rectilinear = lines.filter { it.x1 == it.x2 || it.y1 == it.y2 }
println(solve(rectilinear))
println(solve(lines))
}
fun solve(lines: List<Line>): Int {
val points = mutableMapOf<Pair<Int, Int>, Int>()
lines.forEach { line ->
val dx = (line.x2 - line.x1).sign
val dy = (line.y2 - line.y1).sign
val length = max((line.x1 - line.x2).absoluteValue, (line.y1 - line.y2).absoluteValue)
(0..length).map { i -> Pair(line.x1 + i * dx, line.y1 + i * dy) }.forEach { point ->
points[point] = (points[point] ?: 0).plus(1)
}
}
return points.count { it.value > 1 }
} | 0 | Kotlin | 0 | 0 | dd37372420dc4b80066efd7250dd3711bc677f4c | 1,100 | advent-of-code-2021 | MIT License |
src/main/kotlin/de/consuli/aoc/year2022/days/Day09.kt | ulischulte | 572,773,554 | false | {"Kotlin": 40404} | package de.consuli.aoc.year2022.days
import de.consuli.aoc.common.Day
import de.consuli.aoc.util.Point
import de.consuli.aoc.util.Point.Companion.printMatrixContainingPoints
class Day09 : Day(9, 2022) {
private val movesTestInput: List<String>
private val moves: List<String>
init {
moves = readMovesFromInput(false)
movesTestInput = readMovesFromInput(true)
}
override fun partOne(testInput: Boolean): Any {
return countFieldsVisitedByTail(getMoves(testInput), 2)
}
override fun partTwo(testInput: Boolean): Any {
return countFieldsVisitedByTail(getMoves(testInput), 10)
}
private fun getMoves(testInput: Boolean): List<String> {
return when (testInput) {
true -> movesTestInput
false -> moves
}
}
private fun readMovesFromInput(testInput: Boolean) = getInput(testInput).flatMap { line ->
val (direction, steps) = line.split(' ')
List(steps.toInt()) { direction }
}
private fun countFieldsVisitedByTail(moves: List<String>, ropeLength: Int): Int {
val ropeKnots = MutableList(ropeLength) { Point(0, 0) }
val tailVisits = hashSetOf(ropeKnots.last())
moves.forEach { direction ->
ropeKnots[0] = ropeKnots[0].move(direction)
(1 until ropeLength).forEach { knotIndex ->
ropeKnots[knotIndex] = moveHead(ropeKnots[knotIndex - 1], ropeKnots[knotIndex])
}
tailVisits += ropeKnots.last()
}
tailVisits.printMatrixContainingPoints()
return tailVisits.count()
}
private fun moveHead(head: Point, tail: Point): Point {
if ((tail != head) && !tail.isDirectNeighbor(head)) {
val nextPointInRope = head.minus(tail)
return tail.move(nextPointInRope.x.coerceIn(-1..1), nextPointInRope.y.coerceIn(-1..1))
}
return tail
}
}
| 0 | Kotlin | 0 | 2 | 21e92b96b7912ad35ecb2a5f2890582674a0dd6a | 1,929 | advent-of-code | Apache License 2.0 |
src/main/kotlin/nl/tue/setschematics/util/Support.kt | stenwessel | 316,495,569 | false | {"Java": 137813, "Kotlin": 123105} | package nl.tue.setschematics.util
import nl.hannahsten.utensils.collections.forEachPair
import nl.hannahsten.utensils.math.matrix.distanceTo
import nl.tue.setschematics.Data
import nl.tue.setschematics.grid.Grid
import nl.tue.setschematics.grid.GridLocation
import nl.tue.setschematics.hypergraph.Vertex
import nl.tue.setschematics.state.Edge
import nl.tue.setschematics.state.EdgeSet
fun greedyLocationAssignment(data: Data, grid: Grid<GridLocation>): BiMap<Vertex, GridLocation> {
val map = BiMap<Vertex, GridLocation>()
for (vertex in data.hypergraph.vertices) {
val location = grid.asSequence()
.sortedBy { it.location.distanceTo(vertex.location) }
.first { map.getKey(it) == null }
map.put(vertex, location)
}
return map
}
fun mstSupport(data: Data, locationAssignment: BiMap<Vertex, GridLocation>): EdgeSet {
val spanningTree = EdgeSet(data.hypergraph.hyperedges)
for (hyperedge in data.hypergraph.hyperedges) {
val partitions = mutableSetOf(*hyperedge.vertices.map { setOf(it) }.toTypedArray())
val distances = mutableListOf<Pair<Pair<Vertex, Vertex>, Double>>()
hyperedge.vertices.forEachPair {
distances.add(it to (locationAssignment.getValue(it.first)!!.location.distanceTo(locationAssignment.getValue(it.second)!!.location)))
}
distances.sortBy { it.second }
for ((pair, _) in distances) {
val (u, v) = pair
val setU = partitions.find { u in it } ?: continue
val setV = partitions.find { v in it } ?: continue
if (setU.intersect(setV).isNotEmpty()) continue
val p = UnorderedPair(u, v)
val edge = spanningTree.find { it.endpoints == p } ?: Edge(UnorderedPair(u, v))
edge.hyperedges.add(hyperedge)
spanningTree.add(edge) // Always add such that hyperedge map is updated
partitions.remove(setU)
partitions.remove(setV)
partitions.add(setU + setV)
}
}
return spanningTree
}
| 0 | Java | 0 | 0 | 7e26b70cb0054006897b2b0118024ee34794ab30 | 2,067 | setschematics | MIT License |
src/main/kotlin/io/paly/esetsalaryslipparser/statistics/IncomeStatistics.kt | PaLy | 437,696,484 | false | {"Kotlin": 14570} | package io.paly.esetsalaryslipparser.statistics
import io.paly.esetsalaryslipparser.format.format
import io.paly.esetsalaryslipparser.format.width
import io.paly.esetsalaryslipparser.parser.WageIncome
import io.paly.esetsalaryslipparser.print.Printer
import kotlin.math.max
import kotlin.math.min
class IncomeStatistics(private val sortedIncomes: List<WageIncome>) {
fun movingAvg(kMonths: Int): List<Double> {
val movingSum = movingSum(kMonths)
return movingSum.mapIndexed { index, sum ->
val monthsCount = min(kMonths, index + 1)
sum / monthsCount.toDouble()
}
}
fun movingSum(kMonths: Int): List<Double> {
return List(sortedIncomes.size) { index ->
val firstMonthIndex = max(index - kMonths + 1, 0)
val sum = sortedIncomes.subList(firstMonthIndex, index + 1).sumOf { it.income }
sum
}
}
fun movingAvgAnnualIncrease(): List<Double> {
val movingAvg = movingAvg(12)
return List(sortedIncomes.size) { index ->
if (index < 12) {
0.0
} else {
100 * movingAvg[index] / movingAvg[index - 12] - 100
}
}
}
fun print(printer: Printer) {
val movingAvg = movingAvg(12)
val movingAvgAnnualIncrease = movingAvgAnnualIncrease()
val movingSum = movingSum(12)
printer.println(" Month Income Moving Moving Moving")
printer.println(" annual avg. annual increase annual total")
val dividingLine = "----------------------------------------------------------------------"
printer.println(dividingLine)
sortedIncomes
.forEachIndexed { index, income ->
val movingAvg = movingAvg[index]
val movingAvgAnnualIncrease = movingAvgAnnualIncrease[index]
val movingSum = movingSum[index]
if (income.month == 1) {
printer.println(dividingLine)
}
printer.println(
"${income.year}/${income.month.format(2)}" +
" ${income.income.formatIncome()}" +
" ${movingAvg.formatIncome()}" +
" ${movingAvgAnnualIncrease.formatIncrease()} %" +
" ${movingSum.formatIncome()}"
)
}
printer.println()
val totalIncome = sortedIncomes.sumOf { it.income }
printer.println("Total income: ${totalIncome.formatIncome()}")
}
}
fun Double.formatIncome() = this.format(2).width(9).replace(",", " ")
fun Double.formatIncrease() = this.format(2).width(5) | 0 | Kotlin | 0 | 0 | 9e841fad768dcc07dcbe6d80b220d8194eca3876 | 2,776 | eset-salary-slips | MIT License |
code-sample-kotlin/algorithms/src/main/kotlin/com/codesample/algo/unions.kt | aquatir | 76,377,920 | false | {"Java": 674809, "Python": 143889, "Kotlin": 112192, "Haskell": 57852, "Elixir": 33284, "TeX": 20611, "Scala": 17065, "Dockerfile": 6314, "HTML": 4714, "Shell": 387, "Batchfile": 316, "Erlang": 269, "CSS": 97} | package com.codesample.algo
abstract class Union<T>() {
/** Make two elements point to same union */
abstract fun union(fst: T, snd: T)
/** Return true if two elements are connected or false otherwise. Same elements are always considered connected */
abstract fun connected(fst: T, snd: T): Boolean
}
fun Union<Int>.printConnected(fst: Int, snd: Int) {
if (this.connected(fst, snd))
println("'$fst' and '$snd' are connected") else
println("'$fst' and '$snd' are NOT connected")
}
/** Union with fast 'connected' operation O(1) and slow 'union' O(n)
*
* The entries are connected if and only if they have the same index.
* Implementation is NOT thread-safe!*/
class QuickFindUnion<T> : Union<T>() {
/** Next created union index. Incremented each time a new element in added to this union in 'connected' call */
private var nextUnionIndex = 0
/** Map element to index of union */
private val elements: MutableMap<T, Int> = mutableMapOf()
override fun union(fst: T, snd: T) {
// Maybe insert new element and return if two elements are the same
if (fst == snd) {
oldIndexOrInsertAndIndex(fst)
return
}
val fstIndex = oldIndexOrInsertAndIndex(fst)
val sndIndex = oldIndexOrInsertAndIndex(snd)
if (fstIndex == sndIndex) return // both are already in the union
else {
// Element in union with index 'fstIndex' will now be in secondIndex. Other elements are not changed
for (elem in elements) {
if (elem.value == fstIndex) {
elements[elem.key] = sndIndex
}
}
}
}
override fun connected(fst: T, snd: T): Boolean {
// Assume same element in always connected to itself
if (fst == snd) return true
val fstIndex = oldIndexOrNull(fst)
val sndIndex = oldIndexOrNull(snd)
return fstIndex != null && sndIndex != null && fstIndex == sndIndex
}
private fun exist(elem: T) = elements.containsKey(elem)
/** Get set index of element OR insert element in brand new union */
private fun oldIndexOrInsertAndIndex(elem: T): Int {
return if (exist(elem)) elements.getValue(elem)
else {
val curIndex = nextUnionIndex
elements[elem] = curIndex
nextUnionIndex++
curIndex
}
}
private fun oldIndexOrNull(elem: T): Int? = elements[elem]
}
//
//
//
// Quick Union Union!
//
//
/** Union with fast 'union' operation O(1) and 'slow' 'connected' operation O(n) in worst case,
* but can be optimized to O(log(n)) [QuickUnionUnionOptimized].
* The idea is to add elements as children on union operation which will create long-long trees */
class QuickUnionUnion<T> : Union<T>() {
/** Each element may or may not have a parent. If no parent available -> it's a root of tree */
private val elementToParent: MutableMap<T, T?> = mutableMapOf()
override fun union(fst: T, snd: T) {
insertIfNotExist(fst)
insertIfNotExist(snd)
elementToParent[root(fst)] = root(snd)
}
override fun connected(fst: T, snd: T): Boolean = root(fst) == root(snd)
// Can do like this but harder to read
// private fun insertIfNotExist(elem: T) = elementToParent.computeIfAbsent(elem) { null }
private fun insertIfNotExist(elem: T) {
if (!elementToParent.containsKey(elem)) {
elementToParent[elem] = null
}
}
private fun root(elem: T): T {
var prev = elem
var current = elementToParent[prev]
while (current != null) {
prev = current
current = elementToParent[prev]
}
return prev
}
}
//
//
// Quick Union Union Optimized!
//
//
/** Union with fast 'union' operation O(1) and 'slow' 'connected' operation O(log(n)).
*
* There are 2 optimizations:
* 1. When joining 2 trees -> put smaller one to a root of a larger one (do not let large tree grow further)
* 2. When finding a root of tree -> rebind all children closer to root */
class QuickUnionUnionOptimized<T> : Union<T>() {
/** Each element may or may not have a parent. If no parent available -> it's a root of tree */
private val elementToParent: MutableMap<T, T?> = mutableMapOf()
override fun union(fst: T, snd: T) {
insertIfNotExist(fst)
insertIfNotExist(snd)
// OPTIMIZATION 1 HERE!
// Pick smaller of two trees when linking unions
val rootFst = root(fst)
val rootSnd = root(snd)
if (rootFst.size < rootSnd.size) {
elementToParent[rootFst.root] = rootSnd.root
} else {
elementToParent[rootSnd.root] = rootFst.root
}
}
override fun connected(fst: T, snd: T): Boolean = root(fst).root == root(snd).root
// Can do comment below but seems harder to read
// private fun insertIfNotExist(elem: T) = elementToParent.computeIfAbsent(elem) { null }
private fun insertIfNotExist(elem: T) {
if (!elementToParent.containsKey(elem)) {
elementToParent[elem] = null
}
}
data class RootAndLength<T>(val root: T, val size: Int)
private fun root(elem: T): RootAndLength<T> {
var size = 0
var prev = elem
var current = elementToParent[prev]
while (current != null) {
val oldPrev = prev
prev = current
current = elementToParent[prev]
size++
// OPTIMIZATION 2 HERE!
// Shrink tree on each iteration by rebinding the farthest element 1 step closer to root
elementToParent[oldPrev] = prev
}
return RootAndLength(prev, size)
}
}
//
//
// main() for testing
//
//
fun main() {
// pick one of 3 implementations
// val quickFindUnion = QuickFindUnion<Int>()
// val quickFindUnion = QuickUnionUnion<Int>()
val quickFindUnion = QuickUnionUnionOptimized<Int>()
with(quickFindUnion) {
union(1, 2)
union(6, 5)
union(2, 5)
union(3, 7)
this.printConnected(1, 2) // true
this.printConnected(2, 5) // true
this.printConnected(5, 6) // true
this.printConnected(0, 5) // false
this.printConnected(6, 2) // true
this.printConnected(7, 3) // true
this.printConnected(0, 0) // true
this.printConnected(0, 4) // false
}
}
| 1 | Java | 3 | 6 | eac3328ecd1c434b1e9aae2cdbec05a44fad4430 | 6,490 | code-samples | MIT License |
src/main/kotlin/ru/glukhov/aoc/Day5.kt | cobaku | 576,736,856 | false | {"Kotlin": 25268} | package ru.glukhov.aoc
import java.io.BufferedReader
import java.util.stream.Collectors
private data class Command(val count: Int, val source: Int, val destination: Int)
private class Cargo(private val space: List<ArrayDeque<String>>) {
fun execute(cmd: Command) {
val source = space[cmd.source]
val target = space[cmd.destination]
for (i in 1..cmd.count) {
val head = source.removeFirst()
target.addFirst(head)
}
}
fun execute2(cmd: Command) {
val source = space[cmd.source]
val target = space[cmd.destination]
var buf = ""
for (i in 1..cmd.count) {
val head = source.removeFirst()
buf += head
}
buf.reversed().forEach { target.addFirst(it.toString()) }
}
fun heads(): String = space.stream().map { it.first() }.collect(Collectors.joining())
}
fun main() {
Problem.forDay("day5").use { solveFirst(it) }.let { println("Result of the first problem is $it") }
Problem.forDay("day5").use { solveSecond(it) }.let { println("Result of the first problem is $it") }
}
private fun solveFirst(reader: BufferedReader): String {
val (cargo, commands) = getCargoAndCommands(reader)
commands.forEach { cargo.execute(it) }
return cargo.heads()
}
private fun solveSecond(reader: BufferedReader): String {
val (cargo, commands) = getCargoAndCommands(reader)
commands.forEach { cargo.execute2(it) }
return cargo.heads()
}
private fun getCargoAndCommands(reader: BufferedReader): Pair<Cargo, MutableList<Command>> {
var cargoSpace: MutableList<ArrayDeque<String>>? = null
val commands: MutableList<Command> = mutableListOf()
var parsingCommands = false
while (reader.ready()) {
val line = reader.readLine()
if (line.isEmpty()) {
parsingCommands = true
continue
}
if (parsingCommands) {
commands.add(parseCommand(line))
} else {
if (cargoSpace == null) {
cargoSpace = parseCargoMeta(line)
}
if (line.contains("[")) {
addCargoState(line, cargoSpace)
}
}
}
val cargo = Cargo(cargoSpace ?: throw IllegalArgumentException("There is no cargo space!"))
return Pair(cargo, commands)
}
private fun parseCargoMeta(line: String): MutableList<ArrayDeque<String>> {
val count = normalize(line).trim().split("[").filter { it.isNotBlank() }.size
val target = mutableListOf<ArrayDeque<String>>()
for (i in 0 until count) {
target.add(ArrayDeque())
}
return target
}
private fun addCargoState(line: String, cargoSpace: MutableList<ArrayDeque<String>>) {
val normalized = normalize(line)
val chars = normalized.replace("[", "").replace("]", "").replace(" ", "")
chars.forEachIndexed { index, c ->
if (c != '_') {
cargoSpace[index].addLast(c.toString())
}
}
}
private fun normalize(line: String): String {
var result = line
var old = line
while (true) {
result = result.replaceFirst(" ", " [_] ")
if (result == old) {
return result
}
old = result
}
}
private fun parseCommand(line: String): Command =
line.split(" ").let { Command(it[1].toInt(), it[3].toInt() - 1, it[5].toInt() - 1) } | 0 | Kotlin | 0 | 0 | a40975c1852db83a193c173067aba36b6fe11e7b | 3,374 | aoc2022 | MIT License |
2021/src/main/kotlin/de/skyrising/aoc2021/day10/solution.kt | skyrising | 317,830,992 | false | {"Kotlin": 411565} | package de.skyrising.aoc2021.day10
import de.skyrising.aoc.*
import it.unimi.dsi.fastutil.longs.LongArrayList
val test = TestInput("""
[({(<(())[]>[[{[]{<()<>>
[(()[<>])]({[<{<<[]>>(
{([(<{}[<>[]}>{[]{[(<()>
(((({<>}<{<{<>}{[]{[]{}
[[<[([]))<([[{}[[()]]]
[{[{({}]{}}([{[{{{}}([]
{<[[]]>}<{[{[{[]{()[[[]
[<(<(<(<{}))><([]([]()
<{([([[(<>()){}]>(<<{{
<{([{{}}[<[[[<>{}]]]>[]]
""")
@PuzzleName("Syntax Scoring")
fun PuzzleInput.part1(): Any {
var score = 0
for (line in lines) {
val stack = ArrayDeque<Char>()
for (c in line) {
when (c) {
'(' -> stack.add(')')
'[' -> stack.add(']')
'{' -> stack.add('}')
'<' -> stack.add('>')
else -> {
if (c != stack.removeLast()) {
score += when (c) {
')' -> 3
']' -> 57
'}' -> 1197
'>' -> 25137
else -> throw IllegalArgumentException(c.toString())
}
break
}
}
}
}
}
return score
}
fun PuzzleInput.part2(): Any {
val scores = LongArrayList()
outer@for (line in lines) {
val stack = ArrayDeque<Char>()
for (c in line) {
when (c) {
'(' -> stack.add(')')
'[' -> stack.add(']')
'{' -> stack.add('}')
'<' -> stack.add('>')
else -> {
if (c != stack.removeLast()) {
continue@outer
}
}
}
}
var score = 0L
while (stack.isNotEmpty()) {
score = score * 5 + when (stack.removeLast()) {
')' -> 1
']' -> 2
'}' -> 3
'>' -> 4
else -> throw IllegalArgumentException()
}
}
scores.add(score)
}
scores.sort()
return scores.getLong(scores.size / 2)
}
| 0 | Kotlin | 0 | 0 | 19599c1204f6994226d31bce27d8f01440322f39 | 2,183 | aoc | MIT License |
src/main/kotlin/com/groundsfam/advent/y2015/d07/Day07.kt | agrounds | 573,140,808 | false | {"Kotlin": 281620, "Shell": 742} | package com.groundsfam.advent.y2015.d07
import com.groundsfam.advent.DATAPATH
import kotlin.io.path.div
import kotlin.io.path.useLines
val MAX_SIGNAL = 0x10000.toUInt()
typealias Signal = UInt
infix fun Signal.shiftLeft(amount: Int) = shl(amount) % MAX_SIGNAL
infix fun Signal.shiftRight(amount: Int) = shr(amount)
fun Signal.not(): Signal = inv() % MAX_SIGNAL
sealed class Source
data class ConstantSource(val value: Signal): Source()
data class WireSource(val value: String): Source()
fun String.toSource(): Source =
toUIntOrNull()?.let { ConstantSource(it) } ?: WireSource(this)
sealed class Wiring
data class DirectWiring(val source: Source): Wiring()
data class AndWiring(val source1: Source, val source2: Source): Wiring()
data class OrWiring(val source1: Source, val source2: Source): Wiring()
data class LShiftWiring(val source: Source, val amount: Int): Wiring()
data class RShiftWiring(val source: Source, val amount: Int): Wiring()
data class NotWiring(val source: Source): Wiring()
fun parseWiring(line: String): Pair<String, Wiring> {
val parts = line.split(" ")
val wiring = when (parts.size) {
3 -> DirectWiring(parts[0].toSource())
4 -> NotWiring(parts[1].toSource())
5 ->
when (parts[1]) {
"AND" -> AndWiring(parts[0].toSource(), parts[2].toSource())
"OR" -> OrWiring(parts[0].toSource(), parts[2].toSource())
"LSHIFT" -> LShiftWiring(parts[0].toSource(), parts[2].toInt())
"RSHIFT" -> RShiftWiring(parts[0].toSource(), parts[2].toInt())
else -> throw RuntimeException("Invalid wiring: $line")
}
else -> throw RuntimeException("Invalid wiring: $line")
}
return parts.last() to wiring
}
fun resolveWireA(wiringMap: Map<String, Wiring>, initialSignals: Map<String, Signal>): Signal {
val signals: MutableMap<String, Signal> = initialSignals.toMutableMap()
fun resolveSignal(source: Source): Signal = when (source) {
is ConstantSource -> source.value
is WireSource -> {
val wire = source.value
if (source.value in signals) signals[wire]!!
else {
val resolvedSignal: Signal = when (val wiring = wiringMap[wire]) {
is DirectWiring ->
resolveSignal(wiring.source)
is AndWiring ->
resolveSignal(wiring.source1) and resolveSignal(wiring.source2)
is OrWiring ->
resolveSignal(wiring.source1) or resolveSignal(wiring.source2)
is LShiftWiring ->
resolveSignal(wiring.source) shiftLeft wiring.amount
is RShiftWiring ->
resolveSignal(wiring.source) shiftRight wiring.amount
is NotWiring ->
resolveSignal(wiring.source).not()
null ->
throw RuntimeException("Missing signal for wire $wire")
}
signals[wire] = resolvedSignal
resolvedSignal
}
}
}
return resolveSignal(WireSource("a"))
}
fun main() {
val wiringMap: Map<String, Wiring> = (DATAPATH / "2015/day07.txt").useLines { lines ->
lines.toList().associate(::parseWiring)
}
resolveWireA(wiringMap, emptyMap())
.also { println("Part one: $it") }
resolveWireA(wiringMap, mapOf("b" to 16076.toUInt()))
.also { println("Part two: $it") }
}
| 0 | Kotlin | 0 | 1 | c20e339e887b20ae6c209ab8360f24fb8d38bd2c | 3,559 | advent-of-code | MIT License |
src/nativeMain/kotlin/com.qiaoyuang.algorithm/special/Questions75.kt | qiaoyuang | 100,944,213 | false | {"Kotlin": 338134} | package com.qiaoyuang.algorithm.special
fun test75() {
printlnResult(
array = intArrayOf(2, 3, 3, 7, 3, 9, 2, 1, 7, 2),
comparator = intArrayOf(3, 2, 1),
)
}
/**
* Questions 75:
*/
private fun sortArrayWithOther(array: IntArray, comparator: IntArray): IntArray {
val comparatorMap = buildMap {
comparator.forEachIndexed { index, num ->
this[num] = index
}
}
array.sortedWith { a, b ->
val indexA = comparatorMap[a]
val indexB = comparatorMap[b]
when {
indexA == null && indexB != null -> 1
indexA != null && indexB == null -> -1
indexA == null && indexB == null -> a - b
else -> indexA!!- indexB!!
}
}.forEachIndexed { index, i ->
array[index] = i
}
return array
}
private fun printlnResult(array: IntArray, comparator: IntArray) {
println("Given an IntArray: ${array.toList()},")
println("sorted it by ${comparator.toList()},")
println("we can get: ${sortArrayWithOther(array, comparator).toList()}")
} | 0 | Kotlin | 3 | 6 | 66d94b4a8fa307020d515d4d5d54a77c0bab6c4f | 1,084 | Algorithm | Apache License 2.0 |
src/main/kotlin/Day1.kt | d1snin | 726,126,205 | false | {"Kotlin": 14602} | /*
* 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.
*/
private const val INPUT =
"""
"""
private val lines
get() = INPUT.lines()
.map { it.trim() }
.filter { it.isNotEmpty() }
private val digitMap = mapOf(
"one" to "1",
"two" to "2",
"three" to "3",
"four" to "4",
"five" to "5",
"six" to "6",
"seven" to "7",
"eight" to "8",
"nine" to "9"
)
fun day1() {
println("Running AoC Day 1 (1st part)...")
firstPart()
println()
println("Running AoC Day 1 (2nd part)...")
secondPart()
}
private fun firstPart() {
val res = lines.sumOfDigits()
println("res: $res")
}
private fun secondPart() {
val res = lines.transformWords().sumOfDigits()
println("res: $res")
}
private fun List<String>.sumOfDigits() =
sumOf { line ->
val digits = line.filter {
it.isDigit()
}
digits.singleOrNull()?.let {
numberOf(it, it)
} ?: numberOf(digits.first(), digits.last())
}
private fun List<String>.transformWords() =
map { line ->
var transformedLine = line
var limit = 0
var reverse = false
while (limit <= line.length) {
val batch = if (reverse) transformedLine.takeLast(limit) else transformedLine.take(limit)
var transformedBatch = batch
digitMap.forEach { (word, digit) ->
transformedBatch = transformedBatch.replace(word, digit)
}
val newTransformedLine = transformedLine.replace(batch, transformedBatch)
val transformed = transformedLine != newTransformedLine
if ((transformed || batch.contains("\\d".toRegex())) && !reverse) {
reverse = true
limit = 0
} else {
limit += 1
}
transformedLine = newTransformedLine
}
transformedLine
}
private fun numberOf(first: Char, second: Char) =
String(charArrayOf(first, second)).toInt() | 0 | Kotlin | 0 | 0 | 8b5b34c4574627bb3c6b1a12664cc6b4c9263e30 | 2,575 | aoc-2023 | Apache License 2.0 |
utils/common/src/main/kotlin/Utils.kt | edulix | 387,533,227 | true | {"Kotlin": 3735276, "JavaScript": 265776, "HTML": 115254, "Haskell": 30438, "CSS": 24947, "Python": 20673, "FreeMarker": 16268, "Shell": 12654, "Dockerfile": 12222, "Roff": 7585, "Scala": 6656, "Ruby": 4423, "ANTLR": 1883, "Go": 1235, "Rust": 280, "Emacs Lisp": 191} | /*
* Copyright (C) 2017-2019 HERE Europe B.V.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
* License-Filename: LICENSE
*/
package org.ossreviewtoolkit.utils.common
import java.io.File
/**
* Return recursively all ancestor directories of the given absolute [file], ordered along the path from
* the parent of [file] to the root.
*/
fun getAllAncestorDirectories(file: String): List<String> {
val result = mutableListOf<String>()
var ancestorDir = File(file).parentFile
while (ancestorDir != null) {
result += ancestorDir.invariantSeparatorsPath
ancestorDir = ancestorDir.parentFile
}
return result
}
/**
* Return the longest parent directory that is common to all [files], or null if they have no directory in common.
*/
fun getCommonFileParent(files: Collection<File>): File? =
files.map {
it.normalize().absolutePath
}.reduceOrNull { prefix, path ->
prefix.commonPrefixWith(path)
}?.let {
val commonPrefix = File(it)
if (commonPrefix.isDirectory) commonPrefix else commonPrefix.parentFile
}
/**
* Return the full path to the given executable file if it is in the system's PATH environment, or null otherwise.
*/
fun getPathFromEnvironment(executable: String): File? {
fun String.expandVariable(referencePattern: Regex, groupName: String): String =
replace(referencePattern) {
val variableName = it.groups[groupName]!!.value
Os.env[variableName] ?: variableName
}
val paths = Os.env["PATH"]?.splitToSequence(File.pathSeparatorChar).orEmpty()
return if (Os.isWindows) {
val referencePattern = Regex("%(?<reference>\\w+)%")
paths.mapNotNull { path ->
val expandedPath = path.expandVariable(referencePattern, "reference")
resolveWindowsExecutable(File(expandedPath, executable))
}.firstOrNull()
} else {
val referencePattern = Regex("\\$\\{?(?<reference>\\w+)}?")
paths.map { path ->
val expandedPath = path.expandVariable(referencePattern, "reference")
File(expandedPath, executable)
}.find { it.isFile }
}
}
/**
* Return the concatenated [strings] separated by [separator] whereas blank strings are omitted.
*/
fun joinNonBlank(vararg strings: String, separator: String = " - ") =
strings.filter { it.isNotBlank() }.joinToString(separator)
/**
* Resolve the Windows [executable] to its full name including the optional extension.
*/
fun resolveWindowsExecutable(executable: File): File? {
val extensions = Os.env["PATHEXT"]?.splitToSequence(File.pathSeparatorChar).orEmpty()
return extensions.map { File(executable.path + it.lowercase()) }.find { it.isFile }
?: executable.takeIf { it.isFile }
}
/**
* Temporarily set the specified system [properties] while executing [block]. Afterwards, previously set properties have
* their original values restored and previously unset properties are cleared.
*/
fun <R> temporaryProperties(vararg properties: Pair<String, String?>, block: () -> R): R {
val originalProperties = mutableListOf<Pair<String, String?>>()
properties.forEach { (key, value) ->
originalProperties += key to System.getProperty(key)
value?.also { System.setProperty(key, it) } ?: System.clearProperty(key)
}
return try {
block()
} finally {
originalProperties.forEach { (key, value) ->
value?.also { System.setProperty(key, it) } ?: System.clearProperty(key)
}
}
}
| 5 | Kotlin | 0 | 0 | 65e7b34f5106c08589b5e4f42f9a349d1290ae9b | 4,102 | ort | Apache License 2.0 |
src/array/LeetCode238.kt | Alex-Linrk | 180,918,573 | false | null | package array
/**
* 给定长度为 n 的整数数组 nums,其中 n > 1,返回输出数组 output ,其中 output[i] 等于 nums 中除 nums[i] 之外其余各元素的乘积。
*
*示例:
*
*输入: [1,2,3,4]
*输出: [24,12,8,6]
*说明: 请不要使用除法,且在 O(n) 时间复杂度内完成此题。
*
*进阶:
*你可以在常数空间复杂度内完成这个题目吗?( 出于对空间复杂度分析的目的,输出数组不被视为额外空间。)
*
*来源:力扣(LeetCode)
*链接:https://leetcode-cn.com/problems/product-of-array-except-self
*著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
class LeetCode238 {
fun productExceptSelf(nums: IntArray): IntArray {
if (nums.isEmpty()) return emptyArray<Int>().toIntArray()
val res = IntArray(nums.size)
var value = 1
for (index in 0..res.lastIndex) {
res[index] = value
value *= nums[index]
}
value = 1
for (index in res.lastIndex.downTo(0)) {
res[index] *= value
value *= nums[index]
}
return res
}
} | 0 | Kotlin | 0 | 0 | 59f4ab02819b7782a6af19bc73307b93fdc5bf37 | 1,202 | LeetCode | Apache License 2.0 |
src/main/kotlin/com/dvdmunckhof/aoc/event2023/Day01.kt | dvdmunckhof | 318,829,531 | false | {"Kotlin": 195848, "PowerShell": 1266} | package com.dvdmunckhof.aoc.event2023
class Day01(private val input: List<String>) {
fun solvePart1(): Int {
return input.sumOf { line ->
line.first(Char::isDigit).digitToInt() * 10 + line.last(Char::isDigit).digitToInt()
}
}
fun solvePart2(): Int {
val digits = arrayOf("one", "two", "three", "four", "five", "six", "seven", "eight", "nine")
val digitsMap = digits.mapIndexed { i, word -> word to i + 1 }.toMap() + (1..9).associateBy { i -> i.toString() }
val patternStart = Regex(digits.joinToString("|", "(\\d|", ")"))
val patternEnd = Regex(digits.joinToString("|", ".*(\\d|", ")"))
return input.sumOf { line ->
val digit1 = digitsMap.getValue(patternStart.find(line)!!.groupValues[1])
val digit2 = digitsMap.getValue(patternEnd.find(line)!!.groupValues[1])
digit1 * 10 + digit2
}
}
}
| 0 | Kotlin | 0 | 0 | 025090211886c8520faa44b33460015b96578159 | 922 | advent-of-code | Apache License 2.0 |
advent-of-code-2022/src/main/kotlin/year_2022/Day02.kt | rudii1410 | 575,662,325 | false | {"Kotlin": 37749} | package year_2022
import util.Runner
fun main() {
fun part1(input: List<String>): Int {
val shapeScore = mapOf(
'X' to 1,
'Y' to 2,
'Z' to 3
)
val gameScore = mapOf(
"A Y" to 6,
"B Z" to 6,
"C X" to 6,
"A X" to 3,
"B Y" to 3,
"C Z" to 3
)
return input.sumOf { (shapeScore[it[2]] ?: 0) + (gameScore[it] ?: 0) }
}
Runner.run(::part1, 15)
fun part2(input: List<String>): Int {
val resultScore = mapOf(
'X' to 0,
'Y' to 3,
'Z' to 6
)
val gameScore = mapOf(
"A Y" to 1,
"A Z" to 2,
"A X" to 3,
"B X" to 1,
"B Y" to 2,
"B Z" to 3,
"C Z" to 1,
"C X" to 2,
"C Y" to 3
)
return input.sumOf { (resultScore[it[2]] ?: 0) + (gameScore[it] ?: 0) }
}
Runner.run(::part2, 12)
}
| 1 | Kotlin | 0 | 0 | ab63e6cd53746e68713ddfffd65dd25408d5d488 | 1,023 | advent-of-code | Apache License 2.0 |
src/main/kotlin/leetcode/Problem2002.kt | fredyw | 28,460,187 | false | {"Java": 1280840, "Rust": 363472, "Kotlin": 148898, "Shell": 604} | package leetcode
import kotlin.math.max
/**
* https://leetcode.com/problems/maximum-product-of-the-length-of-two-palindromic-subsequences/
*/
class Problem2002 {
fun maxProduct(s: String): Int {
return maxProduct(s, 0, "", "")
}
private fun maxProduct(s: String, i: Int, word1: String, word2: String): Int {
if (s.length == i) {
if (isPalindrome(word1) && isPalindrome(word2)) {
return word1.length * word2.length
}
return 1
}
val a = maxProduct(s, i + 1, word1 + s[i], word2)
val b = maxProduct(s, i + 1, word1, word2 + s[i])
val c = maxProduct(s, i + 1, word1, word2)
return max(a, max(b, c))
}
private fun isPalindrome(s: String): Boolean {
var i = 0
var j = s.length - 1
while (i < j) {
if (s[i] != s[j]) {
return false
}
i++
j--
}
return true
}
}
| 0 | Java | 1 | 4 | a59d77c4fd00674426a5f4f7b9b009d9b8321d6d | 994 | leetcode | MIT License |
presentation/javagilde/code/src/main/kotlin/javagilde/final.kt | fifth-postulate | 325,780,327 | false | {"Java": 31591, "Elm": 28872, "Kotlin": 20652, "JavaScript": 16757, "Python": 13953, "HTML": 5089, "CSS": 1346, "Makefile": 1194} | package javagilde
// We willen expressies parsen, d.w.z 5*2 + 1
sealed class Expression {
abstract fun evaluate(): Int
}
data class Multiplication(val left: Expression, val right: Expression): Expression() {
override fun evaluate(): Int =
left.evaluate() * right.evaluate()
}
data class Addition(val left: Expression, val right: Expression) : Expression() {
override fun evaluate(): Int =
left.evaluate() + right.evaluate()
}
data class Constant(val value: Int): Expression() {
override fun evaluate(): Int =
value
}
typealias Parser<T> = (String) -> List<Pair<T, String>>
fun parserA(input: String): List<Pair<Char, String>> {
return if (input.startsWith('A')) {
listOf('A' to input.drop(1))
} else {
emptyList()
}}
fun character(target: Char): Parser<Char> = { input: String ->
if (input.startsWith(target)) {
listOf( target to input.drop(1))
} else {
emptyList()
}
}
//val parserA = character('A')
fun satisfy(predicate: (Char) -> Boolean): Parser<Char> = { input: String ->
if (input.length > 0 && predicate(input[0])) {
listOf(input[0] to input.drop(1))
} else {
emptyList()
}
}
val parserAorB = satisfy { it == 'A' || it == 'B'}
fun <T> or(p: Parser<T>, q: Parser<T>): Parser<T> = { input ->
// How to implement?
p(input) + q(input)
}
infix fun <T> Parser<T>.`|||`(p: Parser<T>): Parser<T> =
or(this, p)
fun <S, T> and(p: Parser<S>, q: Parser<T>): Parser<Pair<S,T>> = {input ->
p(input)
.flatMap { (s, intermediate) ->
q(intermediate).map { (t, rest) -> (s to t) to rest }
}
}
infix fun <S, T> Parser<S>.`|&|`(p: Parser<T>): Parser<Pair<S, T>> =
and(this, p)
fun <S, T> map(p: Parser<S>, transform: (S) -> T): Parser<T> = { input ->
p(input)
.map {(s, rest) -> transform(s) to rest }
}
infix fun <S, T> Parser<S>.`&|`(p: Parser<T>): Parser<T> =
map(and(this, p)) {(_, t) -> t}
infix fun <S, T> Parser<S>.`|&`(p: Parser<T>): Parser<S> =
map(and(this, p)) {(s, _) -> s}
fun <T> succeed(result: T): Parser<T> = {input ->
listOf( result to input )
}
fun <T> lazy(p: () -> Parser<T>): Parser<T> = { input ->
p()(input)
}
fun <T> many(p: Parser<T>): Parser<List<T>> =
or(
map(and(p, lazy {many(p)})) { (r, rs) -> listOf(r) + rs},
succeed(emptyList())
)
fun <T> many1(p: Parser<T>): Parser<List<T>> =
map(p `|&|` many(p)) {(r,rs) -> listOf(r) + rs}
val digit: Parser<Int> =
map(satisfy { c -> c in '0' .. '9'}) { it - '0' }
val number: Parser<Int> = map(many1(digit)) {
it.fold(0) {acc, d -> 10*acc + d}
}
val constant: Parser<Expression> =
map(number) {n -> Constant(n)}
fun multiplication(): Parser<Expression> =
constant `|||` map(constant `|&` character('*') `|&|` lazy(::multiplication)) {
(left, right) -> Multiplication(left, right)
}
fun addition(): Parser<Expression> =
multiplication() `|||` map(multiplication() `|&` character('+') `|&|` lazy(::addition)) {
(left, right) -> Addition(left, right)
}
fun expression() : Parser<Expression> =
addition()
fun <T> just(p: Parser<T>): Parser<T> = {input ->
p(input)
.filter {(_, rest) -> rest.isEmpty() }
}
fun <T> parse(parser: Parser<T>, input: String): T? =
just(parser)(input).get(0).first
fun main() {
// 5*2 + 1
val expr = parse(expression(), "5*2+1")//Addition(Multiplication(Constant(5), Constant(2)), Constant(1))
println(expr)
println(expr!!.evaluate())
}
| 3 | Java | 0 | 0 | 61f2c626d6303d88b4b919a1b85a17d6e7290e7d | 3,611 | parser-combinators | MIT License |
src/main/kotlin/com/keithwedinger/Day3.kt | jkwuc89 | 112,970,285 | false | null | package com.keithwedinger
import kotlin.math.abs
import kotlin.math.ceil
import kotlin.math.pow
import kotlin.math.sqrt
/**
* Day 3 Puzzle
* http://adventofcode.com/2017/day/3
*
* @author <NAME> <br>
* Created On: 12/6/17
*/
class Day3 {
fun getSpiralMemoryAccessSteps(input: Int) : Int {
if (input == 0) throw IllegalArgumentException("0 is invalid input")
val distance: Int
if (input == 1) {
distance = 0
} else {
val circle = (ceil(sqrt(input.toDouble())).toInt()) / 2
val circleZero = (circle.toDouble() * 2 - 1).pow(2).toInt()
val centers = ArrayList<Int>()
(1..7 step 2).mapTo(centers) {
circleZero + it * circle
}
val distances = ArrayList<Int>()
centers.forEach { x ->
distances.add(abs(input - x))
}
distance = (circle + distances.min()!!)
}
return distance
}
private enum class Direction {
NORTH, SOUTH, EAST, WEST
}
private fun getValue(map: HashMap<Pair<Int, Int>, Int>, key: Pair<Int, Int>): Int {
var value = 0
if (map.containsKey(key)) {
value = map[key]!!
}
return value
}
fun getNextLargerValue(input: Int) : Int {
if (input == 0) throw IllegalArgumentException("0 is invalid input")
var x = 0
var y = 0
var layerSteps = 1
var newLayer = true
var direction = Direction.EAST
val valueMap = HashMap<Pair<Int, Int>, Int>()
valueMap.put(Pair(0, 0), 1)
while (true) {
var j = 0
while (j < layerSteps) {
when (direction) {
Direction.NORTH -> y += 1
Direction.SOUTH -> y -= 1
Direction.EAST -> x += 1
Direction.WEST -> x -= 1
}
var nextLargerValue = 0
nextLargerValue += getValue(valueMap, Pair(x, y + 1))
nextLargerValue += getValue(valueMap, Pair(x, y - 1))
nextLargerValue += getValue(valueMap, Pair(x + 1, y))
nextLargerValue += getValue(valueMap, Pair(x + 1, y + 1))
nextLargerValue += getValue(valueMap, Pair(x + 1, y - 1))
nextLargerValue += getValue(valueMap, Pair(x - 1, y))
nextLargerValue += getValue(valueMap, Pair(x - 1, y + 1))
nextLargerValue += getValue(valueMap, Pair(x - 1, y - 1))
if (nextLargerValue > input) {
return nextLargerValue
} else {
valueMap.put(Pair(x, y), nextLargerValue)
}
j++
}
direction = when (direction) {
Direction.NORTH -> Direction.WEST
Direction.SOUTH -> Direction.EAST
Direction.EAST -> Direction.NORTH
Direction.WEST -> Direction.SOUTH
}
newLayer = (newLayer.not())
if (newLayer) {
layerSteps += 1
}
}
}
} | 0 | Kotlin | 0 | 0 | 3b88f64a498e4640b021cc91160a5adfcb01d0ec | 3,193 | adventofcode | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/CheckStraightLine.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
/**
* 1232. Check If It Is a Straight Line
* @see <a href="https://leetcode.com/problems/check-if-it-is-a-straight-line/">Source</a>
*/
fun interface CheckStraightLine {
operator fun invoke(coordinates: Array<IntArray>): Boolean
}
class CheckStraightLineSlopeProperty : CheckStraightLine {
override operator fun invoke(coordinates: Array<IntArray>): Boolean {
val deltaY = getYDiff(coordinates[1], coordinates[0])
val deltaX = getXDiff(coordinates[1], coordinates[0])
for (i in 2 until coordinates.size) {
// Check if the slope between points 0 and i, is the same as between 0 and 1.
if (deltaY * getXDiff(coordinates[i], coordinates[0])
!= deltaX * getYDiff(coordinates[i], coordinates[0])
) {
return false
}
}
return true
}
// Returns the delta Y.
private fun getYDiff(a: IntArray, b: IntArray): Int {
return a[1] - b[1]
}
// Returns the delta X.
private fun getXDiff(a: IntArray, b: IntArray): Int {
return a[0] - b[0]
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,747 | kotlab | Apache License 2.0 |
src/main/kotlin/recur/Target.kt | yx-z | 106,589,674 | false | null | package recur
import util.*
import java.lang.Math.floor
// given a list of distinct heights of people H[1..n]
// a shorter guy can aim his/her gun @ his/her neighbor!
// a taller guy can aim @ the first one who is even taller than him/her
// return l[1..n], r[1..n] where l represents the index who can target to the left
// and r represents targeting to the right
// 1. find a O(n log n) algorithm to get l, r
fun OneArray<Int>.target(): Tuple2<OneArray<Int>, OneArray<Int>> {
val H = this
val n = size
if (n == 1) {
return oneArrayOf(0) tu oneArrayOf(0)
}
if (n == 2) {
val L = OneArray(2) { 0 }
val R = OneArray(2) { 0 }
if (H[1] > H[2]) {
L[2] = 1
} else { // H[1] < H[2]
R[1] = 2
}
return L tu R
}
val m = floor(n / 2.0).toInt()
val (ll, lr) = this[1..m].target()
var (rl, rr) = this[m + 1..n].target()
// ! tricky part !
// if we recursively get the right part,
// all non-zero indices should be shifted!
rl = rl.map { if (it == 0) 0 else it + m }.toOneArray()
rr = rr.map { if (it == 0) 0 else it + m }.toOneArray()
val L = ll append rl
val R = lr append rr
// println("$n:\nL: $L\nR: $R\n")
var i = m
var j = m + 1
while (i >= 1 && j <= n) {
when {
R[i] != 0 -> i--
L[j] != 0 -> j++
H[i] < H[j] -> {
R[i] = j
i--
}
else -> { // H[i] > H[j]
L[j] = i
j++
}
}
}
return L tu R
}
// 2. after shooting either of their target, some people die and others survive
// keep performing such "massacre" and only the shortest guy survives
// find # of rounds required to find the winner in O(n)
fun OneArray<Int>.rounds(): Int {
val H = this
val n = size
if (n == 1) {
return 0
}
val survivors = ArrayList<Int>()
H.getterIndexOutOfBoundsHandler = { INF } // sentinel values
for (i in 1..n) {
if (H[i - 1] > H[i] && H[i] < H[i + 1]) { // H[i] is a local minimum
survivors.add(H[i])
}
}
return 1 + survivors.toOneArray().rounds()
}
fun main(args: Array<String>) {
val H = oneArrayOf(3, 8, 1, 6, 5, 7, 2, 4)
println(H.target())
println(H.rounds())
} | 0 | Kotlin | 0 | 1 | 15494d3dba5e5aa825ffa760107d60c297fb5206 | 2,062 | AlgoKt | MIT License |
Retos/Reto #4 - PRIMO, FIBONACCI Y PAR [Media]/kotlin/masdos.kt | mouredev | 581,049,695 | false | {"Python": 3866914, "JavaScript": 1514237, "Java": 1272062, "C#": 770734, "Kotlin": 533094, "TypeScript": 457043, "Rust": 356917, "PHP": 281430, "Go": 243918, "Jupyter Notebook": 221090, "Swift": 216751, "C": 210761, "C++": 164758, "Dart": 159755, "Ruby": 70259, "Perl": 52923, "VBScript": 49663, "HTML": 45912, "Raku": 44139, "Scala": 30892, "Shell": 27625, "R": 19771, "Lua": 16625, "COBOL": 15467, "PowerShell": 14611, "Common Lisp": 12715, "F#": 12710, "Pascal": 12673, "Haskell": 11051, "Assembly": 10368, "Elixir": 9033, "Visual Basic .NET": 7350, "Groovy": 7331, "PLpgSQL": 6742, "Clojure": 6227, "TSQL": 5744, "Zig": 5594, "Objective-C": 5413, "Apex": 4662, "ActionScript": 3778, "Batchfile": 3608, "OCaml": 3407, "Ada": 3349, "ABAP": 2631, "Erlang": 2460, "BASIC": 2340, "D": 2243, "Awk": 2203, "CoffeeScript": 2199, "Vim Script": 2158, "Brainfuck": 1550, "Prolog": 1342, "Crystal": 783, "Fortran": 778, "Solidity": 560, "Standard ML": 525, "Scheme": 457, "Vala": 454, "Limbo": 356, "xBase": 346, "Jasmin": 285, "Eiffel": 256, "GDScript": 252, "Witcher Script": 228, "Julia": 224, "MATLAB": 193, "Forth": 177, "Mercury": 175, "Befunge": 173, "Ballerina": 160, "Smalltalk": 130, "Modula-2": 129, "Rebol": 127, "NewLisp": 124, "Haxe": 112, "HolyC": 110, "GLSL": 106, "CWeb": 105, "AL": 102, "Fantom": 97, "Alloy": 93, "Cool": 93, "AppleScript": 85, "Ceylon": 81, "Idris": 80, "Dylan": 70, "Agda": 69, "Pony": 69, "Pawn": 65, "Elm": 61, "Red": 61, "Grace": 59, "Mathematica": 58, "Lasso": 57, "Genie": 42, "LOLCODE": 40, "Nim": 38, "V": 38, "Chapel": 34, "Ioke": 32, "Racket": 28, "LiveScript": 25, "Self": 24, "Hy": 22, "Arc": 21, "Nit": 21, "Boo": 19, "Tcl": 17, "Turing": 17} | fun main() {
/*
* Escribe un programa que, dado un número, compruebe y muestre si es primo, fibonacci y par.
* Ejemplos:
* - Con el número 2, nos dirá: "2 es primo, fibonacci y es par"
* - Con el número 7, nos dirá: "7 es primo, no es fibonacci y es impar"
*/
println(describeNumber(2))
println(describeNumber(7))
println(describeNumber(0))
println(describeNumber(1))
println(describeNumber(113))
println(describeNumber(-8))
println(describeNumber(89))
}
private fun describeNumber(number: Int): String {
return "$number " +
"${if (isPrime(number)) "es primo" else "no es primo"}, " +
"${if (isFibonacci(number)) "es fibonacci" else "no es fibonacci"} y " +
if (isEven(number)) "es par" else "es impar"
}
private fun isEven(number: Int) = number % 2 == 0
private fun isPrime(number: Int): Boolean {
if (number == 0 || number == 1 || number < 0) return false
for (i in 2 until number) if (number % i == 0) return false
return true
}
private fun isFibonacci(number: Int): Boolean {
if (number < 0) return false
val fibonacciNumbers = mutableListOf(0, 1)
var count = 2
while (fibonacciNumbers.last() < number) {
fibonacciNumbers.add(fibonacciNumbers[count - 1] + fibonacciNumbers[count - 2])
count++
}
return fibonacciNumbers.contains(number)
}
| 4 | Python | 2,929 | 4,661 | adcec568ef7944fae3dcbb40c79dbfb8ef1f633c | 1,330 | retos-programacion-2023 | Apache License 2.0 |
src/Day09.kt | vi-quang | 573,647,667 | false | {"Kotlin": 49703} | import kotlin.math.abs
/**
* Main -------------------------------------------------------------------
*/
fun main() {
fun Int.toIdentity(): Int {
if (this == 0) {
return 0
}
if (this < 1) {
return -1
} else {
return 1
}
}
fun getHeadPositions(input: List<String>): List<Pair<Int, Int>> {
val positionList = mutableListOf<Pair<Int, Int>>()
var headR = 0
var headC = 0
input.forEach {
val token = it.split(" ")
var step = token[1].toInt()
System.err.println(">>$it")
while (step > 0) {
//System.err.println("STEPS: $step")
step-- //we take a step
when (token[0]) {
"R" -> {
headC++
}
"L" -> {
headC--
}
"U" -> {
headR++
}
"D" -> {
headR--
}
}
positionList.add(Pair(headR, headC))
}
}
return positionList
}
fun getTailPositions(headPositions: List<Pair<Int, Int>>): List<Pair<Int, Int>> {
val tailPositions = mutableListOf<Pair<Int, Int>>()
var tailR = 0
var tailC = 0
headPositions.forEach {
val headR = it.first
val headC = it.second
val diffC = headC - tailC
val diffR = headR - tailR
val deltaC = abs(diffC)
val deltaR = abs(diffR)
if (deltaC == 2 || deltaR == 2) {
tailC += diffC.toIdentity()
tailR += diffR.toIdentity()
}
//System.err.println("H:$headR, $headC --- T:$tailR, $tailC")
tailPositions.add(Pair(tailR, tailC))
}
return tailPositions
}
fun part1(input: List<String>): Int {
val headPositions = getHeadPositions(input)
val tailPositions = getTailPositions(headPositions)
return tailPositions.toSet().size
}
fun part2(input: List<String>): Int {
val headPositions = getHeadPositions(input)
var tailPositions = getTailPositions(headPositions) //tail 1
for (i in 2 .. 9) { //tails 2 .. 9
System.err.println("$i")
tailPositions = getTailPositions(tailPositions)
}
return tailPositions.toSet().size
}
val input = readInput(9)
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 2 | ae153c99b58ba3749f16b3fe53f06a4b557105d3 | 2,670 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/g2301_2400/s2376_count_special_integers/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2301_2400.s2376_count_special_integers
// #Hard #Dynamic_Programming #Math #2023_07_02_Time_125_ms_(100.00%)_Space_32.8_MB_(100.00%)
@Suppress("NAME_SHADOWING")
class Solution {
private lateinit var cntMap: IntArray
// number n as an array, splitted by each digit
private lateinit var digits: IntArray
fun countSpecialNumbers(n: Int): Int {
var n = n
if (n < 10) {
return n
}
val len = Math.log10(n.toDouble()).toInt() + 1
cntMap = IntArray(len - 1)
val res = countUnbounded(len)
digits = IntArray(len)
var i = len - 1
while (i >= 0) {
digits[i] = n % 10
i--
n /= 10
}
return res + dfs(0, 0)
}
private fun dfs(i: Int, mask: Int): Int {
if (i == digits.size) {
return 1
}
var res = 0
val startJ = if (i == 0) 1 else 0
for (j in startJ until digits[i]) {
if (mask and (1 shl j) == 0) {
// unbounded lens left
val unbounded = digits.size - 2 - i
res += if (unbounded >= 0) count(unbounded, 9 - i) else 1
}
}
if (mask and (1 shl digits[i]) == 0) {
res += dfs(i + 1, mask or (1 shl digits[i]))
}
return res
}
private fun count(i: Int, max: Int): Int {
return if (i == 0) {
max
} else (max - i) * count(i - 1, max)
}
private fun countUnbounded(len: Int): Int {
var res = 9
cntMap[0] = 9
for (i in 0 until len - 2) {
cntMap[i + 1] = cntMap[i] * (9 - i)
res += cntMap[i + 1]
}
return res
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,739 | LeetCode-in-Kotlin | MIT License |
2k23/aoc2k23/src/main/kotlin/20.kt | papey | 225,420,936 | false | {"Rust": 88237, "Kotlin": 63321, "Elixir": 54197, "Crystal": 47654, "Go": 44755, "Ruby": 24620, "Python": 23868, "TypeScript": 5612, "Scheme": 117} | package d20
import input.read
fun main() {
println("Part 1: ${part1(read("20.txt"))}")
println("Part 2: ${part2(read("20.txt"))}")
}
fun part1(input: List<String>): Int {
val modules = parseInput(input)
val counter = Counter()
repeat(1000) {
press(modules, counter)
}
return counter.times()
}
fun part2(input: List<String>): Long {
val modules = parseInput(input)
val finder = Finder(modules)
while (!finder.allFound()) {
finder.handlePress()
press(modules, finder)
}
return finder.lcm()
}
private fun parseInput(input: List<String>): Map<String, Module> {
val modules = input.associate { line ->
val type = line.first()
val name = line.substring(1).substringBefore(" ")
val destinations = line.substringAfter(" -> ").split(",").map { it.trim() }.filter { it.isNotEmpty() }
when (type) {
'b' -> "broadcaster" to Broadcaster(destinations)
'%' -> name to FlipFlop(name, destinations)
'&' -> name to Conjunction(name, destinations)
else -> throw IllegalArgumentException("Unknown type: $type")
}
}
val conjunctions = modules.values.filterIsInstance<Conjunction>().associateBy { it.name }
modules.values.forEach { module ->
module.destinations.forEach { destination ->
conjunctions[destination]?.addSource(module.name)
}
}
return modules
}
private fun press(modules: Map<String, Module>, pulsable: Pulsable) {
val pulses = ArrayList<Pulse>().apply {
add(Pulse(false, "button", "broadcaster"))
}
while (pulses.isNotEmpty()) {
val pulse = pulses.removeFirst()
pulsable.handlePulse(pulse)
modules[pulse.destination]?.receive(pulse)?.forEach { pulses.add(it) }
}
}
interface Pulsable {
fun handlePulse(pulse: Pulse)
}
class Counter : Pulsable {
private var low = 0
private var high = 0
override fun handlePulse(pulse: Pulse) {
if (pulse.high) {
high++
} else {
low++
}
}
fun times(): Int = low * high
}
class Finder(modules: Map<String, Module>) : Pulsable {
private var pressCount = 0L
private val found = mutableSetOf<String>()
private val watched: MutableMap<String, Long>
init {
val source = modules.values.first { "rx" in it.destinations }
watched = modules.values.filter { source.name in it.destinations }
.toMutableSet()
.associate { it.name to 0L }
.toMutableMap()
}
override fun handlePulse(pulse: Pulse) {
if (pulse.high && pulse.source in watched) {
found.add(pulse.source)
}
found.forEach { name ->
if (watched.getValue(name) == 0L) {
watched[name] = pressCount
}
}
}
fun handlePress() {
pressCount++
}
fun lcm(): Long = watched.values.reduce { acc, i -> lcm(acc, i) }
fun allFound(): Boolean = found.containsAll(watched.keys)
private fun gcd(a: Long, b: Long): Long {
return if (b == 0L) a else gcd(b, a % b)
}
private fun lcm(a: Long, b: Long): Long {
return if (a == 0L || b == 0L) 0 else (a * b) / gcd(a, b)
}
}
class Pulse(val high: Boolean, val source: String, val destination: String)
sealed class Module(val name: String, val destinations: List<String>) {
abstract fun receive(pulse: Pulse): List<Pulse>
fun send(high: Boolean): List<Pulse> = destinations.map { Pulse(high, name, it) }
}
private class Broadcaster(destinations: List<String>) : Module("broadcaster", destinations) {
override fun receive(pulse: Pulse): List<Pulse> = send(pulse.high)
}
private class FlipFlop(name: String, destinations: List<String>) : Module(name, destinations) {
private var on = false
override fun receive(pulse: Pulse): List<Pulse> {
if (pulse.high) {
return emptyList()
}
on = !on
return send(on)
}
}
private class Conjunction(name: String, destinations: List<String>) : Module(name, destinations) {
private val mem = mutableMapOf<String, Boolean>()
fun addSource(source: String) {
if (source !in mem) {
mem[source] = false
}
}
override fun receive(pulse: Pulse): List<Pulse> {
mem[pulse.source] = pulse.high
return send(!mem.values.all { it })
}
}
| 0 | Rust | 0 | 3 | cb0ea2fc043ebef75aff6795bf6ce8a350a21aa5 | 4,473 | aoc | The Unlicense |
src/main/kotlin/cloud/dqn/leetcode/MergeTwoSortedLists.kt | aviuswen | 112,305,062 | false | null | package cloud.dqn.leetcode
/**
* https://leetcode.com/problems/merge-two-sorted-lists/description/
* Merge two sorted linked lists and return it as a new list.
* The new list should be made by splicing together the nodes
* of the first two lists.
*
* Definition for singly-linked list.
* class ListNode(var `val`: Int = 0) {
* var next: ListNode? = null
* }
*/
class MergeTwoSortedLists {
/**
// sanity check beforehande; if either null, empty
Algorithm 0:
Use current,previous snake method
current0 -> l1.head
current1 -> l1.head
var head: ListNode? = null
var tail: ListNode? = null // append area
while (currents != null) {
// warning: handling case of head == null
get lowest from each current
append lowestCurrent to result
current = lowestCurrent.next
}
append the rest of the non-null current to the list
return head
*/
class ListNode(var `val`: Int = 0) {
var next: ListNode? = null
}
class Solution {
fun mergeTwoLists(l1: ListNode?, l2: ListNode?): ListNode? {
var head: ListNode? = null // (0a)->...
var tail: ListNode? = null // (0a)->(2c)->(2d)->(3e)->(4b)-|
var list1 = l1 // (4b)-|
var list2 = l2 // null
while (list1 != null && list2 != null) {
val lowest = if (list1.`val` > list2.`val`) list2 else list1 // (3e)-|
if (head == null) {
head = lowest
}
tail?.next = lowest
tail = lowest
if (list1.`val` > list2.`val`) {
list2 = list2.next
} else {
list1 = list1.next
}
}
tail?.next = list1 ?: list2
return head ?: l1 ?: l2
}
}
} | 0 | Kotlin | 0 | 0 | 23458b98104fa5d32efe811c3d2d4c1578b67f4b | 2,000 | cloud-dqn-leetcode | No Limit Public License |
year2023/src/main/kotlin/net/olegg/aoc/year2023/day3/Day3.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2023.day3
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.utils.Directions.Companion.NEXT_8
import net.olegg.aoc.utils.Vector2D
import net.olegg.aoc.utils.get
import net.olegg.aoc.year2023.DayOf2023
/**
* See [Year 2023, Day 3](https://adventofcode.com/2023/day/3)
*/
object Day3 : DayOf2023(3) {
private val NOT_SYMBOLS = buildSet<Char?> {
addAll('0'..'9')
add('.')
add(null)
}
private val NUMBER = "\\d+".toRegex()
override fun first(): Any? {
return lines
.mapIndexed { y, row ->
NUMBER.findAll(row)
.map { match ->
if (match.range.any { x -> NEXT_8.any { matrix[it.step + Vector2D(x, y)] !in NOT_SYMBOLS } }) {
match.value.toInt()
} else {
0
}
}
.sum()
}
.sum()
}
override fun second(): Any? {
val nextToGears = lines
.flatMapIndexed { y, row ->
NUMBER.findAll(row)
.flatMap { match ->
val value = match.value.toLong()
match.range
.flatMap { x ->
NEXT_8
.map { it.step + Vector2D(x, y) }
.filter { matrix[it] == '*' }
}
.toSet()
.map { it to value }
}
}
return nextToGears.groupBy { it.first }
.filterValues { it.size == 2 }
.mapValues { it.value.first().second * it.value.last().second }
.toList()
.sumOf { it.second }
}
}
fun main() = SomeDay.mainify(Day3)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 1,562 | adventofcode | MIT License |
src/aoc2022/Day03.kt | FluxCapacitor2 | 573,641,929 | false | {"Kotlin": 56956} | package aoc2022
import Day
import intersect
object Day03 : Day(2022, 3) {
override fun part1() {
val sum = lines.sumOf { line ->
// Split each line/rucksack into two halves
val (firstHalf, secondHalf) = line.chunked(line.length / 2)
// Find the common character between the first and second half of the line (rucksack)
val intersection = firstHalf intersect secondHalf
val commonChar = intersection.single()
// Add the priority of this character to the sum
return@sumOf commonChar.priority
}
println("Part 1 result: $sum")
}
override fun part2() {
val sum = lines
.chunked(3) // Group the input into chunks of 3 lines.
// For example: [1, 2, 3, 4, 5, 6] => [[1, 2, 3], [4, 5, 6]]
.sumOf { group ->
// Find the common letter between all 3
val intersection = group[0] intersect group[1] intersect group[2]
val commonChar = intersection.distinct().single()
// Add the priority of this character to the sum
return@sumOf commonChar.priority
}
println("Part 2 result: $sum")
}
private val Char.priority
get() = if (isUpperCase()) {
this - 'A' + 26
} else {
this - 'a'
}
} | 0 | Kotlin | 0 | 0 | a48d13763db7684ee9f9129ee84cb2f2f02a6ce4 | 1,407 | advent-of-code-2022 | Apache License 2.0 |
kotlin/dp/MaxPalindrome.kt | polydisc | 281,633,906 | true | {"Java": 540473, "Kotlin": 515759, "C++": 265630, "CMake": 571} | package dp
import numeric.FFT
import optimization.Simplex
// Find maximum palindromic subsequence of the given string
object MaxPalindrome {
fun maxPalindrome(p: String): String {
val n: Int = p.length()
val s: CharArray = p.toCharArray()
val dp = Array(n + 1) { IntArray(n + 1) }
for (i in 0..n) {
dp[0][i] = i
dp[i][0] = dp[0][i]
}
for (i in 0 until n) {
for (j in 0 until n - 1 - i) {
dp[i + 1][j + 1] = if (s[i] == s[n - 1 - j]) dp[i][j] else Math.min(dp[i][j + 1] + 1, dp[i + 1][j] + 1)
}
}
var min = n
var x = 0
var y = n
for (i in 0..n) {
if (min > dp[i][n - i]) {
min = dp[i][n - i]
x = i
y = n - i
}
}
var middle = ""
for (i in 0 until n) {
if (min > dp[i][n - i - 1]) {
min = dp[i][n - i - 1]
x = i
y = n - i - 1
middle = "" + s[i]
}
}
var res = ""
while (x > 0 && y > 0) {
val a = dp[x - 1][y - 1]
val b = dp[x - 1][y]
val c = dp[x][y - 1]
val m: Int = Math.min(a, Math.min(b, c))
if (a == m) {
res += s[x - 1]
--x
--y
} else if (b == m) {
--x
} else {
--y
}
}
return StringBuilder(res).reverse() + middle + res
}
// Usage example
fun main(args: Array<String?>?) {
val res = maxPalindrome("3213")
System.out.println("323".equals(res))
}
}
| 1 | Java | 0 | 0 | 4566f3145be72827d72cb93abca8bfd93f1c58df | 1,741 | codelibrary | The Unlicense |
src/main/kotlin/com/jacobhyphenated/advent2022/day20/Day20.kt | jacobhyphenated | 573,603,184 | false | {"Kotlin": 144303} | package com.jacobhyphenated.advent2022.day20
import com.jacobhyphenated.advent2022.Day
import kotlin.math.absoluteValue
/**
* Day 20: Grove Positioning System
*
* Decrypt the coordinates using a custom move encryption.
*
* The puzzle input is an array of values that represents a circular list.
* Using the original order, each value moves a number of spaces in the list equal to its value.
* Negative numbers move to the left. Wrap-arounds are possible in either direction.
*/
class Day20: Day<List<Long>> {
override fun getInput(): List<Long> {
return readInputFile("day20").lines().map { it.toLong() }
}
/**
* Move every value in the input list.
* Then find the 1000th, 2000th, and 3000th numbers after the 0.
* return the sum of these numbers.
*/
override fun part1(input: List<Long>): Long {
val nodes = initializeNodeList(input)
doMoveRound(nodes)
return calculateCoordinates(nodes)
}
/**
* Each value is first multiplied by 811589153.
* Then the numbers are mixed 10 times.
* Use the order the numbers originally appeared in for each mixing
*/
override fun part2(input: List<Long>): Long {
val nodes = initializeNodeList(input.map { it * 811589153 })
repeat(10) {
doMoveRound(nodes)
}
return calculateCoordinates(nodes)
}
/**
* Turn our numbers into a circular doubly linked list
*/
private fun initializeNodeList(input: List<Long>): List<Node> {
val nodes = input.mapIndexed { i, value -> Node(value, i)}
val first = nodes.first()
val last = nodes.last()
first.previous = last
last.next = first
first.next = nodes[1]
nodes[1].previous = first
for (i in 1 until nodes.size -1) {
nodes[i].next = nodes[i+1]
nodes[i+1].previous = nodes[i]
}
return nodes
}
/**
* The list of nodes maintains the original order, regardless of the nodes' positions in the linked list.
* Go through each node in order and move its position in the list
*/
private fun doMoveRound(nodes: List<Node>) {
for (i in nodes.indices) {
val current = nodes[i]
val toMove = current.value
// If we move enough times to wrap around the linked list, we don't have to perform every move
// because one node is the moving node, the modulo is the list size - 1
val netMoveAmount = (toMove.absoluteValue % (nodes.size - 1)).toInt()
if (toMove < 0) {
moveLeft(current, netMoveAmount)
} else {
moveRight(current, netMoveAmount)
}
}
}
/**
* Find the position of the value 0 in the circular array
* Form a real array from that starting point.
* Use modulo math to get the 1000th, 2000th, and 3000th values.
*/
private fun calculateCoordinates(nodes: List<Node>): Long {
val zero = nodes.first { it.value == 0L }
var current = zero
val finalArray = mutableListOf(zero.value)
while(current.next.originalIndex != zero.originalIndex) {
finalArray.add(current.next.value)
current = current.next
}
return finalArray[1000 % finalArray.size] + finalArray[2000 % finalArray.size] + finalArray[3000 % finalArray.size]
}
/**
* Move a value in the doubly linked list [amount] positions to the left
*/
private fun moveLeft(startNode: Node, amount: Int) {
repeat(amount) {
val prev = startNode.previous
prev.previous.next = startNode
startNode.previous = prev.previous
startNode.next.previous = prev
prev.next = startNode.next
startNode.next = prev
prev.previous = startNode
}
}
/**
* Move a value in the doubly linked list [amount] positions to the right
*/
private fun moveRight(startNode: Node, amount: Int) {
repeat(amount) {
val next = startNode.next
val rhs = next.next
val lhs = startNode.previous
lhs.next = next
next.previous = lhs
rhs.previous = startNode
startNode.next = rhs
next.next = startNode
startNode.previous = next
}
}
}
class Node (val value: Long, val originalIndex: Int) {
// first time this AoC that I've taken advantage of / abused lateinit
// 10/10 would abuse this language feature again
lateinit var next: Node
lateinit var previous: Node
} | 0 | Kotlin | 0 | 0 | 9f4527ee2655fedf159d91c3d7ff1fac7e9830f7 | 4,671 | advent2022 | The Unlicense |
src/main/kotlin/euclidea/Numeric.kt | jedwidz | 589,137,278 | false | null | package euclidea
import kotlin.math.max
import kotlin.math.min
import kotlin.math.sign
fun solveByBisection(o1: Double, o2: Double, f: (Double) -> Double): Double {
var x1 = min(o1, o2)
var x2 = max(o1, o2)
val so1 = sign(f(x1))
val so2 = sign(f(x2))
if (so1 == 0.0)
return x1
if (so2 == 0.0)
return x2
require(so1 != so2)
while (true) {
val m = (x1 + x2) * 0.5
if (!(x1 < m && m < x2))
return m
val sm = sign(f(m))
if (sm == 0.0)
return m
if (sm == so1)
x1 = m
else
x2 = m
}
}
fun solveByExpansionAndBisection(o: Double, f: (Double) -> Double): Double {
val (o1, o2) = expandRange(o, f)
return solveByBisection(o1, o2, f)
}
fun expandRange(o: Double, f: (Double) -> Double): Pair<Double, Double> {
var d = Epsilon
while (true) {
val x1 = o - d
val x2 = o + d
val so1 = sign(f(x1))
val so2 = sign(f(x2))
if (so1 == 0.0)
return x1 to x1
if (so2 == 0.0)
return x2 to x2
if (so1 != so2)
return x1 to x2
d *= 2
if (d.isInfinite())
error("Failed to bracket solution, sign is asymptotically $so1")
}
}
| 0 | Kotlin | 0 | 1 | 70f7a397bd6abd0dc0d6c295ba9625e6135b2167 | 1,288 | euclidea-solver | MIT License |
src/chapter3/section1/ex4.kt | w1374720640 | 265,536,015 | false | {"Kotlin": 1373556} | package chapter3.section1
import extensions.shuffle
import java.util.*
/**
* 开发抽象数据类型Time和Event来处理表3.1.5中的例子中的数据
*
* 解:自定义可以比较的Time类,Event类直接用String类代替
*/
fun main() {
val inputArray = arrayOf(
Time("09:00:00") to "Chicago",
Time("09:00:03") to "Phoenix",
Time("09:00:13") to "Houston",
Time("09:00:59") to "Chicago",
Time("09:01:10") to "Houston",
Time("09:03:13") to "Chicago",
Time("09:10:11") to "Seattle",
Time("09:10:25") to "Seattle",
Time("09:14:25") to "Phoenix",
Time("09:19:32") to "Chicago",
Time("09:19:46") to "Chicago",
Time("09:21:05") to "Chicago",
Time("09:22:43") to "Seattle",
Time("09:22:54") to "Seattle",
Time("09:25:52") to "Chicago",
Time("09:35:21") to "Chicago",
Time("09:36:14") to "Seattle",
Time("09:37:44") to "Phoenix"
)
inputArray.shuffle()
val orderedST = BinarySearchST<Time, String>()
inputArray.forEach {
orderedST.put(it.first, it.second)
}
check(orderedST.min().time == "09:00:00")
check(orderedST.get(Time("09:00:13")) == "Houston")
check(orderedST.floor(Time("09:05:00")).time == "09:03:13")
check(orderedST.select(7).time == "09:10:25")
val keys = orderedST.keys(Time("09:15:00"), Time("09:25:00"))
var index = 0
keys.forEach {
when (index) {
0 -> check(it.time == "09:19:32")
1 -> check(it.time == "09:19:46")
2 -> check(it.time == "09:21:05")
3 -> check(it.time == "09:22:43")
4 -> check(it.time == "09:22:54")
else -> throw IllegalStateException()
}
index++
}
check(orderedST.ceiling(Time("09:30:00")).time == "09:35:21")
check(orderedST.max().time == "09:37:44")
check(orderedST.size(Time("09:15:00"), Time("09:25:00")) == 5)
check(orderedST.rank(Time("09:10:25")) == 7)
println("Check succeed.")
}
class Time(val time: String) : Comparable<Time> {
var timeList = time.split(":")
init {
require(timeList.size == 3)
for (i in timeList.indices) {
require(timeList[i].length == 2)
}
}
override fun compareTo(other: Time): Int {
for (i in timeList.indices) {
val compare = timeList[i].compareTo(other.timeList[i])
if (compare != 0) {
return compare
}
}
return 0
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this === other) return true
if (other !is Time) return false
return this.compareTo(other) == 0
}
override fun hashCode(): Int {
return Arrays.hashCode(timeList.toTypedArray())
}
} | 0 | Kotlin | 1 | 6 | 879885b82ef51d58efe578c9391f04bc54c2531d | 2,940 | Algorithms-4th-Edition-in-Kotlin | MIT License |
src/main/kotlin/g1101_1200/s1187_make_array_strictly_increasing/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1101_1200.s1187_make_array_strictly_increasing
// #Hard #Array #Dynamic_Programming #Binary_Search
// #2023_05_25_Time_308_ms_(100.00%)_Space_41.1_MB_(100.00%)
class Solution {
fun makeArrayIncreasing(arr1: IntArray, arr2: IntArray): Int {
arr2.sort()
var start = 0
for (i in arr2.indices) {
if (arr2[i] != arr2[start]) {
arr2[++start] = arr2[i]
}
}
val l2 = start + 1
val dp = IntArray(l2 + 2)
for (i in arr1.indices) {
var noChange = dp[dp.size - 1]
if (i > 0 && arr1[i - 1] >= arr1[i]) {
noChange = -1
}
for (j in dp.size - 2 downTo 1) {
if (arr2[j - 1] < arr1[i] && dp[j] != -1) {
noChange = if (noChange == -1) dp[j] else Math.min(noChange, dp[j])
}
if (dp[j - 1] != -1) {
dp[j] = 1 + dp[j - 1]
} else {
dp[j] = -1
}
if (i > 0 && arr1[i - 1] < arr2[j - 1] && dp[dp.size - 1] >= 0) {
dp[j] = if (dp[j] == -1) dp[dp.size - 1] + 1 else Math.min(dp[j], dp[dp.size - 1] + 1)
}
}
dp[0] = -1
dp[dp.size - 1] = noChange
}
var res = -1
for (num in dp) {
if (num != -1) {
res = if (res == -1) num else Math.min(res, num)
}
}
return res
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,522 | LeetCode-in-Kotlin | MIT License |
src/aoc22/Day10.kt | mihassan | 575,356,150 | false | {"Kotlin": 123343} | @file:Suppress("PackageDirectoryMismatch")
package aoc22.day10
import lib.Solution
sealed interface Instruction {
object Noop : Instruction
data class AddX(val value: Int) : Instruction
companion object {
fun parse(line: String): Instruction = when {
line.startsWith("noop") -> Noop
line.startsWith("addx") -> {
val value = line.substringAfter(" ").toInt()
AddX(value)
}
else -> error("Invalid input")
}
}
}
typealias Signal = Int
typealias Cycle = Int
typealias SignalTimeSeries = MutableMap<Cycle, Signal>
data class CPU(
private var signal: Int = 1,
private var cycle: Int = 1,
private var signalTimeSeries: SignalTimeSeries = mutableMapOf(),
) {
private fun tick() {
signalTimeSeries[cycle] = signal
cycle += 1
}
private fun runSingleInstruction(instruction: Instruction) {
when(instruction) {
Instruction.Noop -> tick()
is Instruction.AddX -> {
tick()
tick()
signal += instruction.value
}
}
}
fun runInstructions(instructions: List<Instruction>) =
instructions.forEach { runSingleInstruction(it) }
fun getSignalAtCycle(cycle: Cycle): Signal =
signalTimeSeries[cycle] ?: signal
}
typealias Input = List<Instruction>
typealias Output = String
private val solution = object : Solution<Input, Output>(2022, "Day10") {
override fun parse(input: String): Input = input.lines().map { Instruction.parse(it) }
override fun format(output: Output): String = output
override fun part1(input: Input): Output {
val cpu = CPU()
cpu.runInstructions(input)
return (20..220 step 40)
.sumOf { it * cpu.getSignalAtCycle(it) }
.toString()
}
override fun part2(input: Input): Output {
val cpu = CPU()
cpu.runInstructions(input)
return (1..240).map {
val register = cpu.getSignalAtCycle(it)
val column = (it - 1) % 40
if (register in (column - 1)..(column + 1)) '█' else ' '
}
.joinToString("")
.chunked(40)
.joinToString("\n", prefix = "\n")
}
}
fun main() = solution.run()
| 0 | Kotlin | 0 | 0 | 698316da8c38311366ee6990dd5b3e68b486b62d | 2,105 | aoc-kotlin | Apache License 2.0 |
kotlin/src/com/s13g/aoc/aoc2023/Day16.kt | shaeberling | 50,704,971 | false | {"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245} | package com.s13g.aoc.aoc2023
import com.s13g.aoc.Result
import com.s13g.aoc.Solver
import com.s13g.aoc.XY
import com.s13g.aoc.add
import com.s13g.aoc.resultFrom
import kotlin.math.max
/**
* --- Day 16: The Floor Will Be Lava ---
* https://adventofcode.com/2023/day/16
*/
class Day16 : Solver {
override fun solve(lines: List<String>): Result {
val grid = Grid(lines)
grid.project(XY(-1, 0), Dir.E)
return resultFrom(grid.visited.size, getMaxValue(lines))
}
private fun getMaxValue(lines: List<String>): Int {
var maxV = 0
for (x in lines[0].indices) {
val g1 = Grid(lines)
g1.project(XY(x, -1), Dir.S)
maxV = max(maxV, g1.visited.size)
val g2 = Grid(lines)
g2.project(XY(x, g2.h), Dir.N)
maxV = max(maxV, g2.visited.size)
}
for (y in lines.indices) {
val g1 = Grid(lines)
g1.project(XY(-1, y), Dir.E)
maxV = max(maxV, g1.visited.size)
val g2 = Grid(lines)
g2.project(XY(g2.w, y), Dir.W)
maxV = max(maxV, g2.visited.size)
}
return maxV
}
private fun Grid(data: List<String>) = Grid(data, data[0].length, data.size)
private data class Grid(
val data: List<String>,
val w: Int,
val h: Int
) {
val visited = mutableSetOf<XY>()
val done = mutableSetOf<Pair<XY, Dir>>()
}
private fun Grid.project(xy: XY, dir: Dir) {
var pos = xy.add(dir.d)
if (pos.x < 0 || pos.x >= w || pos.y < 0 || pos.y >= h) return
val key = Pair(pos, dir)
if (key in done) return
done.add(key)
while (at(pos) == '.') {
visited.add(pos)
pos = pos.add(dir.d)
if (pos.x < 0 || pos.x >= w || pos.y < 0 || pos.y >= h) return
}
visited.add(pos)
// Continue without change.
if (dir in setOf(Dir.W, Dir.E) && at(pos) == '-') project(pos, dir)
if (dir in setOf(Dir.N, Dir.S) && at(pos) == '|') project(pos, dir)
// Split out.
if (dir in setOf(Dir.W, Dir.E) && at(pos) == '|') {
project(pos, Dir.N)
project(pos, Dir.S)
} else if (dir in setOf(Dir.N, Dir.S) && at(pos) == '-') {
project(pos, Dir.W)
project(pos, Dir.E)
}
// Deflect.
if (at(pos) == '\\') {
when (dir) {
Dir.N -> project(pos, Dir.W)
Dir.E -> project(pos, Dir.S)
Dir.S -> project(pos, Dir.E)
Dir.W -> project(pos, Dir.N)
}
} else if (at(pos) == '/') {
when (dir) {
Dir.N -> project(pos, Dir.E)
Dir.E -> project(pos, Dir.N)
Dir.S -> project(pos, Dir.W)
Dir.W -> project(pos, Dir.S)
}
}
}
private fun Grid.at(xy: XY) = data[xy.y][xy.x]
private enum class Dir(val d: XY) {
N(XY(0, -1)),
E(XY(1, 0)),
S(XY(0, 1)),
W(XY(-1, 0))
}
}
| 0 | Kotlin | 1 | 2 | 7e5806f288e87d26cd22eca44e5c695faf62a0d7 | 2,740 | euler | Apache License 2.0 |
src/Day16.kt | palex65 | 572,937,600 | false | {"Kotlin": 68582} | @file:Suppress("PackageDirectoryMismatch")
package day16
import readInput
import java.util.PriorityQueue
import kotlin.math.*
const val INT = """(\d+)"""
const val NAME = """([A-Z]+)"""
const val REST = """([A-Z, ]+)"""
val valvePattern = Regex("""Valve $NAME has flow rate=$INT; tunnels? leads? to valves? $REST$""")
data class Valve(val name: String, val rate: Int, val to: List<String>) : Comparable<Valve>{
override fun hashCode() = name.hashCode()
override fun compareTo(other: Valve) = compareValuesBy(this,other) { it.name }
private var tunnels: List<Valve> = emptyList()
var tunnelsToRated: Map<Valve,Int> = emptyMap()
fun buildTunnels(valves: Map<String,Valve>) { tunnels = to.map { name -> checkNotNull(valves[name]) } }
fun buildRatedTunnels() {
fun build(from: Valve, dist: Int, visited: Set<Valve>, to: MutableMap<Valve,Int>): Map<Valve,Int> {
val rated = from.tunnels
.filter { it !in visited }
rated.filter { it.rate > 0 }
.forEach { to[it] = minOf(dist+1, to[it] ?: Int.MAX_VALUE) }
rated.forEach { build(it, dist+1, visited+from, to) }
return to
}
tunnelsToRated = build(this, 0, emptySet(), mutableMapOf())
}
}
fun Valve(line: String): Valve {
val (n, r, t) = (valvePattern.find(line) ?: error("invalid valve \"$line\"")).destructured
return Valve(n, r.toInt(), t.split(", "))
}
typealias Valves = Map<String,Valve>
fun Valves(lines: List<String>): Valves {
val valves = lines.map { Valve(it) }.associateBy { it.name }
valves.values.forEach { it.buildTunnels(valves) }
valves.values.forEach { it.buildRatedTunnels() }
return valves
}
val Valves.rated get() = values.filter { it.rate > 0 }.sortedBy { -it.rate }
data class State(
val time: Int, // Remaining time
val curr: Valve,
val opened: List<Valve> = emptyList(),
val closed: List<Valve>,
val pressure: Int = 0,
val timeElephant: Int = 0, // Part2
val currElephant: Valve = curr, // Part2
) : Comparable<State> {
private val totalPressure: Int = pressure + estimateClosed()
override fun compareTo(other: State) = compareValuesBy(other,this){ it.totalPressure }
private fun estimateClosed(): Int {
var valve = curr
var tm = time
var press = 0
closed.forEach { v ->
tm -= valve.tunnelsToRated[v]!! + 1
press += v.rate * tm
valve = v
}
return press
}
override fun toString() = "State($time,${curr.name},opened=${opened.map { it.name }},closed=${closed.map { it.name }},$pressure,$totalPressure)"
}
fun part1(valves: Valves): Int {
val open = PriorityQueue<State>()
open.add(State(30, valves["AA"]!!, closed = valves.rated ))
var best = 0
val visited: MutableMap<List<Valve>, Int> = mutableMapOf()
while (open.isNotEmpty()) {
val state = open.remove()
best = max(best, state.pressure)
val vis = visited[state.opened]
if (vis!=null && vis > state.pressure) continue
visited[state.opened] = state.pressure
for ((next, dist) in state.curr.tunnelsToRated) {
val newTime = state.time-dist-1
if (newTime >= 0 && next !in state.opened)
open.add(State(newTime, next, (state.opened + next).sorted(), state.closed-next, state.pressure + next.rate * newTime))
}
}
return best
}
fun part2(valves: Valves): Int {
val init = valves["AA"]!!
val open = PriorityQueue<State>()
open.add(State(26, init, emptyList(), valves.rated, 0, 26, init))
var best = 0
val visited: MutableMap<List<Valve>, Int> = mutableMapOf()
while (open.isNotEmpty()) {
val state = open.remove()
best = max(best, state.pressure)
val vis = visited[state.opened]
if (vis!=null && vis > state.pressure) continue
visited[state.opened] = state.pressure
var time = state.time
var curr = state.curr
var timeE = state.timeElephant
var currE = state.currElephant
if (time < timeE) {
time = timeE.also { timeE = time }
curr = currE.also { currE = curr }
}
for ((next, dist) in curr.tunnelsToRated) {
val newTime = time-dist-1
if (newTime >= 0 && next !in state.opened)
open.add(State(newTime, next, (state.opened + next).sorted(), state.closed-next, state.pressure + next.rate * newTime, timeE, currE))
}
}
return best
}
fun main() {
val testValves = Valves(readInput("Day16_test"))
check(part1(testValves) == 1651)
check(part2(testValves) == 1707)
val valves = Valves(readInput("Day16"))
println(part1(valves)) // 1789
println(part2(valves)) // 2496
}
| 0 | Kotlin | 0 | 2 | 35771fa36a8be9862f050496dba9ae89bea427c5 | 4,832 | aoc2022 | Apache License 2.0 |
src/main/kotlin/nl/dirkgroot/adventofcode/year2020/Day12.kt | dirkgroot | 317,968,017 | false | {"Kotlin": 187862} | package nl.dirkgroot.adventofcode.year2020
import nl.dirkgroot.adventofcode.util.Input
import nl.dirkgroot.adventofcode.util.Puzzle
import java.lang.IllegalStateException
import kotlin.math.abs
class Day12(input: Input) : Puzzle() {
private val instructions by lazy { input.lines().map { it[0] to it.substring(1).toInt() } }
class State(val waypoint: Pair<Int, Int>, val ship: Pair<Int, Int> = 0 to 0) {
val manhattanDistance = abs(ship.first) + abs(ship.second)
}
override fun part1() = followInstructions(State(waypoint = 1 to 0), ::moveShip).manhattanDistance
override fun part2() = followInstructions(State(waypoint = 10 to 1), ::moveWaypoint).manhattanDistance
private fun followInstructions(initialState: State, moveCommand: (State, Char, Int) -> State) =
instructions.fold(initialState) { state, (action, value) ->
val (waypointX, waypointY) = state.waypoint
val (shipX, shipY) = state.ship
when (action) {
'F' -> State(state.waypoint, shipX + waypointX * value to shipY + waypointY * value)
'R' -> State(rotate(waypointX, waypointY, value), state.ship)
'L' -> State(rotate(waypointX, waypointY, -value), state.ship)
else -> moveCommand(state, action, value)
}
}
private fun moveShip(state: State, direction: Char, value: Int) =
state.ship.let { (x, y) -> State(state.waypoint, move(x, y, direction, value)) }
private fun moveWaypoint(state: State, direction: Char, value: Int) =
state.waypoint.let { (x, y) -> State(move(x, y, direction, value), state.ship) }
private fun move(x: Int, y: Int, direction: Char, value: Int) =
when (direction) {
'N' -> x to y + value
'E' -> x + value to y
'S' -> x to y - value
'W' -> x - value to y
else -> throw IllegalStateException("Invalid direction: ($direction, $value)")
}
private tailrec fun rotate(dirX: Int, dirY: Int, degrees: Int): Pair<Int, Int> =
if (degrees % 360 == 0) dirX to dirY
else rotate(dirY, -dirX, degrees - 90)
} | 1 | Kotlin | 1 | 1 | ffdffedc8659aa3deea3216d6a9a1fd4e02ec128 | 2,172 | adventofcode-kotlin | MIT License |
src/main/kotlin/io/nozemi/aoc/solutions/year2020/day02/PasswordPhilosophy.kt | Nozemi | 433,882,587 | false | {"Kotlin": 92614, "Shell": 421} | package io.nozemi.aoc.solutions.year2020.day02
import io.nozemi.aoc.puzzle.Puzzle
import io.nozemi.aoc.utils.countChar
import java.util.regex.Pattern
import kotlin.reflect.KFunction0
class PasswordPhilosophy(input: String) : Puzzle<List<String>>(input) {
override fun Sequence<String>.parse(): List<String> = this.toList()
override fun solutions(): List<KFunction0<Any>> = listOf(
::part1,
::part2
)
private fun part1(): Int {
return countValidPart1()
}
private fun part2(): Int {
return countValidPart2()
}
fun countValidPart1(): Int {
var validPasswords = 0
parsedInput.forEach {
val passwordAndPolicy = it.parsePasswordAndPolicy()
if (passwordAndPolicy != null) {
val charOccurrences = passwordAndPolicy.password.countChar(passwordAndPolicy.character)
if (charOccurrences >= passwordAndPolicy.minimum && charOccurrences <= passwordAndPolicy.maximum) validPasswords++
}
}
return validPasswords
}
fun countValidPart2(): Int {
var validPasswords = 0
parsedInput.forEach {
var passwordAndPolicy = it.parsePasswordAndPolicy()
if (passwordAndPolicy != null) {
val char1 = passwordAndPolicy.password[passwordAndPolicy.minimum - 1]
val char2 = passwordAndPolicy.password[passwordAndPolicy.maximum - 1]
if((char1 == passwordAndPolicy.character) xor (char2 == passwordAndPolicy.character)) validPasswords++
}
}
return validPasswords
}
data class PasswordAndPolicy(
val minimum: Int,
val maximum: Int,
val character: Char,
val password: String
)
}
fun String.parsePasswordAndPolicy(): PasswordPhilosophy.PasswordAndPolicy? {
val pattern = Pattern.compile("(\\d*)-(\\d*) (\\w): (.*)")
val matcher = pattern.matcher(this)
if (!matcher.matches()) {
return null
}
return PasswordPhilosophy.PasswordAndPolicy(
minimum = matcher.group(1).toInt(),
maximum = matcher.group(2).toInt(),
character = matcher.group(3).toCharArray()[0],
password = matcher.group(4)
)
} | 0 | Kotlin | 0 | 0 | fc7994829e4329e9a726154ffc19e5c0135f5442 | 2,261 | advent-of-code | MIT License |
src/main/kotlin/sschr15/aocsolutions/util/Algo.kt | sschr15 | 317,887,086 | false | {"Kotlin": 184127, "TeX": 2614, "Python": 446} | package sschr15.aocsolutions.util
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap
import sschr15.aocsolutions.util.watched.WatchedLong
import java.math.BigInteger
import java.util.*
import kotlin.math.absoluteValue
typealias BigPoint = Pair<WatchedLong, WatchedLong>
typealias BiggerPoint = Pair<BigInteger, BigInteger>
fun <T> dijkstra(
start: T,
getNeighbors: (T) -> List<T>,
getCost: (T) -> Int,
): Map<T, Int> {
data class Node(val value: T, val cost: Int)
val visited = mutableSetOf<T>()
val costs = Object2IntOpenHashMap<T>()
val queue = PriorityQueue<Node>(compareBy { it.cost })
queue.add(Node(start, 0))
costs.put(start, 0)
while (queue.isNotEmpty()) {
val (current, currentCost) = queue.poll()
if (current in visited) continue
visited.add(current)
for (neighbor in getNeighbors(current)) {
val newCost = currentCost + getCost(neighbor)
if (newCost < costs.getOrDefault(neighbor as Any, Int.MAX_VALUE)) {
costs.put(neighbor, newCost)
queue.add(Node(neighbor, newCost))
}
}
}
return costs
}
fun shoelace(points: List<Point>): Int {
var sum = 0
for (i in points.indices) {
if (i == points.lastIndex) break
sum += points[i].x * points[i + 1].y
sum -= points[i].y * points[i + 1].x
}
sum += points.last().x * points.first().y
sum -= points.last().y * points.first().x
return sum.absoluteValue
}
@JvmName("shoelaceBig")
fun shoelace(points: List<BigPoint>): WatchedLong {
var sum = WatchedLong(0)
for (i in points.indices) {
if (i == points.lastIndex) break
sum += points[i].first * points[i + 1].second
sum -= points[i].second * points[i + 1].first
}
sum += points.last().first * points.first().second
sum -= points.last().second * points.first().first
return if (sum < 0) sum * -1 else sum
}
@JvmName("shoelaceOhNoItIsCatastrophicallyLarge")
fun shoelace(points: List<BiggerPoint>): BigInteger {
var sum = BigInteger.ZERO
for (i in points.indices) {
if (i == points.lastIndex) break
sum += points[i].first * points[i + 1].second
sum -= points[i].second * points[i + 1].first
}
sum += points.last().first * points.first().second
sum -= points.last().second * points.first().first
return sum.abs() / 2.toBigInteger()
}
| 0 | Kotlin | 0 | 0 | e483b02037ae5f025fc34367cb477fabe54a6578 | 2,444 | advent-of-code | MIT License |
src/main/kotlin/biz/koziolek/adventofcode/year2022/day09/day9.kt | pkoziol | 434,913,366 | false | {"Kotlin": 715025, "Shell": 1892} | package biz.koziolek.adventofcode.year2022.day09
import biz.koziolek.adventofcode.Coord
import biz.koziolek.adventofcode.findInput
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
import kotlin.math.sign
fun main() {
val inputFile = findInput(object {})
val moves = parseMoves(inputFile.bufferedReader().readLines())
val rope = PlanckRope()
val allMovedRopes = moveRopeInSteps(rope, moves)
println("Positions visited by tail at least once: ${countPositionsVisitedByTail(allMovedRopes)}")
val longRope = LongRope.ofLength(10)
val allMovedLongRopes = moveRopeInSteps(longRope, moves)
println("Positions visited by tail at least once: ${countPositionsVisitedByTail(allMovedLongRopes)}")
}
interface Rope {
val head: Coord
val tail: Coord
fun move(move: Move): Rope
fun getSymbol(coord: Coord): Char?
}
data class PlanckRope(
override val head: Coord = Coord(0, 0),
override val tail: Coord = Coord(0, 0),
) : Rope {
override fun move(move: Move): PlanckRope {
val newHead = Coord(
x = head.x + move.dx,
y = head.y + move.dy,
)
val tailDistanceX = newHead.x - tail.x
val tailDistanceY = newHead.y - tail.y
var tailMoveX = 0
var tailMoveY = 0
if (abs(tailDistanceX) > 1) {
tailMoveX = tailDistanceX.sign
if (tail.y != newHead.y) {
tailMoveY = tailDistanceY.sign
}
} else if (abs(tailDistanceY) > 1) {
tailMoveY = tailDistanceY.sign
if (tail.x != newHead.x) {
tailMoveX = tailDistanceX.sign
}
}
val newTail = Coord(
x = tail.x + tailMoveX,
y = tail.y + tailMoveY,
)
return PlanckRope(
head = newHead,
tail = newTail,
)
}
override fun getSymbol(coord: Coord): Char? =
when (coord) {
head -> 'H'
tail -> 'T'
else -> null
}
}
data class LongRope(
val planckRopes: List<PlanckRope>
) : Rope {
companion object {
fun ofLength(length: Int) =
LongRope(List(length - 1) { PlanckRope() })
}
override val head: Coord
get() = planckRopes.first().head
override val tail: Coord
get() = planckRopes.last().tail
override fun move(move: Move): Rope {
val movedPlanckRopes = mutableListOf<PlanckRope>()
var nextMove: Move? = move
for (rope in planckRopes) {
val movedRope = if (nextMove != null) {
rope.move(nextMove)
} else {
rope
}
nextMove = if (movedRope.tail == rope.tail) {
null
} else {
val tailDistanceX = movedRope.tail.x - rope.tail.x
val tailDistanceY = movedRope.tail.y - rope.tail.y
Move.values()
.find { it.dx == tailDistanceX && it.dy == tailDistanceY }
?: throw IllegalStateException("Unexpected tail distance: $tailDistanceX,$tailDistanceY}")
}
movedPlanckRopes.add(movedRope)
}
return LongRope(movedPlanckRopes)
}
private val symbols = ('1'..'9') + ('a'..'z')
override fun getSymbol(coord: Coord): Char? =
if (coord == planckRopes.first().head) {
'H'
} else {
planckRopes.withIndex()
.find { (_, planckRope) -> coord == planckRope.tail }
?.let { (index, _) -> symbols[index] }
}
}
enum class Move(val dx: Int, val dy: Int) {
UP(0, 1),
DOWN(0, -1),
LEFT(-1, 0),
RIGHT(1, 0),
UP_LEFT(-1, 1),
UP_RIGHT(1, 1),
DOWN_LEFT(-1, -1),
DOWN_RIGHT(1, -1),
}
fun <T : Rope> moveRopeInSteps(rope: T, moves: List<Move>): List<T> =
moves.fold(listOf(rope)) { ropes, move ->
@Suppress("UNCHECKED_CAST")
ropes + ropes.last().move(move) as T
}
fun visualizeRope(rope: Rope, corners: Pair<Coord, Coord>, markStart: Boolean = false): String {
val minX = min(corners.first.x, corners.second.x)
val maxX = max(corners.first.x, corners.second.x)
val minY = min(corners.first.y, corners.second.y)
val maxY = max(corners.first.y, corners.second.y)
return buildString {
for (y in maxY downTo minY) {
for (x in minX..maxX) {
val coord = Coord(x, y)
val symbol = rope.getSymbol(coord)
if (symbol != null) {
append(symbol)
} else if (markStart && x == 0 && y == 0) {
append('s')
} else {
append('.')
}
}
if (y > minY) {
append('\n')
}
}
}
}
fun parseMoves(lines: Iterable<String>): List<Move> =
lines.flatMap { line ->
val (dir, count) = line.split(' ')
val move = when (dir) {
"U" -> Move.UP
"D" -> Move.DOWN
"L" -> Move.LEFT
"R" -> Move.RIGHT
else -> throw IllegalArgumentException("Unknown direction: '$dir'")
}
List(count.toInt()) { move }
}
fun countPositionsVisitedByTail(ropes: List<Rope>): Int =
ropes.map { it.tail }.distinct().count()
| 0 | Kotlin | 0 | 0 | 1b1c6971bf45b89fd76bbcc503444d0d86617e95 | 5,400 | advent-of-code | MIT License |
src/main/kotlin/days_2020/Day10.kt | BasKiers | 434,124,805 | false | {"Kotlin": 40804} | package days_2020
import util.Day
class Day10 : Day(10, 2020) {
val input = inputList.map(String::toInt).let { list -> list + 0 + (list.maxOf { it } + 3) }.sorted()
override fun partOne(): Any {
val groups = input.zipWithNext().groupBy { (a, b) -> b - a }
return groups[1]!!.size * (groups[3]!!.size)
}
fun getPossiblePermutations(
hops: List<Pair<Int, Int>>,
knownResults: MutableMap<String, Long> = mutableMapOf()
): Long {
val optionalHop = hops.withIndex().find { (_, value) -> value.first + value.second <= 3 }?.index
if (optionalHop == null) {
return 1
}
val cachedRes = knownResults[hops.toString()];
if (cachedRes != null) {
return cachedRes
}
val lVal = listOf(hops[optionalHop + 1].let { (_, b) -> hops[optionalHop].toList().sum() to b }) + hops.drop(
optionalHop + 2
)
val rVal = listOf(hops[optionalHop + 1]) + hops.drop(
optionalHop + 2
)
val lRes = getPossiblePermutations(lVal, knownResults);
knownResults[lVal.toString()] = lRes;
val rRes = getPossiblePermutations(rVal, knownResults);
knownResults[rVal.toString()] = rRes;
return lRes + rRes;
}
override fun partTwo(): Any {
return getPossiblePermutations(input.zipWithNext().map { (a, b) -> b - a }.zipWithNext())
}
} | 0 | Kotlin | 0 | 0 | 870715c172f595b731ee6de275687c2d77caf2f3 | 1,433 | advent-of-code-2021 | Creative Commons Zero v1.0 Universal |
src/main/kotlin/g2401_2500/s2421_number_of_good_paths/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2401_2500.s2421_number_of_good_paths
// #Hard #Array #Tree #Graph #Union_Find #2023_07_04_Time_909_ms_(100.00%)_Space_65.8_MB_(100.00%)
class Solution {
fun numberOfGoodPaths(vals: IntArray, edges: Array<IntArray>): Int {
val n = vals.size
val parent = IntArray(n)
val maxElement = IntArray(n)
val count = IntArray(n)
for (i in 0 until n) {
parent[i] = i
maxElement[i] = vals[i]
count[i] = 1
}
edges.sortWith(compareBy { a: IntArray -> vals[a[0]].coerceAtLeast(vals[a[1]]) })
var ans = n
for (it in edges) {
val a = findParent(parent, it[0])
val b = findParent(parent, it[1])
if (maxElement[a] != maxElement[b]) {
if (maxElement[a] > maxElement[b]) {
parent[b] = a
} else {
parent[a] = b
}
} else {
parent[b] = a
ans += count[a] * count[b]
count[a] += count[b]
}
}
return ans
}
private fun findParent(parent: IntArray, a: Int): Int {
if (a == parent[a]) {
return a
}
parent[a] = findParent(parent, parent[a])
return parent[a]
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,322 | LeetCode-in-Kotlin | MIT License |
advent/src/test/kotlin/org/elwaxoro/advent/y2021/Dec20.kt | elwaxoro | 328,044,882 | false | {"Kotlin": 376774} | package org.elwaxoro.advent.y2021
import org.elwaxoro.advent.Coord
import org.elwaxoro.advent.PuzzleDayTester
import org.elwaxoro.advent.bounds
/**
* Trench Map
*/
class Dec20 : PuzzleDayTester(20, 2021) {
override fun part1(): Any = glowUpLikeALot(2).size
override fun part2(): Any = glowUpLikeALot(50).size
/**
* OOB coords swap from all '.' to all '#' every other iteration
* Track only the lit coords from round to round
*/
private fun glowUpLikeALot(reps: Int): Set<Coord> = parse().let { (algorithm, litCoords) ->
(0 until reps).fold(litCoords) { acc, i ->
glowUp(algorithm, acc, isOobLit = i % 2 != 0)
}
}
/**
* Grow the bounds by 1 in every direction to consider new coords that might be touching the currently lit ones
* Use isOobLit to decide if coords outside the (non-expanded) bounds are lit or not
*/
private fun glowUp(algorithm: String, litCoords: Set<Coord>, isOobLit: Boolean): Set<Coord> =
litCoords.bounds().let { (min, max) ->
(min.y - 1..max.y + 1).map { y ->
(min.x - 1..max.x + 1).mapNotNull { x ->
Coord(x, y).takeIf { algorithm[it.calcNumber(min to max, litCoords, isOobLit)] == '#'}
}
}.flatten().toSet()
}
private fun Coord.calcNumber(bounds: Pair<Coord, Coord>, litCoords: Set<Coord>, isOobLit: Boolean): Int =
neighbors9().flatten().joinToString("") { neighbor ->
"1".takeIf { litCoords.contains(neighbor) || (isOobLit && bounds.isOob(neighbor)) } ?: "0"
}.toInt(2)
private fun Pair<Coord, Coord>.isOob(c: Coord): Boolean = c.x < first.x || c.x > second.x || c.y < first.y || c.y > second.y
private fun parse(): Pair<String, Set<Coord>> = load(delimiter = "\n\n").let { (algorithm, image) ->
algorithm.replace("\n", "") to
image.split("\n").flatMapIndexed { y, row ->
row.mapIndexedNotNull { x, c ->
Coord(x, y).takeIf { c == '#' }
}
}.toSet()
}
}
| 0 | Kotlin | 4 | 0 | 1718f2d675f637b97c54631cb869165167bc713c | 2,094 | advent-of-code | MIT License |
advent-of-code-2021/src/code/day10/Main.kt | Conor-Moran | 288,265,415 | false | {"Kotlin": 53347, "Java": 14161, "JavaScript": 10111, "Python": 6625, "HTML": 733} | package code.day10
import java.io.File
import java.util.*
fun main() {
doIt("Day 10 Part 1: Test Input", "src/code/day10/test.input", part1)
doIt("Day 10 Part 1: Real Input", "src/code/day10/part1.input", part1)
doIt("Day 10 Part 2: Test Input", "src/code/day10/test.input", part2);
doIt("Day 10 Part 2: Real Input", "src/code/day10/part1.input", part2);
}
fun doIt(msg: String, input: String, calc: (nums: List<String>) -> Long) {
val lines = arrayListOf<String>()
File(input).forEachLine { lines.add(it) }
println(String.format("%s: Ans: %d", msg , calc(lines)))
}
val part1: (List<String>) -> Long = { lines ->
val illegalChars = mutableListOf<Char>()
for(line in lines) {
illegalChars.addAll(doCheck(line))
}
var count = 0
illegalChars.forEach() { c ->
count += when(c) {
')' -> 3
']' -> 57
'}' -> 1197
else -> 25137
}
}
count.toLong()
}
val part2: (List<String>) -> Long = { lines ->
val completionChars = mutableListOf<List<Char>>()
for(line in lines) {
if (doCheck(line).size == 0) {
completionChars.add(doComplete(line))
}
}
var counts = mutableListOf<Long>()
completionChars.forEach() { completionChars ->
counts.add(completionScore(completionChars))
}
counts.sort()
counts[counts.size / 2]
}
fun completionScore(completionChars: List<Char>): Long {
var count: Long = 0
completionChars.forEach() { c ->
count *= 5
count += when (c) {
')' -> 1
']' -> 2
'}' -> 3
else -> 4
}
}
return count
}
fun doCheck(line: String): MutableList<Char> {
val charStack = Stack<Char>()
val illegalChars = mutableListOf<Char>()
for (i in 0 until line.length) {
val char = line[i]
if (isOpen(char)) {
charStack.push(char)
} else {
val prevChar = charStack.pop()
if (!isMatch(char, prevChar)) {
val expected = matchForOp(prevChar)
//println("$line: invalid char $char at $i - expected $expected")
illegalChars.add(char)
break
}
}
}
return illegalChars
}
fun doComplete(line: String): MutableList<Char> {
val charStack = Stack<Char>()
val completionChars = mutableListOf<Char>()
for (i in 0 until line.length) {
val char = line[i]
if (isOpen(char)) {
charStack.push(char)
} else {
charStack.pop()
}
}
while(charStack.isNotEmpty()) {
completionChars.add(matchForOp(charStack.pop()))
}
return completionChars
}
fun isOpen(char: Char): Boolean {
val openChars = setOf('(', '{', '<', '[')
return openChars.contains(char)
}
fun isClose(char: Char): Boolean {
val closeChars = setOf(')', '}', '>', ']')
return closeChars.contains(char)
}
fun matchForOp(openingChar: Char): Char{
val validMatch = mutableMapOf<Char, Char>('(' to ')', '{' to '}', '<' to '>', '[' to ']')
return validMatch[openingChar]!!
}
fun matchForCl(closingChar: Char): Char{
val validMatch = mutableMapOf<Char, Char>(')' to '(', '}' to '{', '>' to '<', ']' to '[')
return validMatch[closingChar]!!
}
fun isMatch(closingChar: Char, openingChar: Char): Boolean {
return matchForCl(closingChar) == openingChar
}
| 0 | Kotlin | 0 | 0 | ec8bcc6257a171afb2ff3a732704b3e7768483be | 3,457 | misc-dev | MIT License |
src/chapter4/section2/ex23_StrongComponent.kt | w1374720640 | 265,536,015 | false | {"Kotlin": 1373556} | package chapter4.section2
import edu.princeton.cs.algs4.Bag
import edu.princeton.cs.algs4.Queue
/**
* 强连通分量
* 设计一种线性时间的算法来计算给定顶点v所在的强连通分量。
* 在这个算法的基础上设计一种平方时间的算法来计算有向图的所有强连通分量。
*
* 解:遍历所有顶点,标记可以从顶点v到达的所有顶点
* 获取有向图的反向图GR,遍历所有顶点,标记可以从顶点v到达的所有顶点
* 在两张图中同时被标记为可达的顶点在顶点v的强连通分量中
*/
class StrongComponentSingleVertex(digraph: Digraph, v: Int) {
private val connected = BooleanArray(digraph.V)
private var count = 0
init {
val paths = BreadthFirstDirectedPaths(digraph, v)
val reversePaths = BreadthFirstDirectedPaths(digraph.reverse(), v)
for (i in 0 until digraph.V) {
if (paths.hasPathTo(i) && reversePaths.hasPathTo(i)) {
connected[i] = true
count++
}
}
}
fun connected(w: Int): Boolean {
return connected[w]
}
fun count(): Int {
return count
}
fun connectedVertex(): Iterable<Int> {
val queue = Queue<Int>()
for (i in connected.indices) {
if (connected[i]) {
queue.enqueue(i)
}
}
return queue
}
}
class StrongComponentAllVertex(digraph: Digraph) {
private val ids = IntArray(digraph.V) { -1 }
private var count = 0
init {
for (i in 0 until digraph.V) {
if (ids[i] == -1) {
val singleVertex = StrongComponentSingleVertex(digraph, i)
singleVertex.connectedVertex().forEach {
ids[it] = count
}
count++
}
}
}
fun connected(v: Int, w: Int): Boolean {
return ids[v] == ids[w]
}
fun count(): Int {
return count
}
fun id(v: Int): Int {
return ids[v]
}
}
fun main() {
val digraph = getTinyDG()
val scc = StrongComponentAllVertex(digraph)
val count = scc.count()
println("$count components")
val bagArray = Array(count) { Bag<Int>() }
for (v in 0 until digraph.V) {
bagArray[scc.id(v)].add(v)
}
bagArray.forEach {
println(it.joinToString())
}
} | 0 | Kotlin | 1 | 6 | 879885b82ef51d58efe578c9391f04bc54c2531d | 2,402 | Algorithms-4th-Edition-in-Kotlin | MIT License |
src/year2022/day04/Day04.kt | lukaslebo | 573,423,392 | false | {"Kotlin": 222221} | package year2022.day04
import check
import readInput
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readInput("2022", "Day04_test")
check(part1(testInput), 2)
check(part2(testInput), 4)
val input = readInput("2022", "Day04")
println(part1(input))
println(part2(input))
}
private fun part1(input: List<String>): Int = input.toRangePairs().count {
it.first fullyContains it.second || it.second fullyContains it.first
}
private fun part2(input: List<String>): Int = input.toRangePairs().count { it.first overlaps it.second }
private fun List<String>.toRangePairs() = map { line ->
val (part1, part2) = line.split(',').map { part ->
val (start, end) = part.split('-').map { it.toInt() }
start..end
}
part1 to part2
}
private infix fun IntRange.fullyContains(other: IntRange) = other.first in this && other.last in this
private infix fun IntRange.overlaps(other: IntRange) =
first in other || last in other || other.first in this || other.last in this | 0 | Kotlin | 0 | 1 | f3cc3e935bfb49b6e121713dd558e11824b9465b | 1,068 | AdventOfCode | Apache License 2.0 |
src/main/kotlin/datastructures/trees/trie/Trie.kt | amykv | 538,632,477 | false | {"Kotlin": 169929} | package datastructures.trees.trie
fun main() {
val trie = Trie()
trie.insert("cooling")
trie.insert("cool")
println(trie.root.children['c']!!.children['e']?.children)
println(trie.delete("cool"))
println(trie.findWord("cool"))
println(trie.root.children['c']!!.children['o']?.children)
}
class Trie {
val root = Node()
// insert
fun insert(string: String) {
var current: Node? = root
for (ch in string.toCharArray()) {
current!!.children.putIfAbsent(ch, Node())
current = current.children[ch]
}
current!!.isWord = true
}
// findWord
fun findWord(string: String): Boolean {
var current: Node? = root
for (ch in string.toCharArray()) {
current = if (current!!.children.containsKey(ch)) {
current.children[ch]
} else {
return false
}
}
return current!!.isWord
}
// delete
fun delete(word: String): Boolean {
var current: Node? = root
var deleteAfter: Node? = root
var ch1 = word[0]
for (i in word.indices) {
val ch = word[i]
if (current!!.children.containsKey(ch)) {
current = current.children[ch]
if (current!!.children.size > 1) {
deleteAfter = current
ch1 = word[i + 1]
}
} else {
return false
}
}
if (current!!.children.isEmpty()) {
deleteAfter!!.children.remove(ch1)
return true
}
return false
}
}
//Node data class
data class Node(var children: HashMap<Char, Node> = HashMap(), var isWord: Boolean = false)
| 0 | Kotlin | 0 | 2 | 93365cddc95a2f5c8f2c136e5c18b438b38d915f | 1,780 | dsa-kotlin | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/KnightDialer.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 dev.shtanko.algorithms.E_9
import dev.shtanko.algorithms.MOD
import java.util.Arrays
/**
* 935. Knight Dialer
* @see <a href="https://leetcode.com/problems/knight-dialer/">Source</a>
*/
fun interface KnightDialer {
operator fun invoke(n: Int): Int
}
/**
* Naive Recursive Code
*/
class KnightDialerBottomUp : KnightDialer {
override operator fun invoke(n: Int): Int {
val dirs = arrayOf(
intArrayOf(4, 6),
intArrayOf(6, 8),
intArrayOf(7, 9),
intArrayOf(4, 8),
intArrayOf(0, 3, 9),
intArrayOf(),
intArrayOf(0, 1, 7),
intArrayOf(2, 6),
intArrayOf(1, 3),
intArrayOf(2, 4),
)
val mod = E_9.toInt() + 7
val dp = Array(n) { IntArray(10) }
Arrays.fill(dp[0], 1)
var res = 0
for (i in 1 until n) {
for (j in 0..9) {
for (next in dirs[j]) {
dp[i][j] = (dp[i][j] + dp[i - 1][next]) % mod
}
}
}
for (i in 0..9) {
res = (res + dp[n - 1][i]) % mod
}
return res
}
}
/**
* Top down Dynamic programming solution
*/
class KnightDialerDP : KnightDialer {
override operator fun invoke(n: Int): Int {
if (n == 1) return 10
val jumpMap = arrayOf(
intArrayOf(4, 6),
intArrayOf(6, 8),
intArrayOf(7, 9),
intArrayOf(4, 8),
intArrayOf(3, 9, 0),
intArrayOf(),
intArrayOf(1, 7, 0),
intArrayOf(2, 6),
intArrayOf(1, 3),
intArrayOf(2, 4),
)
var dp = IntArray(10) { 1 }
for (n0 in n downTo 2) {
val temp = IntArray(10)
for (i in jumpMap.indices) {
for (j in jumpMap[i].indices) {
val position = jumpMap[i][j] // jump from number i, to position
temp[position] = (temp[position] + dp[i] % MOD) % MOD
}
}
dp = temp
}
var ans = 0
for (num in dp) ans = (ans + num % MOD) % MOD
return ans
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,846 | kotlab | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/ValidateBinarySearchTree.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import java.util.ArrayDeque
import java.util.Deque
import java.util.LinkedList
/**
* 98. Validate Binary Search Tree
* https://leetcode.com/problems/validate-binary-search-tree/
*/
fun interface ValidateBinarySearchTree {
operator fun invoke(root: TreeNode): Boolean
}
/**
* Approach 1: Recursive Traversal with Valid Range
*/
class RecursiveTraversalValidRange : ValidateBinarySearchTree {
override fun invoke(root: TreeNode): Boolean {
return validate(root, null, null)
}
private fun validate(root: TreeNode?, low: Int?, high: Int?): Boolean {
// Empty trees are valid BSTs.
if (root == null) {
return true
}
// The current node's value must be between low and high.
return if (low != null && root.value <= low || high != null && root.value >= high) {
false
} else {
validate(root.right, root.value, high) && validate(root.left, low, root.value)
}
// The left and right subtree must also be valid.
}
}
class IterativeTraversalValidRange : ValidateBinarySearchTree {
private val stack: Deque<TreeNode?> = LinkedList()
private val upperLimits: Deque<Int> = LinkedList()
private val lowerLimits: Deque<Int> = LinkedList()
override fun invoke(root: TreeNode): Boolean {
var low: Int? = null
var high: Int? = null
var value: Int
var node: TreeNode? = root
update(node, low, high)
while (stack.isNotEmpty()) {
node = stack.poll()
low = lowerLimits.poll()
high = upperLimits.poll()
if (node == null) continue
value = node.value
if (low != null && value <= low) {
return false
}
if (high != null && value >= high) {
return false
}
update(node.right, value, high)
update(node.left, low, value)
}
return true
}
private fun update(root: TreeNode?, low: Int?, high: Int?) {
stack.add(root)
lowerLimits.add(low)
upperLimits.add(high)
}
}
/**
* Approach 3: Recursive Inorder Traversal
*/
class RecursiveInorderTraversal : ValidateBinarySearchTree {
private var prev: Int? = null
override fun invoke(root: TreeNode): Boolean {
return inorder(root)
}
private fun inorder(root: TreeNode?): Boolean {
if (root == null) {
return true
}
if (!inorder(root.left)) {
return false
}
if (prev != null && root.value <= prev!!) {
return false
}
prev = root.value
return inorder(root.right)
}
}
/**
* Approach 4: Iterative Inorder Traversal
*/
class IterativeInorderTraversal : ValidateBinarySearchTree {
override fun invoke(root: TreeNode): Boolean {
val stack: Deque<TreeNode> = ArrayDeque()
var prev: Int? = null
var node: TreeNode? = root
while (stack.isNotEmpty() || node != null) {
while (node != null) {
stack.push(node)
node = node.left
}
node = stack.pop()
// If next element in inorder traversal
// is smaller than the previous one
// that's not BST.
if (prev != null && node.value <= prev) {
return false
}
prev = node.value
node = node.right
}
return true
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 4,170 | kotlab | Apache License 2.0 |
src/main/kotlin/day4.kt | Gitvert | 433,947,508 | false | {"Kotlin": 82286} | fun day4() {
val lines: List<String> = readFile("day04.txt")
day4part1(lines)
day4part2(lines)
}
fun day4part1(lines: List<String>) {
val bingoNumbers: List<Int> = lines[0].split(",").map { Integer.valueOf(it) }
val bingoCards = createBingoCards(lines.subList(2, lines.size-1))
val answer = playToWin(bingoNumbers, bingoCards)
println("4a: $answer")
}
fun day4part2(lines: List<String>) {
val bingoNumbers: List<Int> = lines[0].split(",").map { Integer.valueOf(it) }
val bingoCards = createBingoCards(lines.subList(2, lines.size-1))
val answer = playToLose(bingoNumbers, bingoCards)
println("4b: $answer")
}
fun createBingoCards(lines: List<String>): List<BingoCard> {
val bingoCards: MutableList<BingoCard> = mutableListOf()
var activeBingoCard = BingoCard(mutableListOf(), false)
lines.forEach { line ->
if (line.isEmpty()) {
bingoCards.add(activeBingoCard)
activeBingoCard = BingoCard(mutableListOf(), false)
} else {
activeBingoCard.matrix.add(line.replace(" ", " ").trimStart().split(" ").map{ Integer.valueOf(it) } as MutableList<Int>)
}
}
return bingoCards
}
fun playToWin(bingoNumbers: List<Int>, bingoCards: List<BingoCard>): Int {
bingoNumbers.forEach { number ->
bingoCards.forEach { bingoCard ->
markNumber(bingoCard, number)
if (checkWin(bingoCard)) {
return calculateFinalScore(bingoCard, number)
}
}
}
return 0
}
fun playToLose(bingoNumbers: List<Int>, bingoCards: List<BingoCard>): Int {
val noOfBingoCards = bingoCards.size
var foundWinningBingoCards = 0
bingoNumbers.forEach { number ->
bingoCards.forEach { bingoCard ->
markNumber(bingoCard, number)
if (checkWin(bingoCard)) {
foundWinningBingoCards++
if (foundWinningBingoCards == noOfBingoCards) {
return calculateFinalScore(bingoCard, number)
}
}
}
}
return 0
}
fun markNumber(bingoCard: BingoCard, number: Int) {
bingoCard.matrix.forEachIndexed { i, row ->
row.forEachIndexed { j, cell ->
if (cell == number) {
bingoCard.matrix[i][j] = -1
}
}
}
}
fun checkWin(bingoCard: BingoCard): Boolean {
if (bingoCard.hasWon) {
return false
}
val rowSeenNumbers: MutableList<Int> = mutableListOf()
val columnSeenNumbers: MutableList<Int> = mutableListOf()
for (i in 0 until bingoCard.matrix.size) {
for (j in 0 until bingoCard.matrix.size) {
rowSeenNumbers.add(bingoCard.matrix[i][j])
columnSeenNumbers.add(bingoCard.matrix[j][i])
}
if (rowSeenNumbers.all { n -> n == -1 } || columnSeenNumbers.all { n -> n == -1 }) {
bingoCard.hasWon = true
return true
}
rowSeenNumbers.clear()
columnSeenNumbers.clear()
}
return false
}
fun calculateFinalScore(bingoCard: BingoCard, number: Int): Int {
var finalScore = 0
bingoCard.matrix.forEach { row ->
row.forEach { cell ->
if (cell != -1) {
finalScore += cell
}
}
}
return finalScore * number
}
data class BingoCard(val matrix: MutableList<MutableList<Int>>, var hasWon: Boolean) | 0 | Kotlin | 0 | 0 | 02484bd3bcb921094bc83368843773f7912fe757 | 3,423 | advent_of_code_2021 | MIT License |
src/main/kotlin/abc/191-e.kt | kirimin | 197,707,422 | false | null | package abc
import java.util.*
fun main(args: Array<String>) {
val sc = Scanner(System.`in`)
val n = sc.nextInt()
val m = sc.nextInt()
val abc = (0 until m).map { Triple(sc.next().toInt(), sc.next().toInt(), sc.next().toInt()) }
println(problem191e(n, m, abc))
}
fun problem191e(n: Int, m: Int, abc: List<Triple<Int, Int, Int>>): String {
class MyComparator : Comparator<Pair<Int, Int>> {
override fun compare(arg0: Pair<Int, Int>, arg1: Pair<Int, Int>): Int {
val x = arg0.second
val y = arg1.second
return if (x < y) {
-1
} else if (x > y) {
1
} else {
0
}
}
}
val routes = Array(n + 1) { mutableListOf<Pair<Int, Int>>() }
for (i in 0 until m) {
val (a, b, c) = abc[i]
routes[a - 1].add(b - 1 to c)
}
val ans = LongArray(n) { 0 }
val q: PriorityQueue<Pair<Int, Int>> = PriorityQueue(n, MyComparator())
for (city in 0 until n) {
q.clear()
val costs = LongArray(n) { Long.MAX_VALUE }
val doneList = BooleanArray(n) { false }
for (j in 0 until routes[city].size) {
val (route, cost) = routes[city][j]
q.add(route to cost)
costs[route] = Math.min(costs[route], cost.toLong())
}
while (q.isNotEmpty()) {
val (route, _) = q.poll()
if (doneList[route]) continue
doneList[route] = true
for (i in 0 until routes[route].size) {
val (nextRoute, nextCost) = routes[route][i]
val cost = costs[route] + nextCost
if (cost < costs[nextRoute]) {
costs[nextRoute] = cost
q.add(nextRoute to cost.toInt())
}
}
}
ans[city] = if (costs[city] == Long.MAX_VALUE) -1 else costs[city]
}
return ans.joinToString("\n")
} | 0 | Kotlin | 1 | 5 | 23c9b35da486d98ab80cc56fad9adf609c41a446 | 1,976 | AtCoderLog | The Unlicense |
src/day10/Day10.kt | HGilman | 572,891,570 | false | {"Kotlin": 109639, "C++": 5375, "Python": 400} | package day10
import readInput
fun main() {
val day = 10
val testInput = readInput("day$day/testInput")
check(part1(testInput) == 13140)
val input = readInput("day$day/input")
println(part1(input))
part2(input)
}
sealed class Command(val cycles: Int)
object Noop : Command(1)
class AddX(val x: Int) : Command(2)
fun parseInput(input: List<String>): List<Command> {
return input.map {
if (it.startsWith("addx")) {
val value = it.substringAfter(" ").toInt()
AddX(value)
} else {
Noop
}
}
}
fun part1(input: List<String>): Int {
val commandQueue = ArrayDeque(parseInput(input))
var cycle = 0
var value = 1
var res = 0
var commandCycle = 0
val interestCycles = listOf(20, 60, 100, 140, 180, 220)
while (commandQueue.isNotEmpty()) {
cycle++
commandCycle++
if (cycle in interestCycles) {
res += value * cycle
}
val command = commandQueue.first()
if (commandCycle == command.cycles) {
if (command is AddX) {
value += command.x
}
commandQueue.removeFirst()
commandCycle = 0
}
}
return res
}
fun part2(input: List<String>) {
val commandQueue = ArrayDeque(parseInput(input))
var cycle = 0
var commandCycle = 0
var spritePos = 1
fun printCurrent() {
val crtPos = (cycle - 1) % 40
if (crtPos == 0) {
println()
}
if (crtPos in spritePos - 1..spritePos + 1) {
print("#")
} else {
print(".")
}
}
while (!commandQueue.isEmpty()) {
cycle++
commandCycle++
printCurrent()
val command = commandQueue.first()
if (commandCycle == command.cycles) {
if (command is AddX) {
spritePos += command.x
}
commandQueue.removeFirst()
commandCycle = 0
}
}
} | 0 | Kotlin | 0 | 1 | d05a53f84cb74bbb6136f9baf3711af16004ed12 | 2,027 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/PacificAtlanticWaterFlow.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import dev.shtanko.algorithms.extensions.lessThanZero
import java.util.LinkedList
import java.util.Queue
private val DIRECTIONS = arrayOf(intArrayOf(0, 1), intArrayOf(1, 0), intArrayOf(-1, 0), intArrayOf(0, -1))
fun interface PacificAtlanticWaterFlow {
operator fun invoke(matrix: Array<IntArray>): List<List<Int>>
}
class PacificAtlanticDFS : PacificAtlanticWaterFlow {
override operator fun invoke(matrix: Array<IntArray>): List<List<Int>> {
val res: MutableList<MutableList<Int>> = LinkedList()
if (matrix.isEmpty() || matrix[0].isEmpty()) {
return res
}
val n: Int = matrix.size
val m: Int = matrix[0].size
val pacific = Array(n) { BooleanArray(m) }
val atlantic = Array(n) { BooleanArray(m) }
for (i in 0 until n) {
dfs(matrix, pacific, Int.MIN_VALUE, i, 0)
dfs(matrix, atlantic, Int.MIN_VALUE, i, m - 1)
}
for (i in 0 until m) {
dfs(matrix, pacific, Int.MIN_VALUE, 0, i)
dfs(matrix, atlantic, Int.MIN_VALUE, n - 1, i)
}
for (i in 0 until n) for (j in 0 until m) if (pacific[i][j] && atlantic[i][j]) res.add(mutableListOf(i, j))
return res
}
private fun dfs(matrix: Array<IntArray>, visited: Array<BooleanArray>, height: Int, x: Int, y: Int) {
val n = matrix.size
val m: Int = matrix[0].size
val left = x.lessThanZero().or(x >= n).or(y.lessThanZero()).or(y >= m)
if (left || visited[x][y] || matrix[x][y] < height) return
visited[x][y] = true
for (d in DIRECTIONS) {
dfs(matrix, visited, matrix[x][y], x + d[0], y + d[1])
}
}
}
class PacificAtlanticBFS : PacificAtlanticWaterFlow {
override operator fun invoke(matrix: Array<IntArray>): List<List<Int>> {
val res: MutableList<MutableList<Int>> = LinkedList()
if (matrix.isEmpty() || matrix[0].isEmpty()) {
return res
}
val n = matrix.size
val m: Int = matrix[0].size
val pacific = Array(n) { BooleanArray(m) }
val atlantic = Array(n) { BooleanArray(m) }
val pQueue: Queue<IntArray> = LinkedList()
val aQueue: Queue<IntArray> = LinkedList()
for (i in 0 until n) {
pQueue.offer(intArrayOf(i, 0))
aQueue.offer(intArrayOf(i, m - 1))
pacific[i][0] = true
atlantic[i][m - 1] = true
}
for (i in 0 until m) {
pQueue.offer(intArrayOf(0, i))
aQueue.offer(intArrayOf(n - 1, i))
pacific[0][i] = true
atlantic[n - 1][i] = true
}
bfs(matrix, pQueue, pacific)
bfs(matrix, aQueue, atlantic)
for (i in 0 until n) {
for (j in 0 until m) {
if (pacific[i][j] && atlantic[i][j]) res.add(mutableListOf(i, j))
}
}
return res
}
private fun bfs(matrix: Array<IntArray>, queue: Queue<IntArray>, visited: Array<BooleanArray>) {
val n = matrix.size
val m: Int = matrix[0].size
while (queue.isNotEmpty()) {
val cur = queue.poll()
for (d in DIRECTIONS) {
val x = cur[0] + d[0]
val y = cur[1] + d[1]
val start = x.lessThanZero().or(x >= n).or(y.lessThanZero()).or(y >= m)
if (start || visited[x][y] || matrix[x][y] < matrix[cur[0]][cur[1]]) {
continue
}
visited[x][y] = true
queue.offer(intArrayOf(x, y))
}
}
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 4,246 | kotlab | Apache License 2.0 |
src/main/kotlin/me/peckb/aoc/_2023/calendar/day18/Day18.kt | peckb1 | 433,943,215 | false | {"Kotlin": 956135} | package me.peckb.aoc._2023.calendar.day18
import me.peckb.aoc._2023.calendar.day18.Day18.Direction.*
import javax.inject.Inject
import me.peckb.aoc.generators.InputGenerator.InputGeneratorFactory
class Day18 @Inject constructor(
private val generatorFactory: InputGeneratorFactory,
) {
fun partOne(filename: String) = generatorFactory.forFile(filename).readAs(::digStep) { input ->
minkowskiSum(input)
}
fun partTwo(filename: String) = generatorFactory.forFile(filename).readAs(::digStep2) { input ->
minkowskiSum(input)
}
private fun minkowskiSum(input: Sequence<DigStep>): Long {
var currentX = 0L
var currentY = 0L
var perimeter = 0L
// populate our convex hull
val pointsOfConvexHull = mutableListOf<Pair<Long, Long>>()
input.forEach { (direction, steps) ->
when (direction) {
UP -> currentY -= steps
LEFT -> currentX -= steps
DOWN -> currentY += steps
RIGHT -> currentX += steps
}
perimeter += steps
pointsOfConvexHull.add(currentY to currentX)
}
// Shoelace Formula over the hull
val shoelaceArea = pointsOfConvexHull.plus(pointsOfConvexHull.first()).windowed(2).fold(0L) { acc, pointPair ->
val (y1, x1) = pointPair.first()
val (y2, x2) = pointPair.last()
acc + ((x1 * y2) - (x2 * y1))
} / 2
// minkowskiSum:
// Shoelace Sum of the inside +
// half the perimeter +
// the width of the edge
val edgeWidth = 1
return shoelaceArea + (perimeter / 2) + edgeWidth
}
private fun digStep(line: String): DigStep {
val (directionStr, stepsStr, _) = line.split(" ")
return DigStep(
direction = Direction.fromSymbol(directionStr.first()),
steps = stepsStr.toInt(),
)
}
private fun digStep2(line: String): DigStep {
val (_, _, colourStr) = line.split(" ")
val encoding = colourStr.drop(2).dropLast(1)
val stepStrHex = encoding.take(5)
val direction = encoding.takeLast(1)
return DigStep(
direction = Direction.fromNumber(direction.first()),
steps = stepStrHex.toInt(16),
)
}
data class DigStep(val direction: Direction, val steps: Int)
enum class Direction(val symbol: Char, val number: Char) {
UP('U', '3'),
LEFT('L', '2'),
DOWN('D', '1'),
RIGHT('R', '0');
companion object {
fun fromSymbol(s: Char) = entries.first { it.symbol == s }
fun fromNumber(s: Char) = entries.first { it.number == s }
}
}
}
| 0 | Kotlin | 1 | 3 | 2625719b657eb22c83af95abfb25eb275dbfee6a | 2,493 | advent-of-code | MIT License |
kotlin/src/main/kotlin/adventofcode/y2018/Day2.kt | 3ygun | 115,948,057 | false | null | package adventofcode.y2018
import adventofcode.DataLoader
import adventofcode.Day
object Day2 : Day {
val STAR1_DATA = DataLoader.readLinesFromFor("/y2018/Day2Star1.txt")
val STAR2_DATA = DataLoader.readLinesFromFor("/y2018/Day2Star2.txt")
override val day: Int = 2
override fun star1Run(): String {
val result = Day2.star1Calc(STAR1_DATA)
return "Checksum is $result"
}
fun star1Calc(input: List<String>): Int {
var foundFor2 = 0
var foundFor3 = 0
input
.map { parseInput(it) }
.forEach {
foundFor2 += it.first
foundFor3 += it.second
}
if (foundFor2 == 0) foundFor2 = 1
if (foundFor3 == 0) foundFor3 = 1
return foundFor2 * foundFor3
}
private fun parseInput(input: String): Pair<Int, Int> = input
.toCharArray()
.groupBy { it }
.map { Pair(it.key, it.value.size) }
.associateBy( { it.second }, { it.first } )
.run {
val twoOfKind = if (this.containsKey(2)) 1 else 0
val threeOfKind = if (this.containsKey(3)) 1 else 0
debug {
val foundFor2 = this[2]
val foundFor3 = this[3]
"For $input, found for 2 = $foundFor2, found for 3 = $foundFor3"
}
return Pair(twoOfKind, threeOfKind)
}
override fun star2Run(): String {
val result = star2Calc(STAR2_DATA)
return "Unchanged characters $result"
}
fun star2Calc(input: List<String>): String {
input.forEach { checking ->
input.forEach { against ->
val doesNotMatch = calculateResult(checking, against)
if (doesNotMatch == 1) {
return result(checking, against)
}
}
}
return "BAD"
}
private fun calculateResult(checking: String, against: String): Int {
val checkingChars = checking.toCharArray()
val againstChars = against.toCharArray()
var doesNotMatch = 0
for (i in checkingChars.indices) {
if (checkingChars[i] != againstChars[i]) {
doesNotMatch++
if (doesNotMatch > 1) {
return 2
}
}
}
return doesNotMatch
}
private fun result(checking: String, against: String): String {
val checkingChars = checking.toCharArray()
val againstChars = against.toCharArray()
debug { "Day 2, Star 2:" }
debug { checking }
debug { against }
for (i in checking.indices) {
if (checkingChars[i] != againstChars[i]) {
return checking.removeRange(i, i+1)
}
}
return "."
}
}
| 0 | Kotlin | 0 | 0 | 69f95bca3d22032fba6ee7d9d6ec307d4d2163cf | 2,837 | adventofcode | MIT License |
src/main/kotlin/Day22.kt | clechasseur | 318,029,920 | false | null | object Day22 {
private val deck1 = listOf(
24,
22,
26,
6,
14,
19,
27,
17,
39,
34,
40,
41,
23,
30,
36,
11,
28,
3,
10,
21,
9,
50,
32,
25,
8
)
private val deck2 = listOf(
48,
49,
47,
15,
42,
44,
5,
4,
13,
7,
20,
43,
12,
37,
29,
18,
45,
16,
1,
46,
38,
35,
2,
33,
31
)
fun part1(): Int = playTillWin(Game(setOf(Player(1, deck1), Player(2, deck2)))).winner!!.score
fun part2(): Int = playRecursiveTillWin(Game(setOf(Player(1, deck1), Player(2, deck2)))).winner!!.score
private data class Player(val id: Int, val deck: List<Int>) {
val score: Int
get() = deck.reversed().withIndex().sumBy { (it.index + 1) * it.value }
fun winCards(cards: List<Int>): Player = copy(deck = deck.drop(1) + cards)
fun loseTopCard(): Player = copy(deck = deck.drop(1))
}
private data class Game(val players: Set<Player>, val winner: Player?) {
constructor(players: Set<Player>) : this(players, players.singleOrNull { it.deck.isNotEmpty() })
fun playOneRound(): Game {
val winnerLosers = players.sortedByDescending { it.deck.first() }
return Game(
setOf(winnerLosers.first().winCards(winnerLosers.map { it.deck.first() })) +
winnerLosers.drop(1).map { it.loseTopCard() }
)
}
fun playOneRecursiveRound(prevStates: Set<Game>): Game = when {
prevStates.contains(this) -> Game(players, players.withId(1))
players.all { it.deck.size > it.deck.first() } -> playSubGame()
else -> playOneRound()
}
private fun playSubGame(): Game {
val wonSubGame = playRecursiveTillWin(Game(players.map { player ->
Player(player.id, player.deck.drop(1).take(player.deck.first()))
}.toSet()))
val cards = listOf(players.withId(wonSubGame.winner!!.id).deck.first()) +
(players - players.withId(wonSubGame.winner.id)).map { it.deck.first() }
return Game(
setOf(players.withId(wonSubGame.winner.id).winCards(cards)) +
(players - players.withId(wonSubGame.winner.id)).map { it.loseTopCard() }
)
}
}
private fun playTillWin(game: Game): Game = generateSequence(game) { prevGame ->
if (prevGame.winner == null) prevGame.playOneRound() else null
}.last()
private fun playRecursiveTillWin(game: Game): Game {
val prevStates = mutableSetOf<Game>()
var curGame = game
while (curGame.winner == null) {
val newGame = curGame.playOneRecursiveRound(prevStates)
prevStates.add(curGame)
curGame = newGame
}
return curGame
}
private fun Set<Player>.withId(id: Int): Player = single { it.id == id }
}
| 0 | Kotlin | 0 | 0 | 6173c9da58e3118803ff6ec5b1f1fc1c134516cb | 3,216 | adventofcode2020 | MIT License |
books/grokking-algorithms/recursion/Recursion.kts | eng-mohamedalmahdy | 450,924,598 | false | {"Kotlin": 9454} | fun factorial(x:Int):Int{
var res = 1
repeat(x){ res *= it+1 }
return res
}
// fact(x) = x * fact(x-1)
// fact(0 & 1) = 1
fun factorial(x: Int): Int {
if (x == 1 || x == 0) return 1
return x * factorial(x - 1)
}
val x = factorial(3)
fun pow(base: Int, power: Int): Int {
var res = 1
repeat(power) { res *= base }
return res
}
// 2 3 => 2 * pow(2,2)
// 2 2 => 4 * pow(2,1)
// 2 1 => 4 * 2
fun pow(base: Int, power: Int): Int {
if (power == 0) return 1
if (power == 1) return base
return base * pow(base, power - 1)
}
val x = pow(2, 3)
print(x)
| 0 | Kotlin | 0 | 7 | 88b9f0593d3b4dc1d4a0a89f8907fd218ece3393 | 592 | meow-readings | Apache License 2.0 |
day18/Kotlin/day18.kt | Ad0lphus | 353,610,043 | false | {"C++": 195638, "Python": 139359, "Kotlin": 80248} | import java.io.*
fun print_day_18() {
val yellow = "\u001B[33m"
val reset = "\u001b[0m"
val green = "\u001B[32m"
println(yellow + "-".repeat(25) + "Advent of Code - Day 18" + "-".repeat(25) + reset)
println(green)
val process = Runtime.getRuntime().exec("figlet Snailfish -c -f small")
val reader = BufferedReader(InputStreamReader(process.inputStream))
reader.forEachLine { println(it) }
println(reset)
println(yellow + "-".repeat(33) + "Output" + "-".repeat(33) + reset + "\n")
}
fun main() {
print_day_18()
println("Puzzle 1: " + Day18().part_1())
println("Puzzle 2: " + Day18().part_2())
println("\n" + "\u001B[33m" + "=".repeat(72) + "\u001b[0m" + "\n")
}
class Day18 {
private val input = File("../Input/day18.txt").readLines()
fun part_1() = input.map { parse(it) }.reduce { a, b -> a + b }.magnitude()
fun part_2() = input.indices.flatMap { i -> input.indices.map { j -> i to j}}.filter {(i,j) -> i != j }.maxOf { (i,j) -> (parse(input[i]) + parse(input[j])).magnitude() }
private fun parse(input: String): Num {
var cur = 0
fun _parse(): Num =
if (input[cur] == '[') {
cur++
val left = _parse()
cur++
val right = _parse()
cur++
Num.NumPair(left, right)
}
else Num.NumValue(input[cur].digitToInt()).also { cur++ }
return _parse()
}
sealed class Num {
var parent: NumPair? = null
class NumValue(var value: Int) : Num() {
override fun toString(): String = value.toString()
fun canSplit(): Boolean = value >= 10
fun split() {
val num = NumPair(NumValue(value / 2), NumValue((value + 1) / 2))
parent?.replaceWith(this, num)
}
}
class NumPair(var left: Num, var right: Num) : Num() {
init {
left.parent = this
right.parent = this
}
override fun toString(): String = "[$left,$right]"
fun explode() {
val x = if (left is NumValue) (left as NumValue).value else null
val y = if (right is NumValue) (right as NumValue).value else null
findValueToLeft()?.let { it.value += x!! }
findValueToRight()?.let { it.value += y!! }
parent?.replaceWith(this, NumValue(0))
}
fun replaceWith(child: Num, newValue: Num) {
if (left == child) { left = newValue }
else if (right == child){ right = newValue }
newValue.parent = this
}
}
fun magnitude(): Int = when(this) {
is NumValue -> value
is NumPair -> left.magnitude() * 3 + right.magnitude() * 2
}
operator fun plus(other: Num): Num =
NumPair(this, other).apply {
left.parent = this
right.parent = this
reduce()
}
fun reduce() {
do {
var exploded = false
var split = false
findNextExplode()?.apply {
explode()
exploded = true
}
if (!exploded) findNextToSplit()?.apply {
split()
split = true
}
} while (exploded || split)
}
fun findValueToRight(): NumValue? {
if (this is NumValue) return this
if (this == parent?.left) return parent!!.right.findValueFurthestLeft()
if (this == parent?.right) return parent!!.findValueToRight()
return null
}
fun findValueToLeft(): NumValue? {
if (this is NumValue) return this
if (this == parent?.left) return parent!!.findValueToLeft()
if (this == parent?.right) return parent!!.left.findValueFurthestRight()
return null
}
private fun findValueFurthestLeft(): NumValue? = when(this) {
is NumValue -> this
is NumPair -> this.left.findValueFurthestLeft()
}
private fun findValueFurthestRight(): NumValue? = when(this) {
is NumValue -> this
is NumPair -> this.right.findValueFurthestRight()
}
private fun findNextToSplit(): NumValue? =
if (this is NumValue && canSplit()) this
else if (this is NumPair) left.findNextToSplit() ?: right.findNextToSplit()
else null
private fun findNextExplode(depth: Int = 0): NumPair? =
if (this is NumPair) {
if (depth >= 4) this
else left.findNextExplode(depth + 1) ?: right.findNextExplode(depth + 1)
}
else null
}
} | 0 | C++ | 0 | 0 | 02f219ea278d85c7799d739294c664aa5a47719a | 4,919 | AOC2021 | Apache License 2.0 |
src/aoc2022/Day13.kt | anitakar | 576,901,981 | false | {"Kotlin": 124382} | package aoc2022
import org.json.JSONArray
import println
import readInput
fun main() {
fun inRightOrder(left: List<Any>, right: List<Any>): Pair<Boolean, Boolean> {
for (i in left.indices) {
if (i >= right.size) {
return Pair(false, true)
}
if (left[i] is Int && right[i] is Int) {
if ((left[i] as Int) < (right[i] as Int)) {
return Pair(true, true)
}
if ((left[i] as Int) > (right[i] as Int)) {
return Pair(false, true)
}
}
if (left[i] is List<*> && right[i] is List<*>) {
val (inOrder, conclusive) = inRightOrder(left[i] as List<Any>, right[i] as List<Any>)
if (conclusive) return Pair(inOrder, true)
}
if (left[i] is Int && right[i] is List<*>) {
val (inOrder, conclusive) = inRightOrder(listOf(left[i]), right[i] as List<Any>)
if (conclusive) return Pair(inOrder, true)
}
if (left[i] is List<*> && right[i] is Int) {
val (inOrder, conclusive) = inRightOrder(left[i] as List<Any>, listOf(right[i]))
if (conclusive) return Pair(inOrder, true)
}
}
if (left.size < right.size) return Pair(true, true)
return Pair(true, false)
}
fun parseArray(jsonArray: JSONArray): List<Any> {
val result = mutableListOf<Any>()
for (i in 0 until jsonArray.length()) {
if (jsonArray[i] is Int) {
result.add(jsonArray.getInt(i))
} else if (jsonArray[i] is JSONArray) {
if (jsonArray.getJSONArray(i).isEmpty) {
result.add(mutableListOf<Any>())
} else {
result.add(parseArray(jsonArray.getJSONArray(i)))
}
}
}
return result
}
fun parseArray(line: String, start: Int): Pair<List<Any>, Int> {
val result = mutableListOf<Any>()
var i = start
while (i < line.length) {
if (line[i] == ']') {
return Pair(result, i + 1)
}
if (line[i] == '[') {
val (arr, j) = parseArray(line, i + 1)
result.add(arr)
i = j
} else {
var next = i
while (line[next].isDigit()) {
next += 1
}
if (next != i) {
result.add(line.substring(i, next).toInt())
i = next
} else {
i = next + 1
}
}
}
return Pair(result, line.length)
}
fun parseLine(line: String): List<Any> {
return parseArray(line, 1).first
}
fun part1(input: List<String>): Int {
var left: List<Any>? = null
var right: List<Any>? = null
var sumIndicesCorrect = 0
for (i in input.indices) {
val line = input[i]
if (line.trim().isBlank()) {
val correct = inRightOrder(left!!, right!!)
if (correct.first) {
sumIndicesCorrect += (i + 1) / 3
}
left = null
right = null
continue
}
val parsed = parseLine(line)
if (left == null) left = parsed else right = parsed
}
if (left != null && right != null) {
val correct = inRightOrder(left!!, right!!)
if (correct.first) {
sumIndicesCorrect += (input.size + 1) / 3
}
}
return sumIndicesCorrect
}
fun part2(input: List<String>): Int {
val newList = mutableListOf<List<Any>>()
newList.add(parseLine("[[2]]"))
newList.add(parseLine("[[6]]"))
input.filter { it.isNotBlank() }.forEach { newList.add(parseLine(it)) }
newList.sortWith { e1, e2 ->
val (smaller, conclusive) = inRightOrder(e1, e2)
if (!conclusive) return@sortWith 0;
if (smaller) return@sortWith -1;
if (!smaller) return@sortWith 1;
return@sortWith 0;
}
var product = 1
for (i in newList.indices) {
if (newList[i] == mutableListOf<Any>(mutableListOf<Any>(2))) {
product *= (i+1)
}
if (newList[i] == mutableListOf<Any>(mutableListOf<Any>(6))) {
product *= (i+1)
}
}
return product
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day13_test")
check(part1(testInput) == 13)
check(part2(testInput) == 140)
val input = readInput("Day13")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 1 | 50998a75d9582d4f5a77b829a9e5d4b88f4f2fcf | 4,941 | advent-of-code-kotlin | Apache License 2.0 |
src/main/kotlin/fp/kotlin/example/chapter06/solution/6-4-treeInsertTailrec.kt | funfunStory | 101,662,895 | false | null | package fp.kotlin.example.chapter06.solution
import fp.kotlin.example.chapter05.FunStream
import fp.kotlin.example.chapter05.addHead
import fp.kotlin.example.chapter05.funStreamOf
/**
*
* 연습문제 6-4
*
* SOF가 일어나지 않도록 insertTailrec을 작성해보자.
*
* 힌트 : 함수의 선언 타입은 아래와 같다.
* 필요하다면 내부 함수를 별도로 생성하자.
*
*/
fun main() {
val tree1 = EmptyTree.insertTailrec(5)
require(tree1 == Node(5, EmptyTree, EmptyTree))
val tree2 = tree1.insertTailrec(3)
require(tree2 ==
Node(5,
Node(3, EmptyTree, EmptyTree),
EmptyTree)
)
val tree3 = tree2.insertTailrec(10)
require(tree3 ==
Node(5,
Node(3, EmptyTree, EmptyTree),
Node(10, EmptyTree, EmptyTree)
)
)
val tree4 = tree3.insertTailrec(20)
require(tree4 ==
Node(5,
Node(3, EmptyTree, EmptyTree),
Node(10,
EmptyTree,
Node(20, EmptyTree, EmptyTree)
)
)
)
val tree5 = tree4.insertTailrec(4)
require(tree5 ==
Node(5,
Node(3,
EmptyTree,
Node(4, EmptyTree, EmptyTree)),
Node(10,
EmptyTree,
Node(20, EmptyTree, EmptyTree)
)
)
)
val tree6 = tree5.insertTailrec(2)
require(tree6 ==
Node(5,
Node(3,
Node(2, EmptyTree, EmptyTree),
Node(4, EmptyTree, EmptyTree)
),
Node(10,
EmptyTree,
Node(20, EmptyTree, EmptyTree)
)
)
)
val tree7 = tree6.insertTailrec(8)
require(tree7 ==
Node(5,
Node(3,
Node(2, EmptyTree, EmptyTree),
Node(4, EmptyTree, EmptyTree)
),
Node(10,
Node(8, EmptyTree, EmptyTree),
Node(20, EmptyTree, EmptyTree)
)
)
)
(1..100000).fold(EmptyTree as Tree<Int>) { acc, i ->
acc.insertTailrec(i)
}
}
fun Tree<Int>.insertTailrec(elem: Int): Tree<Int> = rebuild(path(this, elem), elem)
private fun path(tree: Tree<Int>, value: Int): FunStream<Pair<Tree<Int>, Boolean>> {
tailrec fun loop(tree: Tree<Int>,
path: FunStream<Pair<Tree<Int>, Boolean>>): FunStream<Pair<Tree<Int>, Boolean>> =
when (tree) {
EmptyTree -> path
is Node -> when {
value < tree.value -> loop(tree.leftTree, path.addHead(tree to false))
else -> loop(tree.rightTree, path.addHead(tree to true))
}
}
return loop(tree, funStreamOf())
}
private fun rebuild(path: FunStream<Pair<Tree<Int>, Boolean>>, value: Int): Tree<Int> {
tailrec fun loop(path: FunStream<Pair<Tree<Int>, Boolean>>, subTree: Tree<Int>): Tree<Int> =
when (path) {
FunStream.Nil -> subTree
is FunStream.Cons -> when ((path.head()).second) {
false -> loop(path.tail(),
Node((path.head().first as Node).value, subTree,
(path.head().first as Node).rightTree))
true -> loop(path.tail(), Node((path.head().first as Node).value,
(path.head().first as Node).leftTree, subTree))
}
}
return loop(path, Node(value, EmptyTree, EmptyTree))
} | 1 | Kotlin | 23 | 39 | bb10ea01d9f0e1b02b412305940c1bd270093cb6 | 3,493 | fp-kotlin-example | MIT License |
src/main/kotlin/com/hj/leetcode/kotlin/problem23/Solution2.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem23
import com.hj.leetcode.kotlin.common.model.ListNode
/**
* LeetCode page: [23. Merge k Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/);
*/
class Solution2 {
/* Complexity:
* Time O(NLogK) and Space O(LogK) where N is the total nodes of lists and K is the size of lists;
*/
fun mergeKLists(lists: Array<ListNode?>): ListNode? {
return mergeSorted(lists)
}
private fun mergeSorted(
listOfSorted: Array<ListNode?>,
fromIndex: Int = 0,
toIndex: Int = listOfSorted.lastIndex
): ListNode? {
if (fromIndex > toIndex) return null
if (fromIndex == toIndex) return listOfSorted[fromIndex]
val midIndex = (fromIndex + toIndex) ushr 1
val sorted1 = mergeSorted(listOfSorted, fromIndex, midIndex)
val sorted2 = mergeSorted(listOfSorted, midIndex + 1, toIndex)
return mergeSorted(sorted1, sorted2)
}
private fun mergeSorted(sorted1: ListNode?, sorted2: ListNode?): ListNode? {
val dummyHead = ListNode(-1)
var currTail = dummyHead
var currNode1 = sorted1
var currNode2 = sorted2
while (currNode1 != null && currNode2 != null) {
if (currNode1.`val` < currNode2.`val`) {
currTail.next = currNode1
currNode1 = currNode1.next
} else {
currTail.next = currNode2
currNode2 = currNode2.next
}
currTail = checkNotNull(currTail.next)
}
if (currNode1 != null) currTail.next = currNode1
if (currNode2 != null) currTail.next = currNode2
return dummyHead.next
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 1,711 | hj-leetcode-kotlin | Apache License 2.0 |
src/main/kotlin/ru/timakden/aoc/year2015/Day16.kt | timakden | 76,895,831 | false | {"Kotlin": 321649} | package ru.timakden.aoc.year2015
import arrow.core.Option
import arrow.core.none
import arrow.core.some
import arrow.core.tail
import ru.timakden.aoc.util.measure
import ru.timakden.aoc.util.readInput
import ru.timakden.aoc.year2015.Day16.Aunt.Compound.*
/**
* [Day 16: Aunt Sue](https://adventofcode.com/2015/day/16).
*/
object Day16 {
@JvmStatic
fun main(args: Array<String>) {
measure {
val input = readInput("year2015/Day16")
println("Part One: ${solve(input).map { it.name }}")
println("Part Two: ${solve(input, true).map { it.name }}")
}
}
fun solve(input: List<String>, isPartTwo: Boolean = false): Option<Aunt> {
val auntToFind = Aunt(
"Sue", mapOf(
"children" to 3,
"cats" to 7,
"samoyeds" to 2,
"pomeranians" to 3,
"akitas" to 0,
"vizslas" to 0,
"goldfish" to 5,
"trees" to 3,
"cars" to 2,
"perfumes" to 1
)
)
val regex = "\\w+:*\\s\\d+".toRegex()
val aunts = input.map { inputString ->
val compounds = regex.findAll(inputString).map { it.value }
val name = compounds.first()
val compoundsMap = compounds.tail()
.map { compound -> compound.split(": ").let { it.first() to it.last().toInt() } }
.toMap()
Aunt(name, compoundsMap)
}
aunts.forEach { aunt ->
var auntFound = true
with(aunt) {
compounds[AKITAS]?.let { auntFound = it == checkNotNull(auntToFind.compounds[AKITAS]) }
compounds[CARS]?.let { auntFound = auntFound && (it == checkNotNull(auntToFind.compounds[CARS])) }
compounds[CATS]?.let {
val cats = checkNotNull(auntToFind.compounds[CATS])
val result = when {
isPartTwo -> it > cats
else -> it == cats
}
auntFound = auntFound && result
}
compounds[CHILDREN]?.let {
auntFound = auntFound && (it == checkNotNull(auntToFind.compounds[CHILDREN]))
}
compounds[GOLDFISH]?.let {
val goldfish = checkNotNull(auntToFind.compounds[GOLDFISH])
val result = when {
isPartTwo -> it < goldfish
else -> it == goldfish
}
auntFound = auntFound && result
}
compounds[PERFUMES]?.let {
auntFound = auntFound && (it == checkNotNull(auntToFind.compounds[PERFUMES]))
}
compounds[POMERANIANS]?.let {
val pomeranians = checkNotNull(auntToFind.compounds[POMERANIANS])
val result = when {
isPartTwo -> it < pomeranians
else -> it == pomeranians
}
auntFound = auntFound && result
}
compounds[SAMOYEDS]?.let {
auntFound = auntFound && (it == checkNotNull(auntToFind.compounds[SAMOYEDS]))
}
compounds[TREES]?.let {
val trees = checkNotNull(auntToFind.compounds[TREES])
val result = when {
isPartTwo -> it > trees
else -> it == trees
}
auntFound = auntFound && result
}
compounds[VIZSLAS]?.let {
auntFound = auntFound && (it == checkNotNull(auntToFind.compounds[VIZSLAS]))
}
}
if (auntFound) return aunt.some()
}
return none()
}
class Aunt(val name: String, compounds: Map<String, Int>) {
val compounds: MutableMap<Compound, Int> = mutableMapOf()
init {
compounds.forEach { (key, value) ->
when (key) {
"children" -> this.compounds[CHILDREN] = value
"cats" -> this.compounds[CATS] = value
"samoyeds" -> this.compounds[SAMOYEDS] = value
"pomeranians" -> this.compounds[POMERANIANS] = value
"akitas" -> this.compounds[AKITAS] = value
"vizslas" -> this.compounds[VIZSLAS] = value
"goldfish" -> this.compounds[GOLDFISH] = value
"trees" -> this.compounds[TREES] = value
"cars" -> this.compounds[CARS] = value
"perfumes" -> this.compounds[PERFUMES] = value
}
}
}
enum class Compound {
AKITAS,
CARS,
CATS,
CHILDREN,
GOLDFISH,
PERFUMES,
POMERANIANS,
SAMOYEDS,
TREES,
VIZSLAS
}
}
}
| 0 | Kotlin | 0 | 3 | acc4dceb69350c04f6ae42fc50315745f728cce1 | 5,128 | advent-of-code | MIT License |
src/Day21.kt | MartinsCode | 572,817,581 | false | {"Kotlin": 77324} | fun parseName(text: String): String {
return text.split(": ")[0]
}
fun parseTask(text: String): String {
return text.split(": ")[1]
}
fun isOperation(text: String): Boolean {
return (text.contains(" + ") || text.contains(" - ") || text.contains(" * ") || text.contains(" / "))
}
fun findOperand1(calc: String): String {
return calc.split(" ")[0]
}
fun findOperand2(calc: String): String {
return calc.split(" ")[2]
}
fun findOperator(calc: String): String {
return calc.split(" ")[1]
}
fun main() {
fun part1(input: List<String>): Long {
val results = mutableMapOf<String, Long>()
val calculations = mutableMapOf<String, String>()
input.forEach {
val name = parseName(it)
val task = parseTask(it)
if (isOperation(task)) {
calculations[name] = task
} else {
results[name] = task.toLong()
}
}
while (!results.keys.contains("root")) {
calculations.keys.forEach {
val calculation = calculations[it]!!
val oper1 = findOperand1(calculation)
val oper2 = findOperand2(calculation)
// check, if both results are already present!
if (results.keys.contains(oper1) && results.keys.contains(oper2)) {
// YEAH!
val result = when (findOperator(calculation)) {
"+" -> results[oper1]!! + results[oper2]!!
"-" -> results[oper1]!! - results[oper2]!!
"*" -> results[oper1]!! * results[oper2]!!
"/" -> results[oper1]!! / results[oper2]!!
else -> throw(Exception("wrong operator!"))
}
results[it] = result
// calculations.remove(it)
}
}
}
return results["root"]!!
}
fun part2(input: List<String>): Long {
val results = mutableMapOf<String, Long>()
val calculations = mutableMapOf<String, String>()
input.forEach {
val name = parseName(it)
val task = parseTask(it)
if (isOperation(task)) {
calculations[name] = task
} else {
results[name] = task.toLong()
}
}
results.remove("humn")
results["root"] = 42
calculations.remove("humn")
calculations["root"] = "${findOperand1(calculations["root"]!!)} = ${findOperand2(calculations["root"]!!)}"
while (!results.keys.contains("humn")) {
println("Resolving calculations ... ${calculations.size} left!")
println(calculations)
val toBeRemoved = mutableListOf<String>()
calculations.keys.forEach {
val calculation = calculations[it]!!
val oper1 = findOperand1(calculation)
val oper2 = findOperand2(calculation)
// check, if both results are already present!
if (results.keys.contains(oper1) && results.keys.contains(oper2)) {
// YEAH!
val result = when (findOperator(calculation)) {
"+" -> results[oper1]!! + results[oper2]!!
"-" -> results[oper1]!! - results[oper2]!!
"*" -> results[oper1]!! * results[oper2]!!
"/" -> results[oper1]!! / results[oper2]!!
else -> throw(Exception("wrong operator!"))
}
results[it] = result
toBeRemoved.add(it)
// calculations.remove(it)
}
// check, if one operand and key are already present, so we can track backwards
if (results.keys.contains(it) && results.keys.contains(oper1)) {
val result = when (findOperator(calculation)) {
"+" -> results[it]!! - results[oper1]!!
"-" -> results[oper1]!! - results[it]!!
"*" -> results[it]!! / results[oper1]!!
"/" -> results[oper1]!! / results[it]!!
"=" -> results[oper1]!!
else -> throw(Exception("wrong operator!"))
}
results[oper2] = result
toBeRemoved.add(it)
}
if (results.keys.contains(it) && results.keys.contains(oper2)) {
val result = when (findOperator(calculation)) {
"+" -> results[it]!! - results[oper2]!!
"-" -> results[oper2]!! + results[it]!!
"*" -> results[it]!! / results[oper2]!!
"/" -> results[oper2]!! * results[it]!!
"=" -> results[oper2]!!
else -> throw(Exception("wrong operator!"))
}
results[oper1] = result
toBeRemoved.add(it)
}
}
toBeRemoved.forEach{
calculations.remove(it)
}
}
return results["humn"]!!
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day21-TestInput")
println("Testing part 1 ...")
check(part1(testInput) == 152L)
println("Testing part 2 ...")
check(part2(testInput) == 301L)
val input = readInput("Day21-Input")
println("Calculating part 1 ...")
println(part1(input))
println("Calculating part 2 ...")
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 1aedb69d80ae13553b913635fbf1df49c5ad58bd | 5,745 | AoC-2022-12-01 | Apache License 2.0 |
src/Day01.kt | sungi55 | 574,867,031 | false | {"Kotlin": 23985} | fun main() {
val day = "Day01"
fun part1(input: String): Int = input.sumTopOfCalories(1)
fun part2(input: String): Int = input.sumTopOfCalories(3)
val testInput = readInputText(name = "${day}_test")
val input = readInputText(name = day)
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
println(part1(input))
println(part2(input))
}
private fun String.sumTopOfCalories(top: Int) =
split("\n\n")
.map { it.sumCaloriesInGroup() }
.sortedDescending()
.take(top)
.sum()
private fun String.sumCaloriesInGroup() = lines().sumOf { calorie -> calorie.toInt() }
| 0 | Kotlin | 0 | 0 | 2a9276b52ed42e0c80e85844c75c1e5e70b383ee | 648 | aoc-2022 | Apache License 2.0 |
Kotlin for Java Developers/Week 2/Mastermind/Task/src/mastermind/playMastermind.kt | Jatin-8898 | 179,338,476 | false | {"Jupyter Notebook": 2864151, "HTML": 502909, "MATLAB": 289940, "Kotlin": 93513, "Python": 27760, "CSS": 18638, "JavaScript": 17671, "Rich Text Format": 15630, "Java": 13100, "C++": 9237, "C#": 1784} | package mastermind
/*import kotlin.random.Random*/
import java.util.Random
val ALPHABET = 'A'..'F'
const val CODE_LENGTH = 4
fun main() {
val differentLetters = false
playMastermind(differentLetters)
}
fun playMastermind(
differentLetters: Boolean,
secret: String = generateSecret(differentLetters)
) {
var evaluation: Evaluation
do {
print("Your guess: ")
var guess = readLine()!!
while (hasErrorsInInput(guess)) {
println("Incorrect input: $guess. " +
"It should consist of $CODE_LENGTH characters from $ALPHABET. " +
"Please try again.")
guess = readLine()!!
}
evaluation = evaluateGuess(secret, guess)
if (evaluation.isComplete()) {
println("The guess is correct!")
} else {
println("Right positions: ${evaluation.rightPosition}; " +
"wrong positions: ${evaluation.wrongPosition}.")
}
} while (!evaluation.isComplete())
}
fun Evaluation.isComplete(): Boolean = rightPosition == CODE_LENGTH
fun hasErrorsInInput(guess: String): Boolean {
val possibleLetters = ALPHABET.toSet()
return guess.length != CODE_LENGTH || guess.any { it !in possibleLetters }
}
fun generateSecret(differentLetters: Boolean): String {
val chars = ALPHABET.toMutableList()
return buildString {
for (i in 1..CODE_LENGTH) {
val letter = chars[Random().nextInt(chars.size)]
append(letter)
if (differentLetters) {
chars.remove(letter)
}
}
}
}
| 50 | Jupyter Notebook | 6 | 22 | 1b507a3f5a4f6a21ac480a2cf994d51a6f3767a8 | 1,635 | coursera | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/KInversePairsArray.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 dev.shtanko.algorithms.MOD
import dev.shtanko.algorithms.leetcode.KInversePairsArray.Companion.DEFAULT_ARRAY_SIZE
import kotlin.math.min
/**
* 629. K Inverse Pairs Array
* @see <a href="https://leetcode.com/problems/k-inverse-pairs-array">Source</a>
*/
fun interface KInversePairsArray {
operator fun invoke(length: Int, numberOfPairs: Int): Int
companion object {
const val DEFAULT_ARRAY_SIZE = 1001
}
}
/**
* Approach 2: Using Recursion with Memoization
*/
class KInversePairsArrayRecursion : KInversePairsArray {
private var memo = Array(DEFAULT_ARRAY_SIZE) { arrayOfNulls<Int>(DEFAULT_ARRAY_SIZE) }
override fun invoke(length: Int, numberOfPairs: Int): Int {
if (length == 0) return 0
if (numberOfPairs == 0) return 1
if (memo[length][numberOfPairs] != null) return memo[length][numberOfPairs] ?: -1
var inversePairsCount = 0
for (i in 0..min(numberOfPairs, length - 1)) {
inversePairsCount = (inversePairsCount + invoke(length - 1, numberOfPairs - i)) % MOD
}
memo[length][numberOfPairs] = inversePairsCount
return inversePairsCount
}
}
/**
* Approach 3: Dynamic Programming
*/
class KInversePairsArrayDP : KInversePairsArray {
override fun invoke(length: Int, numberOfPairs: Int): Int {
val dpTable = Array(length + 1) { IntArray(numberOfPairs + 1) }
for (i in 1..length) {
for (j in 0..numberOfPairs) {
if (j == 0) {
dpTable[i][j] = 1
} else {
for (p in 0..min(j, i - 1)) {
dpTable[i][j] = (dpTable[i][j] + dpTable[i - 1][j - p]) % MOD
}
}
}
}
return dpTable[length][numberOfPairs]
}
}
/**
* Approach 4: Dynamic Programming with Cumulative Sum
*/
class CumulativeSum : KInversePairsArray {
override fun invoke(length: Int, numberOfPairs: Int): Int {
val dp = Array(length + 1) { IntArray(numberOfPairs + 1) }
for (i in 1..length) {
for (j in 0..numberOfPairs) {
if (j == 0) {
dp[i][j] = 1
} else {
val value = (
dp[i - 1][j] + MOD - if (j - i >= 0) {
dp[i - 1][j - i]
} else {
0
}
) % MOD
dp[i][j] = (dp[i][j - 1] + value) % MOD
}
}
}
return (dp[length][numberOfPairs] + MOD - if (numberOfPairs > 0) dp[length][numberOfPairs - 1] else 0) % MOD
}
}
/**
* Approach 5: Another Optimized Dynamic Programming Approach
*/
class KInversePairsArrayOptimizedDP : KInversePairsArray {
override operator fun invoke(length: Int, numberOfPairs: Int): Int {
val dp = Array(length + 1) { IntArray(numberOfPairs + 1) }
for (i in 1..length) {
var counter = 0
while (counter <= numberOfPairs && counter <= i * (i - 1) / 2) {
if (i == 1 && counter == 0) {
dp[i][counter] = 1
break
} else if (counter == 0) {
dp[i][counter] = 1
} else {
val value =
(dp[i - 1][counter] + MOD - if (counter - i >= 0) dp[i - 1][counter - i] else 0) % MOD
dp[i][counter] = (dp[i][counter - 1] + value) % MOD
}
counter++
}
}
return dp[length][numberOfPairs]
}
}
/**
* Approach 6: Once Again Memoization
*/
class KInversePairsArrayMemoization : KInversePairsArray {
private var memoizationTable = Array(DEFAULT_ARRAY_SIZE) { arrayOfNulls<Int>(DEFAULT_ARRAY_SIZE) }
override fun invoke(length: Int, numberOfPairs: Int): Int {
val res = computeInversePairs(length, numberOfPairs) + MOD - if (numberOfPairs > 0) {
computeInversePairs(length, numberOfPairs - 1)
} else {
0
}
return res % MOD
}
private fun computeInversePairs(n: Int, k: Int): Int {
if (n == 0) return 0
if (k == 0) return 1
if (memoizationTable[n][k] != null) return memoizationTable[n][k] ?: -1
val value: Int =
(computeInversePairs(n - 1, k) + MOD - if (k - n >= 0) computeInversePairs(n - 1, k - n) else 0) % MOD
memoizationTable[n][k] = (computeInversePairs(n, k - 1) + value) % MOD
return memoizationTable[n][k] ?: -1
}
}
/**
* Approach 7: 1-D Dynamic Programming
*/
class KInversePairsArrayDP1D : KInversePairsArray {
override fun invoke(length: Int, numberOfPairs: Int): Int {
var dp = IntArray(numberOfPairs + 1)
for (i in 1..length) {
val tempDp = IntArray(numberOfPairs + 1)
tempDp[0] = 1
for (j in 1..numberOfPairs) {
val value = (dp[j] + MOD - if (j - i >= 0) dp[j - i] else 0) % MOD
tempDp[j] = (tempDp[j - 1] + value) % MOD
}
dp = tempDp
}
return (dp[numberOfPairs] + MOD - if (numberOfPairs > 0) dp[numberOfPairs - 1] else 0) % MOD
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 5,932 | kotlab | Apache License 2.0 |
advent-of-code-2021/src/main/kotlin/Day14.kt | jomartigcal | 433,713,130 | false | {"Kotlin": 72459} | //Day 14: Extended Polymerization
//https://adventofcode.com/2021/day/14
import java.io.File
fun main() {
val lines = File("src/main/resources/Day14.txt").readLines()
val template = lines.first()
val rules = lines.drop(2).associate {
val (adjacentElements, insertElement) = it.split(" -> ")
adjacentElements to insertElement
}
polymerize(template, rules, 10)
polymerize(template, rules, 40)
}
fun polymerize(template: String, rules: Map<String, String>, steps: Int) {
val list = template.windowed(2).toMutableList()
val map = list.groupingBy { it }.eachCount().mapValues { it.value.toLong() }.toMutableMap()
repeat(steps) {
val tempMap = map.filterValues { it > 0 }
for (key in tempMap.keys.toList()) {
val insert = rules[key]
val count = tempMap.getOrDefault(key, 0L)
map[key] = map.getOrDefault(key, 0L) - count
map["${key.first()}$insert"] = map.getOrDefault("${key.first()}$insert", 0L) + count
map["$insert${key.last()}"] = map.getOrDefault("$insert${key.last()}", 0L) + count
}
}
val letterMap = mutableMapOf<Char, Long>()
map.onEach { item ->
letterMap[item.key.last()] = letterMap.getOrDefault(item.key.last(), 0L) + item.value
}
letterMap[list.first().first()] = letterMap.getOrDefault(list.first().first(), 0L) + 1L
println(letterMap.maxOf { it.value } - letterMap.minOf { it.value })
}
| 0 | Kotlin | 0 | 0 | 6b0c4e61dc9df388383a894f5942c0b1fe41813f | 1,473 | advent-of-code | Apache License 2.0 |
Kotlin/sort/QuickSort/src/QuickSort.kt | HarshCasper | 274,711,817 | false | {"C++": 1488046, "Java": 948670, "Python": 703942, "C": 615475, "JavaScript": 228879, "Go": 166382, "Dart": 107821, "Julia": 82766, "C#": 76519, "Kotlin": 40240, "PHP": 5465} | /*
QuickSort Algortihm works on Divide and Conquer Algorithm. It creates two empty arrays to hold elements less than the pivot value and
elements greater than the pivot value, and then recursively sort the sub arrays. There are two basic operations in the algorithm,
swapping items in place and partitioning a section of the array.
*/
//Importing the Java.util package, it is needed because we are using the scanner object.
import java.util.*
//The function which will sort the given array in ascending order using QuickSort Algortihm
fun quicksort(items:List<Int>):List<Int>{
//If there is only one element in the list, then there is no need to sort
if (items.count() < 2){
return items
}
//Vaiable pivot stores the index of middle element of the list
val pivot = items[items.count()/2]
//Variable equalto stores the elements at the pivot index
val equalto = items.filter { it == pivot }
//Variable lesser stores the list of element with indexes less than the pivot index
val lesser = items.filter { it < pivot }
//Variable greater stores the list of element with indexes less than the pivot index
val greater = items.filter { it > pivot }
//Calling the quicksort function recursively on the splitted arrays
//This will get recursively called until left with multiple arrays with a single element and arranged in order
return quicksort(lesser) + equalto + quicksort(greater)
}
//Main Driver Code
fun main() {
val input = Scanner(System.`in`)
println("Enter the length of the array")
val arrayLength = input.nextInt()
val arrayOfElements = arrayListOf<Int>()
println("Enter the List of numbers you want to Sort:")
for(index in 0 until arrayLength) {
val element = input.nextInt()
arrayOfElements.add(element)
}
print("Original List: ")
for(index in 0..4)
{
val number: Int = arrayOfElements[index]
print("$number\t")
}
print("\nOrdered list: ")
val ordered = quicksort(arrayOfElements)
println(ordered)
}
/*
First Testcasee:
Enter the length of the array
6
Enter the List of numbers you want to Sort:
34
33
67
3
2
45
Original List: 34 33 67 3 2 45
Ordered list: [2, 3, 33, 34, 45, 67]
Time Complexity: O(n log n)
Space Complexity: O(log n)
*/ | 2 | C++ | 1,086 | 877 | 4f1e5bdd6d9d899fa354de94740e0aecf5ecd2be | 2,328 | NeoAlgo | MIT License |
14/kotlin/src/main/kotlin/se/nyquist/Rules.kt | erinyq712 | 437,223,266 | false | {"Kotlin": 91638, "C#": 10293, "Emacs Lisp": 4331, "Java": 3068, "JavaScript": 2766, "Perl": 1098} | package se.nyquist
class Rules(private val ruleMap: Map<String, Char>) {
fun getDistribution(i: Int, s: Map.Entry<String, Long>): Map<Char, Long> {
return getDistribution(i, s.key, s.value)
}
fun getDistribution(i: Int, s: String): Map<Char, Long> {
return getDistribution(i, s, 1L)
}
fun getDistribution(i: Int, s: String, freq: Long): Map<Char, Long> {
return if (i == 0) {
getCharacterDistribution(s, freq)
} else {
val pairs = getPairs(s)
val firstDistribution : Map<Char, Long> = getDistributionExcludingLast(i-1, pairs[0], freq)
val secondDistribution : Map<Char, Long> = getDistribution(i-1, pairs[1], freq)
mergeCharMaps(secondDistribution, firstDistribution)
}
}
fun mergeCharMaps(
secondDistribution: Map<Char, Long>,
firstDistribution: Map<Char, Long>
) : Map<Char, Long> {
val merged = firstDistribution.toMutableMap()
secondDistribution.entries.forEach{
if (merged.containsKey(it.key)) {
merged[it.key] = firstDistribution.getValue(it.key) + secondDistribution.getValue(it.key)
} else {
merged[it.key] = secondDistribution.getValue(it.key)
}
}
return merged
}
fun getDistributionExcludingLast(i: Int, s: String, freq: Long) : Map<Char, Long> {
return if (i == 0) {
getCharacterDistribution(s.substring(0, 1), freq)
} else {
val pairs = getPairs(s)
val firstDistribution : Map<Char, Long> = getDistributionExcludingLast(i-1, pairs[0], freq)
val secondDistribution : Map<Char, Long> = getDistributionExcludingLast(i-1, pairs[1], freq)
mergeCharMaps(secondDistribution, firstDistribution)
}
}
fun getDistributionExcludingLast(i: Int, s: Map.Entry<String, Long>): Map<Char, Long> {
return getDistributionExcludingLast(i, s.key, s.value)
}
private fun getCharacterDistribution(
s: String,
freq: Long
) = s.toList().groupingBy { it }.fold(0L) { acc, _ -> acc + freq }
private fun getPairs(key: String) : List<String> {
val s = key[0] + ruleMap[key].toString() + key[1]
return IntRange(0, s.lastIndex - 1).map { s.substring(it, it + 2) }.toList()
}
fun getValue(it: String): String {
return ruleMap[it].toString()
}
} | 0 | Kotlin | 0 | 0 | b463e53f5cd503fe291df692618ef5a30673ac6f | 2,456 | adventofcode2021 | Apache License 2.0 |
2023/src/main/kotlin/de/skyrising/aoc2023/day13/solution.kt | skyrising | 317,830,992 | false | {"Kotlin": 411565} | package de.skyrising.aoc2023.day13
import de.skyrising.aoc.*
val test = TestInput("""
#.##..##.
..#.##.#.
##......#
##......#
..#.##.#.
..##..##.
#.#.##.#.
#...##..#
#....#..#
..##..###
#####.##.
#####.##.
..##..###
#....#..#
""")
fun CharGrid.checkVertical(x: Int) = (0..<minOf(x, width - x)).sumOf {
(0..<height).count { y -> this[x - it - 1, y] != this[x + it, y] }
}
fun CharGrid.checkHorizontal(y: Int) = (0..<minOf(y, height - y)).sumOf {
(0..<width).count { x -> this[x, y - it - 1] != this[x, y + it] }
}
@PuzzleName("Point of Incidence")
fun PuzzleInput.part1() = lines.splitOnEmpty().sumOf {
CharGrid.parse(it).run {
val xm = (1 until width).firstOrNull { x -> checkVertical(x) == 0 } ?: 0
val ym = (1 until height).firstOrNull { y -> checkHorizontal(y) == 0 } ?: 0
xm + ym * 100
}
}
fun PuzzleInput.part2() = lines.splitOnEmpty().sumOf {
CharGrid.parse(it).run {
val xm = (1 until width).firstOrNull { x -> checkVertical(x) == 1 } ?: 0
val ym = (1 until height).firstOrNull { y -> checkHorizontal(y) == 1 } ?: 0
xm + ym * 100
}
}
| 0 | Kotlin | 0 | 0 | 19599c1204f6994226d31bce27d8f01440322f39 | 1,180 | aoc | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/AverageOfSubtree.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
/**
* 2265. Count Nodes Equal to Average of Subtree
* @see <a href="https://leetcode.com/problems/count-nodes-equal-to-average-of-subtree">Source</a>
*/
fun interface AverageOfSubtree {
operator fun invoke(root: TreeNode?): Int
}
sealed interface AverageOfSubtreeStrategy {
/**
* Approach: Depth First Search (DFS)
*/
data object DFS : AverageOfSubtree, AverageOfSubtreeStrategy {
private var result = 0
override fun invoke(root: TreeNode?): Int {
result = 0
visitNode(root!!)
return result
}
private fun visitNode(node: TreeNode?): Int {
var nodes = 1
val value = node?.value
if (node?.left != null) {
nodes += visitNode(node.left)
node.value += node.left!!.value
}
if (node?.right != null) {
nodes += visitNode(node.right)
node.value += node.right!!.value
}
if (value == node!!.value / nodes) {
result++
}
return nodes
}
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,766 | kotlab | Apache License 2.0 |
app/src/main/java/com/dlight/algoguide/dsa/dynamic_programming/Longest_Common_Subsequence/lcs.kt | kodeflap | 535,790,826 | false | {"Kotlin": 129527} | package com.dlight.algoguide.dsa.dynamic_programming.Longest_Common_Subsequence
import java.util.*
object lcs {
@JvmStatic
fun main(args: Array<String>) {
val s1 = "abcde"
val s2 = "ace"
println("The Length of Longest Common Subsequence is " + longestCommonSubsequence(s1, s2))
}
private fun longestCommonSubsequence(s1: String, s2: String): Int {
val n = s1.length
val m = s2.length
val dp = Array(n + 1) {
IntArray(
m + 1
)
}
for (rows in dp) {
Arrays.fill(rows, -1)
}
for (i in 0..n) {
dp[i][0] = 0
}
for (i in 0..m) {
dp[0][i] = 0
}
for (ind1 in 0..n) {
for (ind2 in 0..m) {
if (s1[ind1] == s2[ind2]) {
dp[ind1][ind2] = 1 + dp[ind1 - 1][ind2 - 1]
} else {
dp[ind1][ind2] = Math.max(dp[ind1 - 1][ind2], dp[ind1][ind2 - 1])
}
}
}
return dp[n][m]
}
}
| 0 | Kotlin | 9 | 10 | c4a7ddba54daecb219a1befa12583e3e8f3fa066 | 1,091 | Algo_Guide | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.