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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
lib/src/main/kotlin/io/nexure/fsm/StateMachineValidator.kt | venture-falcon | 532,830,962 | false | {"Kotlin": 24164, "Makefile": 53} | package io.nexure.fsm
import java.util.Deque
import java.util.LinkedList
internal object StateMachineValidator {
fun <S : Any, E : Any> validate(initialState: S, transitions: List<Edge<S, E>>) {
rejectDuplicates(transitions)
findIllegalCombinations(transitions)
isConnected(initialState, transitions)
}
/**
* Check so a combination of source state, target state and event is not defined more than once
*/
private fun <S : Any, E : Any> rejectDuplicates(transitions: List<Edge<S, E>>) {
val duplicate: Edge<S, E>? = transitions
.duplicatesBy { Triple(it.source, it.target, it.event) }
.firstOrNull()
validate(duplicate == null) {
val (initialState, targetState, byEvent) = duplicate!!
"Transition from $initialState to $targetState via $byEvent occurs twice"
}
}
/**
* Verify that no invalid combinations of transitions are present. Example of such invalid
* combination would be where two edges (connections) with the same source state and same event
* has a different target state, like;
*
* Transition 0: S0 --> E0 --> S1
* Transition 1: S0 --> E0 --> S2
*
* These two transitions would not be allowed to exist in the same state machine at the same
* time.
*/
private fun <S : Any, E : Any> findIllegalCombinations(transitions: List<Edge<S, E>>) {
val illegal: Edge<S, E>? = transitions
.groupBy { it.source }
.filter { it.value.size > 1 }
.map { x -> x.value.map { y -> x.value.map { it to y } } }
.flatten()
.flatten()
.firstOrNull { illegalCombination(it.first, it.second) }
?.first
validate(illegal == null) {
val initialState = illegal!!.source
val byEvent = illegal.event
"Transition from $initialState via $byEvent occurs twice"
}
}
/**
* Return true if this edge and other edge has the same source
* and event but different target, since a source state which is triggered
* by a specific event should always result in the same target state.
*/
private fun <S : Any, E : Any> illegalCombination(e0: Edge<S, E>, e1: Edge<S, E>): Boolean {
if (e0 === e1) {
return false
}
val sameSource: Boolean = e0.source == e1.source
val sameTarget: Boolean = e0.target == e1.target
val sameEvent: Boolean = e0.event == e1.event
return sameSource && sameEvent && !sameTarget
}
/**
* Validate the configuration of the state machine, making sure that state machine is connected
*/
private fun <S : Any, E : Any> isConnected(initialState: S, transitions: List<Edge<S, E>>) {
val stateTransitions: Map<S?, Set<S>> = transitions
.groupBy { it.source }
.mapValues { it.value.map { value -> value.target }.toSet() }
.toMap()
val allNodes: Collection<S> = stateTransitions.keys.filterNotNull() + stateTransitions.values.flatten()
val uniqueNodes: Int = allNodes.distinct().size
validateIsConnected(initialState, stateTransitions, uniqueNodes)
}
/**
* Make sure that the graph representing the state machine is connected. In other words, all states
* of the state machine must be able to reach through a series of valid transitions according to
* this state machine.
*/
private tailrec fun <S : Any> validateIsConnected(
initialState: S,
transitions: Map<S?, Set<S>>,
target: Int,
visited: Set<S> = setOf(initialState),
toVisit: Deque<S> = LinkedList(transitions.getOrDefault(initialState, emptyList()))
) {
validate(visited.size == target || toVisit.isNotEmpty()) {
val remainingNodes: List<S> = transitions.keys.filterNotNull()
"Unable to reach nodes in state machine: $remainingNodes"
}
if (visited.size == target) {
return
} else {
val current: S = toVisit.pop()
val next: Collection<S> = transitions.getOrDefault(current, emptyList())
toVisit.addAll(next)
validateIsConnected(
initialState,
transitions = transitions - current,
target = target,
visited = visited + current,
toVisit = toVisit
)
}
}
}
class InvalidStateMachineException(override val message: String) : Exception()
private inline fun validate(predicate: Boolean, message: () -> String) {
if (!predicate) {
throw InvalidStateMachineException(message())
}
}
private fun <T, R> Iterable<T>.duplicatesBy(keySelector: (T) -> R): Iterable<T> =
this.groupBy(keySelector)
.filter { it.value.size > 1 }
.map { it.value.first() }
| 0 | Kotlin | 0 | 0 | aa12b389ad0e8c0650868d28383ada5f5d6286c0 | 4,930 | fsm | MIT License |
subprojects/common/graph/src/main/kotlin/com/avito/graph/ShortestPath.kt | avito-tech | 230,265,582 | false | {"Kotlin": 3574228, "Java": 67252, "Shell": 27656, "Dockerfile": 12799, "Makefile": 7970} | package com.avito.graph
import org.jgrapht.Graph
import org.jgrapht.GraphPath
import org.jgrapht.alg.shortestpath.BellmanFordShortestPath
import org.jgrapht.graph.DefaultWeightedEdge
import org.jgrapht.graph.DirectedWeightedMultigraph
/**
* @operations nodes describing a DAG
*/
public class ShortestPath<T : Operation>(private val operations: Set<T>) {
private val operationByKey: Map<String, Operation> = operations.map { it.id to it }.toMap()
private val syntheticSource = SimpleOperation("source", duration = 0.toDouble())
private val syntheticSink = SimpleOperation("sink", duration = 0.toDouble())
private val uniquePredecessors = operations.flatMap { it.predecessors }.toSet()
public fun find(): OperationsPath<T> {
if (operations.size <= 1) return OperationsPath(operations.toList())
val graph = build()
val path = graph.shortestPath()
@Suppress("UNCHECKED_CAST")
val operations = path.vertexList
.filterNot { it.isSynthetic() } as List<T>
return OperationsPath(operations)
}
/***
* Builds a graph to find the shortest path.
* Let's see by example. We have operations:
*
* - `A(duration = 1, predecessors = ())`
* - `B(duration = 2, predecessors = (A))`
*
* To calculate the shortest path these operations will be represented as graph:
*
* ```
* vertex SYNTHETIC SOURCE <--- vertex A <---(edge weight = 1)--- vertex B <---(edge weight = 2)--- vertex SYNTHETIC SINK
* ```
*
* Operation A and B become vertexes in graph.
* Durations of operations become edges weights.
*
* Synthetic vertexes for source and sink are needed mostly due to performance reasons.
* Graph can contain multiple sources and sinks. It's cheaper to calculate only one path from single source to single sink.
*
* Let's see on more complex case:
*
* ```
* operation A(duration = 1) <--------------┐
* │
* operation B(duration = 2) <--- operation D(duration = 4) <--- operation E(duration = 1)
*
* operation F(duration = 3) <--- operation G(duration = 2)
* ```
*
* Sources: A, B, F
* Sinks: E, G
*
* These operations will be represented as graph:
*
* ```
* ┌--------- vertex A <--(edge weight = 1)---------┐
* ↓ │
* SYNTHETIC SOURCE <---- vertex B <--(edge weight = 2)-- vertex D <--(edge weight = 4)-- vertex E <--(edge weight = 1)-- SYNTHETIC SINK
* ↑ │
* └--------- vertex F <--(edge weight = 3)------------- vertex G <--(edge weight = 2)------------------------------┘
* ```
*/
private fun build(): Graph<Operation, DefaultWeightedEdge> {
val graph: Graph<Operation, DefaultWeightedEdge> =
DirectedWeightedMultigraph(DefaultWeightedEdge::class.java)
addNodes(graph)
addSource(graph)
addSink(graph)
checkGraphStructure(graph)
return graph
}
private fun Graph<Operation, DefaultWeightedEdge>.shortestPath(): GraphPath<Operation, DefaultWeightedEdge> {
// We could use negative weights to find the shortest path as solution for the longest path in DAG
// Bellman–Ford algorithm supports negative weights but Dijkstra doesn't.
// TODO: try topological sorting, it will be more efficient - O(V+E) instead of O(V*E)
return BellmanFordShortestPath(this)
.getPaths(syntheticSource)
.getPath(syntheticSink)
}
private fun checkGraphStructure(graph: Graph<Operation, DefaultWeightedEdge>) {
checkSinkLinks(graph)
checkSourceLinks(graph)
}
private fun checkSinkLinks(graph: Graph<Operation, DefaultWeightedEdge>) {
graph.incomingEdgesOf(syntheticSink).forEach { edge ->
val sinkNode = graph.getEdgeSource(edge)
check(sinkNode.isSink() && !sinkNode.isSynthetic()) {
"Expected structure: ... <-- node <-- node <-- sink <-- synthetic sink"
}
}
}
private fun checkSourceLinks(graph: Graph<Operation, DefaultWeightedEdge>) {
graph.outgoingEdgesOf(syntheticSource).forEach { edge ->
val sourceNode = graph.getEdgeTarget(edge)
check(sourceNode.isSource() && !sourceNode.isSynthetic()) {
"Expected structure: synthetic source <-- source <-- node <-- node <-- ..."
}
}
}
private fun addNodes(graph: Graph<Operation, DefaultWeightedEdge>) {
operations.forEach { node ->
graph.addVertex(node)
}
operations.forEach { node ->
node.findDependencies().forEach { dependency ->
graph.addWeightedEdge(dependency, node)
}
}
}
private fun addSource(graph: Graph<Operation, DefaultWeightedEdge>) {
graph.addVertex(syntheticSource)
operations
.filter { it.isSource() }
.forEach { source ->
graph.addWeightedEdge(syntheticSource, source)
}
}
private fun addSink(graph: Graph<Operation, DefaultWeightedEdge>) {
graph.addVertex(syntheticSink)
operations
.filter { it.isSink() }
.forEach { sink ->
graph.addWeightedEdge(sink, syntheticSink)
}
}
private fun Graph<Operation, DefaultWeightedEdge>.addWeightedEdge(
from: Operation,
to: Operation
) {
addEdge(from, to)
setEdgeWeight(from, to, from.duration)
}
private fun Operation.findDependencies(): List<Operation> {
// Skip missing nodes
return predecessors.mapNotNull { dependencyKey ->
operationByKey[dependencyKey]
}
}
private fun Operation.isSink(): Boolean {
return !uniquePredecessors.contains(this.id)
}
private fun Operation.isSource() =
predecessors.isEmpty()
/**
* Synthetically added operation
*/
private fun Operation.isSynthetic(): Boolean =
this == syntheticSource || this == syntheticSink
}
| 10 | Kotlin | 48 | 390 | 9d60abdd26fc779dd57aa4f1ad51658b6a245d1e | 6,361 | avito-android | MIT License |
src/lib/Geometry.kt | HGilman | 572,891,570 | false | {"Kotlin": 109639, "C++": 5375, "Python": 400} | package lib
import kotlin.math.abs
import kotlin.math.sign
import kotlin.math.sqrt
data class Point2D(val x: Int, val y: Int) {
override fun toString(): String {
return "x: $x, y: $y"
}
fun toRight() = Point2D(x + 1, y)
fun toLeft() = Point2D(x - 1, y)
fun higher() = Point2D(x, y + 1)
fun lower() = Point2D(x, y - 1)
fun follow(p: Point2D): Point2D {
val dx = (p.x - x).sign
val dy = (p.y - y).sign
return Point2D(x + dx, y + dy)
}
fun distanceTo(p: Point2D): Double {
return distance(this, p)
}
operator fun plus(vec: Vector2D): Point2D {
return Point2D(x + vec.x, y + vec.y)
}
operator fun minus(other: Point2D): Vector2D {
return Vector2D(x - other.x, y - other.y)
}
fun manhattanDistanceTo(p: Point2D): Int {
return abs(p.x - x) + abs(p.y - y)
}
companion object {
fun distance(p1: Point2D, p2: Point2D): Double {
return sqrt((p2.x.toDouble() - p1.x) * (p2.x - p1.x) + (p2.y - p1.y) * (p2.y - p1.y))
}
}
}
data class Vector2D(val x: Int, val y: Int)
val LeftDirection = Vector2D(-1, 0)
val RightDirection = Vector2D(1, 0)
val IncreaseYDirection = Vector2D(0, 1)
val DecreaseYDirection = Vector2D(0, -1)
val directionsClockwise = listOf<Vector2D>(
RightDirection, IncreaseYDirection, LeftDirection, DecreaseYDirection
)
/**
* @param s - start point
* @param e - end point
*/
data class Segment(val s: Point2D, val e: Point2D) {
fun intersects(other: Segment): List<PrecisePoint> {
val k1 = (e.y.toDouble() - s.y) / (e.x - s.x)
val k2 = (other.e.y.toDouble() - other.s.y) / (other.e.x - other.s.x)
val b1 = s.y - k1 * s.x
val b2 = other.s.y - k2 * other.s.x
if (k1 == k2 && b1 == b2) {
val res = mutableListOf<PrecisePoint>()
if (other.s.x in (s.x.. e.x)) {
res.add(PrecisePoint(other.s.x.toDouble(), other.s.y.toDouble()))
}
if (other.e.x in (s.x.. e.x)) {
res.add(PrecisePoint(other.e.x.toDouble(), other.e.y.toDouble()))
}
if (s.x in (other.s.x.. other.e.x)) {
res.add(PrecisePoint(s.x.toDouble(), s.y.toDouble()))
}
if (e.x in (other.s.x.. other.e.x)) {
res.add(PrecisePoint(e.x.toDouble(), e.y.toDouble()))
}
return res
}
val x = (b2 - b1) / (k1 - k2)
val y = b1 + k1 * x
return if ((x >= s.x && x <= e.x) && (x >= other.s.x && x <= other.e.x)) {
listOf(PrecisePoint(x, y))
} else {
emptyList()
}
}
}
/**
* Suppose path goes only vertically or horizontally, but not by diagonal
* */
data class Path(val points: List<Point2D>) {
fun getAllPoints(): List<Point2D> {
val res = mutableListOf<Point2D>()
if (points.isEmpty()) {
return res
}
var prevPoint = points.first()
res.add(prevPoint)
for (p in points.drop(1)) {
if (p == prevPoint) {
continue
}
var followPoint = prevPoint.follow(p)
while (followPoint != p) {
res.add(followPoint)
followPoint = followPoint.follow(p)
}
res.add(followPoint)
prevPoint = p
}
return res
}
}
data class PrecisePoint(val x: Double, val y: Double) | 0 | Kotlin | 0 | 1 | d05a53f84cb74bbb6136f9baf3711af16004ed12 | 3,516 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/HouseRobber.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
fun interface AbstractRobber {
operator fun invoke(arr: IntArray): Int
}
/**
* Figure out recursive relation.
* A robber has 2 options: a) rob current house i; b) don't rob current house.
* If an option "a" is selected it means she can't rob previous i-1 house but can safely proceed to the one before
* previous i-2 and gets all cumulative loot that follows.
* If an option "b" is selected the robber gets all the possible loot from robbery of i-1 and all the
* following buildings.
* So it boils down to calculating what is more profitable:
* - robbery of current house + loot from houses before the previous
* - loot from the previous house robbery and any loot captured before that
*
* Recursive (top-down)
*/
class RecursiveRobber : AbstractRobber {
override operator fun invoke(arr: IntArray): Int {
return arr.rob(arr.size - 1)
}
private fun IntArray.rob(i: Int): Int {
if (i < 0) return 0
return kotlin.math.max(this.rob(i - 2) + this[i], this.rob(i - 1))
}
}
/**
* Recursive + memo (top-down).
* Much better, this should run in O(n) time. Space complexity is O(n) as well, because of the recursion stack
*/
class RecursiveRobberMemo : AbstractRobber {
private lateinit var memo: IntArray
override operator fun invoke(arr: IntArray): Int {
memo = IntArray(arr.size + 1) { -1 }
return arr.rob(arr.size - 1)
}
private fun IntArray.rob(i: Int): Int {
if (i < 0) {
return 0
}
if (memo[i] >= 0) {
return memo[i]
}
val result = kotlin.math.max(this.rob(i - 2) + this[i], this.rob(i - 1))
memo[i] = result
return result
}
}
/**
* Iterative + memo (bottom-up)
*/
class IterativeRobberMemo : AbstractRobber {
override operator fun invoke(arr: IntArray): Int {
if (arr.isEmpty()) return 0
val memo = IntArray(arr.size + 1)
memo[0] = 0
memo[1] = arr[0]
for (i in 1 until arr.size) {
val value = arr[i]
memo[i + 1] = kotlin.math.max(memo[i], memo[i - 1] + value)
}
return memo[arr.size]
}
}
/**
* Iterative + 2 variables (bottom-up)
*
* We can notice that in the previous step we use only memo[i] and memo[i-1], so going just 2 steps back.
* We can hold them in 2 variables instead. This optimization is met in Fibonacci sequence
* creation and some other problems
*/
class IterativeRobber : AbstractRobber {
override operator fun invoke(arr: IntArray): Int {
if (arr.isEmpty()) return 0
var prev1 = 0
var prev2 = 0
for (num in arr) {
val tmp = prev1
prev1 = kotlin.math.max(prev2 + num, prev1)
prev2 = tmp
}
return prev1
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 3,444 | kotlab | Apache License 2.0 |
src/main/kotlin/ru/nrcki/biokotlin/Distance.kt | laxeye | 164,879,760 | false | null | package ru.nrcki.biokotlin
import kotlin.math.abs
import kotlin.math.ln
import kotlin.math.sqrt
class Distance(){
fun rawDistance(seq1: IBioSequence, seq2: IBioSequence): Double {
if(seq1.gaplength == seq1.length) {
throw Exception("Error! Impossible to calculate distance: ${seq1.id} contains only gaps")
}
if(seq2.gaplength == seq2.length) {
throw Exception("Error! Impossible to calculate distance: ${seq2.id} contains only gaps")
}
var matches = 0
var positions = 0
for(i in 0 until seq1.length){
if (seq1.sequence[i] == seq2.sequence[i]){
if(seq1.sequence[i] != '-'){
positions += 1
matches += 1
}
}else{
positions += 1
}
}
return 1.0 - matches.toDouble()/positions.toDouble()
}
fun jcDistance(seq1: IBioSequence, seq2: IBioSequence, nucl: Boolean = true): Double {
val distance = rawDistance(seq1, seq2)
// Constant different for nucleotides and proteins
val b = if(nucl) 0.75 else 0.95
return -b * ln( 1 - distance / b )
}
fun poissonDistance(seq1: IBioSequence, seq2: IBioSequence): Double {
return abs( -ln( 1 - rawDistance(seq1, seq2) ) )
}
fun jcMatrix(alignment: List<IBioSequence>, nucl: Boolean = true){
for(i in 1 until alignment.size){
print(alignment[i].id)
for(j in 0 until i){
print("\t${jcDistance(alignment[i], alignment[j], nucl)}")
}
print("\n")
}
}
fun jcMeanDistance(alignment: List<IBioSequence>, nucl: Boolean = true){
alignment.forEach(){querySeq ->
print("${querySeq.id}\t")
println( alignment.map{jcDistance(querySeq,it,nucl)}.sum().div(alignment.size - 1) )
}
}
fun calcTransitions(seq1: IBioSequence, seq2: IBioSequence): Int {
var transitions = 0
for(i in 0 until seq1.length){
if( ( seq1.sequence[i] == 'A') && ( seq2.sequence[i] == 'G' ) ) transitions++
if( ( seq1.sequence[i] == 'G') && ( seq2.sequence[i] == 'A' ) ) transitions++
if( ( seq1.sequence[i] == 'C') && ( seq2.sequence[i] == 'T' ) ) transitions++
if( ( seq1.sequence[i] == 'C') && ( seq2.sequence[i] == 'U' ) ) transitions++
if( ( seq1.sequence[i] == 'T') && ( seq2.sequence[i] == 'C' ) ) transitions++
if( ( seq1.sequence[i] == 'U') && ( seq2.sequence[i] == 'C' ) ) transitions++
}
return transitions
}
fun calcTransversions(seq1: IBioSequence, seq2: IBioSequence): Int {
var transversions = 0
for(i in 0 until seq1.length){
if( ( seq1.sequence[i] == 'A') && ( seq2.sequence[i] == 'C' ) ) transversions++
if( ( seq1.sequence[i] == 'A') && ( seq2.sequence[i] == 'T' ) ) transversions++
if( ( seq1.sequence[i] == 'A') && ( seq2.sequence[i] == 'U' ) ) transversions++
if( ( seq1.sequence[i] == 'C') && ( seq2.sequence[i] == 'G' ) ) transversions++
if( ( seq1.sequence[i] == 'C') && ( seq2.sequence[i] == 'A' ) ) transversions++
if( ( seq1.sequence[i] == 'G') && ( seq2.sequence[i] == 'C' ) ) transversions++
if( ( seq1.sequence[i] == 'G') && ( seq2.sequence[i] == 'T' ) ) transversions++
if( ( seq1.sequence[i] == 'G') && ( seq2.sequence[i] == 'U' ) ) transversions++
if( ( seq1.sequence[i] == 'T') && ( seq2.sequence[i] == 'A' ) ) transversions++
if( ( seq1.sequence[i] == 'T') && ( seq2.sequence[i] == 'G' ) ) transversions++
if( ( seq1.sequence[i] == 'U') && ( seq2.sequence[i] == 'A' ) ) transversions++
if( ( seq1.sequence[i] == 'U') && ( seq2.sequence[i] == 'G' ) ) transversions++
}
return transversions
}
fun kimuraDistance(seq1: IBioSequence, seq2: IBioSequence): Double {
val transitions = calcTransitions(seq1, seq2).toDouble() / seq1.length
val transversions = calcTransversions(seq1, seq2).toDouble() / seq1.length
val distance = -0.5 * ln( (1.0 - 2 * transitions - transversions ) * sqrt( 1.0 - 2 * transversions ) )
return abs(distance)
}
fun tamuraDistance(seq1: IBioSequence, seq2: IBioSequence): Double {
val gc1 = seq1.sequence.getGCContent()
val gc2 = seq2.sequence.getGCContent()
val C = gc1 + gc2 - 2 * gc1 * gc2
val transitions = calcTransitions(seq1, seq2).toDouble() / seq1.length
val transversions = calcTransversions(seq1, seq2).toDouble() / seq1.length
val distance = -C * ln(1.0 - transitions / C - transversions) - 0.5 * (1.0 - C) * ln(1.0 - 2 * transversions)
return abs(distance)
}
} | 7 | Kotlin | 0 | 0 | fb86e738ee31a082bb71e2c8a73d34e65197f2eb | 4,242 | BioKotlin | MIT License |
day03/kotlin/corneil/src/main/kotlin/solution.kt | timgrossmann | 224,991,491 | true | {"HTML": 2739009, "Python": 169603, "Java": 157274, "Jupyter Notebook": 116902, "TypeScript": 113866, "Kotlin": 89503, "Groovy": 73664, "Dart": 47763, "C++": 43677, "CSS": 34994, "Ruby": 27091, "Haskell": 26727, "Scala": 11409, "Dockerfile": 10370, "JavaScript": 6496, "PHP": 4152, "Go": 2838, "Shell": 2493, "Rust": 2082, "Clojure": 567, "Tcl": 46} | package com.github.corneil.aoc2019.day3
import java.io.BufferedReader
import java.io.File
import java.io.FileReader
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
data class Coord(val x: Int, val y: Int) {
fun distance(target: Coord): Int {
return abs(x - target.x) + abs(y - target.y)
}
}
data class Cell(val coord: Coord, val value: Int, val steps: MutableMap<Int, Int> = mutableMapOf())
fun translateInstruction(instruction: String): Pair<Char, Int> {
val direction = instruction[0]
val amount = instruction.substring(1).toInt()
return Pair(direction, amount)
}
class Grid {
val cells = mutableMapOf<Coord, Cell>(Coord(0, 0) to Cell(Coord(0, 0), 0))
private fun addCell(x: Int, y: Int, value: Int, steps: Int) {
if (!(x == 0 && y == 0)) {
val key = <KEY>)
val existing = cells[key]
if (existing != null) {
if (existing.value != value) {
cells[key] = existing.copy(value = value + existing.value)
}
val existingSteps = cells[key]!!.steps[value]
if (existingSteps == null) {
cells[key]!!.steps[value] = steps
}
} else {
cells[key] = Cell(key, value, mutableMapOf(value to steps))
}
}
}
private fun addEntriesX(startX: Int, endX: Int, y: Int, value: Int, steps: Int): Coord {
var stepsCounted = steps
if (startX < endX) {
for (x in startX..endX) {
addCell(x, y, value, stepsCounted)
stepsCounted += 1
}
} else {
for (x in startX downTo endX) {
addCell(x, y, value, stepsCounted)
stepsCounted += 1
}
}
return Coord(endX, y)
}
private fun addEntriesY(startY: Int, endY: Int, x: Int, value: Int, steps: Int): Coord {
var stepsCounted = steps
if (startY < endY) {
for (y in startY..endY) {
addCell(x, y, value, stepsCounted)
stepsCounted += 1
}
} else {
for (y in startY downTo endY) {
addCell(x, y, value, stepsCounted)
stepsCounted += 1
}
}
return Coord(x, endY)
}
fun updateGrid(trace: List<String>, line: Int) {
var position = Coord(0, 0)
var stepsCounted = 0
trace.forEach { instruction ->
val direction = translateInstruction(instruction)
position = when (direction.first) {
'R' -> {
addEntriesX(position.x, position.x + direction.second, position.y, line, stepsCounted)
}
'L' -> {
addEntriesX(position.x, position.x - direction.second, position.y, line, stepsCounted)
}
'U' -> {
addEntriesY(position.y, position.y + direction.second, position.x, line, stepsCounted)
}
'D' -> {
addEntriesY(position.y, position.y - direction.second, position.x, line, stepsCounted)
}
else -> throw Exception("Unknown instruction $instruction")
}
stepsCounted += direction.second
}
}
fun findNearest(coord: Coord, minValue: Int): Cell {
val closest = cells.values.filter { cell ->
cell.value > minValue
}.sortedBy { cell ->
coord.distance(cell.coord)
}.firstOrNull()
requireNotNull(closest) { "Could not find any cells!!!" }
return closest
}
fun findLowestStepsIntersection(minValue: Int): Int {
val best = cells.values.filter { cell ->
cell.value > minValue
}.sortedBy { cell ->
cell.steps.values.sum()
}.first()
return best.steps.values.sum()
}
fun findClosestManhattenDistance(coord: Coord, minValue: Int): Int {
return coord.distance(findNearest(coord, minValue).coord)
}
fun printGrid(): List<String> {
val minX = min(cells.values.map { it.coord.x }.min() ?: 0, 0) - 1
val maxX = max(cells.values.map { it.coord.x }.max() ?: 0, 0) + 1
val lines = cells.values.groupBy { it.coord.y }.toSortedMap()
return lines.map { entry ->
val lineOut = StringBuilder()
val lineCells = entry.value.map { it.coord.x to it }.toMap()
for (x in minX..maxX) {
val cellX = lineCells[x]
if (cellX != null) {
lineOut.append(cellX.value.toString())
} else {
lineOut.append('.')
}
}
lineOut.toString()
}.reversed()
}
}
fun stringToInstructions(input: String): List<String> {
return input.split(',').map { it.trim() }
}
fun main(args: Array<String>) {
val fileName = if (args.size > 1) args[0] else "input.txt"
val lines = BufferedReader(FileReader(File(fileName))).readLines().mapNotNull {
val line = it.trim()
if (line.length > 0) line else null
}
val grid = Grid()
lines.forEachIndexed { index, line ->
grid.updateGrid(stringToInstructions(line), index + 1)
}
val start = Coord(0, 0)
val distance = grid.findClosestManhattenDistance(start, lines.size)
println("Distance=$distance")
val best = grid.findLowestStepsIntersection(lines.size)
// then
println("Best=$best")
}
| 0 | HTML | 0 | 1 | bb19fda33ac6e91a27dfaea27f9c77c7f1745b9b | 5,606 | aoc-2019 | MIT License |
src/main/kotlin/Problem30.kt | jimmymorales | 496,703,114 | false | {"Kotlin": 67323} | import kotlin.math.pow
/**
* Digit fifth powers
*
* Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits:
*
* 1634 = 1^4 + 6^4 + 3^4 + 4^4
* 8208 = 8^4 + 2^4 + 0^4 + 8^4
* 9474 = 9^4 + 4^4 + 7^4 + 4^4
*
* As 1 = 14 is not a sum it is not included.
*
* The sum of these numbers is 1634 + 8208 + 9474 = 19316.
*
* Find the sum of all the numbers that can be written as the sum of fifth powers of their digits.
*
* https://projecteuler.net/problem=30
*/
fun main() {
println(1634.isDigitPower(4))
println(8208.isDigitPower(4))
println(9474.isDigitPower(4))
println(sumOfDigitPowersOf(4))
println(sumOfDigitPowersOf(5))
}
private fun sumOfDigitPowersOf(n: Int): Int {
var sum = 0
val limit = 9.0.pow(n).times(n).toInt()
for (i in 10..limit) {
if (i.isDigitPower(n)) {
sum += i
}
}
return sum
}
private fun Int.isDigitPower(n: Int): Boolean {
var sum = 0
var num = this
while (num != 0) {
val d = num % 10
sum += d.toDouble().pow(n).toInt()
num /= 10
}
return sum == this
} | 0 | Kotlin | 0 | 0 | e881cadf85377374e544af0a75cb073c6b496998 | 1,153 | project-euler | MIT License |
src/main/kotlin/days/Day17.kt | andilau | 433,504,283 | false | {"Kotlin": 137815} | package days
import kotlin.math.sign
@AdventOfCodePuzzle(
name = "<NAME>",
url = "https://adventofcode.com/2021/day/17",
date = Date(day = 17, year = 2021)
)
class Day17(input: String) : Puzzle {
private val targetArea = input
.substringAfter("target area: ")
.split(", ")
.map { it.substringAfter('=').split("..").map(String::toInt) }
.map { if (it.first() < it.last()) it.first()..it.last() else it.last()..it.first() }
.let { it[0] to it[1] }
private val xRange = targetArea.first
private val yRange = targetArea.second
private val altitudes: Sequence<Int> by lazy {
generateVelocities()
.mapNotNull { velocity -> maxAltitudeIfHittingTargetOrNull(velocity) }
}
override fun partOne(): Int = altitudes.maxOrNull() ?: error("No altitudes found")
override fun partTwo(): Int = altitudes.count()
private fun generateVelocities() = sequence {
for (x in 1..xRange.last)
for (y in yRange.first..500) yield(Point(x, y))
}
internal fun maxAltitudeIfHittingTargetOrNull(velocity: Point): Int? {
val points = velocityByTime(velocity)
.trajectory()
.takeWhile { it.x <= xRange.last && it.y >= yRange.first }
return points.maxOf { it.y }
.takeIf { points.any { it.x in xRange && it.y in yRange } }
}
private fun velocityByTime(velocity: Point) =
generateSequence(velocity) { (x, y) -> Point(x - x.sign, y - 1) }
private fun Sequence<Point>.trajectory(): Sequence<Point> =
runningFold(Point.ORIGIN) { pos, v -> pos + v }
internal fun velocities(): List<Point> =
generateVelocities().filter { maxAltitudeIfHittingTargetOrNull(it) != null }.toList()
} | 0 | Kotlin | 0 | 0 | b3f06a73e7d9d207ee3051879b83e92b049a0304 | 1,778 | advent-of-code-2021 | Creative Commons Zero v1.0 Universal |
src/com/hlq/leetcode/array/Question1.kt | HLQ-Struggle | 310,978,308 | false | null | package com.hlq.leetcode.array
/**
* @author HLQ_Struggle
* @date 2020/11/09
* @desc LeetCode 1. 两数之和 https://leetcode-cn.com/problems/two-sum/
*/
fun main() {
val nums = intArrayOf(3, 2, 4)
val target = 6
// 暴力解法 一
twoSum(nums, target)
// 优化
twoSum2(nums, target)
twoSum3(nums, target)
// 学习 LeetCode 执行用时范例
twoSum4(nums, target)
// 学习 LeetCode 执行消耗内存范例
twoSum5(nums, target)
}
/**
* 双指针解法
*/
fun twoSum(nums: IntArray, target: Int): IntArray {
// 基本校验
if (nums.isEmpty()) {
return IntArray(0)
}
var resultArray = IntArray(2)
var isl = false
var i = 0
var j = 1
while (i < nums.size - 1) {
while (j < nums.size) {
if (nums[i] + nums[j] == target) {
resultArray[0] = i
resultArray[1] = j
isl = true
break
}
j++
}
if (isl) {
break
}
i++
j = i + 1
}
return resultArray
}
/**
* 优化 一
*/
fun twoSum2(nums: IntArray, target: Int): IntArray {
// 基本校验
if (nums.isEmpty()) {
return IntArray(0)
}
var i = 0
var j = 1
while (i < nums.size - 1) {
while (j < nums.size) {
if (nums[i] + nums[j] == target) {
return intArrayOf(i, j)
}
j++
}
i++
j = i + 1
}
return intArrayOf(0, 0)
}
/**
* 继续优化
*/
fun twoSum3(nums: IntArray, target: Int): IntArray {
if (nums.isEmpty()) {
return intArrayOf(0, 0)
}
var i = 0
var j = 1
while (i < nums.size - 1) {
while (j < nums.size) {
if (nums[i] + nums[j] == target) {
return intArrayOf(i, j)
}
j++
}
i++
j = i + 1
}
return intArrayOf(0, 0)
}
/**
* 学习 LeetCode 执行用时最短事例
*/
fun twoSum4(nums: IntArray, target: Int): IntArray {
if (nums.isEmpty()) {
return intArrayOf(0, 0)
}
for (i in nums.indices) {
for (j in 0..i) {
if (i == j) {
continue
}
val a = nums[i];
val b = nums[j];
if (a + b == target) {
return intArrayOf(j, i)
}
}
}
return intArrayOf(0, 0)
}
/**
* 学习 LeetCode 执行消耗内存范例
*/
fun twoSum5(nums: IntArray, target: Int): IntArray {
if (nums.isEmpty()) {
return intArrayOf(0, 0)
}
val map: MutableMap<Int, Int> = HashMap()
for (i in nums.indices) {
val complement = target - nums[i]
if (map.containsKey(complement)) {
return intArrayOf(map[complement]!!, i)
}
map[nums[i]] = i
}
throw Exception()
} | 0 | Kotlin | 0 | 2 | 76922f46432783218ddd34e74dbbf3b9f3c68f25 | 2,908 | LeetCodePro | Apache License 2.0 |
src/Day14.kt | pavlo-dh | 572,882,309 | false | {"Kotlin": 39999} | fun main() {
data class Point(val x: Int, val y: Int) {
operator fun plus(other: Point) = Point(x + other.x, y + other.y)
}
fun parseInput(input: List<String>): MutableMap<Point, Char> {
val cave = mutableMapOf<Point, Char>()
input.forEach { line ->
val points = line.split(" -> ").map { pointCoordinatesString ->
val (x, y) = pointCoordinatesString.split(',').map(String::toInt)
Point(x, y)
}
for (i in 1..points.lastIndex) {
val first = points[i - 1]
val second = points[i]
val xRange = when {
first.x == second.x -> first.x..first.x
second.x > first.x -> first.x..second.x
else -> second.x..first.x
}
val yRange = when {
first.y == second.y -> first.y..first.y
second.y > first.y -> first.y..second.y
else -> second.y..first.y
}
for (x in xRange) {
for (y in yRange) {
cave[Point(x, y)] = '#'
}
}
}
}
return cave
}
val sandUnitMovements = listOf(Point(0, 1), Point(-1, 1), Point(1, 1))
fun part1(input: List<String>): Int {
val cave = parseInput(input)
val start = Point(500, 0)
cave[start] = '+'
val minX = cave.keys.minOf(Point::x)
val maxX = cave.keys.maxOf(Point::x)
val maxY = cave.keys.maxOf(Point::y)
var allSandUnitsRested = false
while (!allSandUnitsRested) {
var sandUnit = start
var sandUnitRested = false
sandUnitFalling@ while (!sandUnitRested) {
var sandUnitMoved = false
for (sandUnitMovement in sandUnitMovements) {
val movedSandUnit = sandUnit + sandUnitMovement
if (movedSandUnit.x < minX || movedSandUnit.x > maxX || movedSandUnit.y > maxY) {
allSandUnitsRested = true
break@sandUnitFalling
} else if (cave[movedSandUnit] == null) {
sandUnit = movedSandUnit
sandUnitMoved = true
break
}
}
if (!sandUnitMoved) {
cave[sandUnit] = 'o'
sandUnitRested = true
}
}
}
// for (j in 0..maxY) {
// for (i in minX..maxX) {
// val point = Point(i, j)
// print(cave[point] ?: '.')
// }
// println()
// }
return cave.values.count { it == 'o' }
}
fun part2(input: List<String>): Int {
val cave = parseInput(input)
val start = Point(500, 0)
val maxY = cave.keys.maxOf(Point::y) + 2
var allSandUnitsRested = false
while (!allSandUnitsRested) {
var sandUnit = start
var sandUnitRested = false
while (!sandUnitRested) {
var sandUnitMoved = false
for (sandUnitMovement in sandUnitMovements) {
val movedSandUnit = sandUnit + sandUnitMovement
if (movedSandUnit.y < maxY && cave[movedSandUnit] == null) {
sandUnit = movedSandUnit
sandUnitMoved = true
break
}
}
if (!sandUnitMoved) {
cave[sandUnit] = 'o'
sandUnitRested = true
if (sandUnit == start) {
allSandUnitsRested = true
}
}
}
}
// val minX = cave.keys.minOf(Point::x)
// val maxX = cave.keys.maxOf(Point::x)
// for (j in 0 until maxY) {
// for (i in minX..maxX) {
// val point = Point(i, j)
// print(cave[point] ?: '.')
// }
// println()
// }
return cave.values.count { it == 'o' }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day14_test")
check(part1(testInput) == 24)
check(part2(testInput) == 93)
val input = readInput("Day14")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 2 | c10b0e1ce2c7c04fbb1ad34cbada104e3b99c992 | 4,523 | aoc-2022-in-kotlin | Apache License 2.0 |
src/algorithms/HungarianAlgorithm.kt | aaronoe | 186,243,764 | false | null | package de.aaronoe.algorithms
import de.aaronoe.models.Seminar
import de.aaronoe.models.Student
import org.jgrapht.alg.matching.KuhnMunkresMinimalWeightBipartitePerfectMatching
import org.jgrapht.graph.DefaultWeightedEdge
import org.jgrapht.graph.SimpleWeightedGraph
import kotlin.system.measureTimeMillis
object HungarianAlgorithm: StudentMatchingAlgorithm {
override suspend fun execute(students: List<Student>, seminars: List<Seminar>): Map<Seminar, List<Student>> {
val studentCount = students.count()
val seminarSeatCount = seminars.sumBy { it.capacity }
val studentList = students.toMutableList()
val seminarList = seminars.toMutableList()
when {
studentCount > seminarSeatCount -> {
val difference = Math.abs(studentCount - seminarSeatCount)
seminarList.add(Seminar("mock", difference))
}
studentCount < seminarSeatCount -> {
val difference = Math.abs(studentCount - seminarSeatCount)
(0 until difference)
.map { Student(name = "mock$it", preferences = emptyList()) }
.let(studentList::addAll)
}
}
val seminarMap = seminarList.associateWith { seminar ->
(0 until seminar.capacity).map {
Seminar("${seminar.name}_$it", id = "${seminar.id}$$it", capacity = 1)
}
}
val graph = SimpleWeightedGraph<String, DefaultWeightedEdge>(DefaultWeightedEdge::class.java)
seminarMap
.flatMap { it.value }
.forEach {
graph.addVertex(it.id)
}
val allSeminarsSet = seminarMap.flatMap { it.value }.toHashSet()
measureTimeMillis {
studentList.forEach { student ->
graph.addVertex(student.id)
val preferenceMap = HashMap<String, Int>(allSeminarsSet.size)
student.preferences.forEachIndexed { index, seminar ->
val list = seminarMap[seminar] ?: error("Seminar List should exist")
list.forEach {
preferenceMap[it.id] = index
}
}
allSeminarsSet.forEach {
val weight = preferenceMap[it.id]?.toDouble() ?: Double.MAX_VALUE
graph.addEdge(student.id, it.id).let {
graph.setEdgeWeight(it, weight)
}
}
}
}.let {
println("Creating Graph: $it ms")
}
val algorithm = KuhnMunkresMinimalWeightBipartitePerfectMatching(
graph,
studentList.map { it.id }.toSet(),
seminarMap.flatMap { it.value }.map { it.id }.toSet()
)
val studentMap = studentList.associateBy { it.id }
val seminarIdMap = seminarList.associateBy { it.id }
val matching = algorithm.matching
println("IsPerfect: ${matching.edges.size == studentList.size}")
matching.edges.forEach { edge ->
val student = studentMap[graph.getEdgeSource(edge)]!!
val seminarId = graph.getEdgeTarget(edge)!!.split("$").first()
val seminar = seminarIdMap[seminarId]!!
seminar.assignments.add(student)
}
return seminars.map { it to it.assignments.toList() }.toMap()
}
} | 0 | Kotlin | 0 | 1 | 8265e6553aca23c3bf2c5236ba56d46ab7e2b3f3 | 3,421 | matching_server | MIT License |
kotlin/src/com/daily/algothrim/leetcode/NumWays.kt | idisfkj | 291,855,545 | false | null | package com.daily.algothrim.leetcode
/**
* 1269. 停在原地的方案数
* 有一个长度为 arrLen 的数组,开始有一个指针在索引 0 处。
*
* 每一步操作中,你可以将指针向左或向右移动 1 步,或者停在原地(指针不能被移动到数组范围外)。
*
* 给你两个整数 steps 和 arrLen ,请你计算并返回:在恰好执行 steps 次操作以后,指针仍然指向索引 0 处的方案数。
*
* 由于答案可能会很大,请返回方案数 模 10^9 + 7 后的结果。
*/
class NumWays {
companion object {
@JvmStatic
fun main(args: Array<String>) {
println(NumWays().numWays(3, 2))
println(NumWays().numWays(4, 2))
println(NumWays().numWays2(3, 2))
println(NumWays().numWays2(4, 2))
}
}
//输入:steps = 3, arrLen = 2
//输出:4
//解释:3 步后,总共有 4 种不同的方法可以停在索引 0 处。
//向右,向左,不动
//不动,向右,向左
//向右,不动,向左
//不动,不动,不动
fun numWays(steps: Int, arrLen: Int): Int {
val mode = 1000000007
val n = Math.min(steps + 1, arrLen)
val status = Array(steps + 1) { IntArray(n) }
status[0][0] = 1
for (i in 1..steps) {
for (j in 0 until n) {
status[i][j] = status[i - 1][j]
if (j - 1 >= 0) {
status[i][j] = (status[i][j] + status[i - 1][j - 1]) % mode
}
if (j + 1 < n) {
status[i][j] = (status[i][j] + status[i - 1][j + 1]) % mode
}
}
}
return status[steps][0]
}
fun numWays2(steps: Int, arrLen: Int): Int {
val mode = 1000000007
val n = Math.min(steps + 1, arrLen)
var status = IntArray(n)
status[0] = 1
for (i in 1..steps) {
val statusNext = IntArray(n)
for (j in 0 until n) {
statusNext[j] = status[j]
if (j - 1 >= 0) {
statusNext[j] = (statusNext[j] + status[j - 1]) % mode
}
if (j + 1 < n) {
statusNext[j] = (statusNext[j] + status[j + 1]) % mode
}
}
status = statusNext
}
return status[0]
}
} | 0 | Kotlin | 9 | 59 | 9de2b21d3bcd41cd03f0f7dd19136db93824a0fa | 2,421 | daily_algorithm | Apache License 2.0 |
src/nativeMain/kotlin/com.qiaoyuang.algorithm/round1/Questions22.kt | qiaoyuang | 100,944,213 | false | {"Kotlin": 338134} | package com.qiaoyuang.algorithm.round1
fun test22() {
val head = SingleDirectionNode(0u)
var current = head
repeat(9) {
val next = SingleDirectionNode(it.toUInt() + 1u)
current.next = next
current = next
}
printlnResult1(8u, head)
printlnResult1(3u, head)
printlnResult1(1u, head)
printlnResult1(0u, head)
printlnResult1(15u, head)
printlnResult2(head)
val head1 = SingleDirectionNode(0u)
current = head1
repeat(8) {
val next = SingleDirectionNode(it.toUInt() + 1u)
current.next = next
current = next
}
printlnResult2(head1)
}
/**
* Questions 22-1: Find the reciprocal k node in a Linked List, the reciprocal starts from 1
*/
private infix fun <T : Comparable<T>> SingleDirectionNode<T>.findReciprocalNodeInLinkedList(k: UInt): SingleDirectionNode<T> {
if (k == 0u)
throw IllegalArgumentException("The k must greater than 0")
val (node, _) = findTheReciprocalAndIndex(k)
return node ?: throw IllegalArgumentException("The k greater than count of the Linked List")
}
private infix fun <T : Comparable<T>> SingleDirectionNode<T>.findTheReciprocalAndIndex(k: UInt): Pair<SingleDirectionNode<T>?, UInt> {
val pair = next?.findTheReciprocalAndIndex(k) ?: return (if (k == 1u) this else null) to 1u
val (node, index) = pair
val myIndex = index + 1u
return when {
myIndex == k -> this to k
node != null -> pair
else -> null to myIndex
}
}
private fun printlnResult1(k: UInt, head: SingleDirectionNode<UInt>) {
print("The linked list is: ")
printlnLinkedList(head)
try {
println("The reciprocal No.$k node is: ${(head findReciprocalNodeInLinkedList k).element}")
} catch (e: Exception) {
println("Caught an exception")
}
}
/**
* Questions 22-2: Return the Linked List's middle node,
* if the count of the Linked List is odd number, return the middle, else return the anyone of the two middle nodes
*/
private fun <T> SingleDirectionNode<T>.findTheMiddleNode(): SingleDirectionNode<T> {
var middle = this
var end = this
while (end.next != null) {
end = end.next!!.next ?: break
middle = middle.next!!
}
return middle
}
private fun printlnResult2(head: SingleDirectionNode<UInt>) {
print("The linked list is: ")
printlnLinkedList(head)
println("The middle node is: ${head.findTheMiddleNode().element}")
} | 0 | Kotlin | 3 | 6 | 66d94b4a8fa307020d515d4d5d54a77c0bab6c4f | 2,461 | Algorithm | Apache License 2.0 |
2016/04/Solution.kt | AdrianMiozga | 588,519,359 | false | {"Kotlin": 110785, "Python": 11275, "Assembly": 3369, "C": 2378, "Pawn": 1390, "Dart": 732} | import java.io.File
private const val FILENAME = "2016/04/input.txt"
private val REGEX = Regex("""([a-z\-]+)(\d+)\[([a-z]+)]""")
fun main() {
partOne()
partTwo()
}
private fun partOne() {
var sum = 0
val lines = File(FILENAME).readLines()
for (line in lines) {
val (encryptedName, sectorID, checksum) = REGEX.matchEntire(line)!!.destructured
val map = encryptedName.replace("-", "").toList().sorted()
.groupingBy { it }.eachCount()
val result = map.toList().sortedByDescending { (_, value) -> value }
.toMap().keys.take(5).joinToString(separator = "")
if (result == checksum) {
sum += sectorID.toInt()
}
}
println(sum)
}
private fun partTwo() {
val lines = File(FILENAME).readLines()
for (line in lines) {
val (encryptedName, sectorID, _) = REGEX.matchEntire(line)!!.destructured
var decryptedName = ""
for (char in encryptedName.replace("-", " ").toCharArray()) {
if (char == ' ') {
decryptedName += char
continue
}
val newAscii = (char.code - 97 + sectorID.toInt()) % 26 + 97
decryptedName += newAscii.toChar()
}
if (decryptedName.contains(("northpole"))) {
println(sectorID)
}
}
}
| 0 | Kotlin | 0 | 0 | c9cba875089d8d4fb145932c45c2d487ccc7e8e5 | 1,352 | Advent-of-Code | MIT License |
src/main/java/kam/wardrober/algorithm/Genetic.kt | kudryaA | 166,642,234 | false | null | package kam.wardrober.algorithm
import kam.wardrober.struct.ListClothes
import kam.wardrober.struct.Temperature
import kam.wardrober.struct.clothes.Set
import java.util.*
import java.util.stream.Collectors
fun geneticSolve(list: ListClothes, temperature: Temperature): Set? {
var gen = Generation(temperature)
for (i in 0..list.maxSize()) {
gen.list.add(list.get(i))
}
var max: Set? = Set(null, null, null, null)
var count = 0
while(count < 10) {
val cur = gen.getMax()
count++
if (cur!= null) {
if(max!!.getMark(temperature) < cur.getMark(temperature) ) {
count = 0
max = cur
} else {
gen.mutation(list)
continue
}
}
gen = gen.createChildren()
}
return max
}
private class Generation(private val temperature: Temperature) {
var list = ArrayList<Set>()
private val comparator = kotlin.Comparator<Set> { o1, o2 ->
(o1.getMark(temperature) - o2.getMark(temperature)).toInt()
}
fun createChildren(): Generation {
list.sortWith(comparator)
list.reverse()
val res = Generation(temperature)
val count = list.size
val max = list[0]
res.list.add(max)
res.list.add(list[1])
for (i in 1 until count / 2) {
val set1 = Set(max.footwear, max.bottomClothes, list[i].topClothes, list[i].headdress)
res.list.add(set1)
val set2 = Set(list[i].footwear, list[i].bottomClothes, max.topClothes, max.headdress)
res.list.add(set2)
}
val buf = res.list.stream()
.distinct()
.collect(Collectors.toList())
res.list.clear()
res.list.addAll(buf)
return res
}
fun getMax(): Set? {
val res = list.maxWith(comparator)
return res
}
fun mutation(listC: ListClothes) {
val random = Random()
list.forEach {
random.nextInt()
val choose = Math.abs(random.nextInt()) % 4
when(choose) {
0 -> {
if (listC.footwear.size > 0) {
val i = Math.abs(random.nextInt()) % listC.footwear.size
it.footwear = listC.footwear[i]
}
}
1 -> {
if (listC.bottomClothes.size > 0) {
val i = Math.abs(random.nextInt()) % listC.bottomClothes.size
it.bottomClothes = listC.bottomClothes[i]
}
}
2 -> {
if (listC.topClothes.size > 0) {
val i = Math.abs(random.nextInt()) % listC.topClothes.size
it.topClothes = listC.topClothes[i]
}
}
3 -> {
if (listC.headdress.size > 0) {
val i = Math.abs(random.nextInt()) % listC.headdress.size
it.headdress = listC.headdress[i]
}
}
}
}
}
} | 0 | Kotlin | 0 | 0 | 7685418dd0a96187d0ca53c4223e711e869aeb82 | 3,204 | Wardrober-genetic-algorithm | MIT License |
src/main/kotlin/solved/p1679/Solution.kt | mr-nothing | 469,475,608 | false | {"Kotlin": 162430} | package solved.p1679
class Solution {
class SortingApproach {
fun maxOperations(nums: IntArray, k: Int): Int {
val sorted = nums.sorted()
var operations = 0
var head = 0
var tail = nums.lastIndex
while (head < tail) {
while (tail > head) {
val headValue = sorted[head]
val tailValue = sorted[tail]
val kSum = headValue + tailValue
if (kSum > k) { // if sum is greater than k then we need a lower number thus we need to move tail to the left
tail--
} else if (kSum < k) { // if sum is lower than k then we need a greater number thus we need to move tail to the right
head++
} else { // we found 2 numbers that sum up to k this move both head and tail pointers
operations++
head++
tail--
}
}
}
return operations
}
}
class HashMapApproach {
fun maxOperations(nums: IntArray, k: Int): Int {
val frequencies = hashMapOf<Int, Int>()
var operations = 0
for (first in nums) {
val second = k - first
val secondFrequency = frequencies.getOrDefault(second, 0) // get second number frequency
if (secondFrequency > 0) {
// if number has been already met (frequency > 0) then decrement frequency and increment result
// since we found a pair that sum up to k
frequencies[second] = secondFrequency - 1
operations++
} else {
// if we have not met number yet, than increment numbers frequency
val firstFrequency = frequencies.getOrDefault(first, 0)
frequencies[first] = firstFrequency + 1
}
}
return operations
}
}
} | 0 | Kotlin | 0 | 0 | 0f7418ecc8675d8361ef31cbc1ee26ea51f7708a | 2,110 | leetcode | Apache License 2.0 |
src/main/kotlin/day3/Part1.kt | Pinaki93 | 573,867,953 | false | {"Kotlin": 4415, "Assembly": 10} | package day3
import util.readFileFromResources
val alphabetMap: Map<Char, Int> = ('a'..'z')
.zip((1..26).toList()).toMap() + ('A'..'Z').zip((27..52).toList()).toMap()
fun findCommonCharacter(list1: List<Char>, list2: List<Char>): Char {
val sortedList1 = list1.sorted()
val sortedList2 = list2.sorted()
var firstIndex = 0
var secondIndex = 0
while (firstIndex < sortedList1.size && secondIndex < sortedList2.size) {
if (sortedList1[firstIndex] == sortedList2[secondIndex]) {
return sortedList1[firstIndex]
} else if (sortedList1[firstIndex] < sortedList2[secondIndex]) {
firstIndex++
} else {
secondIndex++
}
}
throw IllegalArgumentException("No common character found")
}
fun splitString(input: String): Pair<List<Char>, List<Char>> {
val midpoint = input.length / 2
return Pair(input.substring(0, midpoint).toList(), input.substring(midpoint).toList())
}
fun main() {
val lines = readFileFromResources("/day3/input.txt")
var output = 0
lines.forEach { line ->
val (firstHalf, secondHalf) = splitString(line)
val commonCharacter = findCommonCharacter(firstHalf, secondHalf)
output += alphabetMap[commonCharacter]!!
}
println(output)
} | 0 | Kotlin | 0 | 0 | c1518c3adfb1aee49838fe439e1913f4f6f825dd | 1,294 | advent-of-code-2022 | MIT License |
src/iii_conventions/MyDate.kt | vavrajosef | 155,741,898 | true | {"Kotlin": 72636, "Java": 3851} | package iii_conventions
import iii_conventions.nextDay
import iii_conventions.addTimeIntervals
data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int)
operator fun MyDate.rangeTo(other: MyDate): DateRange = DateRange(this, other)
operator fun MyDate.compareTo(other: MyDate): Int {
if(this.year == other.year) {
if(this.month == other.month) {
return this.dayOfMonth - other.dayOfMonth
}
return this.month - other.month
}
return this.year - other.year
}
operator fun MyDate.plus(intervalToAdd: TimeInterval): MyDate = addTimeIntervals(intervalToAdd, 1)
operator fun MyDate.plus(multiplier: TimeIntervalMultiplier): MyDate = addTimeIntervals(multiplier.timeInterval, multiplier.times)
class TimeIntervalMultiplier(val timeInterval: TimeInterval, val times: Int)
enum class TimeInterval {
DAY,
WEEK,
YEAR;
operator fun times(multiplier: Int): TimeIntervalMultiplier = TimeIntervalMultiplier(this, multiplier)
}
class DateRange(val start: MyDate, val endInclusive: MyDate) : Iterable<MyDate> {
override fun iterator(): Iterator<MyDate> {
return object : Iterator<MyDate> {
var next = start
override fun hasNext(): Boolean {
return next <= endInclusive
}
override fun next(): MyDate {
val current = next
next = this.next.nextDay()
return current
}
}
}
}
operator fun DateRange.contains(lookingFor: MyDate): Boolean =
lookingFor.compareTo(start) >= 0 && lookingFor.compareTo(endInclusive) <= 0
| 0 | Kotlin | 0 | 0 | 839c58cd2901c3901ec0c259ea7afe00d4cb85cc | 1,635 | kotlin-koans | MIT License |
src/chapter4/section3/ex41_LongestMSTEdge.kt | w1374720640 | 265,536,015 | false | {"Kotlin": 1373556} | package chapter4.section3
import extensions.formatDouble
import kotlin.math.PI
import kotlin.math.log2
import kotlin.math.sqrt
/**
* 最小生成树中的最长边
* 运行实验并根据经验分析最小生成树中最长边的长度以及图中不长于该边的边的总数
*/
fun ex41_LongestMSTEdge(graph: EWG, mst: MST): Pair<Edge, Int> {
val iterator = mst.edges().iterator()
require(iterator.hasNext())
var maxEdge = iterator.next()
while (iterator.hasNext()) {
val nextEdge = iterator.next()
if (nextEdge > maxEdge) {
maxEdge = nextEdge
}
}
var count = 0
graph.edges().forEach {
if (it <= maxEdge) {
count++
}
}
return maxEdge to count
}
fun main() {
val V = 1000
// 权重均匀分布的随机稀疏图
val evenlyEWG = RandomSparseEvenlyEWG(V)
// 权重高斯分布的随机稀疏图
val gaussianEWG = RandomSparseGaussianEWG(V)
val threshold = sqrt(log2(V.toDouble()) / (PI * V))
// 稀疏的欧几里得图
val euclideanEWG = getRandomEWG(V, threshold * 2).first
// E=V*(V-1)/2的稠密图
val denseEWG = getDenseGraph(V)
val evenlyResult = ex41_LongestMSTEdge(evenlyEWG, PrimMST(evenlyEWG))
// 除了打印最小生成树中的最大边和图中不长于该边的总数外,还打印总数和顶点数量的比例
println("maxEdge: ${evenlyResult.first} count=${evenlyResult.second} ratio=${formatDouble(evenlyResult.second.toDouble() / V, 2)}")
val gaussianResult = ex41_LongestMSTEdge(gaussianEWG, PrimMST(gaussianEWG))
println("maxEdge: ${gaussianResult.first} count=${gaussianResult.second} ratio=${formatDouble(gaussianResult.second.toDouble() / V, 2)}")
val euclideanResult = ex41_LongestMSTEdge(euclideanEWG, PrimMST(euclideanEWG))
println("maxEdge: ${euclideanResult.first} count=${euclideanResult.second} ratio=${formatDouble(euclideanResult.second.toDouble() / V, 2)}")
val denseResult = ex41_LongestMSTEdge(denseEWG, PrimMST(denseEWG))
println("maxEdge: ${denseResult.first} count=${denseResult.second} ratio=${formatDouble(denseResult.second.toDouble() / V, 2)}")
} | 0 | Kotlin | 1 | 6 | 879885b82ef51d58efe578c9391f04bc54c2531d | 2,183 | Algorithms-4th-Edition-in-Kotlin | MIT License |
src/day19/Day19.kt | armanaaquib | 572,849,507 | false | {"Kotlin": 34114} | package day19
import readInputAsText
fun main() {
fun parseInput(input: String) = input.split("\n\n")
.map { elf -> elf.split("\n").map { it.toInt() } }
fun part1(input: String): Int {
val data = parseInput(input)
return data.maxOf { it.sum() }
}
fun part2(input: String): Int {
val data = parseInput(input)
return data.map { it.sum() }.sortedDescending().take(3).sum()
}
// test if implementation meets criteria from the description, like:
check(part1(readInputAsText("Day01_test")) == 24000)
println(part1(readInputAsText("Day01")))
check(part2(readInputAsText("Day01_test")) == 45000)
println(part2(readInputAsText("Day01")))
/*
-> clay-collecting robots -> clay -> obsidian-collecting robots -> obsidian -> geode-cracking robots
Ore-collecting robots -> Ore
*/
}
| 0 | Kotlin | 0 | 0 | 47c41ceddacb17e28bdbb9449bfde5881fa851b7 | 875 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/com/vaclavbohac/advent2023/day3/GearRatios.kt | vaclavbohac | 725,991,261 | false | {"Kotlin": 15155} | package com.vaclavbohac.advent2023.day3
class GearRatios(private val lines: List<String>) {
fun getSumOfAllParts(): Int {
val validNumbers = mutableListOf<Int>()
lines.forEachIndexed { i, line ->
var j = 0
var number = StringBuffer()
var indexStart = 0
while (j < line.length) {
if (line[j].isDigit()) {
if (number.isEmpty()) {
indexStart = j
}
number.append(line[j])
}
if (number.isNotEmpty() && (!line[j].isDigit() || j == line.length - 1)) {
if (isValidNumber(indexStart, j - 1, i)) {
validNumbers.add(number.toString().toInt())
}
number = StringBuffer()
}
j += 1
}
}
return validNumbers.sum()
}
fun getSumOfGears(): Int {
val stars: MutableMap<Pair<Int, Int>, MutableList<Int>> = mutableMapOf()
lines.forEachIndexed { i, line ->
var j = 0
var number = StringBuffer()
var indexStart = 0
while (j < line.length) {
if (line[j].isDigit()) {
if (number.isEmpty()) {
indexStart = j
}
number.append(line[j])
}
if (number.isNotEmpty() && (!line[j].isDigit() || j == line.length - 1)) {
val num = number.toString().toInt()
val star = getAdjacentStar(indexStart, j - 1, i)
if (star != null) {
if (stars[star].isNullOrEmpty()) {
stars[star] = mutableListOf(num)
} else {
stars[star]?.add(num)
}
}
number = StringBuffer()
}
j += 1
}
}
return stars
.filter { star -> star.value.size == 2 }
.map { star -> star.value.fold(1) { prod, num -> prod * num } }
.sum()
}
private fun isValidNumber(start: Int, end: Int, line: Int): Boolean {
val columnRange = maxOf(start - 1, 0).rangeTo(minOf(end + 1, lines[0].length))
val rowRange = maxOf(line - 1, 0).rangeTo(minOf(line + 1, lines.size - 1))
for (i in columnRange) {
for (j in rowRange) {
val c = lines[j][i]
if (!c.isDigit() && c != '.') {
return true
}
}
}
return false
}
private fun getAdjacentStar(start: Int, end: Int, line: Int): Pair<Int, Int>? {
val columnRange = maxOf(start - 1, 0).rangeTo(minOf(end + 1, lines[0].length))
val rowRange = maxOf(line - 1, 0).rangeTo(minOf(line + 1, lines.size - 1))
for (i in columnRange) {
for (j in rowRange) {
val c = lines[j][i]
if (c == '*') {
return Pair(j, i)
}
}
}
return null
}
} | 0 | Kotlin | 0 | 0 | daa1feb960c4e3d26c3c75842afbd414ecc2f008 | 3,249 | advent-of-code-2023 | MIT License |
2022/src/main/kotlin/day3_func.kt | madisp | 434,510,913 | false | {"Kotlin": 388138} | import utils.Parser
import utils.Solution
import utils.badInput
import utils.map
import utils.mapItems
import utils.split
fun main() {
Day3Func.run()
}
typealias Day3Input = List<Pair<Set<Char>, Set<Char>>>
val Char.priority: Int get() = when (this) {
in ('A' .. 'Z') -> this - 'A' + 26
else -> this - 'a'
}
object Day3Func : Solution<Day3Input>() {
override val name = "day3"
override val parser = Parser.lines.mapItems { line -> line.split().map { it.toCharArray().toSet() } }
override fun part1(input: Day3Input): Int {
return input
.flatMap { sets -> sets.first intersect sets.second }
.sumOf { it.priority + 1 }
}
override fun part2(input: Day3Input): Int {
return input
.chunked(3)
.flatMap { group ->
group.map { (x, y) -> x + y }
.reduce { acc, set -> acc intersect set }
}
.sumOf { it.priority + 1 }
}
}
| 0 | Kotlin | 0 | 1 | 3f106415eeded3abd0fb60bed64fb77b4ab87d76 | 899 | aoc_kotlin | MIT License |
src/main/kotlin/aoc23/Day01.kt | tahlers | 725,424,936 | false | {"Kotlin": 65626} | package aoc23
object Day01 {
private val word2NumberRegex = """(one|two|three|four|five|six|seven|eight|nine|\d)""".toRegex()
private val word2NumberRegexRev = """(eno|owt|eerht|ruof|evif|xis|neves|thgie|enin|\d)""".toRegex()
fun calculateCalibrationSum(input: String): Int =
input.trim().lines().sumOf { line ->
val digits = line.filter { it.isDigit() }
val first = digits.first()
val last = digits.last()
"$first$last".toInt()
}
fun calculateCalibrationSum2(input: String): Int =
input.trim().lines().sumOf { line ->
val first = findFirst(line)
val last = findLast(line)
"$first$last".toInt()
}
private fun findFirst(input: String): Char =
word2NumberRegex.replace(input) { m ->
when (m.value) {
"one" -> "1"
"two" -> "2"
"three" -> "3"
"four" -> "4"
"five" -> "5"
"six" -> "6"
"seven" -> "7"
"eight" -> "8"
"nine" -> "9"
else -> m.value
}
}.first { it.isDigit() }
private fun findLast(input: String): Char =
word2NumberRegexRev.replace(input.reversed()) { m ->
when (m.value) {
"eno" -> "1"
"owt" -> "2"
"eerht" -> "3"
"ruof" -> "4"
"evif" -> "5"
"xis" -> "6"
"neves" -> "7"
"thgie" -> "8"
"enin" -> "9"
else -> m.value
}
}.first { it.isDigit() }
} | 0 | Kotlin | 0 | 0 | 0cd9676a7d1fec01858ede1ab0adf254d17380b0 | 1,697 | advent-of-code-23 | Apache License 2.0 |
src/Lesson3TimeComplexity/FrogJmp.kt | slobodanantonijevic | 557,942,075 | false | {"Kotlin": 50634} | /**
* 100/100
* @param X
* @param Y
* @param D
* @return
*/
fun solution(X: Int, Y: Int, D: Int): Int {
return Math.ceil((Y - X).toDouble() / D).toInt()
}
/**
* A small frog wants to get to the other side of the road. The frog is currently located at position X and wants to get to a position greater than or equal to Y. The small frog always jumps a fixed distance, D.
*
* Count the minimal number of jumps that the small frog must perform to reach its target.
*
* Write a function:
*
* class Solution { public int solution(int X, int Y, int D); }
*
* that, given three integers X, Y and D, returns the minimal number of jumps from position X to a position equal to or greater than Y.
*
* For example, given:
*
* X = 10
* Y = 85
* D = 30
* the function should return 3, because the frog will be positioned as follows:
*
* after the first jump, at position 10 + 30 = 40
* after the second jump, at position 10 + 30 + 30 = 70
* after the third jump, at position 10 + 30 + 30 + 30 = 100
* Write an efficient algorithm for the following assumptions:
*
* X, Y and D are integers within the range [1..1,000,000,000];
* X ≤ Y.
*/ | 0 | Kotlin | 0 | 0 | 155cf983b1f06550e99c8e13c5e6015a7e7ffb0f | 1,167 | Codility-Kotlin | Apache License 2.0 |
src/main/kotlin/dev/siller/aoc2023/Day09.kt | chearius | 725,594,554 | false | {"Kotlin": 50795, "Shell": 299} | package dev.siller.aoc2023
data object Day09 : AocDayTask<Int, Int>(
day = 9,
exampleInput =
"""
|0 3 6 9 12 15
|1 3 6 10 15 21
|10 13 16 21 30 45
""".trimMargin(),
expectedExampleOutputPart1 = 114,
expectedExampleOutputPart2 = 2
) {
override fun runPart1(input: List<String>): Int =
input.sumOf { line ->
calculateSeriesElement(
series = line.split(' ').map(String::toInt),
elementAccessor = { it.last() },
accumulateOperation = { acc, current -> acc + current }
)
}
override fun runPart2(input: List<String>): Int =
input.sumOf { line ->
calculateSeriesElement(
series = line.split(' ').map(String::toInt),
elementAccessor = { it.first() },
accumulateOperation = { acc, current -> current - acc }
)
}
private fun calculateSeriesElement(
series: List<Int>,
elementAccessor: (List<Int>) -> Int,
accumulateOperation: (Int, Int) -> Int
): Int {
var diffs = series.zipWithNext { a, b -> b - a }
val elements = mutableListOf(elementAccessor(series), elementAccessor(diffs))
while (diffs.distinct().size > 1) {
diffs = diffs.zipWithNext { a, b -> b - a }
elements += elementAccessor(diffs)
}
return elements.reversed().fold(0, accumulateOperation)
}
}
| 0 | Kotlin | 0 | 0 | fab1dd509607eab3c66576e3459df0c4f0f2fd94 | 1,492 | advent-of-code-2023 | MIT License |
src/main/kotlin/g0001_0100/s0095_unique_binary_search_trees_ii/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g0001_0100.s0095_unique_binary_search_trees_ii
// #Medium #Dynamic_Programming #Tree #Binary_Tree #Backtracking #Binary_Search_Tree
// #2023_07_10_Time_167_ms_(100.00%)_Space_36.6_MB_(100.00%)
import com_github_leetcode.TreeNode
/*
* Example:
* var ti = TreeNode(5)
* var v = ti.`val`
* Definition for a binary tree node.
* class TreeNode(var `val`: Int) {
* var left: TreeNode? = null
* var right: TreeNode? = null
* }
*/
class Solution {
fun generateTrees(n: Int): List<TreeNode?> {
var result: MutableList<TreeNode?> = ArrayList<TreeNode?>()
result.add(TreeNode(1))
for (i in 2..n) {
val nresult: MutableList<TreeNode?> = ArrayList<TreeNode?>()
for (r in result) {
var node = TreeNode(i, r, null)
nresult.add(node)
var previous: TreeNode? = r
while (previous != null) {
node = TreeNode(i)
val cr: TreeNode? = copy(r)
insert(cr, node, previous)
previous = node.left
nresult.add(cr)
}
}
result = nresult
}
return result
}
private fun insert(dest: TreeNode?, n: TreeNode, from: TreeNode) {
if (dest != null && dest.`val` == from.`val`) {
val h: TreeNode? = dest.right
dest.right = n
n.left = h
return
}
if (dest != null) {
insert(dest.right, n, from)
}
}
private fun copy(n: TreeNode?): TreeNode? {
return if (n == null) {
null
} else { TreeNode(n.`val`, copy(n.left), copy(n.right)) }
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,732 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/com/sherepenko/leetcode/challenges/Algorithms.kt | asherepenko | 264,648,984 | false | null | package com.sherepenko.leetcode.challenges
import com.sherepenko.leetcode.Solution
import com.sherepenko.leetcode.data.ListNode
import com.sherepenko.leetcode.solutions.AddTwoNumbers
import com.sherepenko.leetcode.solutions.Fibonacci
import com.sherepenko.leetcode.solutions.LengthOfLongestUniqueSubstring
import com.sherepenko.leetcode.solutions.LongestCommonSubstring
import com.sherepenko.leetcode.solutions.LongestPalindromicSubstring
import com.sherepenko.leetcode.solutions.OddEvenList
import com.sherepenko.leetcode.solutions.Palindrome
import com.sherepenko.leetcode.solutions.ReverseLinkedList
import com.sherepenko.leetcode.solutions.TwoSum
object Algorithms : Solution {
private val challenges = listOf(
TwoSum(
numbers = intArrayOf(2, 7, 11, 15),
target = 9
),
AddTwoNumbers(
head1 = ListNode(2).apply {
next = ListNode(4)
next!!.next = ListNode(3)
},
head2 = ListNode(5).apply {
next = ListNode(6)
next!!.next = ListNode(4)
}
),
LengthOfLongestUniqueSubstring(
str = "abcabcbb"
),
ReverseLinkedList(
head = ListNode(1).apply {
next = ListNode(2)
next!!.next = ListNode(3)
next!!.next!!.next = ListNode(4)
next!!.next!!.next!!.next = ListNode(5)
}
),
OddEvenList(
head = ListNode(1).apply {
next = ListNode(2)
next!!.next = ListNode(3)
next!!.next!!.next = ListNode(4)
next!!.next!!.next!!.next = ListNode(5)
}
),
Palindrome(
str = "test"
),
Fibonacci(
number = 10
),
LongestCommonSubstring(
text1 = "abc",
text2 = "fabcd"
),
LongestPalindromicSubstring(
str = "babbad"
)
)
override fun resolve() {
println("========== A L G O R I T H M S ==========")
challenges.forEach {
it.resolve()
}
}
}
| 0 | Kotlin | 0 | 0 | 49e676f13bf58f16ba093f73a52d49f2d6d5ee1c | 2,188 | leetcode | The Unlicense |
leetcode2/src/leetcode/shuffle-an-array.kt | hewking | 68,515,222 | false | null | package leetcode
import java.util.*
/**
* 384. 打乱数组
* https://leetcode-cn.com/problems/shuffle-an-array/
* Created by test
* Date 2019/7/19 1:18
* Description
* 打乱一个没有重复元素的数组。
示例:
// 以数字集合 1, 2 和 3 初始化数组。
int[] nums = {1,2,3};
Solution solution = new Solution(nums);
// 打乱数组 [1,2,3] 并返回结果。任何 [1,2,3]的排列返回的概率应该相同。
solution.shuffle();
// 重设数组到它的初始状态[1,2,3]。
solution.reset();
// 随机返回数组[1,2,3]打乱后的结果。
solution.shuffle();
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shuffle-an-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
object ShffleAnArray {
@JvmStatic
fun main(args: Array<String>) {
Solution(arrayOf(3,2,5,6,34,32,13,87).toIntArray()).shuffle2()
}
class Solution(nums: IntArray) {
private var arr: IntArray = nums.copyOf()
/** Resets the array to its original configuration and return it. */
fun reset(): IntArray {
return arr
}
/** Returns a random shuffling of the array. */
fun shuffle(): IntArray {
val retval = arr.copyOf()
for (i in 0 until retval.size) {
val tmp = retval[i]
val j = (Math.random() * (retval.size - 1)).toInt()
retval[i] = retval[j]
retval[j]= tmp
}
return retval
}
fun shuffle2(): IntArray {
val retval = arr.copyOf()
val random = Random()
for (i in retval.size - 1 downTo 0) {
val x = random.nextInt(i + 1)
println(x)
val t = retval[i]
retval[i] = retval[x]
retval[x] = t
}
return retval
}
}
} | 0 | Kotlin | 0 | 0 | a00a7aeff74e6beb67483d9a8ece9c1deae0267d | 1,969 | leetcode | MIT License |
aoc2016/src/main/kotlin/io/github/ajoz/sequences/Sequences.kt | ajoz | 116,427,939 | false | null | package io.github.ajoz.sequences
/**
* Returns a sequence containing the results of applying the given [transform] function to each element in the original
* sequence and the result of previous application. For the case of first element in the sequence the [initial] value
* will be used as the "previous result" and passed to [transform] function.
* @param initial Initial element from which the scan should take place.
* @param transform Two argument function used to perform scan operation.
*/
fun <T, R> Sequence<T>.scan(initial: R, transform: (R, T) -> R): Sequence<R> {
return TransformingScanSequence(this, initial, transform)
}
/**
* A sequence which returns the results of applying the given [transformer] function to the values in the underlying
* [sequence]. Each [transformer] is given a previously calculated value and a new value. In case of the first element
* of the given [sequence] the [transformer] function will use [initial] as the "previously calculated value".
*/
internal class TransformingScanSequence<T, R>
constructor(private val sequence: Sequence<T>,
private val initial: R,
private val transformer: (R, T) -> R) : Sequence<R> {
override fun iterator(): Iterator<R> = object : Iterator<R> {
val iterator = sequence.iterator()
var previous = initial
override fun next(): R {
val mapped = transformer(previous, iterator.next())
previous = mapped
return mapped
}
override fun hasNext(): Boolean {
return iterator.hasNext()
}
}
}
/**
* Returns first repeated element in the [Sequence]. Can throw a [NoSuchElementException] if the [Sequence] doesn't have
* elements or there are no repeating elements
*/
fun <T> Sequence<T>.firstRepeated(): T {
val set = HashSet<T>()
for (element in this) {
if (set.contains(element)) return element
else set.add(element)
}
throw NoSuchElementException("Sequence contains no repeating elements")
}
| 0 | Kotlin | 0 | 0 | 49ba07dd5fbc2949ed3c3ff245d6f8cd7af5bebe | 2,039 | kotlin-workshop | Apache License 2.0 |
src/Day01.kt | kritanta | 574,453,685 | false | {"Kotlin": 8568} | fun main() {
fun getCalories(input: List<String>, numberToTake: Int): Int {
var elfTotals = mutableMapOf<Int,Int>()
var elfNumber = 0
input.forEach {
s ->
if(s.isNullOrEmpty()){
elfNumber++
}
else{
elfTotals[elfNumber] = elfTotals[elfNumber]?.plus(s.toInt()) ?: s.toInt()
}
}
return elfTotals.values.sortedDescending().take(numberToTake).sum();
}
fun part1(input: List<String>): Int {
return getCalories(input,1);
}
fun part2(input: List<String>): Int {
return getCalories(input,3);
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 834259cf076d0bfaf3d2e06d1bc1d5df13cffd6c | 950 | AOC-2022-Kotlin | Apache License 2.0 |
src/main/kotlin/nl/kelpin/fleur/advent2018/Extensions.kt | fdlk | 159,925,533 | false | null | package nl.kelpin.fleur.advent2018
import java.util.*
fun String.matchingChars(other: String): String =
this.zip(other).filter { it.first == it.second }
.map { it.first }
.joinToString("")
fun IntRange.overlaps(other: IntRange): Boolean =
start <= other.endInclusive && other.start <= endInclusive
fun IntRange.length(): Int = endInclusive - start + 1
fun IntRange.split(): Set<IntRange> =
if (endInclusive == start)
setOf(this)
else {
val halfWay = start + (endInclusive - start) / 2
setOf(start .. halfWay, halfWay+1..endInclusive)
}
fun IntRange.distance(x: Int) = when{
contains(x) -> 0
x < start -> start - x
else -> x - endInclusive
}
// Frequency counting
data class Frequency<T>(val element: T, val occurrence: Int)
fun <T> Collection<T>.mostFrequent(): Frequency<T> {
val (value: T, count: Int) = groupingBy { it }.eachCount().maxBy { it.value }!!
return Frequency(value, count)
}
fun List<Int>.range(): IntRange = min()!!..max()!!
fun IntRange.stretch(factor: Float): IntRange {
val diff = ((endInclusive - start) * factor).toInt()
return (start - diff) .. (endInclusive + diff)
}
fun <T> Deque<T>.cycle(n: Int) {
repeat(n) { addLast(removeFirst()) }
repeat(-n) { addFirst(removeLast()) }
}
fun <T> MutableList<T>.update(from: T, to: T?) {
if (to == null) {
remove(from)
} else {
val index = indexOf(from)
if (index != -1) {
this[index] = to
}
}
}
fun <T> Set<T>.split(predicate: (T) -> Boolean): Pair<Set<T>, Set<T>> {
val filtered = this.filter(predicate).toSet()
return filtered to this - filtered
}
fun Char.asDigit() = if (isDigit()) (this - '0').toByte() else throw IllegalArgumentException() | 0 | Kotlin | 0 | 3 | a089dbae93ee520bf7a8861c9f90731eabd6eba3 | 1,830 | advent-2018 | MIT License |
src/main/kotlin/g2401_2500/s2415_reverse_odd_levels_of_binary_tree/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2401_2500.s2415_reverse_odd_levels_of_binary_tree
// #Medium #Depth_First_Search #Breadth_First_Search #Tree #Binary_Tree
// #2023_07_04_Time_499_ms_(87.50%)_Space_47.7_MB_(12.50%)
import com_github_leetcode.TreeNode
import java.util.LinkedList
import java.util.Queue
/*
* Example:
* var ti = TreeNode(5)
* var v = ti.`val`
* Definition for a binary tree node.
* class TreeNode(var `val`: Int) {
* var left: TreeNode? = null
* var right: TreeNode? = null
* }
*/
class Solution {
private val list: MutableList<Int> = ArrayList()
fun reverseOddLevels(root: TreeNode): TreeNode? {
solve(root)
return enrich(list, 0)
}
private fun enrich(list: List<Int>, i: Int): TreeNode? {
var root: TreeNode? = null
if (i < list.size) {
root = TreeNode(list[i])
root.left = enrich(list, 2 * i + 1)
root.right = enrich(list, 2 * i + 2)
}
return root
}
private fun solve(root: TreeNode) {
val q: Queue<TreeNode?> = LinkedList()
q.add(root)
var level = 0
while (q.isNotEmpty()) {
val size = q.size
val res: MutableList<Int> = ArrayList()
for (i in 0 until size) {
val cur = q.remove()
res.add(cur!!.`val`)
if (cur.left != null) {
q.add(cur.left)
}
if (cur.right != null) {
q.add(cur.right)
}
}
if (level % 2 != 0) {
for (i in res.indices.reversed()) {
list.add(res[i])
}
} else {
list.addAll(res)
}
level++
}
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,776 | LeetCode-in-Kotlin | MIT License |
src/test/kotlin/adventofcode/day11/Day11.kt | jwcarman | 573,183,719 | false | {"Kotlin": 183494} | /*
* Copyright (c) 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package adventofcode.day11
import adventofcode.util.readAsString
import adventofcode.util.removeAll
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals
class Day11 {
@Test
fun example1() {
assertEquals(10605, calculatePart1(readAsString("day11-example.txt")))
}
@Test
fun part1() {
assertEquals(316888, calculatePart1(readAsString("day11.txt")))
}
@Test
fun example2() {
assertEquals(2713310158L, calculatePart2(readAsString("day11-example.txt")))
}
@Test
fun part2() {
assertEquals(35270398814L, calculatePart2(readAsString("day11.txt")))
}
private fun calculatePart1(input: String): Long {
val monkeys = parseMonkeys(input)
return playKeepAway(20, monkeys) { it / 3 }
}
private fun calculatePart2(input: String): Long {
val monkeys = parseMonkeys(input)
val productOfDivisors = monkeys.map { it.testDivisor }.reduce(Long::times)
return playKeepAway(10000, monkeys) { it % productOfDivisors }
}
private fun playKeepAway(rounds: Int, monkeys: List<Monkey>, worryLevelFn: (Long) -> Long): Long {
val inspectionCounts = monkeys.map { 0L }.toMutableList()
repeat(rounds) {
monkeys.forEachIndexed { i, monkey ->
while (monkey.items.isNotEmpty()) {
val (recipient, worryLevel) = monkey.inspectItem(worryLevelFn)
monkeys[recipient].items.add(worryLevel)
inspectionCounts[i]++
}
}
}
return monkeyBusiness(inspectionCounts)
}
private fun monkeyBusiness(inspectionCounts: MutableList<Long>) =
inspectionCounts.sortedDescending().take(2).reduce(Long::times)
private fun parseMonkeys(input: String) = input.split("\n\n").map { parseMonkey(it) }
data class Monkey(
val items: MutableList<Long>,
val operation: (Long) -> Long,
val testDivisor: Long,
val pass: Int,
val fail: Int
) {
fun inspectItem(worryLevelFn: (Long) -> Long): Pair<Int, Long> {
val value = worryLevelFn(operation(items.removeFirst()))
return if (value % testDivisor == 0L) {
Pair(pass, value)
} else {
Pair(fail, value)
}
}
}
private fun parseMonkey(input: String): Monkey {
val fields = input.replace("\n", "\t")
.removeAll(
" Starting items: ",
" Operation: new = ",
" Test: divisible by ",
" If true: throw to monkey ",
" If false: throw to monkey "
)
.split("\t")
return Monkey(
items = parseInitialItems(fields[1]),
operation = parseOperation(fields[2]),
testDivisor = fields[3].toLong(),
pass = fields[4].toInt(),
fail = fields[5].toInt()
)
}
private fun parseInitialItems(input: String): MutableList<Long> =
input.removeAll(" ").split(",").map { it.toLong() }.toMutableList()
private fun parseOperation(expression: String): (Long) -> Long {
return when {
expression == "old * old" -> { old -> old * old }
expression.startsWith("old *") -> { old -> old * parseOperand(expression) }
else -> { old -> old + parseOperand(expression) }
}
}
private fun parseOperand(expression: String) = expression.substringAfterLast(' ').toLong()
} | 0 | Kotlin | 0 | 0 | d6be890aa20c4b9478a23fced3bcbabbc60c32e0 | 4,172 | adventofcode2022 | Apache License 2.0 |
src/main/kotlin/com/jacobhyphenated/advent2022/day21/Day21.kt | jacobhyphenated | 573,603,184 | false | {"Kotlin": 144303} | package com.jacobhyphenated.advent2022.day21
import com.jacobhyphenated.advent2022.Day
/**
* Day 21: Monkey Math
*
* Monkey math involves monkeys yelling out numbers.
* Some always yell out a single number.
* Others yell out the math result of two other monkey's numbers.
*
* The puzzle input shows each monkey's name, and the number or math operation associated with that monkey.
*/
class Day21: Day<List<Monkey>> {
override fun getInput(): List<Monkey> {
return parseInput(readInputFile("day21"))
}
/**
* There is a monkey named root. What number does it yell out?
*/
override fun part1(input: List<Monkey>): Long {
val root = input.first { it.name == "root"}
return root.getNumber()
}
/**
* Root's operation is actually equals. The two monkey numbers in the operation should equal each other.
* The monkey named "humn" is you. Ignore the number next to "humn".
* What number should "humn" should out to make the root monkey's equivalence true?
*/
override fun part2(input: List<Monkey>): Long {
val root = input.first { it.name == "root"}
return if (root.operation!!.lhsMonkey.containsHuman()) {
val equal = root.operation!!.rhsMonkey.getNumber()
root.operation!!.lhsMonkey.determineHumanNumber(equal)
} else {
val equal = root.operation!!.lhsMonkey.getNumber()
root.operation!!.rhsMonkey.determineHumanNumber(equal)
}
}
fun parseInput(input: String): List<Monkey> {
val monkeyMap = mutableMapOf<String, Monkey>()
for (line in input.lines()) {
val (name, value) = line.split(": ")
val monkey = monkeyMap.getOrPut(name) { Monkey(name) }
val operation = value.trim().split(" ")
if (operation.size == 1) {
monkey.number = operation[0].toLong()
}
else {
val (m1, operator, m2) = operation
val monkey1 = monkeyMap.getOrPut(m1) { Monkey(m1) }
val monkey2 = monkeyMap.getOrPut(m2) { Monkey(m2) }
monkey.operation = Operation(monkey1, monkey2, operator)
}
}
return monkeyMap.values.toList()
}
}
class Monkey (val name: String, var number: Long? = null, var operation: Operation? = null) {
var resolveOperation: Long? = null
// Recursive, since we need to know the other monkey's results first
fun getNumber(): Long {
if (number != null) {
return number!!
}
// some lite memoization for performance
if (resolveOperation != null) {
return resolveOperation!!
}
return operation!!.invoke().also {
resolveOperation = it
}
}
fun containsHuman(): Boolean {
if (name == "humn") { return true }
if (number != null) { return false }
return operation!!.lhsMonkey.containsHuman() || operation!!.rhsMonkey.containsHuman()
}
/**
* Figure out what the human needs to shout by reversing the algebra
* @param expectedResult The equals side of the operation such that:
* expectedResult = lhsMonkey.getNumber() operation rhsMonkey.getNumber()
*/
fun determineHumanNumber(expectedResult: Long): Long {
if (name == "humn") {
return expectedResult
}
val op = operation!!
// do some algebra. Pretty ugly
return when (op.operator) {
"*" -> {
if (op.lhsMonkey.containsHuman()) {
val otherNumber = op.rhsMonkey.getNumber()
op.lhsMonkey.determineHumanNumber(expectedResult / otherNumber)
} else {
val otherNumber = op.lhsMonkey.getNumber()
op.rhsMonkey.determineHumanNumber(expectedResult / otherNumber)
}
}
"/" -> {
if (op.lhsMonkey.containsHuman()) {
val otherNumber = op.rhsMonkey.getNumber()
op.lhsMonkey.determineHumanNumber(expectedResult * otherNumber)
} else {
val otherNumber = op.lhsMonkey.getNumber()
op.rhsMonkey.determineHumanNumber(otherNumber / expectedResult)
}
}
"+" -> {
if (op.lhsMonkey.containsHuman()) {
val otherNumber = op.rhsMonkey.getNumber()
op.lhsMonkey.determineHumanNumber(expectedResult - otherNumber)
} else {
val otherNumber = op.lhsMonkey.getNumber()
op.rhsMonkey.determineHumanNumber(expectedResult - otherNumber)
}
}
"-" -> {
if (op.lhsMonkey.containsHuman()) {
val otherNumber = op.rhsMonkey.getNumber()
op.lhsMonkey.determineHumanNumber(expectedResult + otherNumber)
} else {
val otherNumber = op.lhsMonkey.getNumber()
op.rhsMonkey.determineHumanNumber((expectedResult - otherNumber) * -1)
}
}
else -> throw NotImplementedError("Invalid operator ${op.operator}")
}
}
}
// Helper class to store the LHS and RHS sides of the operation and the mathematical operator
class Operation(val lhsMonkey: Monkey, val rhsMonkey: Monkey, val operator: String) {
fun invoke(): Long {
val lhs = lhsMonkey.getNumber()
val rhs = rhsMonkey.getNumber()
return when(operator) {
"+" -> lhs + rhs
"-" -> lhs - rhs
"*" -> lhs * rhs
"/" -> lhs / rhs
else -> throw NotImplementedError("Invalid Operation")
}
}
} | 0 | Kotlin | 0 | 0 | 9f4527ee2655fedf159d91c3d7ff1fac7e9830f7 | 5,834 | advent2022 | The Unlicense |
src/main/kotlin/net/voldrich/aoc2023/Day01.kt | MavoCz | 434,703,997 | false | {"Kotlin": 119158} | package net.voldrich.aoc2023
import net.voldrich.BaseDay
// https://adventofcode.com/2023/day/1
fun main() {
Day01().run()
}
class Day01 : BaseDay() {
override fun task1() : Int {
return input.lines().filter { it.isNotBlank() }.sumOf { line ->
val digits = line.filter { it.isDigit() }
val first = Character.getNumericValue(digits.first())
val last = Character.getNumericValue(digits.last())
first * 10 + last
}
}
private val numbers = mapOf(
"one" to 1,
"two" to 2,
"three" to 3,
"four" to 4,
"five" to 5,
"six" to 6,
"seven" to 7,
"eight" to 8,
"nine" to 9,
"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
)
override fun task2() : Int {
return input.lines().filter { it.isNotBlank() }.sumOf { line ->
val first = line.findAnyOf(numbers.keys)?.second?.let { numbers.getOrDefault(it, 0) } ?: 0
val last = line.findLastAnyOf(numbers.keys)?.second?.let { numbers.getOrDefault(it, 0) } ?: 0
first * 10 + last
}
}
}
| 0 | Kotlin | 0 | 0 | 0cedad1d393d9040c4cc9b50b120647884ea99d9 | 1,249 | advent-of-code | Apache License 2.0 |
src/main/kotlin/github/walkmansit/aoc2020/Day17.kt | walkmansit | 317,479,715 | false | null | package github.walkmansit.aoc2020
class Day17(val input: List<String>) : DayAoc<Int, Int> {
private class Simulation(val inpLines: List<String>, val turns: Int) {
private fun increaseRange(range: IntRange): IntRange {
return range.first - 1..range.last + 1
}
fun simulate3DAndGetSum(): Int {
var deep = 0 // z
var height = 0 // y
var width = 0 // x
var activeZ = 0..1
var activeY = 0..1
var activeX = 0..1
fun initGreed(): Array<Array<Array<Boolean>>> {
val offset = turns + 1
height = inpLines.size + 2 * offset
width = inpLines[0].length + 2 * offset
deep = 1 + 2 * offset
activeZ = (offset..offset)
activeX = (offset until offset + inpLines[0].length)
activeY = (offset until offset + inpLines.size)
val result = Array(deep) { Array(height) { Array(width) { false } } }
for ((i, line) in inpLines.withIndex())
for ((j, char) in line.withIndex()) {
if (char == '#') { // isActive
result[offset][offset + i][offset + j] = true
}
}
return result
}
var greed = initGreed() // Z,Y,X
fun getNextTurnSimulation(): Array<Array<Array<Boolean>>> {
fun cloneCurrentGreed(): Array<Array<Array<Boolean>>> {
val result = Array(deep) { Array(height) { Array(width) { false } } }
for (z in activeZ)
for (y in activeY)
for (x in activeX)
if (greed[z][y][x]) result[z][y][x] = true
return result
}
fun getActiveNeigbordsCount(z: Int, y: Int, x: Int): Int {
val range = -1..1
var sum = 0
for (i in range)
for (j in range)
for (k in range) {
if (i == 0 && j == 0 && k == 0)
continue
if (greed[z + i][y + j][x + k]) sum++
}
return sum
}
val buffer = cloneCurrentGreed()
for (z in activeZ)
for (y in activeY)
for (x in activeX) {
val activeCount = getActiveNeigbordsCount(z, y, x)
buffer[z][y][x] =
if (greed[z][y][x]) {
activeCount == 2 || activeCount == 3
} else (activeCount == 3)
}
return buffer
}
var currentTurn = 0
while (currentTurn != turns) {
activeZ = increaseRange(activeZ)
activeY = increaseRange(activeY)
activeX = increaseRange(activeX)
greed = getNextTurnSimulation()
currentTurn++
}
var sum = 0
for (z in 0 until deep)
for (y in 0 until height)
for (x in 0 until width)
if (greed[z][y][x]) sum++
return sum
}
fun simulate4DAndGetSum(): Int {
var deep = 0 // z
var height = 0 // y
var width = 0 // x
var vsize = 0 // v
var activeZ = 0..1
var activeY = 0..1
var activeX = 0..1
var activeV = 0..1
fun initGreed(): Array<Array<Array<Array<Boolean>>>> {
val offset = turns + 1
height = inpLines.size + 2 * offset
width = inpLines[0].length + 2 * offset
vsize = inpLines.size + 2 * offset
deep = 1 + 2 * offset
activeZ = (offset..offset)
activeX = (offset until offset + inpLines[0].length)
activeY = (offset until offset + inpLines.size)
activeV = (offset..offset)
val result = Array(deep) { Array(height) { Array(width) { Array(vsize) { false } } } }
for ((i, line) in inpLines.withIndex())
for ((j, char) in line.withIndex()) {
if (char == '#') { // isActive
result[offset][offset + i][offset + j][offset] = true
}
}
return result
}
var greed = initGreed() // Z,Y,X
fun getNextTurnSimulation(): Array<Array<Array<Array<Boolean>>>> {
fun cloneCurrentGreed(): Array<Array<Array<Array<Boolean>>>> {
val result = Array(deep) { Array(height) { Array(width) { Array(vsize) { false } } } }
for (z in activeZ)
for (y in activeY)
for (x in activeX)
for (v in activeV)
if (greed[z][y][x][v]) result[z][y][x][v] = true
return result
}
fun getActiveNeigbordsCount(z: Int, y: Int, x: Int, v: Int): Int {
val range = -1..1
var sum = 0
for (i in range)
for (j in range)
for (k in range)
for (m in range) {
if (i == 0 && j == 0 && k == 0 && m == 0)
continue
if (greed[z + i][y + j][x + k][v + m]) sum++
}
return sum
}
val buffer = cloneCurrentGreed()
for (z in activeZ)
for (y in activeY)
for (x in activeX)
for (v in activeV) {
val activeCount = getActiveNeigbordsCount(z, y, x, v)
buffer[z][y][x][v] =
if (greed[z][y][x][v]) {
activeCount == 2 || activeCount == 3
} else (activeCount == 3)
}
return buffer
}
var currentTurn = 0
while (currentTurn != turns) {
activeZ = increaseRange(activeZ)
activeY = increaseRange(activeY)
activeX = increaseRange(activeX)
activeV = increaseRange(activeV)
greed = getNextTurnSimulation()
currentTurn++
}
var sum = 0
for (z in 0 until deep)
for (y in 0 until height)
for (x in 0 until width)
for (v in 0 until vsize)
if (greed[z][y][x][v]) sum++
return sum
}
}
override fun getResultPartOne(): Int {
return Simulation(input, 6).simulate3DAndGetSum()
}
override fun getResultPartTwo(): Int {
return Simulation(input, 6).simulate4DAndGetSum()
}
}
| 0 | Kotlin | 0 | 0 | 9c005ac4513119ebb6527c01b8f56ec8fd01c9ae | 7,573 | AdventOfCode2020 | MIT License |
src/main/kotlin/advent/of/code/day17/Solution.kt | brunorene | 160,263,437 | false | null | package advent.of.code.day17
import java.io.File
import java.util.*
class Position(name1: String, val1: Int, val2: Int) : Comparable<Position> {
val x: Int
val y: Int
init {
if (name1 == "x") {
x = val1
y = val2
} else {
x = val2
y = val1
}
}
override fun compareTo(other: Position): Int {
return compareBy<Position>({ it.y }, { it.x }).compare(this, other)
}
override fun toString(): String {
return "(${x.toString().padStart(3, ' ')},${y.toString().padStart(3, ' ')})"
}
}
val input = File("day17.txt")
val multipleCoord = Regex("(x|y)=([.0-9]+)\\.\\.([.0-9]+)")
val oneCoord = Regex("(x|y)=([.0-9]+)")
class Underground(input: File) {
val clay: MutableSet<Position> = TreeSet()
init {
input.readLines().forEach { line ->
val parts = line.split(",").map { it.trim() }
var multiResult = multipleCoord.find(parts[0])
if (multiResult != null) {
val coordName1 = multiResult.groupValues[1]
val startCoord1 = multiResult.groupValues[2].toInt()
val endCoord1 = multiResult.groupValues[3].toInt()
val oneResult = oneCoord.find(parts[1])
val startCoord2 = oneResult!!.groupValues[2].toInt()
for (c in (startCoord1..endCoord1))
clay.add(Position(coordName1, c, startCoord2))
} else {
val oneResult = oneCoord.find(parts[0])
val coordName1 = oneResult!!.groupValues[1]
val startCoord1 = oneResult.groupValues[2].toInt()
multiResult = multipleCoord.find(parts[1])
val startCoord2 = multiResult!!.groupValues[2].toInt()
val endCoord2 = multiResult.groupValues[3].toInt()
for (c in (startCoord2..endCoord2))
clay.add(Position(coordName1, startCoord1, c))
}
}
}
}
fun part1(): Int {
val underground = Underground(input)
println(underground.clay)
return 1
}
fun part2() = 2 | 0 | Kotlin | 0 | 0 | 0cb6814b91038a1ab99c276a33bf248157a88939 | 2,139 | advent_of_code_2018 | The Unlicense |
src/main/kotlin/days/Day2.kt | butnotstupid | 571,247,661 | false | {"Kotlin": 90768} | package days
class Day2 : Day(2) {
// A < B < C < A
// X < Y < Z < X
private val winsTo = mapOf('A' to 'B', 'B' to 'C', 'C' to 'A')
private val loseTo = mapOf('B' to 'A', 'C' to 'B', 'A' to 'C')
override fun partOne(): Any {
return inputList.sumOf {
val (one, another) = it[0] to Char('A'.code + it[2].code - 'X'.code)
val winPoints = when {
winsTo[one] == another -> 6
one == another -> 3
else -> 0
}
another.points() + winPoints
}
}
override fun partTwo(): Any {
return inputList.sumOf {
val (one, result) = it[0] to it[2]
when (result) {
'X' -> 0 + loseTo.getValue(one).points()
'Y' -> 3 + one.points()
'Z' -> 6 + winsTo.getValue(one).points()
else -> error("Unexpected input $it")
}
}
}
private fun Char.points() = 1 + this.code - 'A'.code
}
| 0 | Kotlin | 0 | 0 | 4760289e11d322b341141c1cde34cfbc7d0ed59b | 1,016 | aoc-2022 | Creative Commons Zero v1.0 Universal |
src/Day01.kt | georgiizorabov | 573,050,504 | false | {"Kotlin": 10501} | fun main() {
fun read(input: List<String>): List<Int> {
var input1 = input
val list: MutableList<Int> = arrayListOf()
var i = 0
repeat(input1.size) {
i += 1
list.add(input1.takeWhile { elem -> elem != "" }.sumOf { it.toInt() })
input1 = input1.dropWhile { elem -> elem != "" }.drop(1)
}
return list
}
fun part1(input: List<String>): Int {
return read(input).max()
}
fun part2(input: List<String>): Int {
return read(input).sorted().takeLast(3).sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01.txt")
check(part1(testInput) == 1)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | bf84e55fe052c9c5f3121c245a7ae7c18a70c699 | 817 | aoc2022 | Apache License 2.0 |
src/main/kotlin/me/peckb/aoc/_2018/calendar/day03/Day03.kt | peckb1 | 433,943,215 | false | {"Kotlin": 956135} | package me.peckb.aoc._2018.calendar.day03
import me.peckb.aoc.generators.InputGenerator.InputGeneratorFactory
import javax.inject.Inject
class Day03 @Inject constructor(private val generatorFactory: InputGeneratorFactory) {
fun partOne(filename: String) = generatorFactory.forFile(filename).readAs(::pattern) { input ->
val fabric = Array(FABRIC_SIZE) { Array(FABRIC_SIZE) { 0 } }
input.forEach { pattern ->
(pattern.startX..pattern.endX).forEach { x ->
(pattern.startY..pattern.endY).forEach { y ->
fabric[y][x]++
}
}
}
fabric.sumOf { row -> row.count { it >= 2 } }
}
fun partTwo(filename: String) = generatorFactory.forFile(filename).readAs(::pattern) { input ->
val patterns = input.toList()
val patternWithNoOverlaps = patterns.withIndex().find { indexedPattern ->
!(patterns.indices).any { patternIndex ->
if (patternIndex == indexedPattern.index) {
false
} else {
val overlap = indexedPattern.value.overlaps(patterns[patternIndex])
overlap
}
}
}
patternWithNoOverlaps?.value?.id
}
private fun pattern(line: String): Pattern {
// #1 @ 1,3: 4x4
val parts = line.split(" ")
val id = parts[0].drop(1).toInt()
val startY = parts[2].substringAfter(",").dropLast(1).toInt()
val startX = parts[2].substringBefore(",").toInt()
val endY = startY + parts[3].substringAfter("x").toInt() - 1
val endX = startX + parts[3].substringBefore("x").toInt() - 1
return Pattern(id, startY, startX, endY, endX)
}
data class Pattern(val id: Int, val startY: Int, val startX: Int, val endY: Int, val endX: Int) {
fun overlaps(other: Pattern): Boolean {
return startX <= other.endX && endX >= other.startX && startY <= other.endY && endY >= other.startY
}
}
companion object {
const val FABRIC_SIZE = 1000
}
}
| 0 | Kotlin | 1 | 3 | 2625719b657eb22c83af95abfb25eb275dbfee6a | 1,907 | advent-of-code | MIT License |
src/Day10.kt | chrisjwirth | 573,098,264 | false | {"Kotlin": 28380} | import kotlin.math.abs
fun main() {
class SignalCalculator(
val input: List<String>,
val cyclesToConsider: List<Int>,
val shouldUpdateScreen: Boolean
) {
private var cycle = 1
private var registerValue = 1
private var sumOfConsideredCycles = 0
private val screenHeight = cyclesToConsider.size
private val screenWidth = cyclesToConsider[0]
private val screen = List(screenHeight) { MutableList(screenWidth) { '.' } }
init {
processInstructions()
}
private fun parsedInstruction(instruction: String): String {
return instruction.substring(0, 4)
}
private fun parsedValueToAdd(instruction: String): Int {
return instruction.substring(5).toInt()
}
private fun addConsideredCyclesToSum() {
if (cycle in cyclesToConsider) sumOfConsideredCycles += (cycle * registerValue)
}
private fun updateScreen() {
if (!shouldUpdateScreen) return
val crtVerticalPosition = (cycle - 1).floorDiv(screenWidth)
val crtHorizontalPosition = (cycle - 1) % screenWidth
val spriteHorizontalPosition = registerValue % screenWidth
if (abs(crtHorizontalPosition - spriteHorizontalPosition) <= 1) {
screen[crtVerticalPosition][crtHorizontalPosition] = '#'
}
}
private fun incrementCycle() {
cycle++
addConsideredCyclesToSum()
}
private fun noopHandler() {
updateScreen()
incrementCycle()
updateScreen()
}
private fun addxHandler(value: Int) {
updateScreen()
incrementCycle()
updateScreen()
registerValue += value
incrementCycle()
}
private fun processInstructions() {
input.forEach {
if (parsedInstruction(it) == "noop") {
noopHandler()
} else {
addxHandler(parsedValueToAdd(it))
}
}
}
fun getSumOfConsideredCycles(): Int {
return sumOfConsideredCycles
}
fun drawScreen() {
screen.forEach {
println(it.joinToString(" "))
}
}
}
fun part1(input: List<String>): Int {
val cyclesToConsider = listOf(20, 60, 100, 140, 180, 220)
val signalCalculator = SignalCalculator(input, cyclesToConsider, false)
return signalCalculator.getSumOfConsideredCycles()
}
fun part2(input: List<String>) {
val cyclesToConsider = listOf(40, 80, 120, 160, 200, 240)
val signalCalculator = SignalCalculator(input, cyclesToConsider, true)
signalCalculator.drawScreen()
}
// Test
val testInput = readInput("Day10_test")
check(part1(testInput) == 13140)
part2(testInput)
// Final
val input = readInput("Day10")
println(part1(input))
part2(input)
} | 0 | Kotlin | 0 | 0 | d8b1f2a0d0f579dd23fa1dc1f7b156f728152c2d | 3,078 | AdventOfCode2022 | Apache License 2.0 |
advent-of-code-2022/src/main/kotlin/eu/janvdb/aoc2022/day13/IntTree.kt | janvdbergh | 318,992,922 | false | {"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335} | package eu.janvdb.aoc2022.day13
interface TreeItem : Comparable<TreeItem>
class TreeLeaf(val value: Int) : TreeItem {
override fun compareTo(other: TreeItem): Int {
if (other is TreeLeaf) {
return this.value.compareTo(other.value)
}
return TreeNode(listOf(this)).compareTo(other)
}
override fun toString(): String = value.toString()
}
class TreeNode(val items: List<TreeItem>) : TreeItem {
override fun compareTo(other: TreeItem): Int {
return if (other is TreeNode) {
this.compareTo(other)
} else {
this.compareTo(TreeNode(listOf(other)))
}
}
private fun compareTo(other: TreeNode): Int {
var index = 0
while (index < this.items.size && index < other.items.size) {
val value = this.items[index].compareTo(other.items[index])
if (value!=0) return value
index++
}
return this.items.size.compareTo(other.items.size)
}
override fun toString(): String = items.toString()
}
fun String.toTreeNode(): TreeItem {
fun readTreeItem(from: Int): Pair<TreeItem, Int> {
fun readLeaf(from: Int): Pair<TreeItem, Int> {
var index = from
var value = 0
while (this[index].isDigit()) {
value = value * 10 + (this[index] - '0')
index++
}
return Pair(TreeLeaf(value), index)
}
fun readNode(from: Int): Pair<TreeItem, Int> {
var index = from + 1
val items = mutableListOf<TreeItem>()
while (this[index] != ']') {
if (this[index] == ',') {
index++
} else {
val pair = readTreeItem(index)
items.add(pair.first)
index = pair.second
}
}
return Pair(TreeNode(items), index + 1)
}
return if (this[from] == '[') readNode(from) else readLeaf(from)
}
return readTreeItem(0).first
} | 0 | Java | 0 | 0 | 78ce266dbc41d1821342edca484768167f261752 | 1,691 | advent-of-code | Apache License 2.0 |
year2021/day12/caves/src/main/kotlin/com/curtislb/adventofcode/year2021/day12/caves/CaveSystem.kt | curtislb | 226,797,689 | false | {"Kotlin": 2146738} | package com.curtislb.adventofcode.year2021.day12.caves
/**
* A system of large and small caves, connected by undirected edges (representing passages).
*
* @param cavesString A string representing the cave system. Each line must be of the form
* `"${caveA}-${caveB}"`, indicating that an edge exists between `caveA` and `caveB`.
*
* @throws IllegalArgumentException If `cavesString` does not match the required format.
*/
class CaveSystem(cavesString: String) {
/**
* A map from each cave to all caves that are connected to it by an edge.
*/
private val edges: Map<String, Set<String>> = mutableMapOf<String, MutableSet<String>>().apply {
for (line in cavesString.trim().lines()) {
val matchResult = EDGE_REGEX.matchEntire(line.trim())
require(matchResult != null) { "Malformed edge string: $line" }
// Add an edge from caveA to caveB, and vice versa
val (caveA, caveB) = matchResult.destructured
getOrPut(caveA) { mutableSetOf() }.add(caveB)
getOrPut(caveB) { mutableSetOf() }.add(caveA)
}
}
/**
* Returns the number of valid paths through the cave system from [startCave] to [endCave].
*
* A path is valid if it visits [startCave] and [endCave] exactly once each and visits any other
* previously-visited small cave at most [maxSmallRepeatCount] times. Other large caves can be
* visited any number of times along a valid path.
*
* A cave is small if the first character of its name is a lowercase letter. All other caves are
* large.
*
* @throws IllegalArgumentException If either of [startCave] or [endCave] is a large cave, or if
* [maxSmallRepeatCount] is negative.
*/
fun countPaths(startCave: String, endCave: String, maxSmallRepeatCount: Int = 0): Int {
require(startCave.isSmallCave()) { "Start cave must be a small cave: $startCave" }
require(endCave.isSmallCave()) { "End cave must be a small cave: $endCave" }
require(maxSmallRepeatCount >= 0) {
"Maximum repeat count must be non-negative: $maxSmallRepeatCount"
}
return countPathsInternal(
startCave,
endCave,
maxSmallRepeatCount,
originalStartCave = startCave,
visitedSmallCaves = mutableSetOf()
)
}
/**
* Recursive helper function for [countPaths].
*/
private fun countPathsInternal(
cave: String,
endCave: String,
maxSmallRepeatCount: Int,
originalStartCave: String,
visitedSmallCaves: MutableSet<String>
): Int =
if (cave == endCave) {
// Base case: There's only one valid path from a cave to itself
1
} else {
// Mark this cave as visited if it isn't already
val isFirstVisit = if (cave.isSmallCave()) {
visitedSmallCaves.add(cave)
} else {
false
}
// Count the number of paths from this cave
val pathCount = edges.getOrDefault(cave, emptySet()).sumOf { nextCave ->
when {
// A valid path can't revisit the original start cave
nextCave == originalStartCave -> 0
// Count all paths from the next cave if it's unvisited
nextCave !in visitedSmallCaves ->
countPathsInternal(
nextCave,
endCave,
maxSmallRepeatCount,
originalStartCave,
visitedSmallCaves
)
// Count paths from the next (visited) cave if it can be repeated
nextCave in visitedSmallCaves && maxSmallRepeatCount > 0 ->
countPathsInternal(
nextCave,
endCave,
maxSmallRepeatCount - 1,
originalStartCave,
visitedSmallCaves
)
// The next cave is visited and can't be repeated
else -> 0
}
}
// Un-mark this cave as visited before returning (if needed)
if (isFirstVisit) {
visitedSmallCaves.remove(cave)
}
pathCount
}
companion object {
/**
* A regex matching an undirected edge between two caves.
*/
private val EDGE_REGEX = Regex("""([a-zA-Z]+)-([a-zA-Z]+)""")
/**
* Checks if this string name corresponds to a small cave, rather than a large one.
*
* See [countPaths] for the definitions of small and large caves.
*/
private fun String.isSmallCave(): Boolean = first().isLowerCase()
}
}
| 0 | Kotlin | 1 | 1 | 6b64c9eb181fab97bc518ac78e14cd586d64499e | 4,986 | AdventOfCode | MIT License |
aoc-2018/src/main/kotlin/nl/jstege/adventofcode/aoc2018/days/Day02.kt | JStege1206 | 92,714,900 | false | null | package nl.jstege.adventofcode.aoc2018.days
import nl.jstege.adventofcode.aoccommon.days.Day
import nl.jstege.adventofcode.aoccommon.utils.extensions.*
class Day02 : Day(title = "Inventory Management System") {
override fun first(input: Sequence<String>): Any = input
.asSequence()
.map { id -> id.groupingBy { it }.eachCount().values }
.fold(Pair(0, 0)) { (twos, threes), counts ->
Pair(
if (2 in counts) twos + 1 else twos,
if (3 in counts) threes + 1 else threes
)
}.let { (twos, threes) -> twos * threes }
override fun second(input: Sequence<String>): Any = input
.toList()
.tails()
.asSequence()
.flatMap { c -> c.head.let { head -> c.tail.map { Pair(head, it) }.asSequence() } }
.mapNotNull { (current, other) ->
current.extractCommonCharacters(other).takeIf { it.length == current.length - 1 }
}
.first()
private fun String.extractCommonCharacters(other: String): String =
this.iterator().extractCommonCharacters(other.iterator())
private fun CharIterator.extractCommonCharacters(other: CharIterator): String {
tailrec fun extractCommon(
t: Char,
o: Char,
diffs: Int,
acc: StringBuilder
): StringBuilder =
if (diffs > 1) acc
else if (!this.hasNext() || !other.hasNext()) acc.applyIf({ t == o }) { append(t) }
else if (t == o) extractCommon(this.next(), other.next(), diffs, acc.append(t))
else extractCommon(this.next(), other.next(), diffs + 1, acc)
return extractCommon(this.next(), other.next(), 0, StringBuilder()).toString()
}
}
| 0 | Kotlin | 0 | 0 | d48f7f98c4c5c59e2a2dfff42a68ac2a78b1e025 | 1,751 | AdventOfCode | MIT License |
advent-of-code-2020/src/main/kotlin/eu/janvdb/aoc2020/day11/Seating.kt | janvdbergh | 318,992,922 | false | {"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335} | package eu.janvdb.aoc2020.day11
enum class Seat(val symbol: Char) {
FLOOR('.'), EMPTY('L'), FILLED('#')
}
fun toSeat(symbol: Char): Seat {
return Seat.values()
.find { it.symbol == symbol }!!
}
class Seating {
private val width: Int
private val height: Int
private val seats: List<Seat>
constructor(input: List<String>) {
width = input[0].length
height = input.size
seats = IntRange(0, height - 1)
.flatMap { x -> IntRange(0, width - 1).map { y -> input[x][y] } }
.map(::toSeat)
}
constructor(width: Int, height: Int, seats: List<Seat>) {
this.width = width
this.height = height
this.seats = seats
}
fun getSeat(x: Int, y: Int): Seat {
if (x < 0 || x >= height || y < 0 || y >= width) return Seat.EMPTY
return seats[x * width + y]
}
fun print() {
for (x in 0 until height) {
for (y in 0 until width) {
val seat = getSeat(x, y)
print(seat.symbol)
}
println()
}
val numberFilled = seats.count { seat -> seat == Seat.FILLED }
println("${numberFilled} seats filled.")
println()
}
fun step1(): Seating {
fun filled(x: Int, y: Int): Int {
return if (getSeat(x, y) == Seat.FILLED) 1 else 0
}
fun calculateNext(x: Int, y: Int): Seat {
val filledNeighbours =
filled(x - 1, y - 1) + filled(x - 1, y) + filled(x - 1, y + 1) +
filled(x, y - 1) + filled(x, y + 1) +
filled(x + 1, y - 1) + filled(x + 1, y) + filled(x + 1, y + 1)
val seat = getSeat(x, y)
if (seat == Seat.FILLED && filledNeighbours >= 4) return Seat.EMPTY
if (seat == Seat.EMPTY && filledNeighbours == 0) return Seat.FILLED
return seat
}
val newSeats = IntRange(0, height - 1)
.flatMap { x -> IntRange(0, width - 1).map { y -> calculateNext(x, y) } }
return Seating(width, height, newSeats)
}
fun step2(): Seating {
fun filled(x: Int, y: Int, stepX: Int, stepY: Int): Int {
when (getSeat(x, y)) {
Seat.FILLED -> return 1
Seat.EMPTY -> return 0
Seat.FLOOR -> return filled(x + stepX, y + stepY, stepX, stepY)
}
}
fun calculateNext(x: Int, y: Int): Seat {
val filledNeighbours = filled(x - 1, y - 1, -1, -1) +
filled(x - 1, y, -1, 0) +
filled(x - 1, y + 1, -1, +1) +
filled(x, y - 1, 0, -1) +
filled(x, y + 1, 0, +1) +
filled(x + 1, y - 1, +1, -1) +
filled(x + 1, y, +1, 0) +
filled(x + 1, y + 1, +1, +1)
val seat = getSeat(x, y)
if (seat == Seat.FILLED && filledNeighbours >= 5) return Seat.EMPTY
if (seat == Seat.EMPTY && filledNeighbours == 0) return Seat.FILLED
return seat
}
val newSeats = IntRange(0, height - 1)
.flatMap { x -> IntRange(0, width - 1).map { y -> calculateNext(x, y) } }
return Seating(width, height, newSeats)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Seating
if (width != other.width) return false
if (height != other.height) return false
if (seats != other.seats) return false
return true
}
override fun hashCode(): Int {
var result = width
result = 31 * result + height
result = 31 * result + seats.hashCode()
return result
}
} | 0 | Java | 0 | 0 | 78ce266dbc41d1821342edca484768167f261752 | 3,148 | advent-of-code | Apache License 2.0 |
src/main/kotlin/days/Day19.kt | andilau | 399,220,768 | false | {"Kotlin": 85768} | package days
@AdventOfCodePuzzle(
name = "<NAME>",
url = "https://adventofcode.com/2020/day/19",
date = Date(day = 19, year = 2020)
)
class Day19(lines: List<String>) : Puzzle {
private val dictionary: MutableMap<String, List<List<String>>> = readRules(lines)
private val messages = readMessages(lines)
override fun partOne() = messages.count { match(it) }
override fun partTwo(): Int {
dictionary["8"] = "42 | 42 8".parseRuleLine()
dictionary["11"] = "42 31 | 42 11 31".parseRuleLine()
return partOne()
}
fun match(message: String, rules: List<String> = dictionary.getValue("0").first()): Boolean {
if (message.isEmpty() && rules.isEmpty()) return true
if (message.isEmpty() || rules.isEmpty()) return false
val firstRule = rules.first()
return when {
// match found
message[0] == firstRule[0] ->
match(message.drop(1), rules.drop(1))
// reference found
dictionary.containsKey(firstRule) ->
dictionary.getValue(firstRule)
.any { match(message, it + rules.drop(1)) }
else -> false
}
}
private fun readRules(input: List<String>) = input
.takeWhile { it.isNotEmpty() }
.associate { line ->
line.substringBefore(": ") to line
.substringAfter(": ")
.parseRuleLine()
}.toMutableMap()
private fun String.parseRuleLine() = split(" | ")
.map { orRule ->
orRule
.split(" ")
.map { it.trim('\"') }
}
private fun readMessages(input: List<String>) = input.dropWhile { it.isNotBlank() }.drop(1)
} | 7 | Kotlin | 0 | 0 | 2809e686cac895482c03e9bbce8aa25821eab100 | 1,757 | advent-of-code-2020 | Creative Commons Zero v1.0 Universal |
src/main/kotlin/io/github/clechasseur/adventofcode2021/Day12.kt | clechasseur | 435,726,930 | false | {"Kotlin": 315943} | package io.github.clechasseur.adventofcode2021
object Day12 {
private val data = """
start-kc
pd-NV
start-zw
UI-pd
HK-end
UI-kc
pd-ih
ih-end
start-UI
kc-zw
end-ks
MF-mq
HK-zw
LF-ks
HK-kc
ih-HK
kc-pd
ks-pd
MF-pd
UI-zw
ih-NV
ks-HK
MF-kc
zw-NV
NV-ks
""".trimIndent()
private val possiblePaths = data.lines().flatMap { line ->
val (a, b) = line.split("-")
listOf(a to b, b to a)
}.groupBy { it.first }.mapValues { (_, l) -> l.map { it.second } }
fun part1(): Int = paths(listOf("start"), false).count()
fun part2(): Int = paths(listOf("start"), true).count()
private fun paths(soFar: List<String>, canVisitOneTwice: Boolean): List<List<String>> {
if (soFar.last() == "end") {
return listOf(soFar)
}
val smallCavesVisited = soFar.filter { it.lowercase() == it }.groupBy { it }.mapValues { (_, l) -> l.size }
val visitedOneTwice = smallCavesVisited.any { it.value == 2 }
val possibleNextDestinations = possiblePaths[soFar.last()]!!.filter {
it !in smallCavesVisited || (canVisitOneTwice && !visitedOneTwice && it != "start" && it != "end")
}
return possibleNextDestinations.flatMap { paths(soFar + it, canVisitOneTwice) }
}
}
| 0 | Kotlin | 0 | 0 | 4b893c001efec7d11a326888a9a98ec03241d331 | 1,453 | adventofcode2021 | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/ChampagneTower.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 kotlin.math.min
/**
* 799. Champagne Tower
* https://leetcode.com/problems/champagne-tower/
*/
fun interface ChampagneTower {
operator fun invoke(poured: Int, queryRow: Int, queryGlass: Int): Double
}
class ChampagneTowerSimulation : ChampagneTower {
override operator fun invoke(poured: Int, queryRow: Int, queryGlass: Int): Double {
val arr = Array(SIZE) { DoubleArray(SIZE) }
arr[0][0] = poured.toDouble()
for (r in 0..queryRow) {
for (c in 0..r) {
val q = (arr[r][c] - 1.0) / 2.0
if (q > 0) {
arr[r + 1][c] += q
arr[r + 1][c + 1] += q
}
}
}
return min(1.0, arr[queryRow][queryGlass])
}
companion object {
private const val SIZE = 102
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,478 | kotlab | Apache License 2.0 |
src/main/kotlin/days/Day09.kt | TheMrMilchmann | 571,779,671 | false | {"Kotlin": 56525} | /*
* Copyright (c) 2022 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package days
import utils.*
import kotlin.math.*
fun main() {
data class Move(val dir: Direction, val steps: Int)
val moves = readInput().map { line ->
val (d, a) = line.split(' ')
Move(
dir = when (d) {
"U" -> Direction.UP
"D" -> Direction.DOWN
"L" -> Direction.LEFT
"R" -> Direction.RIGHT
else -> error("Unknown direction: $d")
},
steps = a.toInt()
)
}
fun Point.isAdjacent(other: Point): Boolean =
x - other.x in -1..1 && y - other.y in -1..1
fun solve(length: Int): Int {
val visited = mutableSetOf<Point>()
val rope = MutableList(length) { Point(0, 0) }
visited += rope.last()
for (move in moves) {
for (s in 0 until move.steps) {
rope[0] = move.dir.advance(rope[0])
for (i in 1 until rope.size) {
val prevPos = rope[i - 1]
val tailPos = rope[i]
if (!tailPos.isAdjacent(prevPos)) {
rope[i] = Point(
tailPos.x + (prevPos.x - tailPos.x).sign,
tailPos.y + (prevPos.y - tailPos.y).sign
)
}
}
visited += rope.last()
}
}
return visited.size
}
println("Part 1: ${solve(2)}")
println("Part 2: ${solve(10)}")
}
private data class Point(val x: Int, val y: Int)
private enum class Direction(val advance: (Point) -> Point) {
UP({ it.copy(y = it.y - 1) }),
DOWN({ it.copy(y = it.y + 1) }),
LEFT({ it.copy(x = it.x - 1) }),
RIGHT({ it.copy(x = it.x + 1) })
} | 0 | Kotlin | 0 | 1 | 2e01ab62e44d965a626198127699720563ed934b | 2,896 | AdventOfCode2022 | MIT License |
src/main/kotlin/com/felipecsl/OfflineBalancedBinPacking.kt | felipecsl | 140,735,494 | false | {"Kotlin": 8689} | package com.felipecsl
import java.util.*
/**
* Collection of bin packing algorithms optimized for evenly filling the available bins (balanced).
* Offline means the full list of items is known beforehand.
*/
class OfflineBalancedBinPacking {
/** https://www.sciencedirect.com/science/article/pii/0885064X85900226?via%3Dihub */
fun firstFitDecreasing(
items: List<Item>,
maxBinSize: Int,
maxBins: Int
): List<Bin> {
if (items.sumBy(Item::weight) > (maxBins.toLong() * maxBinSize.toLong())) {
throw IllegalArgumentException("Can't fit all items in the provided bins.")
}
if (items.any { it.weight > maxBinSize }) {
throw IllegalArgumentException("All items' weights must be under `maxBinSize`.")
}
if (maxBins <= 0) return listOf()
val bins = mutableListOf<Bin>()
val sortedItems = items.toQueueDesc()
var maxWeightSoFar = 0
var i = 0
val newBin = {
if (bins.size < maxBins) {
Bin(maxBinSize).also { bins.add(it) }
} else {
throw IllegalArgumentException("Not enough space found to store all items.")
}
}
while (sortedItems.isNotEmpty()) {
val nextItemWeight = sortedItems.peek().weight
val currentBin = findBinForItem(bins, i++ % maxBins, nextItemWeight, maxWeightSoFar, maxBins)
?: newBin()
while (currentBin.isEmpty()
|| (bins.all { it.weight == maxWeightSoFar }
&& currentBin.remainingWeight >= nextItemWeight
&& sortedItems.isNotEmpty()
&& bins.size == maxBins)
|| (currentBin.weight < maxWeightSoFar
&& sortedItems.isNotEmpty()
&& currentBin.remainingWeight >= nextItemWeight)
) {
currentBin.add(sortedItems.remove())
}
maxWeightSoFar = Math.max(maxWeightSoFar, currentBin.weight)
}
return bins
}
/** Fills bins more evenly than [firstFitDecreasing] but tends to use more bins. */
fun bestFitDecreasing(
items: List<Item>,
maxBinSize: Int,
maxBins: Int
): List<Bin> {
if (maxBins <= 0) return listOf()
val sortedItems = items.toQueueDesc()
val bins = mutableListOf<Bin>()
var maxWeightSoFar = 0
while (sortedItems.isNotEmpty()) {
if (bins.size < maxBins) bins.add(Bin(maxBinSize))
val currentBin = bins.minBy { it.weight }!!
var currentBinWeight = currentBin.weight
while (sortedItems.isNotEmpty() &&
(currentBin.isEmpty() || currentBinWeight < maxWeightSoFar)) {
val nextItem = if (maxWeightSoFar > 0
&& (currentBinWeight + sortedItems.peek().weight > maxWeightSoFar)) {
sortedItems.removeLast()
} else {
sortedItems.removeFirst()
}
currentBinWeight += nextItem.weight
currentBin.add(nextItem)
}
maxWeightSoFar = Math.max(maxWeightSoFar, currentBinWeight)
}
return bins.filter { it.isNotEmpty() }
}
private fun List<Item>.toQueueDesc() = ArrayDeque(sortedByDescending(Item::weight))
private fun findBinForItem(
bins: List<Bin>,
startIndex: Int,
itemWeight: Int,
maxWeightSoFar: Int,
maxBins: Int
): Bin? {
return if (bins.all { it.weight == maxWeightSoFar } && bins.size < maxBins) {
null
} else {
// start searching at startIndex and wrap around
val search = bins.drop(startIndex + 1) + bins.take(startIndex)
recurseFindBinForItem(search, itemWeight)
}
}
private fun recurseFindBinForItem(bins: List<Bin>, itemWeight: Int): Bin? {
if (bins.isEmpty()) return null
return if (bins[0].remainingWeight >= itemWeight) {
bins[0]
} else {
recurseFindBinForItem(bins.drop(1), itemWeight)
}
}
}
| 0 | Kotlin | 0 | 1 | 27136b336e001ca35cb2c6f6e2d99ca7d2ff3443 | 3,750 | bin-packing | MIT License |
src/main/adventofcode/Day11Solver.kt | eduardofandrade | 317,942,586 | false | null | package adventofcode
import java.io.InputStream
import java.util.stream.Collectors
class Day11Solver(stream: InputStream) : Solver {
private val processedInput: List<ArrayList<Char>>
private var numberOfRows = 0
private var numberOfColumns = 0
init {
processedInput = processInput(stream)
numberOfRows = processedInput.size
numberOfColumns = processedInput[numberOfRows - 1].size
}
private fun processInput(stream: InputStream): List<ArrayList<Char>> {
return stream.bufferedReader().readLines().stream()
.map { line ->
val columns = arrayListOf<Char>()
line.toCharArray().map { c -> columns.add(c) }
columns
}
.collect(Collectors.toList())
}
override fun getPartOneSolution(): Long {
var oldState = processedInput
var newState: ArrayList<ArrayList<Char>> = arrayListOf()
while (updateStateWithPartOneRules(oldState, newState)) {
oldState = newState
newState = arrayListOf()
}
return newState.map { rows -> rows.toCharArray().filter { c -> c == '#' }.size }.sum().toLong()
}
override fun getPartTwoSolution(): Long {
var oldState = processedInput
var newState: ArrayList<ArrayList<Char>> = arrayListOf()
while (updateStateWithPartTwoRules(oldState, newState)) {
oldState = newState
newState = arrayListOf()
}
return newState.map { rows -> rows.toCharArray().filter { c -> c == '#' }.size }.sum().toLong()
}
private fun updateStateWithPartOneRules(oldState: List<ArrayList<Char>>, newState: ArrayList<ArrayList<Char>>): Boolean {
for (i in oldState.indices) {
newState.add(arrayListOf())
for (j in oldState[i].indices) {
if (oldState[i][j] == 'L' && getAdjacentSeats(oldState, i, j).none { s -> s == '#' }) {
newState[i].add('#')
} else if (oldState[i][j] == '#' && getAdjacentSeats(oldState, i, j).filter { s -> s == '#' }.size >= 4) {
newState[i].add('L')
} else {
newState[i].add(oldState[i][j])
}
}
}
return !stateEquals(oldState, newState)
}
private fun getAdjacentSeats(state: List<ArrayList<Char>>, row: Int, column: Int): List<Char> {
val adjacentSeats = arrayListOf<Char>()
for (i in row - 1..row + 1) {
if (i >= 0 && i <= numberOfRows - 1) {
for (j in column - 1..column + 1) {
if (j >= 0 && j <= numberOfColumns - 1) {
if (i == row && j == column) continue
adjacentSeats.add(state[i][j])
}
}
}
}
return adjacentSeats
}
private fun updateStateWithPartTwoRules(oldState: List<ArrayList<Char>>, newState: ArrayList<ArrayList<Char>>): Boolean {
for (i in oldState.indices) {
newState.add(arrayListOf())
for (j in oldState[i].indices) {
if (oldState[i][j] == 'L' && getVisibleSeats(oldState, i, j).none { s -> s == '#' }) {
newState[i].add('#')
} else if (oldState[i][j] == '#' && getVisibleSeats(oldState, i, j).filter { s -> s == '#' }.size >= 5) {
newState[i].add('L')
} else {
newState[i].add(oldState[i][j])
}
}
}
return !stateEquals(oldState, newState)
}
private fun getVisibleSeats(state: List<ArrayList<Char>>, row: Int, column: Int): List<Char> {
val coords = listOf(
Pair(-1, -1), Pair(0, -1), Pair(1, -1),
Pair(-1, 0), Pair(1, 0), Pair(-1, 1),
Pair(0, 1), Pair(1, 1)
)
return coords.map { p -> getVisibleSeat(state, row, column, p.first, p.second) }.filter { s -> s != ' ' }
}
private fun getVisibleSeat(state: List<ArrayList<Char>>, row: Int, column: Int, xDirection: Int, yDirection: Int): Char {
val xCoord = column + xDirection
val yCoord = row + yDirection
if (xCoord >= 0 && yCoord >= 0 && xCoord <= numberOfColumns - 1 && yCoord <= numberOfRows - 1) {
val seat = state[yCoord][xCoord]
if (seat != '.') {
return seat
}
return getVisibleSeat(state, yCoord, xCoord, xDirection, yDirection)
}
return ' '
}
private fun stateEquals(oldState: List<ArrayList<Char>>, newState: List<ArrayList<Char>>): Boolean {
for (i in oldState.indices) {
for (j in oldState[i].indices) {
if (oldState[i][j] != newState[i][j]) return false
}
}
return true
}
} | 0 | Kotlin | 0 | 0 | 147553654412ae1da4b803328e9fc13700280c17 | 4,921 | adventofcode2020 | MIT License |
src/main/kotlin/g1901_2000/s1986_minimum_number_of_work_sessions_to_finish_the_tasks/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1901_2000.s1986_minimum_number_of_work_sessions_to_finish_the_tasks
// #Medium #Array #Dynamic_Programming #Bit_Manipulation #Backtracking #Bitmask
// #2023_06_21_Time_153_ms_(100.00%)_Space_35.6_MB_(100.00%)
class Solution {
fun minSessions(tasks: IntArray, sessionTime: Int): Int {
val len = tasks.size
// minimum, all tasks can fit into 1 session
var i = 1
// maximum, each task take 1 session to finish
var j = len
while (i < j) {
// try m sessions to see whether it can work
val m = (i + j) / 2
if (canFit(tasks, IntArray(m), sessionTime, len - 1)) {
j = m
} else {
i = m + 1
}
}
return i
}
private fun canFit(tasks: IntArray, sessions: IntArray, sessionTime: Int, idx: Int): Boolean {
// all tasks have been taken care of
if (idx == -1) {
return true
}
val dup: MutableSet<Int> = HashSet()
// now to take care of tasks[idx]
// try each spot
for (i in sessions.indices) {
// current spot cannot fit
if (sessions[i] + tasks[idx] > sessionTime || dup.contains(sessions[i] + tasks[idx])) {
continue
}
dup.add(sessions[i] + tasks[idx])
sessions[i] += tasks[idx]
if (canFit(tasks, sessions, sessionTime, idx - 1)) {
return true
}
sessions[i] -= tasks[idx]
}
return false
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,571 | LeetCode-in-Kotlin | MIT License |
src/day20/Parser.kt | g0dzill3r | 576,012,003 | false | {"Kotlin": 172121} | package day20
import readInput
data class Coordinate (val value: Long, val index: Int) {
override fun toString(): String = "($value, @$index)"
}
data class Coordinates (val input: List<Long>) {
val data = input.mapIndexed { i, coord -> Coordinate (coord, i) }.toMutableList ()
fun get (index: Int): Coordinate {
return data[index % data.size]
}
fun findValue (value: Long): Int {
for (i in data.indices) {
if (data[i].value == value) {
return i
}
}
return -1
}
fun find (index: Int): Int {
if (index < 0 || index >= data.size) {
throw IllegalArgumentException ("Invalid index: $index")
}
for (i in data.indices) {
if (data[i].index == index) {
return i
}
}
throw IllegalStateException ("Index not found")
}
fun indices (): List<Int> = data.map { it.index }
fun mix (which: Int, debug: (Any) -> Unit = {}) {
val origin = find (which)
val rec = data[origin]
if (rec.value == 0L) {
return
}
data.removeAt (origin)
var dest = origin + rec.value
if (dest in 0 until data.size) {
data.add (dest.toInt (), rec)
} else if (dest == data.size.toLong()) {
data.add (rec)
} else if (dest > data.size){
dest %= data.size
data.add (dest.toInt (), rec)
} else {
dest = data.size + dest % data.size
data.add (dest.toInt (), rec)
}
}
fun mix () {
for (i in input.indices) {
mix (i)
}
return
}
fun dump (which: Int) {
val index = find (which)
val maxWidth = data.fold (0) { acc, v -> Math.max (acc, v.value.toString ().length) }
val format = { value: Long, selected: Boolean ->
if (selected) {
String.format ("[%${maxWidth}d] ", value)
} else {
String.format (" %${maxWidth}d ", value)
}
}
for (i in data.size - 3 until data.size) {
print (format (data[i].value, false))
}
print (" | ")
for (i in data.indices) {
print (format (data[i].value, i == index))
}
print (" | ")
for (i in 0 .. 2) {
print (format (data[i].value, false))
}
println ()
}
fun dump () = println (toString ())
fun <T> coordinates (func: (Int, Coordinate)-> T): List<T> = data.mapIndexed { i, c -> func (i, c) }
fun coordinates (): List<Long> = data.map {it.value }
override fun toString(): String {
return StringBuffer().apply {
append ("data: ${data.joinToString (", ")}\n")
append ("indices: ${indices()}\n")
append ("coords : ${coordinates()}")
}.toString ()
}
companion object {
fun parse (input: String): Coordinates {
return Coordinates (input.trim ().split ("\n").map { it.toLong () })
}
}
}
fun loadCoordinates (example: Boolean): Coordinates = Coordinates.parse (readInput (20, example))
fun main (args: Array<String>) {
val example = true
val coords = loadCoordinates(example)
coords.dump ()
coords.mix ()
coords.dump ()
return
}
// EOF | 0 | Kotlin | 0 | 0 | 6ec11a5120e4eb180ab6aff3463a2563400cc0c3 | 3,396 | advent_of_code_2022 | Apache License 2.0 |
src/day13/Day13.kt | ritesh-singh | 572,210,598 | false | {"Kotlin": 99540} | package day13
import readInput
import java.util.*
sealed class Packet {
data class ListsPacket(val packet: MutableList<Packet>) : Packet() {
override fun toString(): String {
return packet.toString()
}
}
data class IntegerPacket(val packet: Int) : Packet() {
fun toList() = ListsPacket(packet = mutableListOf(this))
override fun toString(): String {
return packet.toString()
}
}
}
fun main() {
fun buildPacket(packet: String): Packet {
val stack = Stack<Packet>()
stack.push(Packet.ListsPacket(mutableListOf()))
var dupPacket = packet
while (dupPacket.isNotEmpty()) {
when (dupPacket[0]) {
'[' -> {
stack.push(Packet.ListsPacket(mutableListOf()))
dupPacket = dupPacket.substring(1)
}
']' -> {
val topItem = stack.pop()
(stack.peek() as Packet.ListsPacket).packet.add(topItem)
dupPacket = dupPacket.substring(1)
}
',' -> {
dupPacket = dupPacket.substring(1)
}
else -> {
// it's a digit
val digString = StringBuilder()
var i = 0
while (dupPacket[i].isDigit()) {
digString.append(dupPacket[i++])
}
(stack.peek() as Packet.ListsPacket).packet.add(Packet.IntegerPacket(digString.toString().toInt()))
dupPacket = dupPacket.substring(digString.length)
}
}
}
return stack.pop()
}
fun Packet.toListPacket(): Packet.ListsPacket {
if (this is Packet.IntegerPacket)
return this.toList()
return this as Packet.ListsPacket
}
fun packetInRightOrder(
leftPacket: Packet.ListsPacket,
rightPacket: Packet.ListsPacket,
): Pair<Boolean,Boolean> {
var lCounter = 0
var rCounter = 0
while (lCounter < leftPacket.packet.size && rCounter < rightPacket.packet.size) {
val f = leftPacket.packet[lCounter]
val s = rightPacket.packet[rCounter]
if (f is Packet.IntegerPacket && s is Packet.IntegerPacket) {
if (f.packet < s.packet) return Pair(true, true)
if (f.packet > s.packet) return Pair(false,true)
lCounter++
rCounter++
continue
}
if (f is Packet.IntegerPacket && s is Packet.ListsPacket) {
lCounter++
rCounter++
val pair = packetInRightOrder(f.toListPacket(), s)
if (pair.second) return pair
}
if (f is Packet.ListsPacket && s is Packet.IntegerPacket) {
lCounter++
rCounter++
val pair = packetInRightOrder(f, s.toListPacket())
if (pair.second) return pair
}
if (f is Packet.ListsPacket && s is Packet.ListsPacket) {
lCounter++
rCounter++
val pair = packetInRightOrder(f, s)
if (pair.second) return pair
}
}
return if (lCounter == leftPacket.packet.size && rCounter != rightPacket.packet.size) {
Pair(true,true)
} else if (lCounter != leftPacket.packet.size && rCounter == rightPacket.packet.size) {
Pair(false,true)
} else {
Pair(false,false)
}
}
fun part1(input: List<String>): Int {
var sum = 0
input.filter { it.isNotEmpty() }
.windowed(2, step = 2)
.forEachIndexed { index, list ->
val (left, right) = list.map { buildPacket(it) }
val rightOrder = packetInRightOrder(
(left as Packet.ListsPacket).packet.first() as Packet.ListsPacket,
(right as Packet.ListsPacket).packet.first() as Packet.ListsPacket
)
if (rightOrder.first) {
sum += index + 1
}
}
return sum
}
fun part2(input: List<String>): Int {
val decoderKey1 = (buildPacket("[[2]]") as Packet.ListsPacket).packet.first() as Packet.ListsPacket
val decoderKey2 = (buildPacket("[[6]]") as Packet.ListsPacket).packet.first() as Packet.ListsPacket
val list = input.filter { it.isNotEmpty() }
.map {
(buildPacket(it) as Packet.ListsPacket).packet.first() as Packet.ListsPacket
}.toMutableList().apply {
add(decoderKey1)
add(decoderKey2)
}
list.sortWith { o1, o2 ->
val res = packetInRightOrder(o1, o2)
if (res.first) -1 else 1
}
return (list.indexOf(decoderKey1)+1) * (list.indexOf(decoderKey2)+1)
}
val testInput = readInput("/day13/Day13_test")
println(part1(testInput))
println(part2(testInput))
println("-----------------------------------------------")
val input = readInput("/day13/Day13")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 17fd65a8fac7fa0c6f4718d218a91a7b7d535eab | 5,320 | aoc-2022-kotlin | Apache License 2.0 |
src/Day09.kt | chrisjwirth | 573,098,264 | false | {"Kotlin": 28380} | import kotlin.math.abs
fun main() {
open class TailTracker(numberOfKnots: Int) {
private val head = Knot(0, 0)
private val tail = Knot(0, 0)
private val knots = if (numberOfKnots == 2) {
arrayOf(head, tail)
} else {
val middleKnots = Array(numberOfKnots - 2) { Knot(0, 0) }
arrayOf(head, *middleKnots, tail)
}
private var tailLocations = mutableSetOf(Pair(0, 0))
private inner class Knot(
var x: Int,
var y: Int
) {
fun move(direction: Char) {
when (direction) {
'U' -> y++
'D' -> y--
'R' -> x++
'L' -> x--
}
}
}
private fun leaderAndFollowerXDifference(leader: Knot, follower: Knot): Int {
return abs(leader.x - follower.x)
}
private fun leaderAndFollowerYDifference(leader: Knot, follower: Knot): Int {
return abs(leader.y - follower.y)
}
private fun nonDiagonalFollowerMovementRequired(leader: Knot, follower: Knot): Boolean {
return leaderAndFollowerXDifference(leader, follower) == 2 ||
leaderAndFollowerYDifference(leader, follower) == 2
}
private fun diagonalFollowerMovementRequired(leader: Knot, follower: Knot): Boolean {
return (leaderAndFollowerXDifference(leader, follower) >= 1 &&
leaderAndFollowerYDifference(leader, follower) == 2) ||
(leaderAndFollowerXDifference(leader, follower) == 2 &&
leaderAndFollowerYDifference(leader, follower) >= 1)
}
private fun calculateXDirection(leader: Knot, follower: Knot): Char {
return if ((leader.x - follower.x) >= 1) {
'R'
} else {
'L'
}
}
private fun calculateYDirection(leader: Knot, follower: Knot): Char {
return if ((leader.y - follower.y) >= 1) {
'U'
} else {
'D'
}
}
private fun moveFollowerDiagonally(leader: Knot, follower: Knot) {
follower.move(calculateXDirection(leader, follower))
follower.move(calculateYDirection(leader, follower))
}
private fun moveFollowerNonDiagonally(leader: Knot, follower: Knot) {
if (leaderAndFollowerXDifference(leader, follower) >= 1) {
follower.move(calculateXDirection(leader, follower))
} else {
follower.move(calculateYDirection(leader, follower))
}
}
private fun moveFollower(leader: Knot, follower: Knot) {
if (diagonalFollowerMovementRequired(leader, follower)) {
moveFollowerDiagonally(leader, follower)
} else if (nonDiagonalFollowerMovementRequired(leader, follower)) {
moveFollowerNonDiagonally(leader, follower)
}
}
fun moveKnots(headDirection: Char, headDistance: Int) {
repeat(headDistance) {
head.move(headDirection)
for (knotNumber in 1 until knots.size) {
val leader = knots[knotNumber - 1]
val follower = knots[knotNumber]
moveFollower(leader, follower)
}
tailLocations.add(Pair(tail.x, tail.y))
}
}
fun getNumberUniqueTailLocations(): Int {
return tailLocations.size
}
}
fun numberUniqueTailLocations(numberOfKnots: Int, input: List<String>): Int {
val tailTracker = TailTracker(numberOfKnots)
input.forEach {
val direction = it[0]
val distance = it.substring(2).toInt()
tailTracker.moveKnots(direction, distance)
}
return tailTracker.getNumberUniqueTailLocations()
}
fun part1(input: List<String>): Int {
return numberUniqueTailLocations(2, input)
}
fun part2(input: List<String>): Int {
return numberUniqueTailLocations(10, input)
}
// Test
val testInput1 = readInput("Day09_test_1")
check(part1(testInput1) == 13)
check(part2(testInput1) == 1)
val testInput2 = readInput("Day09_test_2")
check(part2(testInput2) == 36)
// Final
val input = readInput("Day09")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | d8b1f2a0d0f579dd23fa1dc1f7b156f728152c2d | 4,524 | AdventOfCode2022 | Apache License 2.0 |
Problems/Algorithms/542. 01 Matrix/01Matrix2.kt | xuedong | 189,745,542 | false | {"Kotlin": 332182, "Java": 294218, "Python": 237866, "C++": 97190, "Rust": 82753, "Go": 37320, "JavaScript": 12030, "Ruby": 3367, "C": 3121, "C#": 3117, "Swift": 2876, "Scala": 2868, "TypeScript": 2134, "Shell": 149, "Elixir": 130, "Racket": 107, "Erlang": 96, "Dart": 65} | class Solution {
fun updateMatrix(mat: Array<IntArray>): Array<IntArray> {
val n = mat.size
val m = mat[0].size
val queue = ArrayDeque<IntArray>()
val results: Array<IntArray> = Array(n) { IntArray(m) { Int.MAX_VALUE } }
for (i in 0..n-1) {
for (j in 0..m-1) {
if (mat[i][j] == 0) {
results[i][j] = 0
queue.add(intArrayOf(i, j))
}
}
}
val neighbors = arrayOf(intArrayOf(0, 1), intArrayOf(0, -1), intArrayOf(1, 0), intArrayOf(-1, 0))
while (!queue.isEmpty()) {
val curr = queue.removeFirst()
val r = curr[0]
val c = curr[1]
for (neighbor in neighbors) {
val x = r + neighbor[0]
val y = c + neighbor[1]
if (isValid(n, m, x, y)) {
if (results[x][y] > results[r][c] + 1) {
results[x][y] = results[r][c] + 1
queue.add(intArrayOf(x, y))
}
}
}
}
return results;
}
private fun isValid(n: Int, m: Int, r: Int, c: Int): Boolean {
return r >= 0 && r < n && c >= 0 && c < m
}
}
| 0 | Kotlin | 0 | 1 | 5e919965b43917eeee15e4bff12a0b6bea4fd0e7 | 1,350 | leet-code | MIT License |
day03/kotlin/bit-jkraushaar/solution.kts | timgrossmann | 224,991,491 | true | {"HTML": 2739009, "Python": 169603, "Java": 157274, "Jupyter Notebook": 116902, "TypeScript": 113866, "Kotlin": 89503, "Groovy": 73664, "Dart": 47763, "C++": 43677, "CSS": 34994, "Ruby": 27091, "Haskell": 26727, "Scala": 11409, "Dockerfile": 10370, "JavaScript": 6496, "PHP": 4152, "Go": 2838, "Shell": 2493, "Rust": 2082, "Clojure": 567, "Tcl": 46} | #!/usr/bin/env -S kotlinc-jvm -script
import java.io.File
import java.lang.RuntimeException
import kotlin.math.absoluteValue
// tag::point[]
typealias Point = Pair<Int, Int>
fun Point.manhattanDistance(): Int = this.first.absoluteValue + this.second.absoluteValue
// end::point[]
// tag::line[]
typealias Line = Triple<Point, Point, String>
fun Line.expandPoints(): List<Point> {
val points = mutableListOf<Point>()
val (startingPoint, endingPoint, direction) = this
val (startX, startY) = startingPoint
val (endX, endY) = endingPoint
when (direction) {
"R" -> {
for (x in startX + 1..endX) {
points.add(Point(x, startY))
}
}
"L" -> {
for (x in startX - 1 downTo endX) {
points.add(Point(x, startY))
}
}
"U" -> {
for (y in startY + 1..endY) {
points.add(Point(startX, y))
}
}
"D" -> {
for (y in startY - 1 downTo endY) {
points.add(Point(startX, y))
}
}
else -> throw RuntimeException("Unknown direction: $direction")
}
return points
}
// end::line[]
// tag::pointConversion[]
fun List<String>.toListOfPoints(): List<Point> {
val points = mutableListOf<Point>()
var currentPoint = Point(0, 0)
for (vector in this) {
val line = createLine(currentPoint, vector)
points.addAll(line.expandPoints())
currentPoint = line.second
}
return points
}
fun createLine(startingPoint: Point, vector: String): Line {
val partition = vector.partition { it.isLetter() }
val direction = partition.first
val distance = partition.second.toInt()
val endingPoint = when (direction) {
"R" -> Point(startingPoint.first + distance, startingPoint.second)
"L" -> Point(startingPoint.first - distance, startingPoint.second)
"U" -> Point(startingPoint.first, startingPoint.second + distance)
"D" -> Point(startingPoint.first, startingPoint.second - distance)
else -> throw RuntimeException("Unknown direction: $direction")
}
return Line(startingPoint, endingPoint, direction)
}
// end::pointConversion[]
// tag::utilityFunction[]
fun List<Point>.asDistanceMap(): Map<Point, Int> = this.mapIndexed { index, point -> point to index + 1 }.toMap()
// end::utilityFunction[]
// tag::firstStar[]
val wires = File("./input.txt")
.readLines()
.map { it.split(",") }
.map { it.toListOfPoints() }
val intersections = wires[0].intersect(wires[1]) - Point(0, 0)
val lowestManhattanDistance = intersections
.map { it.manhattanDistance() }
.min()
println(lowestManhattanDistance)
// end::firstStar[]
// tag::secondStar[]
val wire1DistanceMap = wires[0].asDistanceMap().filterKeys { intersections.contains(it) }
val wire2DistanceMap = wires[1].asDistanceMap().filterKeys { intersections.contains(it) }
val minimumDistance: Int? = wire1DistanceMap.map { it.value + (wire2DistanceMap[it.key] ?: throw RuntimeException()) }.min()
println(minimumDistance ?: -1)
// end::secondStar[] | 0 | HTML | 0 | 1 | bb19fda33ac6e91a27dfaea27f9c77c7f1745b9b | 3,142 | aoc-2019 | MIT License |
internal/test-utils/src/commonMain/kotlin/coil3/test/utils/maths.kt | coil-kt | 201,684,760 | false | {"Kotlin": 967712, "Shell": 1710, "JavaScript": 209} | package coil3.test.utils
import kotlin.math.pow
import kotlin.math.roundToInt
import kotlin.math.sqrt
/**
* Returns the cross correlation between two arrays.
*
* https://en.wikipedia.org/wiki/Cross-correlation
*/
fun crossCorrelation(x: IntArray, y: IntArray): Double {
require(x.count() == y.count()) { "Input arrays must be of equal size." }
val xVar = x.variance()
val yVar = y.variance()
val squaredVariance = sqrt(xVar * yVar)
val xAvg = x.average()
val yAvg = y.average()
val count = x.count()
var sum = 0.0
for (index in 0 until count) {
sum += (x[index] - xAvg) * (y[index] - yAvg)
}
return sum / count / squaredVariance
}
/**
* Returns the cross correlation between two arrays.
*
* https://en.wikipedia.org/wiki/Cross-correlation
*/
fun crossCorrelation(x: ByteArray, y: ByteArray): Double {
require(x.count() == y.count()) { "Input arrays must be of equal size." }
val xVar = x.variance()
val yVar = y.variance()
val squaredVariance = sqrt(xVar * yVar)
val xAvg = x.average()
val yAvg = y.average()
val count = x.count()
var sum = 0.0
for (index in 0 until count) {
sum += (x[index] - xAvg) * (y[index] - yAvg)
}
return sum / count / squaredVariance
}
/**
* Returns an average value of elements in the array.
*/
fun IntArray.variance(): Double {
if (isEmpty()) return Double.NaN
val average = average()
return sumOf { (it - average).pow(2) } / count()
}
/**
* Returns an average value of elements in the array.
*/
fun ByteArray.variance(): Double {
if (isEmpty()) return Double.NaN
val average = average()
return sumOf { (it - average).pow(2) } / count()
}
/**
* Round the given value to the nearest [Double] with [precision] number of decimal places.
*/
fun Double.round(precision: Int): Double {
val multiplier = 10.0.pow(precision)
return (this * multiplier).roundToInt() / multiplier
}
| 42 | Kotlin | 629 | 10,059 | 75ed843355778bd62840e91762bd01f1a4e2e901 | 1,962 | coil | Apache License 2.0 |
advent/src/test/kotlin/org/elwaxoro/advent/y2021/Dec02.kt | elwaxoro | 328,044,882 | false | {"Kotlin": 376774} | package org.elwaxoro.advent.y2021
import org.elwaxoro.advent.PuzzleDayTester
/**
* Dive!
*/
class Dec02 : PuzzleDayTester(2, 2021) {
override fun part1(): Any = loadMaster().fold(SubCoord(), Instruction::diveDiveDive).whereAmI()
override fun part2(): Any = loadMaster().fold(SubCoord(), Instruction::diveButAimThisTime).whereAmI()
private fun loadMaster() = load().map(Instruction::fromString)
enum class Direction {
FORWARD,
DOWN,
UP
}
data class SubCoord(
val x: Int = 0,
val y: Int = 0,
val aim: Int = 0,
) {
fun whereAmI(): Int = x * y
}
data class Instruction(
val direction: Direction,
val distance: Int,
) {
companion object {
fun fromString(input: String): Instruction = input.split(" ").let {
Instruction(Direction.valueOf(it.first().uppercase()), it.last().toInt())
}
fun diveDiveDive(start: SubCoord, i: Instruction): SubCoord = when (i.direction) {
Direction.FORWARD -> SubCoord(start.x + i.distance, start.y)
Direction.DOWN -> SubCoord(start.x, start.y + i.distance)
Direction.UP -> SubCoord(start.x, start.y - i.distance)
}
fun diveButAimThisTime(start: SubCoord, i: Instruction): SubCoord = when (i.direction) {
Direction.FORWARD -> SubCoord(start.x + i.distance, start.y + (start.aim * i.distance), start.aim)
Direction.DOWN -> SubCoord(start.x, start.y, start.aim + i.distance)
Direction.UP -> SubCoord(start.x, start.y, start.aim - i.distance)
}
}
}
}
| 0 | Kotlin | 4 | 0 | 1718f2d675f637b97c54631cb869165167bc713c | 1,698 | advent-of-code | MIT License |
week7matchnumberseasy/MatchNumbersEasy.kt | laitingsheng | 341,616,623 | false | null | class MatchNumbersEasy {
private fun compare(sb1: StringBuilder, sb2: StringBuilder): Int {
if (sb1.isEmpty() || sb2.isEmpty())
return sb1.length - sb2.length
var nz1 = sb1.indexOfFirst { c -> c != '0' }
if (nz1 == -1)
nz1 = sb1.length - 1
var nz2 = sb2.indexOfFirst { c -> c != '0' }
if (nz2 == -1)
nz2 = sb2.length - 1
val l1 = sb1.length - nz1
val l2 = sb2.length - nz2
var cr = l1 - l2
if (cr != 0)
return cr
for (i in 0 until Math.min(l1, l2)) {
cr = sb1[nz1 + i] - sb2[nz2 + i]
if (cr != 0)
return cr
}
return 0
}
fun maxNumber(matches: IntArray, n: Int): String {
val record = Array(n + 1) { StringBuilder(n) }
var sb = StringBuilder(n)
for (m in 1 .. n) {
matches.forEachIndexed { i, match ->
for (j in match .. m) {
val prev = record[j - match]
if (prev.isEmpty() || prev.first() <= '0' + i) {
sb.append(i)
sb.append(prev)
} else {
sb.append(prev)
sb.append(i)
}
val curr = record[m]
if (compare(sb, curr) > 0) {
record[m] = sb
sb = curr
}
sb.setLength(0)
}
}
}
sb.setLength(0)
return record.foldRight(sb) { acc, isb -> if (compare(isb, acc) > 0) isb else acc }.toString()
}
}
| 0 | Kotlin | 0 | 0 | 2fc3e7a23d37d5e81cdf19a9ea19901b25941a49 | 1,699 | 2020S1-COMP-SCI-7007 | ISC License |
src/Day01.kt | ricardorlg-yml | 573,098,872 | false | {"Kotlin": 38331} | fun main() {
fun parseInput(input: List<String>): List<Long> {
val tot = mutableListOf<Long>()
var accum = 0L
input.forEach { v ->
if (v.isNotBlank()) {
accum += v.toLong()
} else {
tot.add(accum)
accum = 0L
}
}
tot.add(accum)//add last one
return tot.sorted()
}
fun part1(input: List<String>): Long {
return parseInput(input).last()
}
fun part2(input: List<String>): Long {
return parseInput(input)
.takeLast(3)
.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000L)
check(part2(testInput) == 45000L)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | d7cd903485f41fe8c7023c015e4e606af9e10315 | 903 | advent_code_2022 | Apache License 2.0 |
src/Day01.kt | RisenAsh | 573,606,790 | false | {"Kotlin": 2330} | fun main() {
fun part1(input: List<String>): Int {
var i = 0
var highest = 0
input.forEach {
if (it != "") {
// Count = Count + value from that line converted into an Integer
i += it.toInt()
}
else {
if (i > highest) {
highest = i
}
// Reset i after summing section
i = 0
}
}
return highest
}
fun part2(input: List<String>): Int {
var i = 0
var highest = 0
var highest2 = 0
var highest3 = 0
input.forEach {
if (it != "") {
// Count = Count + value from that line converted into an Integer
i += it.toInt()
}
else {
if (i > highest) {
highest3 = highest2
highest2 = highest
highest = i
}
else if (i > highest2) {
highest3 = highest2
highest2 = i
}
else if (i > highest3) {
highest3 = i
}
// Reset i after summing section
i = 0
}
}
return highest + highest2 + highest3
}
val inputSam = readInput("sam/Day01")
val inputAgaton = readInput("agaton/Day01")
println("Part 1")
println("Sam: " + part1(inputSam))
println("Agaton: " + part1(inputAgaton))
println("\nPart 2")
println("Sam: " + part2(inputSam))
println("Agaton: " +part2(inputAgaton))
}
| 0 | Kotlin | 0 | 0 | 752ac6ce9a4a06798fae5bd9da037290f7f42ecd | 1,686 | aoc-2022-kotlin | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/LeafSimilarTrees.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
/**
* 872. Leaf-Similar Trees
* @see <a href="https://leetcode.com/problems/leaf-similar-trees">Source</a>
*/
fun interface LeafSimilarTrees {
operator fun invoke(root1: TreeNode?, root2: TreeNode?): Boolean
}
class LeafSimilarDepthFirstSearch : LeafSimilarTrees {
override fun invoke(root1: TreeNode?, root2: TreeNode?): Boolean {
val leaves1: MutableList<Int?> = ArrayList()
val leaves2: MutableList<Int?> = ArrayList()
dfs(root1, leaves1)
dfs(root2, leaves2)
return leaves1 == leaves2
}
private fun dfs(node: TreeNode?, leafValues: MutableList<Int?>) {
if (node != null) {
if (node.left == null && node.right == null) leafValues.add(node.value)
dfs(node.left, leafValues)
dfs(node.right, leafValues)
}
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,468 | kotlab | Apache License 2.0 |
src/main/kotlin/io/github/dca/tax/Optimization.kt | laguiar | 476,662,074 | false | {"Kotlin": 43279} | package io.github.dca.tax
import io.github.dca.ZERO
/**
* From a given list of transactions, this function calculates the balance among all BUY and SELL transactions.
*
* The remaining list contains only BUY transactions with adjusted quantities and ready to be used for
* tax allowance calculations.
*
* @return List of adjusted BUY transactions
*/
internal fun consolidateTransactionHistory(transactions: List<Transaction>): List<Transaction> =
transactions
.groupBy { it.ticker }
.flatMap { (_, assetTransactions) -> processAssetTransactions(assetTransactions) }
.sortedBy { it.date }
private fun processAssetTransactions(transactions: List<Transaction>): List<Transaction> =
transactions
.sortedBy { it.date }
.fold(listOf<Transaction>() to ZERO) { (adjustedTransactions, sold), transaction ->
when (transaction.direction) {
Direction.BUY -> {
val remaining = transaction.shares - sold
if (remaining > ZERO) {
adjustedTransactions + transaction.copy(shares = remaining) to ZERO
} else {
adjustedTransactions to sold - transaction.shares
}
}
Direction.SELL -> {
// get the oldest transaction - it will always have at least one BUY transaction
val oldestTransaction = adjustedTransactions.first()
val remaining = oldestTransaction.shares - transaction.shares
if (remaining > 0) {
// replace old transaction with updated one
val updatedTransaction = oldestTransaction.copy(shares = remaining)
listOf(updatedTransaction) + adjustedTransactions.drop(1) to ZERO
} else {
adjustNegativeRenamingSellTransaction(transaction, adjustedTransactions) to sold
}
}
}
}.first
/**
* Process the next items in search for BUY transactions that might need to be adjusted or removed
*
* @param transaction actual SELL transaction that quantity surpass the oldest BUY transaction
* @param adjustedTransactions mutable list that receives the adjusted transactions
* @return the adjustedTransactions list
*/
private fun adjustNegativeRenamingSellTransaction(
transaction: Transaction,
adjustedTransactions: List<Transaction>
): List<Transaction> =
adjustTransactions(transaction.shares, adjustedTransactions.asSequence())
.toList()
private fun adjustTransactions(sold: Double, adjustedTransactions: Sequence<Transaction>): Sequence<Transaction> {
if (adjustedTransactions.none()) return emptySequence()
val firstTransaction = adjustedTransactions.first()
val remaining = sold - firstTransaction.shares
return if (areMoreSharesLeftThanSoldOnes(remaining, firstTransaction.shares, sold)) {
if (remaining != ZERO) {
// replace old transaction with updated one
sequenceOf(
firstTransaction.copy(shares = firstTransaction.shares - sold)
) + adjustedTransactions.dropFirst()
} else {
adjustedTransactions.dropFirst()
}
} else {
adjustTransactions(remaining, adjustedTransactions.dropFirst())
}
}
private fun areMoreSharesLeftThanSoldOnes(
remaining: Double,
transactionShares: Double,
sold: Double
) = remaining < transactionShares && sold <= transactionShares
private fun Sequence<Transaction>.dropFirst() = this.drop(1)
| 0 | Kotlin | 1 | 0 | 2b07dc89982390cf990765ac414f676aba69bf45 | 3,657 | dca-optimizer | MIT License |
compiler/src/main/kotlin/edu/cornell/cs/apl/viaduct/syntax/Operators.kt | s-ren | 386,161,765 | true | {"Kotlin": 878757, "Java": 43761, "C++": 13898, "Python": 11991, "Lex": 6620, "Dockerfile": 1844, "Makefile": 1785, "SWIG": 1212, "Shell": 698} | package edu.cornell.cs.apl.viaduct.syntax
import edu.cornell.cs.apl.prettyprinting.Document
import edu.cornell.cs.apl.prettyprinting.PrettyPrintable
import edu.cornell.cs.apl.viaduct.syntax.types.FunctionType
import edu.cornell.cs.apl.viaduct.syntax.values.Value
/**
* Determines how operators of the same [Precedence] are grouped in the absence of parentheses.
*
* For example, the expression `x ~ y ~ z` would be parsed as follows given the
* corresponding associativity of `~`:
*
* - Left associative: `(x ~ y) ~ z`
* - Right associative: `x ~ (y ~ z)`
* - Non-associative: syntax error.
*/
enum class Associativity {
LEFT, RIGHT, NON
}
/**
* Determines the order of operations in the absence of parentheses.
*
* For example, multiplication (conventionally) has higher precedence than addition, so
* `x + y * z` is parsed as `x + (y * z)`.
*/
interface Precedence {
/**
* Determines the [Order] of this precedence with respect to [other].
*
* The result of `x.compareTo(y)` may be [Order.UNDETERMINED], in which case the order is determined by
* `y.compareTo(x)`. If both of these are [Order.UNDETERMINED], then the precedences are not ordered, which is
* valid.
*
* This design supports extensibility. Old operators do not need to know about new operators; their precedence can
* (and should) compare as [Order.UNDETERMINED] to the precedence of operators they do not know about.
* This way, newly added operators can declare their precedence with respect to existing operators without having
* to change the code for existing operators.
*
* This function should satisfy the following properties:
*
* - If `x.compareTo(y)` returns [Order.LOWER], then
* `y.compareTo(x)` must return [Order.HIGHER] or [Order.UNDETERMINED].
* - If `x.compareTo(y)` returns [Order.HIGHER], then
* `y.compareTo(x)` must return [Order.LOWER] or [Order.UNDETERMINED].
*
* However, this function is not required to be transitive or total. That is, not all operators are required to be
* ordered with respect to each other. This design facilitates modularity
* (see [Parsing Mixfix Operators](https://link.springer.com/chapter/10.1007/978-3-642-24452-0_5)).
*
* Note that two different objects implementing this interface can never denote the same precedence since [Order]
* does not have an `EQUAL` option. If two operators have the same precedence, than [Operator.precedence] must
* return the same object for both.
*/
fun compareTo(other: Precedence): Order = Order.UNDETERMINED
}
/** The precedence that is higher than all other precedences. */
object HighestPrecedence : Precedence {
override fun compareTo(other: Precedence): Order = Order.HIGHER
}
/** The precedence that is lower than all other precedences. */
object LowestPrecedence : Precedence {
override fun compareTo(other: Precedence): Order = Order.LOWER
}
/** The result of comparing two [Precedence]s. */
enum class Order {
LOWER, HIGHER, UNDETERMINED
}
/** A pure function from values to a value. */
interface Operator {
/**
* Determines the grouping of consecutive operators that have the same precedence.
*
* @see Associativity
*/
val associativity: Associativity
/**
* Determines the order of this operator with respect to (a subset of) other operators.
* Operators with higher precedence bind tighter than operators with lower precedence
* (for example, multiplication has higher precedence than addition).
*
* @see Precedence
*/
val precedence: Precedence
/** The type of this operator. */
val type: FunctionType
/** In lieu of polymorphic types, have an optional list of alternative
types to check against. */
fun alternativeTypes(): List<FunctionType> = listOf()
/** Computes the result of applying this operator to [arguments]. */
fun apply(arguments: List<Value>): Value
/** Shows this operator applied to [arguments]. */
fun asDocument(arguments: List<PrettyPrintable>): Document
}
/**
* Returns true when this operator has precedence higher than or equal to [other].
*
* This function is reflexive, that is, `x.bindsTighterThan(x)` returns true.
* However, it is not necessarily transitive, and it does not order all operators.
*
* Two operators `x` and `y` have the same precedence if `x.bindsTighterThan(y)` and
* `y.bindsTighterThan(x)`.
*/
fun Operator.bindsTighterThan(other: Operator): Boolean =
this.precedence == other.precedence ||
this.precedence.compareTo(other.precedence) == Order.HIGHER ||
other.precedence.compareTo(this.precedence) == Order.LOWER
/**
* An operator that is written before its operands.
*
* A prefix operator has an operand that comes after all its named parts.
* For example, negation (`-x`) and if expressions (`if b then x else y`) are prefix operators.
*
* Prefix operators are right associative.
*/
interface PrefixOperator : Operator {
override val associativity: Associativity
get() = Associativity.RIGHT
}
/**
* An operator that is written between its operands.
*
* An infix operator has an operand that comes before and an operand that comes after all its
* named parts.
* For example, addition (`x + y`) and the conditional operator (`b ? x : y`) are infix operators.
*/
interface InfixOperator : Operator
/**
* An operator that is written after its operands.
*
* A postfix operator has an operand that comes before all its named parts.
* For example, taking the factorial (`x!`) is a postfix operator.
*
* Postfix operators are left associative.
*/
interface PostfixOperator : Operator {
override val associativity: Associativity
get() = Associativity.LEFT
}
/**
* An operator that surrounds its operands.
*
* An operator is closed if all its operands are contained between its named parts.
* For example, a pair of parentheses (`(x)`) is a closed operator.
*
* Closed operators are non-associative.
*/
interface ClosedOperator : Operator {
override val associativity: Associativity
get() = Associativity.NON
}
/**
* An operator that takes a single argument.
*/
interface UnaryOperator : Operator {
override fun apply(arguments: List<Value>): Value {
checkArguments(arguments)
return apply(arguments[0])
}
override fun asDocument(arguments: List<PrettyPrintable>): Document {
checkArguments(arguments)
return asDocument(arguments[0])
}
/** Computes the result of applying this operator to [argument]. */
fun apply(argument: Value): Value
/** Shows this operator applied to [argument]. */
fun asDocument(argument: PrettyPrintable): Document
}
/**
* An operator that takes two arguments.
*/
interface BinaryOperator : Operator {
override fun apply(arguments: List<Value>): Value {
checkArguments(arguments)
return apply(arguments[0], arguments[1])
}
override fun asDocument(arguments: List<PrettyPrintable>): Document {
checkArguments(arguments)
return asDocument(arguments[0], arguments[1])
}
/** Computes the result of applying this operator to [argument1] and [argument2]. */
fun apply(argument1: Value, argument2: Value): Value
/** Shows this operator applied to [argument1] and [argument2]. */
fun asDocument(argument1: PrettyPrintable, argument2: PrettyPrintable): Document
}
/** The number of arguments this operator takes. */
val Operator.arity: Int
get() = type.arguments.size
/** Asserts that the correct number of arguments are passed to this operator. */
private fun Operator.checkArguments(arguments: List<*>) {
require(arguments.size == this.arity) {
"Operator takes ${this.arity} arguments but was given ${arguments.size}."
}
}
| 0 | null | 0 | 0 | 337b3873e10f642706b195b10f939e9c1c7832ef | 7,890 | viaduct | MIT License |
src/main/java/challenges/cracking_coding_interview/object_oriented_design/jigsaw/Question.kt | ShabanKamell | 342,007,920 | false | null | package challenges.cracking_coding_interview.object_oriented_design.jigsaw
import java.util.*
/**
* Jigsaw: Implement an NxN jigsaw puzzle. Design the data structures and explain an algorithm to solve the puzzle.
* You can assume that you have a fitsWith method which, when passed two puzzle edges,
* returns true if the two edges belong together.
*/
object Question {
fun createRandomEdge(code: String): Edge {
val random = Random()
var type = Shape.INNER
if (random.nextBoolean()) {
type = Shape.OUTER
}
return Edge(type, code)
}
fun createEdges(
puzzle: Array<Array<Piece?>>,
column: Int,
row: Int
): Array<Edge?> {
val key = "$column:$row:"
/* Get left edge */
val left =
if (column == 0) Edge(
Shape.FLAT,
key + "h|e"
) else puzzle[row][column - 1]!!
.getEdgeWithOrientation(Orientation.RIGHT)
._createMatchingEdge()
/* Get top edge */
val top =
if (row == 0) Edge(
Shape.FLAT,
key + "v|e"
) else puzzle[row - 1][column]!!
.getEdgeWithOrientation(Orientation.BOTTOM)
._createMatchingEdge()
/* Get right edge */
val right =
if (column == puzzle[row].size - 1) Edge(
Shape.FLAT,
key + "h|e"
) else createRandomEdge(key + "h")
/* Get bottom edge */
val bottom =
if (row == puzzle.size - 1) Edge(
Shape.FLAT,
key + "v|e"
) else createRandomEdge(key + "v")
return arrayOf(left, top, right, bottom)
}
fun initializePuzzle(size: Int): LinkedList<Piece?> {
/* Create completed puzzle. */
val puzzle = Array(size) { arrayOfNulls<Piece>(size) }
for (row in 0 until size) {
for (column in 0 until size) {
val edges = createEdges(puzzle, column, row)
puzzle[row][column] = Piece(edges)
}
}
/* Shuffle and rotate pieces. */
val pieces = LinkedList<Piece?>()
val r = Random()
for (row in 0 until size) {
for (column in 0 until size) {
val rotations = r.nextInt(4)
val piece = puzzle[row][column]
piece!!.rotateEdgesBy(rotations)
val index = if (pieces.size == 0) 0 else r.nextInt(pieces.size)
pieces.add(index, piece)
}
}
return pieces
}
fun solutionToString(solution: Array<Array<Piece?>>?): String {
if (solution == null) return ""
val sb = StringBuilder()
for (h in solution.indices) {
for (w in 0 until solution[h].size) {
val p = solution[h][w]
if (p == null) {
sb.append("null")
} else {
sb.append(p.toString())
}
}
sb.append("\n")
}
return sb.toString()
}
/* Used for testing. Check if puzzle is solved. */
fun validate(solution: Array<Array<Piece?>>?): Boolean {
if (solution == null) return false
for (r in solution.indices) {
for (c in 0 until solution[r]!!.size) {
val piece = solution[r]!![c] ?: return false
if (c > 0) { /* match left */
val left = solution[r]!![c - 1]
if (!left!!.getEdgeWithOrientation(Orientation.RIGHT).fitsWith(
piece.getEdgeWithOrientation(
Orientation.LEFT
)
)
) {
return false
}
}
if (c < solution[r]!!.size - 1) { /* match right */
val right = solution[r][c + 1]
if (!right!!.getEdgeWithOrientation(Orientation.LEFT).fitsWith(
piece.getEdgeWithOrientation(
Orientation.RIGHT
)
)
) {
return false
}
}
if (r > 0) { /* match top */
val top = solution[r - 1][c]
if (!top!!.getEdgeWithOrientation(Orientation.BOTTOM).fitsWith(
piece.getEdgeWithOrientation(
Orientation.TOP
)
)
) {
return false
}
}
if (r < solution.size - 1) { /* match bottom */
val bottom = solution[r + 1][c]
if (!bottom!!.getEdgeWithOrientation(Orientation.TOP).fitsWith(
piece.getEdgeWithOrientation(
Orientation.BOTTOM
)
)
) {
return false
}
}
}
}
return true
}
fun testSize(size: Int): Boolean {
val pieces = initializePuzzle(size)
val puzzle = Puzzle(size, pieces)
puzzle.solve()
val solution = puzzle.currentSolution
println(solutionToString(solution))
val result = validate(solution)
println(result)
return result
}
@JvmStatic
fun main(args: Array<String>) {
for (size in 1..9) {
if (!testSize(size)) {
println("ERROR: $size")
}
}
}
} | 0 | Kotlin | 0 | 0 | ee06bebe0d3a7cd411d9ec7b7e317b48fe8c6d70 | 5,867 | CodingChallenges | Apache License 2.0 |
src/main/kotlin/g0901_1000/s0980_unique_paths_iii/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g0901_1000.s0980_unique_paths_iii
// #Hard #Array #Matrix #Bit_Manipulation #Backtracking
// #2023_05_09_Time_134_ms_(100.00%)_Space_34.8_MB_(76.92%)
class Solution {
private val row = intArrayOf(0, 0, 1, -1)
private val col = intArrayOf(1, -1, 0, 0)
private fun isSafe(grid: Array<IntArray>, rows: Int, cols: Int, i: Int, j: Int): Int {
if (i < 0 || j < 0 || i >= rows || j >= cols || grid[i][j] == -1) {
return 0
}
if (grid[i][j] == 2) {
for (l in 0 until rows) {
for (m in 0 until cols) {
if (grid[l][m] == 0) {
/* Return 0 if all zeros in the path are not covered */
return 0
}
}
}
/* Return 1, as we covered all zeros in the path */
return 1
}
/* mark as visited */
grid[i][j] = -1
var result = 0
for (k in 0..3) {
/* travel in all four directions (up,down,right,left) */
result += isSafe(grid, rows, cols, i + row[k], j + col[k])
}
/* Mark unvisited again to backtrack */
grid[i][j] = 0
return result
}
fun uniquePathsIII(grid: Array<IntArray>): Int {
val rows = grid.size
val cols = grid[0].size
var result = 0
for (k in 0 until rows) {
for (m in 0 until cols) {
if (grid[k][m] == 1) {
/* find indexes where 1 is located and start covering paths */
result = isSafe(grid, rows, cols, k, m)
break
}
}
}
return result
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,726 | LeetCode-in-Kotlin | MIT License |
src/com/talkspace/exercises/sum3.kt | BobString | 149,514,840 | false | null | package com.talkspace.exercises
// Write a function that takes as its arguments a sorted array of unique integers, `intArray`, and an integer, `int`, and returns 3 integers from `intArray` that sum up to `int`.
fun main(args: Array<String>) {
println(threeSum(listOf(-1, 2, 3, 4, 5, 7, 8, 12), 6)) // [4, 3, -1]
println(twoSum(listOf(-1, 2, 3, 4, 5, 7, 8, 12), 6)) // [4, 2]
println(twoSum(listOf(-1, 2, 3, 4, 5, 7, 8, 12), 20)) // [12, 8]
}
fun threeSum(ints: List<Int>, total: Int): List<Int> {
for (integer in ints) {
val mutableTemp = ints.toMutableList()
mutableTemp.remove(integer)
val res = twoSum(mutableTemp, total - integer)
if (res.isNotEmpty()) {
val mutableRes = res.toMutableList()
mutableRes.add(integer)
return mutableRes
}
}
return listOf()
}
fun twoSum(ints: List<Int>, total: Int): List<Int> {
val hash = mutableMapOf<Int, Int>()
for (integer in ints) {
val matchingSolution = total - integer
if (hash.containsKey(matchingSolution)) {
return listOf(integer, matchingSolution)
} else {
hash[integer] = matchingSolution
}
}
return listOf()
}
| 0 | Kotlin | 0 | 0 | a3ef2830cf8266f7565250a841432abcea710efc | 1,246 | kotlin-exercises | MIT License |
백준/문제 추천 시스템 Version 2.kt | jisungbin | 382,889,087 | false | null | import java.io.BufferedReader
import java.io.BufferedWriter
import java.io.InputStreamReader
import java.io.OutputStreamWriter
import java.util.TreeMap
private enum class ProblemLevelType {
EASY, HARD
}
private enum class ProblemNumberType {
SMALL, BIG
}
private data class ProblemInfo(val level: Int, val group: Int)
private val problems = mutableMapOf<Int, ProblemInfo>()
private val groupedProblemsTree = TreeMap<Int, TreeMap<Int, TreeMap<Int, Int>>>() // <분류 - <난이도 - <문제 번호, 아무값>>>
private val problemsTree = TreeMap<Int, TreeMap<Int, Int>>() // <난이도 - <문제 번호, 아무값>>
fun main() {
val br = BufferedReader(InputStreamReader(System.`in`))
val bw = BufferedWriter(OutputStreamWriter(System.out))
repeat(br.readLine()!!.toInt()) {
val (problemNumber, problemLevel, problemGroup) = br.readLine()!!.split(" ").map { it.toInt() }
updateProblemsTree(
problemNumber = problemNumber,
problemLevel = problemLevel,
problemGroup = problemGroup
)
}
repeat(br.readLine()!!.toInt()) {
val commands = br.readLine().split(" ")
val command = commands[0]
when (command) {
"add" -> {
val problemNumber = commands[1].toInt()
val problemLevel = commands[2].toInt()
val problemGroup = commands[3].toInt()
updateProblemsTree(
problemNumber = problemNumber,
problemLevel = problemLevel,
problemGroup = problemGroup
)
}
"solved" -> {
// groupedProblemsTree = <분류 - <난이도 - <문제 번호, 아무값>>>
// problemsTree = <난이도 - <문제 번호, 아무값>>
val problemNumber = commands[1].toInt()
val problemInfo = problems[problemNumber]!!
groupedProblemsTree[problemInfo.group]!![problemInfo.level]!!.remove(problemNumber)
problemsTree[problemInfo.level]!!.remove(problemNumber)
}
"recommend" -> {
val problemGroup = commands[1].toInt()
val problemLevelType = commands[2]
val recommandProblemNumber = if (problemLevelType == "1") { // 가장 어려운 문제
recommendProblemNumber(group = problemGroup, problemLevelType = ProblemLevelType.HARD)
} else { // 가장 쉬운 문제
recommendProblemNumber(group = problemGroup, problemLevelType = ProblemLevelType.EASY)
}
bw.write("$recommandProblemNumber\n")
}
"recommend2" -> {
val problemLevelType = commands[1]
val recommandProblemNumber = if (problemLevelType == "1") { // 가장 어려운 문제
recommend2ProblemNumber(problemLevelType = ProblemLevelType.HARD)
} else { // 가장 쉬운 문제
recommend2ProblemNumber(problemLevelType = ProblemLevelType.EASY)
}
bw.write("$recommandProblemNumber\n")
}
"recommend3" -> {
val problemNumberType = commands[1]
val problemLevel = commands[2].toInt()
val recommandProblemNumber = if (problemNumberType == "1") { // 난이도가 problemLevel 보다 크거나 같은 문제
recommend3ProblemNumber(level = problemLevel, problemNumberType = ProblemNumberType.BIG)
} else { // 난이도가 problemLevel 보다 작은 문제
recommend3ProblemNumber(level = problemLevel, problemNumberType = ProblemNumberType.SMALL)
}
bw.write("$recommandProblemNumber\n")
}
}
}
br.close()
bw.flush()
bw.close()
}
private fun updateProblemsTree(problemNumber: Int, problemLevel: Int, problemGroup: Int) {
// <분류 - <난이도 - <문제 번호, 아무값>>>
groupedProblemsTree[problemGroup] =
groupedProblemsTree.getOrDefault(problemGroup, TreeMap<Int, TreeMap<Int, Int>>()).apply {
// this = <난이도 - <문제 번호, 아무값>>
this[problemLevel] = this.getOrDefault(problemLevel, TreeMap<Int, Int>()).apply {
// this = <문제 번호, 아무값>>
this[problemNumber] = 0
}
}
// <난이도 - <문제 번호, 아무값>>
problemsTree[problemLevel] = problemsTree.getOrDefault(problemLevel, TreeMap<Int, Int>()).apply {
// this = <문제 번호, 아무값>>
this[problemNumber] = 0
}
val problemInfo = ProblemInfo(level = problemLevel, group = problemGroup)
problems[problemNumber] = problemInfo
}
// groupedProblemsTree = <분류 - <난이도 - <문제 번호, 아무값>>>
// 추천 문제 리스트에서 알고리즘 분류가 group인 문제 중 가장 난이도가 type한 문제 번호를 출력한다.
// 조건을 만족하는 문제가 여러 개라면 그 중 문제 번호가 큰/작은 것으로 출력한다.
private fun recommendProblemNumber(group: Int, problemLevelType: ProblemLevelType): Int {
val problemsLevelTree = groupedProblemsTree[group]!! // <난이도 - <문제 번호, 아무값>>
val problemLevel = if (problemLevelType == ProblemLevelType.HARD) {
problemsLevelTree.lastKey()
} else {
problemsLevelTree.firstKey()
}
val problemsTree = problemsLevelTree[problemLevel]!!
if (problemsTree.isEmpty()) { // 만약 해당하는 난이도에 대한 문제가 없다면 해당 난이도를 없애고 다시 조회
groupedProblemsTree[group]!!.remove(problemLevel)
return recommendProblemNumber(group, problemLevelType)
}
return if (problemLevelType == ProblemLevelType.HARD) {
problemsTree.lastKey()
} else {
problemsTree.firstKey()
}
}
// problemsTree = <난이도 - <문제 번호, 아무값>>
// 추천 문제 리스트에서 **알고리즘 분류 상관 없이** 문제 중 가장 난이도가 type한 문제 번호를 출력한다.
// 조건을 만족하는 문제가 여러 개라면 그 중 문제 번호가 큰/작은 것으로 출력한다.
private fun recommend2ProblemNumber(problemLevelType: ProblemLevelType): Int {
val problemLevel = if (problemLevelType == ProblemLevelType.HARD) {
problemsTree.lastKey()
} else {
problemsTree.firstKey()
}
val problems = problemsTree[problemLevel]!!
if (problems.isEmpty()) {
problemsTree.remove(problemLevel)
return recommend2ProblemNumber(problemLevelType)
}
return if (problemLevelType == ProblemLevelType.HARD) {
problems.lastKey()
} else {
problems.firstKey()
}
}
// problemsTree = <난이도 - <문제 번호, 아무값>>
// 추천 문제 리스트에서 **알고리즘 분류 상관 없이** 문제 중 가장 난이도가 level 보다 크거나 같은/작은 문제 중 가장 쉬운 문제 번호를 출력한다.
// 조건을 만족하는 문제가 여러 개라면 그 중 문제 번호가 **작은/큰** 으로 출력한다.
private fun recommend3ProblemNumber(level: Int, problemNumberType: ProblemNumberType): Int {
val problemLevels = if (problemNumberType == ProblemNumberType.BIG) { // 난이도가 level 보다 크거나 같은
problemsTree.tailMap(level)
} else { // 난이도가 level 보다 작은
problemsTree.headMap(level)
} // problemLevels = <난이도 - <문제 번호, 아무값>>
if (problemLevels.isEmpty()) {
return -1
}
val problemLevel = if (problemNumberType == ProblemNumberType.BIG) { // 난이도가 낮은 문제 중에서
problemLevels.firstKey()
} else { // 난이도가 높은 문제 중에서
problemLevels.lastKey()
}
val problems = problemLevels[problemLevel]!! // <문제 번호, 아무값>
if (problems.isEmpty()) {
problemsTree.remove(problemLevel) // 없는 난이도 제거 후 함수 함수 돌리기
return recommend3ProblemNumber(level, problemNumberType)
}
return if (problemNumberType == ProblemNumberType.BIG) { // 문제 번호가 작은 것으로 출력
problems.firstKey()
} else { // 문제 번호가 큰 것으로 출력
problems.lastKey()
}
}
| 0 | Kotlin | 1 | 10 | ee43375828ca7e748e7c79fbed63a3b4d27a7a2c | 8,420 | algorithm-code | MIT License |
src/aoc2022/Day01.kt | anitakar | 576,901,981 | false | {"Kotlin": 124382} | package aoc2022
import println
import readInput
import java.util.*
fun main() {
fun part1(input: List<String>): Int {
var sum = 0;
var maxSum = 0;
for (cur in input) {
if (cur.isEmpty()) {
if (sum > maxSum) {
maxSum = sum
}
sum = 0
} else {
sum += cur.toInt()
}
}
return maxSum
}
fun part2(input: List<String>): Int {
val queue = PriorityQueue<Int>()
var sum = 0
for (elem in input) {
if (elem.isBlank()) {
if (queue.size >= 3) {
if (queue.peek() < sum) {
queue.poll()
queue.add(sum)
}
} else {
queue.add(sum)
}
sum = 0;
} else {
sum += elem.toInt()
}
}
return queue.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
val input = readInput("Day01")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 1 | 50998a75d9582d4f5a77b829a9e5d4b88f4f2fcf | 1,265 | advent-of-code-kotlin | Apache License 2.0 |
dcp_kotlin/src/main/kotlin/dcp/day250/day250.kt | sraaphorst | 182,330,159 | false | {"C++": 577416, "Kotlin": 231559, "Python": 132573, "Scala": 50468, "Java": 34742, "CMake": 2332, "C": 315} | //package dcp.day250
//
//import java.lang.NumberFormatException
//
//
//fun <T> List<T>.indexOfOrNull(t: T): Int? {
// val idx = this.indexOf(t)
// return if (idx == -1) null else idx
//}
//
//fun crypto_solve(word1: String, word2: String, wordSum: String): Map<Char, Int>? {
// // Collect all the characters and make sure there are at most 10.
// // We want to collect them in columns starting at the right.
// val chars = (0..wordSum.length).map {
// listOf(word1.elementAtOrNull(it), word2.elementAtOrNull(it), wordSum.elementAtOrNull(it))
// }.flatten().filterNotNull().distinct()
// require(chars.size <= 10) { "Crytopuzzle can have at most 10 characters" }
//
//
// // map: We want to assign Ints to chars in the order of chars to be able to do backtracking by exploiting
// // partial sums.
// val map: MutableList<Int> = mutableListOf()
// val digitsUsed: MutableList<Boolean> = MutableList(10) { false }
//
//
// fun backtrack(extending: Boolean = true): Map<Char, Int>? {
//
// // Check to see if the arithmetic over the last column columns is correct.
// fun isValid(column: Int, full: Boolean = false): Boolean {
// val w1 = if (full) word1 else word1.takeLast(column)
// val w2 = if (full) word2 else word2.takeLast(column)
// val wSum = if (full) wordSum else wordSum.takeLast(column)
//
// // Now convert each into a number to the best of our ability.
// fun wordToInt(word: String): Int? =
// try {
// word.fold(word) { acc, char -> acc.replace(char.toString(), map[chars.indexOf(char)].toString()) }.toInt()
// } catch (_: NumberFormatException) {
// null
// }
//
// val i1 = wordToInt(w1)
// val i2 = wordToInt(w2)
// val iSum = wordToInt(wSum)
//
// if (i1 == null || i2 == null || iSum == null)
// return false
//
// // Unfortunately convert to String and use to chop off the potentially leading 1.
// return (i1 + i2).toString().take(wSum.length) == iSum.toString()
// }
//
// // Sanity check: unassigned + assigned should be 10.
// val numDigitsLeft = digitsUsed.count { !it }
// require(numDigitsLeft + map.size == 10) { "Something went wrong" }
//
// // If we have a complete solution, return it.
// if (map.size == chars.size)
// return chars.zip(map).toMap()
//
// // If we have explored the whole backtrack tree and found no solution and are back at the root, we are done.
// if (!extending && map.isEmpty())
// return null
//
// // Get the candidates, possibly above a certain number.
// fun getCandidates(lowerBound: Int = 0): List<Int> =
// digitsUsed.withIndex().filter { !it.value && it.index >= lowerBound }.map { it.index }
//
//
// // If we are extending, try the first digit available.
// if (extending) {
// // We are storing for the character at key.
// val key = map.size
// val candidates = getCandidates()
// for (candidate in candidates) {
// map[map.size] = candidate
// digitsUsed[candidate] = true
// // If we are at the end of a column, check our math and backtrack if it fails.
// if (map.size % 3 != 0 || isValid(map.size / 3, map.size == chars.size))
// return backtrack(true)
// }
// return backtrack(false)
// }
//
// // Otherwise, we are backtracking. We return the current character, try the next available one, and extend.
// // If there are no more available characters, we continue to backtrack.
// else {
// val prevCandidate = map.last()
// val candidates = getCandidates(prevCandidate + 1)
// digitsUsed[prevCandidate] = false
//
// for (candidate in candidates) {
//
// }
// // If value is not null, extend.
// if (value != null) {
// digitsUsed[value] = true
// return backtrack(map.dropLast(1) + Pair(key, value), digitsUsed, extending = true)
// } else {
// return backtrack(map.dropLast(1), digitsUsed, extending = false)
// }
// }
// }
//
// return backtrack()
//}
//
//
//fun main() {
// println("hello".toCharArray().drop(1))
//} | 0 | C++ | 1 | 0 | 5981e97106376186241f0fad81ee0e3a9b0270b5 | 4,523 | daily-coding-problem | MIT License |
app/src/main/java/com/keridano/soccersim/model/Match.kt | keridano | 489,078,382 | false | null | package com.keridano.soccersim.model
import com.keridano.soccersim.model.enum.Bonus
/**
* A football [Match] between two [Team]s
*
* @param homeTeam the home team
* @param awayTeam the away team
* @param homeTeamGoals the number of goals scored by the home team
* @param awayTeamGoals the number of goals scored by the away team
*/
data class Match(
val homeTeam: Team,
val awayTeam: Team,
val matchDay: Int,
var homeTeamGoals: Int = 0,
var awayTeamGoals: Int = 0
)
/**
* The [Match] simulation consists in a simple math calculation based on the following rules:
*
* - the home team gets 5 bonus points (12th man effect)
* - every team has got a [Bonus] which gives bonus points or better chances
* - a Random value, representing the chance, is added to the team strength and bonuses
*/
fun Match.simulateMatch() {
val homeBonus = 5
var homeTeamPoints = homeTeam.strength + homeBonus
var awayTeamPoints = awayTeam.strength
// add bonus perks
if (homeTeam.bonuses.contains(Bonus.BEST_PLAYERS)) homeTeamPoints += 10
if (homeTeam.bonuses.contains(Bonus.BEST_COACH)) homeTeamPoints += 5
if (awayTeam.bonuses.contains(Bonus.BEST_PLAYERS)) awayTeamPoints += 10
if (awayTeam.bonuses.contains(Bonus.BEST_COACH)) awayTeamPoints += 5
homeTeamPoints += if (homeTeam.bonuses.contains(Bonus.LUCKY_TEAM))
(10..50).random() // The luckiest team has got better chances
else
(0..40).random()
awayTeamPoints += if (awayTeam.bonuses.contains(Bonus.LUCKY_TEAM))
(10..50).random() // The luckiest team has got better chances
else
(0..40).random()
// calculate the scored goals based on the calculated points
homeTeamGoals = transformPointsInGoals(homeTeamPoints)
awayTeamGoals = transformPointsInGoals(awayTeamPoints)
// remove 1 conceded goal if the team has the best defense Bonus
if (homeTeam.bonuses.contains(Bonus.BEST_DEFENSE) && homeTeamGoals > 0) homeTeamGoals -= 1
if (awayTeam.bonuses.contains(Bonus.BEST_DEFENSE) && awayTeamGoals > 0) awayTeamGoals -= 1
}
/**
* transform points calculated in the simulation in goals using this rule:
* - values lower than 65 doesn't produce goals
* - starting from 66 every 5 points results in a scored goal
* - scored goals cap is 6
*/
fun transformPointsInGoals(points: Int): Int {
return when (points) {
in 0..65 -> 0
in 66..71 -> 1
in 72..77 -> 2
in 78..83 -> 3
in 84..89 -> 4
in 90..95 -> 5
else -> 6
}
} | 0 | Kotlin | 0 | 0 | e2917b70246c42dd0c1b147270b8cf643ec1c96a | 2,549 | Soccer-Sim | MIT License |
src/Day21.kt | spaikmos | 573,196,976 | false | {"Kotlin": 83036} | fun main() {
fun parseInput(input: List<String>): Pair<MutableMap<String, Long>, MutableMap<String, List<String>>> {
val nums = mutableMapOf<String, Long>()
val ops = mutableMapOf<String, List<String>>()
val regexNum = """(.{4}): (\d+)""".toRegex()
val regexString = """(.{4}): (.{4}) (.) (.{4})""".toRegex()
for (i in input) {
// Length less than 16 means it's a value and not an operation
if (i.length < 16) {
val (name, value) = regexNum.find(i)!!.destructured
nums.put(name, value.toLong())
} else {
val (name, arg1, arg2, arg3) = regexString.find(i)!!.destructured
ops.put(name, listOf(arg1, arg2, arg3))
}
}
return Pair(nums, ops)
}
fun part1(input: Pair<MutableMap<String, Long>, MutableMap<String, List<String>>>): Long {
val nums = input.first
val ops = input.second
while (ops.size > 0) {
for (op in ops) {
val name = op.key
val (arg1, operator, arg2) = op.value
if (nums.contains(arg1) && nums.contains(arg2)) {
var value = 0L
val num1 = nums.get(arg1)!!
val num2 = nums.get(arg2)!!
when (operator) {
"+" -> value = num1 + num2
"-" -> value = num1 - num2
"*" -> value = num1 * num2
"/" -> value = num1 / num2
}
// Insert the new value into the nums map
nums[name] = value
// Ideally remove the element from this map so we don't continue to process the
// same operation over and over again....
if (name == "root") {
return value
}
}
}
}
return 0L
}
fun part2(input: Pair<MutableMap<String, Long>, MutableMap<String, List<String>>>): Long {
val nums = input.first
val ops = input.second
val humanList = ArrayDeque<String>()
// Build a list of variables that are calculated using the humn value
humanList.add("humn")
var curString = "humn"
while (curString != "root") {
for (op in ops) {
val name = op.key
val (arg1, operator, arg2) = op.value
if ((arg1 == curString) || (arg2 == curString)) {
humanList.add(name)
curString = name
}
}
}
// Unwind the operations. From trial and error I know mwrd is the correct value.
// The last operation is "root: hsdb + mwrd" so start with hsdb as the prevString
var value = nums.get("mwrd")!!
curString = humanList.removeLast() // Remove root
curString = humanList.removeLast() // Remove hsdb
while (curString != "mnfl") {
val prevString = curString
curString = humanList.removeLast()
val (arg1, operator, arg2) = ops.get(prevString)!!
if (curString == arg1) {
val num2 = nums.get(arg2)!!
when (operator) {
"+" -> value -= num2
"-" -> value += num2
"*" -> value /= num2
"/" -> value *= num2
}
} else {
val num1 = nums.get(arg1)!!
when (operator) {
"+" -> value -= num1
"-" -> value = num1 - value
"*" -> value /= num1
"/" -> value = num1 / value
}
}
}
// The last operation using humn is "mnfl: cqgp + humn". Undo this one too
return value - nums.get("cqgp")!!
}
val input = readInput("../input/Day21")
var input2 = parseInput(input)
println(part1(input2)) // 124765768589550
println(part2(input2)) // 3059361893920
} | 0 | Kotlin | 0 | 0 | 6fee01bbab667f004c86024164c2acbb11566460 | 4,141 | aoc-2022 | Apache License 2.0 |
src/Day06.kt | 6234456 | 572,616,769 | false | {"Kotlin": 39979} | fun main() {
fun part1(input: List<String>): Int {
val s = input.first()
val l = s.length
val dp = Array<IntArray>(l+1){ IntArray(l+1){0} }
val lastPos = IntArray(26){0}
lastPos[s[0] - 'a'] = 1
var j = 1
var i = j + 1
while (j <= l){
while(i <= l) {
val ls = lastPos[s[i-1] - 'a']
if (ls < j){
dp[j][i] = dp[j][i-1] + 1
}else{
dp[ls+1][i] = i - ls
j = ls + 1
}
if (dp[j][i] == 14)
return i
lastPos[s[i-1] - 'a'] = i++
}
}
return 0
}
fun part2(input: List<String>): String {
return ""
}
var input = readInput("Test06")
println(part1(input))
println(part2(input))
input = readInput("Day06")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | b6d683e0900ab2136537089e2392b96905652c4e | 975 | advent-of-code-kotlin-2022 | Apache License 2.0 |
solutions/aockt/y2022/Y2022D05.kt | Jadarma | 624,153,848 | false | {"Kotlin": 435090} | package aockt.y2022
import aockt.y2022.Y2022D05.CraneDialect.*
import io.github.jadarma.aockt.core.Solution
object Y2022D05 : Solution {
/** Parses the input and returns the initial [CraneStackState] and a list of instructions. */
private fun parseInput(input: String): Pair<CraneStackState, List<CraneMove>> {
val inputStream = input.lineSequence().iterator()
lateinit var line: String
val craneStacks = buildList {
while (inputStream.hasNext()) {
line = inputStream.next()
if (line.trimStart().firstOrNull() != '[') return@buildList
line
.replace(Regex("""\[([A-Z])]\s?""")) { it.groupValues[1] }
.replace(Regex("""\s{3,4}"""), "_")
.toList()
.let(::add)
}
}
val labels = line.trim().split(Regex("\\s+"))
val craneState = buildMap(capacity = labels.size) {
labels.forEachIndexed { index, stackName ->
val stack = craneStacks
.mapNotNull { it.getOrNull(index) }
.filter { it != '_' }
.asReversed()
.let { ArrayDeque(it) }
put(stackName, stack)
}
}.let(::CraneStackState)
inputStream.next()
val instructions = buildList {
while (inputStream.hasNext()) {
add(inputStream.next().let(CraneMove::parse))
}
}
return (craneState to instructions)
}
/** Known dialects for different CraneMover models.*/
private enum class CraneDialect { CrateMover9000, CrateMover9001 }
/** A single instruction to move crates between stacks. Behavior depends on [CraneDialect]. */
private data class CraneMove(val takeFrom: String, val moveTo: String, val amount: Int) {
override fun toString() = "move $amount from $takeFrom to $moveTo"
companion object {
private val craneInstructionRegex = Regex("""^move (\d+) from (\S+) to (\S+)$""")
/** Parse an [input] into a [CraneMove] or throw an [IllegalArgumentException] if it is invalid. */
fun parse(input: String): CraneMove {
val match = craneInstructionRegex.matchEntire(input)
requireNotNull(match) { "Input '$input' is not a valid CraneMove." }
return CraneMove(
takeFrom = match.groupValues[2],
moveTo = match.groupValues[3],
amount = match.groupValues[1].toInt(),
)
}
}
}
@JvmInline
private value class CraneStackState(private val state: Map<String, ArrayDeque<Char>>) {
/** Executes the [instruction], using a specific [craneDialect]. Mutates inner state. */
fun execute(instruction: CraneMove, craneDialect: CraneDialect) {
val fromStack = state[instruction.takeFrom] ?: return
val toStack = state[instruction.moveTo] ?: return
when (craneDialect) {
CrateMover9000 -> repeat(instruction.amount) {
toStack.addLast(fromStack.removeLast())
}
CrateMover9001 -> {
(1..instruction.amount)
.map { fromStack.removeLast() }
.asReversed()
.forEach(toStack::addLast)
}
}
}
/** Returns a string of all characters of each crate stack's top crate label, ignoring empty stacks. */
fun topOfStack(): String = state.values.map { it.lastOrNull() ?: "" }.joinToString("")
}
/**
* Given an [input] and a crane [dialect], simulates the crate moving and returns the string made out of all
* the letters of each top of the stack.
*/
private fun solve(input: String, dialect: CraneDialect): String = parseInput(input).let { (state, moves) ->
moves.forEach { state.execute(it, dialect) }
state.topOfStack()
}
override fun partOne(input: String) = solve(input, CrateMover9000)
override fun partTwo(input: String) = solve(input, CrateMover9001)
}
| 0 | Kotlin | 0 | 3 | 19773317d665dcb29c84e44fa1b35a6f6122a5fa | 4,241 | advent-of-code-kotlin-solutions | The Unlicense |
src/main/kotlin/day2.kt | tianyu | 574,561,581 | false | {"Kotlin": 49942} | import Move.*
import Outcome.*
import java.lang.IllegalStateException
private fun main() {
part1("The total score of (not) following the strategy guide is:") {
playRockPaperScissors { theirs, ours ->
val ourMove = ours.asMove()
val theirMove = theirs.asMove()
val outcome = outcome(theirMove, ourMove)
ourMove.score + outcome.score
}.sum()
}
part2("The total score of following the strategy guide is:") {
playRockPaperScissors { theirs, ours ->
val theirMove = theirs.asMove()
val outcome = ours.asOutcome()
val ourMove = outcome.counterMove(theirMove)
ourMove.score + outcome.score
}.sum()
}
}
private enum class Move(val id: Int) {
Rock(0), Paper(1), Scissors(2);
val score = id + 1
}
private enum class Outcome(val diff: Int) {
Lose(-1), Tie(0), Win(1);
val score = 3 * (diff + 1)
}
private fun outcome(theirs: Move, ours: Move): Outcome = when (ours.id - theirs.id) {
-1, 2 -> Lose
1, -2 -> Win
else -> Tie
}
private fun Outcome.counterMove(theirs: Move): Move = when ((theirs.id + diff).mod(3)) {
0 -> Rock
1 -> Paper
2 -> Scissors
else -> throw AssertionError()
}
private inline fun <T> playRockPaperScissors(crossinline action: (theirs: Char, ours: Char) -> T) = sequence {
withInputLines("day2.txt") {
forEach { line ->
yield(action(line[0], line[2]))
}
}
}
private fun Char.asMove() = when (this) {
'A', 'X' -> Rock
'B', 'Y' -> Paper
'C', 'Z' -> Scissors
else -> throw IllegalStateException("Cannot read move: '$this'")
}
private fun Char.asOutcome() = when (this) {
'X' -> Lose
'Y' -> Tie
'Z' -> Win
else -> throw IllegalStateException("Cannot read outcome: '$this'")
} | 0 | Kotlin | 0 | 0 | 6144cc0ccf1a51ba2e28c9f38ae4e6dd4c0dc1ea | 1,716 | AdventOfCode2022 | MIT License |
Advent-of-Code-2023/src/Day16.kt | Radnar9 | 726,180,837 | false | {"Kotlin": 93593} | private const val AOC_DAY = "Day16"
private const val TEST_FILE = "${AOC_DAY}_test"
private const val INPUT_FILE = AOC_DAY
/**
* Calculates the number of energized tiles starting from the initial position/movement.
*/
private fun energizedTiles(initialMovement: Movement, input: List<String>): Int {
val seen = mutableSetOf<Movement>()
val queue = ArrayDeque<Movement>().apply { add(initialMovement) }
while (queue.isNotEmpty()) {
val (currentPos, direction) = queue.removeFirst()
val nextPos = Position(currentPos.row + direction.row, currentPos.col + direction.col)
if (nextPos.row < 0 || nextPos.row >= input.size || nextPos.col < 0 || nextPos.col >= input[0].length) continue
val nextChar = input[nextPos.row][nextPos.col]
if (nextChar == '.' || (nextChar == '-' && direction.col != 0) || (nextChar == '|' && direction.row != 0)) {
val mov = Movement(nextPos, direction)
if (mov !in seen) {
seen.add(mov)
queue.add(mov)
}
} else if (nextChar == '/') {
val newDir = Position(-direction.col, -direction.row)
val mov = Movement(nextPos, newDir)
if (mov !in seen) {
seen.add(mov)
queue.add(mov)
}
} else if (nextChar == '\\') {
val newDir = Position(direction.col, direction.row)
val mov = Movement(nextPos, newDir)
if (mov !in seen) {
seen.add(mov)
queue.add(mov)
}
} else if (nextChar == '|') {
val dirs = listOf(Position(1, 0), Position(-1, 0))
for (dir in dirs) {
val mov = Movement(nextPos, dir)
if (mov !in seen) {
seen.add(mov)
queue.add(mov)
}
}
} else { // nextChar = '-'
val dirs = listOf(Position(0, 1), Position(0, -1))
for (dir in dirs) {
val mov = Movement(nextPos, dir)
if (mov !in seen) {
seen.add(mov)
queue.add(mov)
}
}
}
}
val uniquePos = seen.map { it.currentPos }.toSet()
return uniquePos.size
}
private data class Movement(val currentPos: Position, val direction: Position)
/**
* Finds the number of energized tiles starting from the required initial position and following movement.
*/
private fun part1(input: List<String>): Int {
return energizedTiles(Movement(Position(0, -1), Position(0, 1)), input)
}
/**
* Finds the starting position that allows to reach the maximum number of energized tiles.
*/
private fun part2(input: List<String>): Int {
var maxEnergized = 0
// Check the positions on the first and last columns where the tile goes right and left, respectively.
for (row in input.indices) {
maxEnergized = maxOf(maxEnergized, energizedTiles(Movement(Position(row, -1), Position(0, 1)), input))
maxEnergized = maxOf(maxEnergized, energizedTiles(Movement(Position(row, input[0].length), Position(0, -1)), input))
}
// Check the downwards and upwards positions on top and bottom, respectively.
for (col in input[0].indices) {
maxEnergized = maxOf(maxEnergized, energizedTiles(Movement(Position(-1, col), Position(1, 0)), input))
maxEnergized = maxOf(maxEnergized, energizedTiles(Movement(Position(input.size, col), Position(-1, 0)), input))
}
return maxEnergized
}
fun main() {
createTestFiles(AOC_DAY)
val testInput = readInputToList(TEST_FILE)
val part1ExpectedRes = 46
println("---| TEST INPUT |---")
println("* PART 1: ${part1(testInput)}\t== $part1ExpectedRes")
val part2ExpectedRes = 51
println("* PART 2: ${part2(testInput)}\t== $part2ExpectedRes\n")
val input = readInputToList(INPUT_FILE)
val improving = false
println("---| FINAL INPUT |---")
println("* PART 1: ${part1(input)}${if (improving) "\t== 7392" else ""}")
println("* PART 2: ${part2(input)}${if (improving) "\t== ???" else ""}")
}
| 0 | Kotlin | 0 | 0 | e6b1caa25bcab4cb5eded12c35231c7c795c5506 | 4,158 | Advent-of-Code-2023 | Apache License 2.0 |
y2017/src/main/kotlin/adventofcode/y2017/Day13.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2017
import adventofcode.io.AdventSolution
object Day13 : AdventSolution(2017, 13, "Packet Scanners") {
override fun solvePartOne(input: String): String = parseInput(input)
.filter { (depth, range) -> depth % (range * 2 - 2) == 0 }
.entries
.sumOf { (depth, range) -> depth * range }
.toString()
override fun solvePartTwo(input: String): String {
val lasers = parseInput(input)
val shortestSafeDelay = generateSequence(0) { it + 1 }
.indexOfFirst { delay ->
lasers.none { (depth, range) ->
(depth + delay) % (range * 2 - 2) == 0
}
}
return shortestSafeDelay.toString()
}
private fun parseInput(input: String) = input.lines()
.map { it.split(": ") }
.associate { (depth, range) -> depth.toInt() to range.toInt() }
}
| 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 794 | advent-of-code | MIT License |
com/ztoais/dailycoding/algoexpert/hard/FourNumberSum.kt | RanjithRagavan | 479,563,314 | false | {"Kotlin": 7371} | package com.ztoais.dailycoding.algoexpert.hard
/*
Write a function that takes in a non-empty array of distinct integers and an integer representing a target sum. The
function should find all quadruplets in the array that sum up to the target sum and return a tow-dimensional array of
all these quadruplets in no particular order.
If no four numbers sum up to the target sum, the function should return an empty array
Sample input
array = [7,6,4,-1,1,2]
targetSum = 16
Sample output
[[7,6,4,-1],[7,6,1,2]]
*/
/*
*/
fun fourNumberSum(array: MutableList<Int>, targetSum:Int):List<List<Int>>{
val result = mutableListOf<List<Int>>()
val appPairSums = mutableMapOf<Int,List<Pair<Int,Int>>>()
for (i in 1 until array.size-1) {
for(j in i+1 until array.size){
val currentSum:Int = array[i]+array[j]
val difference = targetSum - currentSum
if(appPairSums.containsKey(difference)){
val pairValues = appPairSums[difference]
pairValues?.let {
for(pair in it){
val quadruplets = listOf(pair.first,pair.second, array[i], array[j])
result.add(quadruplets)
}
}
}
}
for(k in 0 until i){
val currentSum = array[i]+array[k]
if(!appPairSums.containsKey(currentSum)){
appPairSums[currentSum] = listOf(Pair(array[k],array[i]))
}else{
val pairList = appPairSums[currentSum]?.toMutableList()
pairList?.add(Pair(array[k],array[i]))
if (pairList != null) {
appPairSums[currentSum] = pairList.toList()
}
}
}
}
return result
}
/*
Tests
Quick Test
Sandbox
Test Case 1
{
"array": [7, 6, 4, -1, 1, 2],
"targetSum": 16
}
Test Case 2
{
"array": [1, 2, 3, 4, 5, 6, 7],
"targetSum": 10
}
Test Case 3
{
"array": [5, -5, -2, 2, 3, -3],
"targetSum": 0
}
Test Case 4
{
"array": [-2, -1, 1, 2, 3, 4, 5, 6, 7, 8, 9],
"targetSum": 4
}
Test Case 5
{
"array": [-1, 22, 18, 4, 7, 11, 2, -5, -3],
"targetSum": 30
}
Test Case 6
{
"array": [-10, -3, -5, 2, 15, -7, 28, -6, 12, 8, 11, 5],
"targetSum": 20
}
Test Case 7
{
"array": [1, 2, 3, 4, 5],
"targetSum": 100
}
Test Case 8
{
"array": [1, 2, 3, 4, 5, -5, 6, -6],
"targetSum": 5
}
*/ | 0 | Kotlin | 0 | 0 | a5f29dd82c0c50fc7d2490fd1be6234cdb4d1d8a | 2,435 | daily-coding | MIT License |
src/main/kotlin/days/Day11.kt | hughjdavey | 433,597,582 | false | {"Kotlin": 53042} | package days
import util.Utils
class Day11 : Day(11) {
private fun octos() = inputList.flatMapIndexed { y, s -> s.mapIndexed { x, c -> Octopus(c.toString().toInt(), Utils.Coord(x, y)) } }
override fun partOne(): Any {
return (1..100).fold(0 to octos()) { (flashes, octos), _ ->
flashes + step(octos) to octos }.first
}
override fun partTwo(): Any {
return generateSequence(1 to octos()) { (step, octos) -> step(octos); step + 1 to octos }
.takeWhile { (step, octos) -> octos.any { it.energy != 0 } }.last().first
}
data class Octopus(var energy: Int, val coord: Utils.Coord, var hasFlashed: Boolean = false)
companion object {
// todo make this functional/immutable
fun step(octos: List<Octopus>): Int {
var flashes = 0
octos.forEach { it.energy++ }
while (octos.any { it.energy > 9 && !it.hasFlashed }) {
val flashing = octos.filter { it.energy > 9 && !it.hasFlashed }
flashes += flashing.size
val adjacent = flashing.flatMap { it.coord.getAdjacent(true) }.mapNotNull { octos.find { o -> o.coord == it } }
adjacent.forEach { it.energy++ }
flashing.forEach { it.hasFlashed = true }
}
octos.forEach { if (it.hasFlashed) { it.energy = 0; it.hasFlashed = false } }
return flashes
}
fun toString(octos: List<Octopus>): String {
val len = octos.maxOf { it.coord.x + 1 }
return octos.chunked(len).joinToString("\n") { it.joinToString("") { it.energy.toString() } }
}
}
}
| 0 | Kotlin | 0 | 0 | a3c2fe866f6b1811782d774a4317457f0882f5ef | 1,662 | aoc-2021 | Creative Commons Zero v1.0 Universal |
src/main/kotlin/days/Day3Data.kt | yigitozgumus | 572,855,908 | false | {"Kotlin": 26037} | package days
import utils.SolutionData
import utils.Utils.getPriority
fun main() = with(Day3Data()) {
solvePart1()
solvePart2()
}
class Day3Data : SolutionData(inputFile = "inputs/day3.txt") {
val part1Data = rawData.map { it.toList() }.map { it.chunked(it.size / 2) }
val part2Data = rawData.map { it.toList() }.chunked(3)
}
fun Day3Data.solvePart1() {
val priorityList = part1Data.flatMap { lists ->
lists.first()
.mapNotNull { target -> lists.last().firstOrNull { target == it } }
.distinct()
}
println(priorityList.sumOf { getPriority(it) })
}
fun Day3Data.solvePart2() {
val badgeList = part2Data.flatMap {
it.first().toSet()
.intersect(it[1].toSet())
.intersect(it.last().toSet())
}
println(badgeList.sumOf { getPriority(it) })
}
| 0 | Kotlin | 0 | 0 | 9a3654b6d1d455aed49d018d9aa02d37c57c8946 | 768 | AdventOfCode2022 | MIT License |
src/algorithmdesignmanualbook/datastructures/MatrixMultiplication.kt | realpacific | 234,499,820 | false | null | package algorithmdesignmanualbook.datastructures
import utils.PrintUtils
import kotlin.test.assertFails
typealias Matrix = Array<Array<Int>>
typealias Dimen = Pair<Int, Int>
fun main() {
val matA = arrayOf(arrayOf(1, 2, 3), arrayOf(3, 3, 3), arrayOf(5, 4, 3))
val matB = arrayOf(arrayOf(1, 3), arrayOf(2, 3), arrayOf(3, 3))
multiplyMatrix(matA, matB)
val matA2 = arrayOf(arrayOf(1, 2, 3), arrayOf(3, 3, 3))
val matB2 = arrayOf(arrayOf(1, 3), arrayOf(3, 3))
assertFails { multiplyMatrix(matA2, matB2) }
}
/**
* Complexity of this algorithm = O(xyz) i.e. CUBIC
*/
fun multiplyMatrix(matA: Matrix, matB: Matrix): Matrix {
PrintUtils.printArr(matA.toList())
println("x")
PrintUtils.printArr(matB.toList())
require(matA[0].size == matB.size) {
"Matrix multiplication not possible between ${matA.dimension().str()} & ${matB.dimension().str()}"
}
val result = Array(matA[0].size) {
Array(matB[0].size) { 0 }
}
for (i in 0..matA[0].lastIndex) {
for (j in 0..matB[0].lastIndex) {
result[i][j] = 0
for (k in 0..matA.lastIndex) {
result[i][j] += matA[i][k] * matB[k][j]
}
}
}
return result.also {
PrintUtils.printArr(result.toList())
println()
}
}
private fun Matrix.dimension(): Dimen = Pair(this.size, this[0].size)
private fun Dimen.str(): String = "${first}x${second} "
| 4 | Kotlin | 5 | 93 | 22eef528ef1bea9b9831178b64ff2f5b1f61a51f | 1,449 | algorithms | MIT License |
_14_Longest_Common_Prefix/src/main/kotlin/LongestCommonPrefix.kt | Edsonctm | 584,187,846 | false | null | fun main() {
val strs = arrayOf("flower","flow","flight")
val strs2 = arrayOf("dog","racecar","car")
val strs3 = arrayOf("a")
val strs4 = arrayOf("reflower","flow","flight")
val strs5 = arrayOf("aaa","aa","aaa")
longestCommonPrefix(strs)
longestCommonPrefix(strs2)
longestCommonPrefix(strs3)
longestCommonPrefix(strs4)
longestCommonPrefix(strs5)
}
fun longestCommonPrefix(strs: Array<String>): String {
var menorPalavra = strs[0]
var resposta = ""
var index = 0
var contador = menorPalavra.length
if(strs.isEmpty()) return ""
if(strs.size == 1) return strs[0]
strs.forEach {
if(it == "") return ""
if(it.length < menorPalavra.length){
menorPalavra = it
}
}
val strsFiltrado = strs.filter { it != menorPalavra }
strsFiltrado.forEach{
var i = 0
while (i < it.length && contador > 0)
if (index < menorPalavra.length && it[index] == menorPalavra[index]){
index++
i++
} else if (index < contador) {
contador = index
i = it.length
index = 0
} else {
i = it.length
index = 0
}
}
resposta = menorPalavra.substring(0, contador)
return resposta
} | 0 | Kotlin | 0 | 0 | 5e9ae01b7ae68d2681f496bafa21bade33974535 | 1,305 | LeetCodeKotlin | MIT License |
2022/main/day_04/Main.kt | Bluesy1 | 572,214,020 | false | {"Rust": 280861, "Kotlin": 94178, "Shell": 996} | package day_04_2022
import java.io.File
fun part1(input: List<String>) {
val res = input.stream().mapToInt {
val range1str = it.split(',')[0]
val range2str = it.split(',')[1]
val range1 = (range1str.split('-')[0].toInt()..range1str.split('-')[1].toInt()).toSet()
val range2 = (range2str.split('-')[0].toInt()..range2str.split('-')[1].toInt()).toSet()
if (range1.containsAll(range2) || range2.containsAll(range1)) 1 else 0
}.sum()
print("The number of contained assignment pairs is $res")
}
fun part2(input: List<String>) {
val res = input.stream().mapToInt {
val range1str = it.split(',')[0]
val range2str = it.split(',')[1]
val range1 = (range1str.split('-')[0].toInt()..range1str.split('-')[1].toInt()).toSet()
val range2 = (range2str.split('-')[0].toInt()..range2str.split('-')[1].toInt()).toSet()
if (range1.intersect(range2).isNotEmpty()) 1 else 0
}.sum()
print("The number of overlapping assignment pairs is $res")
}
fun main(){
val inputFile = File("src/inputs/Day_04.txt")
print("\n----- Part 1 -----\n")
part1(inputFile.readLines())
print("\n----- Part 2 -----\n")
part2(inputFile.readLines())
} | 0 | Rust | 0 | 0 | 537497bdb2fc0c75f7281186abe52985b600cbfb | 1,232 | AdventofCode | MIT License |
src/Day06.kt | sebastian-heeschen | 572,932,813 | false | {"Kotlin": 17461} | fun main() {
fun findMarker(input: List<String>, markerSize: Int) = input
.first()
.let { line ->
val packetMarker = line.windowed(markerSize)
.first { marker -> marker.toCharArray().distinct().count() == markerSize }
line.indexOf(packetMarker) + markerSize
}
fun part1(input: List<String>): Int = findMarker(input, 4)
fun part2(input: List<String>): Int = findMarker(input, 14)
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day06_test")
check(part1(testInput) == 7)
check(part1(listOf("bvwbjplbgvbhsrlpgdmjqwftvncz")) == 5)
check(part1(listOf("nppdvjthqldpwncqszvftbrmjlhg")) == 6)
check(part1(listOf("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg")) == 10)
check(part1(listOf("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw")) == 11)
check(part2(testInput) == 19)
check(part2(listOf("bvwbjplbgvbhsrlpgdmjqwftvncz")) == 23)
check(part2(listOf("nppdvjthqldpwncqszvftbrmjlhg")) == 23)
check(part2(listOf("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg")) == 29)
check(part2(listOf("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw")) == 26)
val input = readInput("Day06")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 4432581c8d9c27852ac217921896d19781f98947 | 1,254 | advent-of-code-2022 | Apache License 2.0 |
src/Day03.kt | oleksandrbalan | 572,863,834 | false | {"Kotlin": 27338} | import kotlin.math.log2
fun main() {
val input = readInput("Day03")
.filterNot { it.isEmpty() }
val part1 = input.sumOf {
val first = it.substring(0, it.length / 2)
val second = it.substring(it.length / 2, it.length)
val result = first.content and second.content
log2(result.toDouble()).toInt() + 1
}
println("Part1: $part1")
val part2 = input.windowed(3, 3).sumOf { (elf1, elf2, elf3) ->
val result = elf1.content and elf2.content and elf3.content
log2(result.toDouble()).toInt() + 1
}
println("Part2: $part2")
}
private val Char.priority: Int
get() = if (isLowerCase()) code - 96 else code - 38
private val String.content: Long
get() {
var result = 0L
forEach {
val bit = 1L shl (it.priority - 1)
result = result or bit
}
return result
}
| 0 | Kotlin | 0 | 2 | 1493b9752ea4e3db8164edc2dc899f73146eeb50 | 897 | advent-of-code-2022 | Apache License 2.0 |
src/main/java/com/marcinmoskala/math/PermutationsExt.kt | MarcinMoskala | 87,302,297 | false | null | @file:JvmName("DiscreteMath")
@file:JvmMultifileClass
package com.marcinmoskala.math
/**
* Permutations are all different ways to arrange elements from some collection (https://en.wikipedia.org/wiki/Permutation).
* For sets it's number is n!, for lists it is n! / (n1! * n2! * ...) where n1, n2... are numbers elements that are the same.
*/
/* This function returns number of all permutations of elements from set. It is equal to n! where n is size of set. */
fun <T> Set<T>.permutationsNumber(): Long = size.factorial()
/* This function returns number of all permutations of elements from list. It is equal to n! / (n1! * n2! * ...) where n1, n2... are numbers elements that are the same. */
fun <T> List<T>.permutationsNumber(): Long = if (size < 1) 1L else size.factorial() / groupBy { it }.map { it.value.size.factorial() }.product()
/* This function returns all permutations of elements from set. These are different ways to arrange elements from this list. */
fun <T> Set<T>.permutations(): Set<List<T>> = toList().permutations()
/* This function returns all permutations of elements from list. These are different ways to arrange elements from this list. */
fun <T> List<T>.permutations(): Set<List<T>> = when {
isEmpty() -> setOf()
size == 1 -> setOf(listOf(get(0)))
else -> {
val element = get(0)
drop(1).permutations()
.flatMap { sublist -> (0..sublist.size).map { i -> sublist.plusAt(i, element) } }
.toSet()
}
}
internal fun <T> List<T>.plusAt(index: Int, element: T): List<T> = when {
index !in 0..size -> throw Error("Cannot put at index $index because size is $size")
index == 0 -> listOf(element) + this
index == size -> this + element
else -> dropLast(size - index) + element + drop(index)
} | 4 | Kotlin | 17 | 178 | 17a7329af042c5de232051027ec1155011d57da8 | 1,801 | KotlinDiscreteMathToolkit | Apache License 2.0 |
src/main/kotlin/net/voldrich/aoc2022/Day03.kt | MavoCz | 434,703,997 | false | {"Kotlin": 119158} | package net.voldrich.aoc2022
import net.voldrich.BaseDay
// https://adventofcode.com/2022/day/3
fun main() {
Day03().run()
}
// Written mostly by copilot
class Day03 : BaseDay() {
override fun task1() : Int {
return input.lines().map { line ->
val (left, right) = splitStringIntoHalf(line)
val leftCharMap = stringToCharacterMap(left)
val rightCharMap = stringToCharacterMap(right)
val commonChars = leftCharMap.keys.intersect(rightCharMap.keys)
commonChars.map{charToPriority(it)}.sum()
}.sum()
}
override fun task2() : Int {
return input.lines().chunked(3).map { group ->
val (left, middle, right) = group
val leftCharMap = stringToCharacterMap(left)
val middleCharMap = stringToCharacterMap(middle)
val rightCharMap = stringToCharacterMap(right)
val intersected = leftCharMap.keys
.intersect(middleCharMap.keys)
.intersect(rightCharMap.keys)
charToPriority(intersected.first())
}.sum()
}
fun charToPriority(char: Char) : Int {
if (char.code < 'a'.code) {
return char.code - 65 + 27
} else {
return char.code - 96
}
}
// proposed by copilot
fun splitStringIntoHalf(string: String): Pair<String, String> {
val half = string.length / 2
return Pair(string.substring(0, half), string.substring(half))
}
// proposed by copilot
fun stringToCharacterMap(string: String): Map<Char, Int> {
return string.groupingBy { it }.eachCount()
}
}
| 0 | Kotlin | 0 | 0 | 0cedad1d393d9040c4cc9b50b120647884ea99d9 | 1,665 | advent-of-code | Apache License 2.0 |
src/ad/kata/aoc2021/day08/DisplayTroubleshooting.kt | andrej-dyck | 433,401,789 | false | {"Kotlin": 161613} | package ad.kata.aoc2021.day08
import ad.kata.aoc2021.PuzzleInput
import ad.kata.aoc2021.extensions.splitTrim
class DisplayTroubleshooting(val entries: List<TroubleshootingEntry>) {
constructor(vararg entries: TroubleshootingEntry) : this(entries.toList())
fun deducedOutputValues() = entries.map { it.deduceOutputValue() }
}
data class TroubleshootingEntry(
val uniqueSignals: List<Signal>,
val outputSignals: List<Signal>
) {
private val deducedOutputDigits by lazy {
SignalDeduction(uniqueSignals).deduceDigits(outputSignals)
}
fun deduceOutputValue() =
if (deducedOutputDigits.any { it == null }) null
else deducedOutputDigits.filterNotNull().toInt()
}
fun troubleShootingFromInput(filename: String) = DisplayTroubleshooting(
PuzzleInput(filename).lines()
.map(String::parseTroubleshootingEntry)
.toList()
)
private fun String.parseTroubleshootingEntry() =
splitTrim('|')
.map { signals -> listOfSignals(signals, delimiter = ' ') }
.let { (sp, ov) -> TroubleshootingEntry(uniqueSignals = sp, outputSignals = ov) }
fun listOfSignals(segments: String, delimiter: Char = ' ') =
segments.split(delimiter).map { Signal(it) }
| 0 | Kotlin | 0 | 0 | 28d374fee4178e5944cb51114c1804d0c55d1052 | 1,229 | advent-of-code-2021 | MIT License |
src/main/kotlin/com/psmay/exp/advent/y2021/Day02.kt | psmay | 434,705,473 | false | {"Kotlin": 242220} | package com.psmay.exp.advent.y2021
object Day02 {
enum class Direction(val keyword: String) {
FORWARD("forward"),
DOWN("down"),
UP("up");
companion object {
private val byKeyword = values().associateBy({ it.keyword }, { it })
fun valueOfKeyword(keyword: String): Direction =
byKeyword.getOrElse(keyword) {
throw IllegalArgumentException("'$keyword' is not the name of a valid direction.")
}
}
}
data class PositionWithAim(val x: Int, val y: Int, val aim: Int)
data class Instruction(val direction: Direction, val magnitude: Int) {
fun apply(origin: Pair<Int, Int>): Pair<Int, Int> {
val (x, y) = origin
val dx = when (direction) {
Direction.FORWARD -> magnitude
else -> 0
}
val dy = when (direction) {
Direction.DOWN -> -magnitude
Direction.UP -> magnitude
else -> 0
}
return (x + dx) to (y + dy)
}
fun apply(origin: PositionWithAim): PositionWithAim {
val dAim = when (direction) {
Direction.DOWN -> magnitude
Direction.UP -> -magnitude
else -> 0
}
val dx = when (direction) {
Direction.FORWARD -> magnitude
else -> 0
}
val dy = when (direction) {
Direction.FORWARD -> -origin.aim * magnitude
else -> 0
}
return PositionWithAim(origin.x + dx, origin.y + dy, origin.aim + dAim)
}
companion object {
private val commandFormat = """^(\w+)\s+(\d+)$""".toRegex()
fun parse(command: String): Instruction {
val (keywordIn, magnitudeIn) = commandFormat.find(command)?.destructured
?: throw IllegalArgumentException("Instruction '$command' is not in a recognized format.")
val direction = Direction.valueOfKeyword(keywordIn)
val magnitude = magnitudeIn.toIntOrNull()
?: throw IllegalArgumentException("$magnitudeIn could not be parsed as an integer.")
return Instruction(direction, magnitude)
}
}
}
fun Iterable<Instruction>.applyAll(position: Pair<Int, Int> = Pair(0, 0)) =
this.fold(position) { origin, instruction -> instruction.apply(origin) }
fun Iterable<Instruction>.applyAll(position: PositionWithAim) =
this.fold(position) { origin, instruction -> instruction.apply(origin) }
fun part1(instructions: Iterable<Instruction>): Int {
val (x, y) = instructions.applyAll()
val depth = -y
return x * depth
}
fun part2(instructions: Iterable<Instruction>): Int {
val (x, y, _) = instructions.applyAll(PositionWithAim(0, 0, 0))
val depth = -y
return x * depth
}
} | 0 | Kotlin | 0 | 0 | c7ca54612ec117d42ba6cf733c4c8fe60689d3a8 | 3,031 | advent-2021-kotlin | Creative Commons Zero v1.0 Universal |
algorithms/src/main/kotlin/io/nullables/api/playground/algorithms/PrimMST.kt | AlexRogalskiy | 331,076,596 | false | null | /*
* Copyright (C) 2021. <NAME>. All Rights Reserved.
*
* 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 io.nullables.api.playground.algorithms
class PrimMST(G: UWGraph) : MST {
var weight: Double = 0.0
var edges: Queue<UWGraph.Edge> = Queue()
/**
* distTo[v] = distance of shortest s->v path
*/
private val distTo: DoubleArray = DoubleArray(G.V) { Double.POSITIVE_INFINITY }
/**
* edgeTo[v] = last edge on shortest s->v path
*/
private val edgeTo: Array<UWGraph.Edge?> = arrayOfNulls(G.V)
/**
* priority queue of vertices
*/
private val pq: IndexedPriorityQueue<Double> = IndexedPriorityQueue(G.V)
private val visited = Array(G.V) { false }
init {
for (s in G.vertices()) {
if (!visited[s]) {
distTo[s] = 0.0
pq.insert(s, 0.0)
while (!pq.isEmpty()) {
val v = pq.poll().first
visited[v] = true
for (e in G.adjacentEdges(v)) {
scan(e, v)
}
}
}
}
for (v in edgeTo.indices) {
val e = edgeTo[v]
if (e != null) {
edges.add(e)
weight += e.weight
}
}
}
private fun scan(e: UWGraph.Edge, v: Int) {
val w = e.other(v)
if (!visited[w]) { // v-w is obsolete edge
if (e.weight < distTo[w]) {
distTo[w] = e.weight
edgeTo[w] = e
if (pq.contains(w)) {
pq.decreaseKey(w, distTo[w])
} else {
pq.insert(w, distTo[w])
}
}
}
}
override fun edges(): Iterable<UWGraph.Edge> {
return edges
}
override fun weight(): Double {
return weight
}
}
| 13 | Kotlin | 2 | 2 | d7173ec1d9ef227308d926e71335b530c43c92a8 | 2,437 | gradle-kotlin-sample | Apache License 2.0 |
challenges/hacker-rank/kotlin/src/main/kotlin/com/raphaelnegrisoli/hackerrank/hashmaps/CountTriplets.kt | rbatista | 36,197,840 | false | {"Scala": 34929, "Kotlin": 23388} | /**
* https://www.hackerrank.com/challenges/count-triplets-1/
*/
package com.raphaelnegrisoli.hackerrank.hashmaps
import java.math.BigInteger
fun countTriplets(arr: List<Long>, ratio: Long): BigInteger {
val singlets = mutableMapOf<Long, BigInteger>()
val doublets = mutableMapOf<Pair<Long, Long>, BigInteger>()
var triplets = BigInteger.ZERO
for (i in arr) {
if (i % ratio == 0L) {
val previous = i / ratio
val previousDoublet = (previous / ratio) to previous
if ((doublets[previousDoublet] ?: BigInteger.ZERO) > BigInteger.ZERO) {
triplets += doublets[previousDoublet]!!
}
val previousValue = singlets[previous] ?: BigInteger.ZERO
if (previousValue > BigInteger.ZERO) {
val doublet = previous to i
doublets[doublet] = (doublets[doublet] ?: BigInteger.ZERO) + previousValue
}
}
singlets[i] = (singlets[i] ?: BigInteger.ZERO) + BigInteger.ONE
}
return triplets
}
fun main(args: Array<String>) {
val (_, ratio) = readLine().orEmpty().trim()
.split(" ")
.map { it.toLong() }
val arr = readLine().orEmpty().trim()
.split(" ")
.map { it.toLong() }
val result = countTriplets(arr, ratio)
println(result)
}
| 2 | Scala | 0 | 0 | f1267e5d9da0bd5f6538b9c88aca652d9eb2b96c | 1,347 | algorithms | MIT License |
src/com/ncorti/aoc2022/Day03.kt | cortinico | 571,724,497 | false | {"Kotlin": 5773} | package com.ncorti.aoc2022
fun Char.priority(): Int = when {
this.isLowerCase() -> this - 'a' + 1
else -> this - 'A' + 27
}
fun String.splitHalf(): List<String> =
listOf(this.substring(0, this.length / 2), this.substring(this.length / 2))
fun List<String>.findCommonChar(): Char {
var commonChars = this.first().toSet()
this.forEach {
commonChars = commonChars.intersect(it.toSet())
}
return commonChars.first()
}
fun main() {
fun part1() = getInputAsText("03") { split("\n") }
.map(String::splitHalf)
.map(List<String>::findCommonChar)
.sumOf(Char::priority)
fun part2() = getInputAsText("03") { split("\n") }
.windowed(3, 3)
.map(List<String>::findCommonChar)
.sumOf(Char::priority)
println(part1())
println(part2())
}
| 4 | Kotlin | 0 | 1 | cd9ad108a1ed1ea08f9313c4cad5e52a200a5951 | 777 | adventofcode-2022 | MIT License |
src/Day06.kt | JohannesPtaszyk | 573,129,811 | false | {"Kotlin": 20483} | fun main() {
fun List<String>.findMarkerWithLength(markerLength: Int) = map { line ->
var marker = ""
for (i in 0..line.length) {
val markerCandidate = line.substring(i, i + markerLength)
val chars = markerCandidate.toList().distinct()
val hasDuplicates = chars.size < markerLength
if(!hasDuplicates) {
marker = markerCandidate
break
}
}
line.indexOf(marker) + markerLength
}.first()
fun part1(input: List<String>): Int = input.findMarkerWithLength(4)
fun part2(input: List<String>): Int = input.findMarkerWithLength(14)
val testInput = readInput("Day06_test")
val input = readInput("Day06")
println("Part1 test: ${part1(testInput)}")
check(part1(testInput) == 7)
println("Part 1: ${part1(input)}")
println("Part2 test: ${part2(testInput)}")
check(part2(testInput) == 19)
println("Part 2: ${part2(input)}")
}
| 0 | Kotlin | 0 | 1 | 6f6209cacaf93230bfb55df5d91cf92305e8cd26 | 987 | advent-of-code-2022 | Apache License 2.0 |
src/exercises/Day02.kt | Njko | 572,917,534 | false | {"Kotlin": 53729} | // ktlint-disable filename
package exercises
import readInput
fun main() {
fun part1(input: List<String>): Int {
var playerWin = 0
input.forEach { line ->
when (line) {
"B X" -> playerWin += 1 // loss with rock
"C Y" -> playerWin += 2 // loss with paper
"A Z" -> playerWin += 3 // loss with scissors
"C X" -> playerWin += (1 + 6) // win with rock
"A Y" -> playerWin += (2 + 6) // win with paper
"B Z" -> playerWin += (3 + 6) // win with scissors
"A X" -> playerWin += (1 + 3) // draw with rock
"B Y" -> playerWin += (2 + 3) // draw with paper
"C Z" -> playerWin += (3 + 3) // draw with scissors
else -> { /*nothing */
}
}
}
return playerWin
}
fun part2(input: List<String>): Int {
var playerWin = 0
input.forEach { line ->
when (line) {
"B X" -> playerWin += 1 // paper + loose = rock
"C Y" -> playerWin += (3 + 3) // scissors + draw = scissors
"A Z" -> playerWin += (2 + 6) // rock + win = paper
"C X" -> playerWin += 2 // scissors + loose = paper
"A Y" -> playerWin += (1 + 3) // rock + draw = rock
"B Z" -> playerWin += (3 + 6) // paper + win = scissors
"A X" -> playerWin += 3 // rock + loose = scissors
"B Y" -> playerWin += (2 + 3) // paper + draw = paper
"C Z" -> playerWin += (1 + 6) // scissors + win = rock
else -> { /*nothing */
}
}
}
return playerWin
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
println("Test results:")
println(part1(testInput))
check(part1(testInput) == 15)
println(part2(testInput))
check(part2(testInput) == 12)
val input = readInput("Day02")
println("Final results:")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 2 | 68d0c8d0bcfb81c183786dfd7e02e6745024e396 | 2,145 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/nl/tiemenschut/aoc/y2023/day14.kt | tschut | 723,391,380 | false | {"Kotlin": 61206} | package nl.tiemenschut.aoc.y2023
import nl.tiemenschut.aoc.lib.dsl.aoc
import nl.tiemenschut.aoc.lib.dsl.day
import nl.tiemenschut.aoc.lib.util.grid.CharGridParser
import nl.tiemenschut.aoc.lib.util.grid.Grid
import nl.tiemenschut.aoc.lib.util.points.by
fun main() {
aoc(CharGridParser) {
puzzle { 2023 day 14 }
fun Grid<Char>.setCol(x: Int, value: String) {
(0..<height()).forEach { y -> this[x by y] = value[y] }
}
fun Grid<Char>.setRow(y: Int, value: String) {
(0..<width()).forEach { x -> this[x by y] = value[x] }
}
val cache = mutableMapOf<String, String>()
fun String.tilt(): String {
cache[this]?.let { return it }
var targetPos = -1
val result = this.toMutableList()
indices.forEach { i ->
when (result[i]) {
'.' -> if (targetPos == -1) targetPos = i
'O' -> {
if (targetPos != -1) {
result[targetPos] = 'O'
result[i] = '.'
targetPos++
}
}
else -> targetPos = -1
}
}
return result.joinToString("").also { cache[this] = it }
}
fun Grid<Char>.totalLoad(): Int = (0..<height()).sumOf { y ->
(height() - y) * getRow(y).count { it == 'O' }
}
fun Grid<Char>.tiltNorth(): Grid<Char> = this.also { repeat(width()) { x -> setCol(x, getCol(x).tilt()) } }
fun Grid<Char>.tiltWest(): Grid<Char> = this.also { repeat(height()) { y -> setRow(y, getRow(y).tilt()) } }
fun Grid<Char>.tiltSouth(): Grid<Char> =
this.also { repeat(width()) { x -> setCol(x, getCol(x).reversed().tilt().reversed()) } }
fun Grid<Char>.tiltEast(): Grid<Char> =
this.also { repeat(height()) { y -> setRow(y, getRow(y).reversed().tilt().reversed()) } }
fun Grid<Char>.spin(): Grid<Char> {
return this.tiltNorth().tiltWest().tiltSouth().tiltEast()
}
part1 { input ->
input.tiltNorth().totalLoad()
}
fun Grid<Char>.spin(times: Int): Grid<Char> {
val loopDetection = mutableListOf<Int>()
var x = 0
while (x < times) {
val hashcode = (0..<height()).joinToString { y -> getRow(y) }.hashCode()
if (loopDetection.contains(hashcode)) {
val loopSize = x - loopDetection.indexOf(hashcode)
x += loopSize * ((times - x) / loopSize)
} else {
loopDetection.add(hashcode)
}
this.spin()
x++
}
return this
}
part2 { input ->
input.spin(1_000_000_000).totalLoad()
}
}
}
| 0 | Kotlin | 0 | 1 | a1ade43c29c7bbdbbf21ba7ddf163e9c4c9191b3 | 2,950 | aoc-2023 | The Unlicense |
src/main/kotlin/days/day02.kt | josergdev | 573,178,933 | false | {"Kotlin": 20792} | package days
import java.nio.file.Files
import java.nio.file.Paths
import kotlin.streams.asSequence
sealed interface Option
object Rock : Option
object Paper : Option
object Scissors : Option
fun String.parseOption() = when (this) {
"A", "X" -> Rock
"B", "Y" -> Paper
"C", "Z" -> Scissors
else -> throw IllegalArgumentException(this)
}
fun Pair<Option, Option>.matchPoints() = when(this) {
Pair(Scissors, Rock), Pair(Rock, Paper), Pair(Paper, Scissors) -> 6
else -> when (this.first) {
this.second -> 3
else -> 0
}
}
fun Option.selectionPoints() = when(this) {
Rock -> 1
Paper -> 2
Scissors -> 3
}
fun day2Part1() = Files.lines(Paths.get("input/02.txt")).asSequence()
.map { it.split(" ") }
.map { it[0].parseOption() to it[1].parseOption() }
.map { it.matchPoints() + it.second.selectionPoints() }
.sum()
sealed interface Result
object Win: Result
object Draw: Result
object Lose: Result
fun String.parseResult() = when (this) {
"X" -> Lose
"Y" -> Draw
"Z" -> Win
else -> throw IllegalArgumentException(this)
}
fun neededFor(result: Result, option: Option) = when (result) {
Lose -> when (option) {
Rock -> Scissors
Paper -> Rock
Scissors -> Paper
}
Draw -> option
Win -> when (option) {
Rock -> Paper
Paper -> Scissors
Scissors -> Rock
}
}
fun day2part2() = Files.lines(Paths.get("input/02.txt")).asSequence()
.map { it.split(" ") }
.map { it[0].parseOption() to it[1].parseResult() }
.map { (option, result) -> option to neededFor(result, option) }
.map { it.matchPoints() + it.second.selectionPoints() }
.sum() | 0 | Kotlin | 0 | 0 | ea17b3f2a308618883caa7406295d80be2406260 | 1,700 | aoc-2022 | MIT License |
endlessRunnersGame/src/main/kotlin/cz/woitee/endlessRunners/game/algorithms/dfs/SearchStatsSummer.kt | woitee | 219,872,458 | false | null | package cz.woitee.endlessRunners.game.algorithms.dfs
import java.util.*
import kotlin.repeat
/**
* A methods that averages statistics of searches to batches and prints them once in a while.
*
* @param sumEvery Number of iterations after we perform the averaging and print.
* @param callback What should happen after this number of iterations - default is printing to standard output.
*/
class SearchStatsSummer(val sumEvery: Int, val callback: (SearchStatsAverage) -> Unit = { average -> println(average) }) {
data class SearchStatsAverage(
var count: Int = 0,
var searchedStates: Double = 0.0,
var backtrackedStates: Double = 0.0,
var reachedDepth: Double = 0.0,
var success: Double = 0.0,
var cachedStates: Double = 0.0,
var timeTaken: Double = 0.0
) {
override fun toString(): String {
fun roundDouble(x: Double, precision: Int = 2): Double {
var dec = 1
repeat(precision, { dec *= 10 })
return Math.round(x * dec).toDouble() / dec
}
return "SearchStatsAverage(" +
"count=$count, " +
"searched=${roundDouble(searchedStates)}, " +
"backtracked=${roundDouble(backtrackedStates)}, " +
"reachedDepth=${roundDouble(reachedDepth)}, " +
"success=${roundDouble(success)}, " +
"cachedStates=${roundDouble(cachedStates)}, " +
"timeTaken=${roundDouble(timeTaken * 1000)}ms" +
")"
}
}
val myStatsList = ArrayList<SearchStats>()
fun noteStats(stats: SearchStats) {
myStatsList.add(stats)
if (myStatsList.count() >= sumEvery) {
callback(average(myStatsList))
myStatsList.clear()
}
}
fun average(statsList: List<SearchStats>): SearchStatsAverage {
val result = SearchStatsAverage()
if (statsList.isEmpty())
return result
for (stats in statsList) {
result.searchedStates += stats.searchedStates
result.backtrackedStates += stats.backtrackedStates
result.reachedDepth += stats.reachedDepth
result.success += if (stats.success) 1 else 0
result.cachedStates += stats.cachedStates
result.timeTaken += stats.timeTaken
}
result.searchedStates /= statsList.count()
result.backtrackedStates /= statsList.count()
result.reachedDepth /= statsList.count()
result.cachedStates /= statsList.count()
result.success /= statsList.count()
result.timeTaken /= statsList.count()
result.count = statsList.count()
return result
}
}
| 0 | Kotlin | 0 | 1 | 5c980f44397f0b4f122e7b2cb51b82cf1c0419df | 2,756 | endlessRunners | Apache License 2.0 |
src/Day05.kt | amelentev | 573,120,350 | false | {"Kotlin": 87839} | fun main() {
val input = readInput("Day05")
run {
var seeds = input[0].substringAfter("seeds: ").split(' ').map { it.toLong() }.toMutableSet()
var next = mutableSetOf<Long>()
var i = 3
while (i < input.size) {
if (input[i].isBlank()) {
seeds = (seeds + next).toMutableSet()
next = mutableSetOf()
i+=2
continue
}
val (d,s,l) = input[i].split(' ').map { it.toLong() }
val affected = seeds.filter { s <= it && it < s + l }.toSet()
seeds.removeAll(affected)
next.addAll(affected.map { it - s + d })
i++
}
println((seeds + next).min())
}
run {
var seeds = input[0].substringAfter("seeds: ").split(' ').map { it.toLong() }.let {
(it.indices step 2).map { i ->
it[i] to (it[i]+it[i+1])
}
}.toMutableSet()
var next = mutableSetOf<Pair<Long, Long>>()
var i = 3
while (i < input.size) {
if (input[i].isBlank()) {
seeds = (seeds + next).toMutableSet()
next = mutableSetOf()
i+=2
continue
}
val (d,s,l) = input[i].split(' ').map { it.toLong() }
val queue = ArrayDeque(seeds)
while (queue.isNotEmpty()) {
val r = queue.removeFirst()
val n = maxOf(s, r.first) to minOf(s+l, r.second)
if (n.first < n.second) {
seeds.remove(r)
next.add(n.first - s + d to n.second - s + d)
val n1 = s+l to r.second
if (n1.first < n1.second) {
seeds.add(n1)
queue.add(n1)
}
val n2 = r.first to s
if (n2.first < n2.second) {
seeds.add(n2)
queue.add(n2)
}
}
}
i++
}
println((seeds + next).minOf { it.first })
}
} | 0 | Kotlin | 0 | 0 | a137d895472379f0f8cdea136f62c106e28747d5 | 2,157 | advent-of-code-kotlin | Apache License 2.0 |
src/Day11.kt | MartinsCode | 572,817,581 | false | {"Kotlin": 77324} |
fun main() {
class Monkey(details: List<String>) {
val items = ArrayDeque<Long>()
var operation: String = ""
var test: Int = 0 // seems like all are "divisible by", so we only save the int
var trueReceiver: Int = 0
var falseReceiver: Int = 0
var myNumber: Int = 0
var processedItems = 0L
var uneasy: Boolean = false
var commonDiv = 0L
init {
details.forEach {
when {
it.matches("Monkey (.*):".toRegex()) -> {
var number = it.split(" ")[1]
number = number.replace(":", "")
myNumber = number.toInt()
}
it.matches(" Starting items: (.*)".toRegex()) -> {
val numbers = it.split(": ")[1]
numbers.split(", ").map { it.toLong() }.forEach {
items.add(it)
}
}
it.matches(" Operation: (.*)".toRegex()) -> {
var op = it.split(": ")[1]
check(op.matches("new = (.*)".toRegex())) // by now we don't handle other cases!
op = op.split(" = ")[1]
operation = op
}
it.matches(" Test: (.*)".toRegex()) -> {
val t = it.split(": ")[1]
check(t.matches("divisible by (.*)".toRegex())) // no handling of other cases right now
test = t.split(" by ")[1].toInt()
}
it.matches(" If true: (.*)".toRegex()) -> {
val rec = it.split(": ")[1]
check(rec.matches("throw to monkey (.*)".toRegex()))
trueReceiver = rec.split(" monkey ")[1].toInt()
}
it.matches(" If false: (.*)".toRegex()) -> {
val rec = it.split(": ")[1]
check(rec.matches("throw to monkey (.*)".toRegex()))
falseReceiver = rec.split(" monkey ")[1].toInt()
}
}
}
}
fun processAllItems(): List<Pair<Int, Long>> {
val itemList = mutableListOf<Pair<Int, Long>>()
while (items.size > 0) {
val item = items.removeFirst()
itemList.add(process(item))
}
return itemList
}
/**
* Process one item.
*
* @return Pair<Int, Int> with monkey and items to give
*/
fun process(item: Long): Pair<Int, Long> {
var level = when {
operation.matches("old [*] old".toRegex()) -> {
item * item
}
operation.matches("old [*] (.*)".toRegex()) -> {
item * operation.split(" * ")[1].toLong()
}
operation.matches("old [+] (.*)".toRegex()) -> {
item + operation.split(" + ")[1].toLong()
}
else -> {
throw Exception("Operation not supported: $operation")
}
}
if (commonDiv != 0L)
level %= commonDiv
if (!uneasy)
level /= 3L
val recMonkey = when ((level.mod(test.toLong()) == 0L)) {
true -> trueReceiver
false -> falseReceiver
}
processedItems++
return (Pair(recMonkey, level))
}
fun give(item: Long) {
items.add(item)
}
}
fun part1(input: List<String>): Long {
// parse Monkey-Business
val monkeys = mutableListOf<Monkey>()
var firstMonkeyLine = 0
var lastMonkeyLine = 0
fun give(monkey: Int, item: Long) {
monkeys.find { it.myNumber == monkey }!!.give(item)
}
while (lastMonkeyLine <= input.size) {
// create monkeys from monkey-List
if (lastMonkeyLine == input.size) {
monkeys.add(Monkey(input.subList(firstMonkeyLine, lastMonkeyLine)))
} else {
if (input[lastMonkeyLine] == "") {
monkeys.add(Monkey(input.subList(firstMonkeyLine, lastMonkeyLine)))
firstMonkeyLine = lastMonkeyLine + 1
}
}
lastMonkeyLine++
}
// iterate 20 rounds of each monkey
for (i in 1..20) {
// (monkeys 0 to max, each iterates ALSO over the already given in THIS round!)
// keep track of inspections
for (monkey in monkeys) {
val itemList = monkey.processAllItems()
itemList.forEach {
give(it.first, it.second)
}
}
}
// get list of number of monkey-inspections
val inspections = monkeys.map { it.processedItems }.toMutableList()
while (inspections.size > 2) {
inspections.remove(inspections.min())
}
// take two most numbers, multiply, return
return inspections[0] * inspections[1]
}
fun part2(input: List<String>): Long {
// Problem is, that Long is not enough for levels, bit BigInt is was too slow.
// So let's return to Long, and ... well, let's see. probably some arithmetic game.
// parse Monkey-Business
val monkeys = mutableListOf<Monkey>()
var firstMonkeyLine = 0
var lastMonkeyLine = 0
fun give(monkey: Int, item: Long) {
monkeys.find { it.myNumber == monkey }!!.give(item)
}
while (lastMonkeyLine <= input.size) {
// create monkeys from monkey-List
if (lastMonkeyLine == input.size) {
monkeys.add(Monkey(input.subList(firstMonkeyLine, lastMonkeyLine)))
} else {
if (input[lastMonkeyLine] == "") {
monkeys.add(Monkey(input.subList(firstMonkeyLine, lastMonkeyLine)))
firstMonkeyLine = lastMonkeyLine + 1
}
}
lastMonkeyLine++
}
monkeys.forEach{
it.uneasy = true
}
var commonDiv = 1L
monkeys.forEach {
commonDiv *= it.test
}
monkeys.forEach{
it.commonDiv = commonDiv
}
// iterate some rounds of each monkey
for (i in 1..10_000) {
// (monkeys 0 to max, each iterates ALSO over the already given in THIS round!)
// keep track of inspections
for (monkey in monkeys) {
val itemList = monkey.processAllItems()
itemList.forEach {
give(it.first, it.second)
}
}
if (i in arrayOf(1, 20, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000)) {
println("\n== After round $i ==")
monkeys.forEach{
println("Monkey ${it.myNumber} inspected items ${it.processedItems} times.")
}
}
if (i % 10 == 0)
print(".")
}
// get list of number of monkey-inspections
val inspections = monkeys.map { it.processedItems }.toMutableList()
while (inspections.size > 2) {
inspections.remove(inspections.min())
}
// take two most numbers, multiply, return
return inspections[0] * inspections[1]
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day11-TestInput")
check(part1(testInput) == 10605L)
check(part2(testInput) == 2713310158)
val input = readInput("Day11-Input")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 1aedb69d80ae13553b913635fbf1df49c5ad58bd | 8,000 | AoC-2022-12-01 | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.