path
stringlengths
5
169
owner
stringlengths
2
34
repo_id
int64
1.49M
755M
is_fork
bool
2 classes
languages_distribution
stringlengths
16
1.68k
content
stringlengths
446
72k
issues
float64
0
1.84k
main_language
stringclasses
37 values
forks
int64
0
5.77k
stars
int64
0
46.8k
commit_sha
stringlengths
40
40
size
int64
446
72.6k
name
stringlengths
2
64
license
stringclasses
15 values
src/main/kotlin/com/jacobhyphenated/day15/Day15.kt
jacobhyphenated
572,119,677
false
{"Kotlin": 157591}
package com.jacobhyphenated.day15 import com.jacobhyphenated.Day import com.jacobhyphenated.day9.IntCode import java.io.File import java.util.* import kotlin.random.Random // Oxygen System class Day15: Day<List<Long>> { override fun getInput(): List<Long> { return this.javaClass.classLoader.getResource("day15/input.txt")!! .readText() .split(",") .map { it.toLong() } } /** * Move the repair robot to the oxygen system. * The repair robot runs an IntCode program that takes an input * (A direction 1-4) and returns an output (0 - wall, 1 - empty space, 2 - oxygen system) * * We have no knowledge of what is around the repair robot. * What is the shortest number of commands we can use to move the robot to the oxygen system? */ override fun part1(input: List<Long>): Number { val robot = IntCode(input) var currentLocation = Pair(0,0) val grid = mutableMapOf(currentLocation to Location.EMPTY) var lastDirection: Direction? = null // Do a random walk with the robot until we find the system, mapping as we go while(true) { val moveAttempt = chooseNextMove(currentLocation, grid, lastDirection) robot.execute(listOf(moveAttempt.getCode())) val result = getLocationType(robot.output[0].toInt()) robot.output.clear() val position = fromCurrentLocation(currentLocation, moveAttempt) grid[position] = result // stay in our current position if the robot hits a wall if (result != Location.WALL) { currentLocation = position lastDirection = moveAttempt } // Once we find the O2 System, we can stop if (result == Location.SYSTEM) { break } } val target = grid.entries.first { (_,v) -> v == Location.SYSTEM }.key return shortestPath(Pair(0,0), grid).getValue(target) } /** * Once the Oxygen is repaired, it will fill up, starting at the system * and moving one adjacent space in all directions per minute. * How long until the entire area fills with Oxygen? */ override fun part2(input: List<Long>): Number { val robot = IntCode(input) var currentLocation = Pair(0,0) val grid = mutableMapOf(currentLocation to Location.EMPTY) var lastDirection: Direction? = null // In this loop, we just map the entire location while(true) { val moveAttempt = chooseNextMove(currentLocation, grid, lastDirection) robot.execute(listOf(moveAttempt.getCode())) val result = getLocationType(robot.output[0].toInt()) robot.output.clear() val position = fromCurrentLocation(currentLocation, moveAttempt) grid[position] = result if (result != Location.WALL) { currentLocation = position lastDirection = moveAttempt } // Break out of the loop if there are no spaces with adjacent unexplored locations val unexplored = grid.entries.filter { (_,v) -> v == Location.EMPTY || v == Location.SYSTEM } .any { (k, _) -> Direction.values().map{ grid[fromCurrentLocation(k, it)]}.any { it == null }} if (!unexplored) { break } } // Re-use dijkstra's algorithm, this time starting at the System space val target = grid.entries.first { (_,v) -> v == Location.SYSTEM }.key val paths = shortestPath(target, grid) return paths.values.filter { it < Int.MAX_VALUE }.max() } /** * Implementation of Dijkstra's algorithm. The only weight/cost is the distance from the start position * as measured by the path the robot can take through empty adjacent (non-diagonal) spaces * * @param start the start position from which distances will be measured * @param grid a map of (x,y) pairs to the type of space at that location (empty, wall, etc.) * * @return A map of all positions to the cost of getting to that position. * Note: WALL positions may have a cost of MAX_INT */ private fun shortestPath(start: Pair<Int,Int>, grid: Map<Pair<Int,Int>, Location>): Map<Pair<Int,Int>, Int> { val distances: MutableMap<Pair<Int,Int>, Int> = grid.keys.fold(mutableMapOf()){ map, position -> map[position] = Int.MAX_VALUE map } // Use a priority queue implementation - min queue sorted by lowest "cost" val queue = PriorityQueue<PathCost> { a, b -> a.cost - b.cost } queue.add(PathCost(start, 0)) distances[start] = 0 var current: PathCost do { // Traverse from the lowest cost position on our queue. This position is "solved" current = queue.remove() // If we already found a less expensive way to reach this position if (current.cost > (distances[current.position] ?: Int.MAX_VALUE)) { continue } // From the current position, look in each direction for an empty space val adjacent = Direction.values().map { fromCurrentLocation(current.position, it) } .filter { grid[it] == Location.EMPTY || grid[it] == Location.SYSTEM } adjacent.forEach { val cost = distances.getValue(current.position) + 1 // If the cost to this space is less than what was previously known, put this on the queue if (cost < distances.getValue(it)) { distances[it] = cost queue.add(PathCost(it, cost)) } } } while (queue.size > 0) return distances } /** * Helper method to determine where the robot should move to next. * * If there is an unexplored position adjacent to the current location, do that first. * Otherwise, try not to go back the direction we just came from unless there is no other option * * If there are multiple valid moves to make, pick one at random */ private fun chooseNextMove(currentLocation: Pair<Int,Int>, grid:Map<Pair<Int,Int>, Location>, lastDirection: Direction?): Direction { val moves = Direction.values().map { it to grid[fromCurrentLocation(currentLocation, it)] } val (unknown, known) = moves.partition { it.second == null } if (unknown.isNotEmpty()) { return unknown[Random.nextInt(unknown.size)].first } val allowedMoves = known.filter { it.second != Location.WALL }.map { it.first }.toMutableList() if (lastDirection != null && allowedMoves.size > 1) { allowedMoves.remove(lastDirection.inverse()) } return allowedMoves[Random.nextInt(allowedMoves.size)] } private fun getLocationType(locationType: Int): Location { return when(locationType) { 0 -> Location.WALL 1 -> Location.EMPTY 2 -> Location.SYSTEM else -> throw NotImplementedError("Invalid location code $locationType") } } private fun fromCurrentLocation(location: Pair<Int,Int>, direction: Direction): Pair<Int,Int> { val (x,y) = location return when(direction) { Direction.NORTH -> Pair(x, y-1) Direction.SOUTH -> Pair(x, y+1) Direction.WEST -> Pair(x-1, y) Direction.EAST -> Pair(x+1, y) } } } enum class Direction { NORTH, SOUTH, WEST, EAST; fun getCode(): Long { return (this.ordinal + 1).toLong() } fun inverse(): Direction { return when(this) { NORTH -> SOUTH SOUTH -> NORTH EAST -> WEST WEST -> EAST } } } enum class Location { EMPTY, WALL, SYSTEM } data class PathCost(val position: Pair<Int,Int>, val cost: Int)
0
Kotlin
0
0
1a0b9cb6e9a11750c5b3b5a9e6b3d63649bf78e4
8,030
advent2019
The Unlicense
solutions/src/solutions/y19/day 12.kt
Kroppeb
225,582,260
false
null
@file:Suppress("PackageDirectoryMismatch") package solutions.solutions.y19.d12 import helpers.* import kotlinx.coroutines.runBlocking import kotlin.math.* data class Moon(var p:Point3D, var v:Point3D) private fun part1(data: IntLines)= runBlocking { val moons = data.map{(x,y,z) -> Moon(x toP y toP z, 0 toP 0 toP 0) } repeat(1000){ moons.forEach{ moon -> moons.forEach { val (dx,dy,dz) = it.p - moon.p moon.v += dx.sign toP dy.sign toP dz.sign } } moons.forEach{ it.p += it.v } } println( moons.sumBy{ it.p.manDist() * it.v.manDist() } ) } private fun part2(data: IntLines) = runBlocking { val moons = data.map{(x,y,z) -> Moon(x toP y toP z, 0 toP 0 toP 0) } val orig = moons.map{it.copy()} var x = 0L var y = 0L var z = 0L var ite = 0L while(x == 0L || y == 0L || z == 0L){ ite+=1 moons.forEach{ moon -> moons.forEach { val (dx,dy,dz) = it.p - moon.p moon.v += dx.sign toP dy.sign toP dz.sign } } moons.forEach{ it.p += it.v } if(x == 0L && moons.zip(orig).all{(it, o) -> it.p.x == o.p.x && it.v.x == 0}) x = ite if(y == 0L && moons.zip(orig).all{(it, o) -> it.p.y == o.p.y && it.v.y == 0}) y = ite if(z == 0L && moons.zip(orig).all{(it, o) -> it.p.z == o.p.z && it.v.z == 0}) z = ite } val q = x / gcd(x, y) * y println(z / gcd(z, q) * q) } private fun gcd(a:Long, b:Long):Long = if(a == 0L) b else gcd(b % a, a) fun main() { val data: IntLines = getIntLines(2019_12) part1(data) part2(data) }
0
Kotlin
0
1
744b02b4acd5c6799654be998a98c9baeaa25a79
1,502
AdventOfCodeSolutions
MIT License
src/main/kotlin/Day03.kt
arosenf
726,114,493
false
{"Kotlin": 40487}
import kotlin.system.exitProcess fun main(args: Array<String>) { if (args.isEmpty() or (args.size < 2)) { println("Schematic document not specified") exitProcess(1) } val fileName = args.first() println("Reading $fileName") val lines = readLines(fileName) val schematic = lines .map(String::toList) .toList() val result = if (args[1] == "part1") { Day03().readSchematic1(schematic) } else { Day03().readSchematic2(schematic) } println("Result: $result") } class Day03 { fun readSchematic1(schematic: List<List<Char>>): Int { return findValidPartNumbers( schematic, ::isValidPartNumberLocationDesignator ).sumOf { partNumber -> (partNumber.number) } } fun readSchematic2(schematic: List<List<Char>>): Int { val validGears = mutableListOf<Int>() val validNumbers = findValidPartNumbers(schematic, ::isValidGearLocationDesignator) for ((rowIndex, row) in schematic.withIndex()) { for ((colIndex, element) in row.withIndex()) { if (isValidGearLocationDesignator(element)) { val validLocations = mutableSetOf( Position(rowIndex - 1, colIndex - 1), Position(rowIndex - 1, colIndex), Position(rowIndex - 1, colIndex + 1), Position(rowIndex, colIndex - 1), Position(rowIndex, colIndex + 1), Position(rowIndex + 1, colIndex - 1), Position(rowIndex + 1, colIndex), Position(rowIndex + 1, colIndex + 1) ) val candidates = validNumbers.asSequence() .filter { isAtValidLocation(it, validLocations) } .toList() if (candidates.size == 2) { validGears.add(candidates.map { it.number }.reduce { x, y -> x * y }) validNumbers.subtract(candidates) } } } } return validGears.sum() } private fun findValidPartNumbers( schematic: List<List<Char>>, validLocationDesignator: (Char) -> Boolean ): List<PartNumber> { val validNumbers = mutableListOf<PartNumber>() val validLocations = markValidPartNumberLocations(schematic, validLocationDesignator) schematic.forEachIndexed { row, line -> var i = 0 while (i < line.size) { if (line[i].isDigit()) { val partNumber = findNumber(line, i, row) if (isAtValidLocation(partNumber, validLocations)) { validNumbers.add(partNumber) } i = partNumber.endIndex + 1 } else { i += 1 } } } return validNumbers } private fun markValidPartNumberLocations( schematic: List<List<Char>>, validLocationDesignator: (Char) -> Boolean ): Set<Position> { val validLocations = mutableSetOf<Position>() for ((rowIndex, row) in schematic.withIndex()) { for ((colIndex, element) in row.withIndex()) { if (validLocationDesignator.invoke(element)) { validLocations.add(Position(rowIndex - 1, colIndex - 1)) validLocations.add(Position(rowIndex - 1, colIndex)) validLocations.add(Position(rowIndex - 1, colIndex + 1)) validLocations.add(Position(rowIndex, colIndex - 1)) validLocations.add(Position(rowIndex, colIndex + 1)) validLocations.add(Position(rowIndex + 1, colIndex - 1)) validLocations.add(Position(rowIndex + 1, colIndex)) validLocations.add(Position(rowIndex + 1, colIndex + 1)) } } } return validLocations.toSet() } private fun isValidPartNumberLocationDesignator(char: Char): Boolean { return !char.isDigit() && char != '.' } private fun isValidGearLocationDesignator(char: Char): Boolean { return char == '*' } // Expand left and right from given position until no digits -> found a number // No guards here: expects it to point at a digit private fun findNumber(line: List<Char>, pos: Int, row: Int): PartNumber { val number = mutableListOf(line[pos]) // Scan to the right var rightScan = pos + 1 while (rightScan < line.size) { val candidate = line[rightScan] if (candidate.isDigit()) { number.add(candidate) } else { break } rightScan += 1 } // Scan to the left var leftScan = pos - 1 while (leftScan >= 0) { val candidate = line[leftScan] if (candidate.isDigit()) { number.add(0, candidate) } else { break } leftScan -= 1 } return PartNumber( number.joinToString("").toInt(), row, leftScan + 1, rightScan - 1 ) } private fun isAtValidLocation(partNumber: PartNumber, validLocations: Set<Position>): Boolean { return generateSequence(partNumber.startIndex) { it + 1 } .take(partNumber.endIndex + 1 - partNumber.startIndex) .map { i -> Position(partNumber.row, i) } .toList() .intersect(validLocations) .isNotEmpty() } data class PartNumber(val number: Int, val row: Int, val startIndex: Int, val endIndex: Int) data class Position(val rowIndex: Int, val colIndex: Int) }
0
Kotlin
0
0
d9ce83ee89db7081cf7c14bcad09e1348d9059cb
5,960
adventofcode2023
MIT License
engine/taskpool-collector/src/main/kotlin/io/holunda/camunda/taskpool/enricher/ProcessVariablesTaskCommandEnricherFilter.kt
kgeis
244,446,791
true
{"Kotlin": 429712}
package io.holunda.camunda.taskpool.enricher import org.camunda.bpm.engine.variable.VariableMap /** * Groups one or more {@linkplain VariableFilter process variable filters}. Assumes (but does not enforce) that among the given individual filter instances, * at most one is contained for any specific process, and at most one "global" filter (that is applied to all processes) is contained. */ class ProcessVariablesFilter( vararg variableFilters: VariableFilter ) { private var processSpecificFilters: Map<ProcessDefinitionKey, VariableFilter> = variableFilters.filter { it.processDefinitionKey != null }.associateBy { it.processDefinitionKey!! } private var commonFilter: VariableFilter? = variableFilters.find { it.processDefinitionKey == null } fun filterVariables(processDefinitionKey: ProcessDefinitionKey, taskDefinitionKey: TaskDefinitionKey, variables: VariableMap): VariableMap { val variableFilter = processSpecificFilters[processDefinitionKey] ?: commonFilter ?: return variables return variables.filterKeys { variableFilter.filter(taskDefinitionKey, it) } } } /** * This filter allows to either explicitly include (whitelist) or exclude (blacklist) process variables for all user tasks of a certain * process (if a process definition key is given), or for all user tasks of <i>all</i> processes (if no process definition key is given). * If a differentiation between individual user tasks of a process is required, use a {@link TaskVariableFilter} instead. */ data class ProcessVariableFilter( override val processDefinitionKey: ProcessDefinitionKey?, val filterType: FilterType, val processVariables: List<VariableName> = emptyList() ): VariableFilter { constructor(filterType: FilterType, processVariables: List<VariableName>): this(null, filterType, processVariables) override fun filter(taskDefinitionKey: TaskDefinitionKey, variableName: VariableName): Boolean { return (filterType == FilterType.INCLUDE) == processVariables.contains(variableName) } } /** * This filter allows to either explicitly include (whitelist) or exclude (blacklist) process variables for user tasks of a certain process. * If the differentiation between individual user tasks is not required, use a {@link ProcessVariableFilter} instead. */ data class TaskVariableFilter( override val processDefinitionKey: ProcessDefinitionKey, val filterType: FilterType, val taskVariables: Map<TaskDefinitionKey, List<VariableName>> = emptyMap() ): VariableFilter { override fun filter(taskDefinitionKey: TaskDefinitionKey, variableName: VariableName): Boolean { val taskFilter = taskVariables[taskDefinitionKey] ?: return true return (filterType == FilterType.INCLUDE) == taskFilter.contains(variableName) } } /** * To be implemented by classes that filter process variables. Used during enrichment to decide which process variables are added to a task's payload. */ interface VariableFilter { val processDefinitionKey: ProcessDefinitionKey? /** * Returns whether or not the process variable with the given name shall be contained in the payload of the given task. * @param taskDefinitionKey the key of the task to be enriched * @param variableName the name of the process variable */ fun filter(taskDefinitionKey: TaskDefinitionKey, variableName: VariableName): Boolean } typealias ProcessDefinitionKey = String typealias TaskDefinitionKey = String typealias VariableName = String enum class FilterType { INCLUDE, EXCLUDE }
0
null
0
0
6308ef1b3b49c3378c8b9f272c0e7ab28800a384
3,512
camunda-bpm-taskpool
Apache License 2.0
kotlin/src/main/kotlin/adventofcode/day11/Day11_2.kt
thelastnode
160,586,229
false
null
package adventofcode.day11 object Day11_2 { data class Coord(val x: Int, val y: Int, val w: Int) fun powerLevel(coord: Pair<Int, Int>, gridSerial: Int): Int { val (x, y) = coord val rackId = x + 10 val t = (rackId * y + gridSerial) * rackId return (t / 100) % 10 - 5 } fun process(gridSerial: Int): Coord { val grid = mutableMapOf<Pair<Int, Int>, Int>() for (x in 1..300) { for (y in 1..300) { grid[Pair(x, y)] = powerLevel(Pair(x, y), gridSerial) } } val powers: Array<Array<IntArray>> = Array(301) { Array(301) { IntArray(301) } } // base case for (x in 1..300) for (y in 1..300) { powers[x][y][1] = grid[Pair(x, y)]!! } for (w in 2..300) for (x in 1..(300 - w + 1)) for (y in 1..(300 - w + 1)) { var power = powers[x][y][w - 1] for (i in 0 until w) { power += grid[Pair(x + i, y + w - 1)]!! } for (j in 0 until w) { power += grid[Pair(x + w - 1, y + j)]!! } power += grid[Pair(x + w - 1, y + w - 1)]!! powers[x][y][w] = power } var maxVal = Int.MIN_VALUE var maxCoord = Coord(-1, -1, -1) for (w in 2..300) for (x in 1..(300 - w + 1)) for (y in 1..(300 - w + 1)) { if (powers[x][y][w] > maxVal) { maxVal = powers[x][y][w] maxCoord = Coord(x, y, w) } } return maxCoord } } fun main(args: Array<String>) { // println(Day11_2.process(18)) // println(Day11_2.process(42)) println(Day11_2.process(3214)) }
0
Kotlin
0
0
8c9a3e5a9c8b9dd49eedf274075c28d1ebe9f6fa
1,713
adventofcode
MIT License
2023/day04-25/src/main/kotlin/Day08.kt
CakeOrRiot
317,423,901
false
{"Kotlin": 62169, "Python": 56994, "C#": 20675, "Rust": 10417}
import java.io.File import java.math.BigInteger class Day08 { fun solve1() { val input = File("inputs/8.txt").inputStream().bufferedReader().lineSequence().toList() val turns = input[0] val map = emptyMap<String, Pair<String, String>>().toMutableMap() input.drop(2).forEach { line -> val split = line.split(' ', ',', '(', ')', '=').filter { it.isNotBlank() } map[split[0]] = Pair(split[1], split[2]) } var turnIdx = 0 var curLocation = "AAA" var steps = 0 while (true) { curLocation = if (turns[turnIdx] == 'L') map.getValue(curLocation).first else map.getValue(curLocation).second steps++ if (curLocation == "ZZZ") { println(steps) break } turnIdx = (turnIdx + 1) % turns.count() } } fun solve2() { val input = File("inputs/8.txt").inputStream().bufferedReader().lineSequence().toList() val turns = input[0] val map = emptyMap<String, Pair<String, String>>().toMutableMap() input.drop(2).forEach { line -> val split = line.split(' ', ',', '(', ')', '=').filter { it.isNotBlank() } map[split[0]] = Pair(split[1], split[2]) } val startLocations = map.filterKeys { it.endsWith("A") }.keys.toList() val periods = startLocations.map { startLocation -> var curLocation = startLocation var turnIdx = 0 var steps = 0.toBigInteger() var isFirstZ = true while (true) { curLocation = if (turns[turnIdx] == 'L') map.getValue(curLocation).first else map.getValue(curLocation).second if (!isFirstZ) steps++ if (curLocation.endsWith("Z")) { if (isFirstZ) { isFirstZ = false } else { break } } turnIdx = (turnIdx + 1) % turns.count() } steps } val g = periods.reduce { acc, x -> gcd(acc, x) } val lcm = periods.reduce { acc, x -> acc * x / g } println(lcm) } private fun gcd(x: BigInteger, y: BigInteger): BigInteger { if (y == 0.toBigInteger()) return x return gcd(y, x % y) } }
0
Kotlin
0
0
8fda713192b6278b69816cd413de062bb2d0e400
2,452
AdventOfCode
MIT License
AdventOfCode/Challenge2023Day10.kt
MartinWie
702,541,017
false
{"Kotlin": 90565}
import org.junit.Test import java.io.File import kotlin.math.ceil import kotlin.test.assertEquals class Challenge2023Day10 { data class Coord(val row: Int, val col: Int) private fun solve1(map: List<String>): Int { val startCoord = map.withIndex().find { (_, line) -> 'S' in line } ?.let { Coord(it.index, it.value.indexOf('S')) } var prev: Coord? = null var current = startCoord var steps = 0 while (true) { val adjacent = findAdjacentCoords(current!!, map).firstOrNull { it != prev } steps++ if (adjacent == null || adjacent == startCoord) { break } prev = current current = adjacent } return ceil(steps.toDouble() / 2).toInt() } private fun findAdjacentCoords( coord: Coord, map: List<String>, ): List<Coord> { val adj = mutableListOf<Coord>() // Check the coordinate above if (coord.row > 0 && "S|JL".contains(map[coord.row][coord.col])) { if ("|7F".contains(map[coord.row - 1][coord.col])) { adj.add(Coord(coord.row - 1, coord.col)) } } // Check the coordinate below if (coord.row < map.size - 1 && "S|7F".contains(map[coord.row][coord.col])) { if ("|JL".contains(map[coord.row + 1][coord.col])) { adj.add(Coord(coord.row + 1, coord.col)) } } // Check the coordinate to the left if (coord.col > 0 && "S-7J".contains(map[coord.row][coord.col])) { if ("-FL".contains(map[coord.row][coord.col - 1])) { adj.add(Coord(coord.row, coord.col - 1)) } } // Check the coordinate to the right if (coord.col < map[0].length - 1 && "S-LF".contains(map[coord.row][coord.col])) { if ("-J7".contains(map[coord.row][coord.col + 1])) { adj.add(Coord(coord.row, coord.col + 1)) } } return adj } @Test fun test() { val lines = File("./AdventOfCode/Data/Day10-1-Test-Data.txt").bufferedReader().readLines() val exampleSolution1 = solve1(lines) println("Example solution 1: $exampleSolution1") assertEquals(4, exampleSolution1) val lines2 = File("./AdventOfCode/Data/Day10-1-Test-Data2.txt").bufferedReader().readLines() val exampleSolution2 = solve1(lines2) println("Example solution 1: $exampleSolution2") assertEquals(4, exampleSolution2) val realLines = File("./AdventOfCode/Data/Day10-1-Data.txt").bufferedReader().readLines() val solution1 = solve1(realLines) println("Solution 1: $solution1") assertEquals(6701, solution1) } }
0
Kotlin
0
0
47cdda484fabd0add83848e6000c16d52ab68cb0
2,824
KotlinCodeJourney
MIT License
klogic-core/src/main/kotlin/org/klogic/core/State.kt
UnitTestBot
594,002,694
false
{"Kotlin": 146776}
package org.klogic.core import kotlinx.collections.immutable.PersistentSet import kotlinx.collections.immutable.persistentHashSetOf import kotlinx.collections.immutable.toPersistentHashSet import org.klogic.unify.toUnificationState typealias InequalityConstraints = PersistentSet<InequalityConstraint> /** * Represents a current immutable state of current [run] expression with [substitution] for [Var]s and * passed satisfiable [Constraint]s. */ data class State( val substitution: Substitution, val constraints: PersistentSet<Constraint<*>> = persistentHashSetOf(), ) { constructor( map: Map<UnboundedValue<*>, Term<*>>, constraints: PersistentSet<Constraint<*>>, ) : this(Substitution(map), constraints) private val inequalityConstraints: InequalityConstraints = constraints.filterIsInstance<InequalityConstraint>().toPersistentHashSet() /** * Returns a new state with [substitution] extended with passed not already presented association * of [variable] to the [term] of the same type. */ private fun <T : Term<T>> extend(variable: Var<T>, term: Term<T>): State { require(variable !in substitution) { "Variable $variable already exists in substitution $substitution" } return State(substitution + (variable to term), inequalityConstraints) } /** * Tries to unify [left] and [right] terms with the current [substitution]. * If the unification succeeds, tries to [verify] current [constraints] with calculated unification substitution, * and returns null otherwise. * If constraints verification succeeds, returns new [State] with unification substitution and verified simplified * constraints, and returns null otherwise. */ fun <T : Term<T>> unifyWithConstraintsVerification(left: Term<T>, right: Term<T>): State? { val unificationState = toUnificationState() val successfulUnificationState = left.unify(right, unificationState) ?: return null if (successfulUnificationState.substitutionDifference.isEmpty()) { // Empty difference allows us to not verify constraints as they should be already verified. return this } val unificationSubstitution = successfulUnificationState.substitution val verifiedConstraints = verify(unificationSubstitution, constraints) ?: return null return copy(substitution = unificationSubstitution, constraints = verifiedConstraints.toPersistentHashSet()) } operator fun <T : Term<T>> plus(pair: Pair<Var<T>, Term<T>>): State = extend(pair.first, pair.second) companion object { private val EMPTY_STATE: State = State(Substitution.empty) val empty: State = EMPTY_STATE } } /** * Verifies [constraints] with passed [substitution] by invoking [Constraint.verify] - if any constraint is violated, returns null. * Otherwise, returns a [Collection] of new constraints simplified according to theirs [Constraint.verify]. */ fun <T : Constraint<T>> verify(substitution: Substitution, constraints: Collection<T>): Collection<T>? { val simplifiedConstraints = mutableSetOf<T>() for (constraint in constraints) { when (val constraintVerificationResult = constraint.verify(substitution)) { is ViolatedConstraintResult -> return null is SatisfiableConstraintResult<T> -> simplifiedConstraints += constraintVerificationResult.simplifiedConstraint is RedundantConstraintResult -> { // Skip this constraint } } } return simplifiedConstraints }
2
Kotlin
1
1
c086377208a1482231769779ea702cb823869590
3,634
klogic
MIT License
Word_Ladder.kt
xiekch
166,329,519
false
{"C++": 165148, "Java": 103273, "Kotlin": 97031, "Go": 40017, "Python": 22302, "TypeScript": 17514, "Swift": 6748, "Rust": 6579, "JavaScript": 4244, "Makefile": 349}
// https://leetcode.com/problems/word-ladder/solution/ import java.util.* import kotlin.collections.ArrayList import kotlin.collections.HashMap import kotlin.collections.set class Solution { fun ladderLength(beginWord: String, endWord: String, wordList: List<String>): Int { val levelMap = HashMap<String, Int>() val allComboDict = HashMap<String, MutableList<String>>() val wordLen = beginWord.length for (word in wordList) { levelMap[word] = 0 for (i in 0 until wordLen) { val newWord = word.substring(0, i) + '*' + word.substring(i + 1, wordLen) val transformations = allComboDict.getOrDefault(newWord, ArrayList()) transformations.add(word) allComboDict[newWord] = transformations } } levelMap[beginWord] = 1 val qu = LinkedList<String>() qu.add(beginWord) while (!qu.isEmpty()) { val word = qu.remove() for (i in 0 until wordLen) { val newWord = word.substring(0, i) + '*' + word.substring(i + 1, wordLen) for (adjacentWord in allComboDict.getOrDefault(newWord, ArrayList())) { if (levelMap[adjacentWord] == 0) { levelMap[adjacentWord] = (levelMap[word] ?: 0) + 1 if (adjacentWord == endWord) return levelMap[adjacentWord]!! qu.add(adjacentWord) } } } } return 0 } } fun main() { val solution = Solution() println(solution.ladderLength("hit", "cog", listOf("hot", "dot", "dog", "lot", "log", "cog"))) }
0
C++
0
0
eb5b6814e8ba0847f0b36aec9ab63bcf1bbbc134
1,711
leetcode
MIT License
2021/src/day20/day20.kt
scrubskip
160,313,272
false
{"Kotlin": 198319, "Python": 114888, "Dart": 86314}
package day20 import java.io.File fun main() { val file = File("src/day20", "day20input.txt").readLines() val algorithm = file[0] val image = Image.parse(file.drop(2)) println(algorithm) println(image.getBounds()) println(image) val enhance = image.enhance(algorithm) //println(enhance) val enhance2 = enhance.enhance(algorithm) //println(enhance2) println(enhance2.getOnPixels()) var imageEnhanced = image (1..50).forEach { _ -> imageEnhanced = imageEnhanced.enhance(algorithm) } println(imageEnhanced.getOnPixels()) } typealias Point = Pair<Int, Int> class Image { private val pixels: MutableMap<Point, Boolean> = mutableMapOf() private var lowestX: Int = 0 private var lowestY: Int = 0 private var greatestX: Int = 0 private var greatestY: Int = 0 var voidPixel = false private val MARGIN = 3 fun getPixel(coordinate: Point): Boolean { if (coordinate.first < lowestX || coordinate.first > greatestX || coordinate.second < lowestY || coordinate.second > greatestY) { return voidPixel } return pixels.getOrDefault(coordinate, false) } fun setPixel(coordinate: Point, value: Boolean) { pixels[coordinate] = value if (value) { if (coordinate.first < lowestX) lowestX = coordinate.first if (coordinate.first > greatestX) greatestX = coordinate.first if (coordinate.second < lowestY) lowestY = coordinate.second if (coordinate.second > greatestY) greatestY = coordinate.second } } fun enhance(algorithm: String): Image { val newImage = Image() if (algorithm[0] == '#') newImage.voidPixel = !voidPixel for (x in lowestX - MARGIN..greatestX + MARGIN) { for (y in lowestY - MARGIN..greatestY + MARGIN) { // for each pixel in this image, get a window val coordinate = Point(x, y) val pixel = algorithm[getLookupIndex(coordinate)] == '#' newImage.setPixel(coordinate, pixel) } } return newImage } fun getBounds(): Pair<Point, Point> { return Pair(Point(lowestX, lowestY), Point(greatestX, greatestY)) } fun getLookupIndex(coordinate: Point): Int { return buildList<Char> { for (y in coordinate.second - 1..coordinate.second + 1) { for (x in coordinate.first - 1..coordinate.first + 1) { add(if (getPixel(Point(x, y))) '1' else '0') } } }.joinToString(separator = "").padStart(12, '0').toInt(2) } fun getOnPixels(): Int { return pixels.count { it.value } } override fun toString(): String { return (lowestY - MARGIN..greatestY + MARGIN).joinToString(separator = "\n") { y -> (lowestX - MARGIN..greatestX + MARGIN).map { x -> if (getPixel(Point(x, y)) || voidPixel) '#' else '.' }.joinToString("") } } companion object { fun parse(input: Iterable<String>): Image { val image = Image() input.withIndex().forEach { row -> row.value.withIndex().forEach { pixel -> if (pixel.value == '#') { image.setPixel(Point(pixel.index, row.index), true) } } } return image } } }
0
Kotlin
0
0
a5b7f69b43ad02b9356d19c15ce478866e6c38a1
3,496
adventofcode
Apache License 2.0
src/Day03.kt
acrab
573,191,416
false
{"Kotlin": 52968}
import com.google.common.truth.Truth.assertThat fun scoreForItem(char: Char): Int = if (char in 'a'..'z') { (char.code - 97) + 1 } else { (char.code - 65) + 27 } fun main() { fun part1(input: List<String>): Int = input //Split into two parts .map { it.chunked(it.length / 2) } //Find unique element .map { it[0].first { char -> char in it[1] } } //Score .sumOf { scoreForItem(it) } fun part2(input: List<String>): Int = input .chunked(3) .sumOf { group -> val (first, second, third) = group println("Testing $first, $second, $third") scoreForItem(first.filter { it in second }.filter { it in third }[0]) } val testInput = readInput("Day03_test") assertThat(part1(testInput)).isEqualTo(157) val input = readInput("Day03") println("-- part 1 --") println(part1(input)) assertThat(part2(testInput)).isEqualTo(70) println("-- part 2 --") println(part2(input)) }
0
Kotlin
0
0
0be1409ceea72963f596e702327c5a875aca305c
1,038
aoc-2022
Apache License 2.0
complex/src/main/kotlin/net/fwitz/math/binary/complex/functions/Binomial.kt
txshtkckr
410,419,365
false
{"Kotlin": 558762}
package net.fwitz.math.binary.complex.functions import net.fwitz.math.binary.complex.Complex import net.fwitz.math.binary.complex.functions.Factorial.factorial object Binomial { const val BINOMIAL_MAX_N = 33 private val BINOMIAL: List<IntArray> = run { val table = ArrayList<IntArray>(BINOMIAL_MAX_N + 1) var prevRow = intArrayOf(1) table.add(prevRow) for (n in 1..BINOMIAL_MAX_N) { val row = IntArray(n + 1) row[n] = 1 row[0] = row[n] row[n - 1] = n row[1] = row[n - 1] val mid = n shr 1 for (k in 2..mid) { row[n - k] = prevRow[k - 1] + prevRow[k] row[k] = row[n - k] } prevRow = row table.add(row) } table } fun binom(n: Int, k: Int): Int { require(!(n < 0 || n > BINOMIAL_MAX_N)) { "binom(n=$n, k=$k): n must be in the range [0, $BINOMIAL_MAX_N] (larger values risk a sign overflow)" } require(!(k < 0 || k > n)) { "binom(n=$n, k=$k): k must be in the range [0, n]" } return BINOMIAL[n][k] } fun binomRow(n: Int): IntArray { require(!(n < 0 || n > BINOMIAL_MAX_N)) { "binomRow(n=$n): n must be in the range [0, $BINOMIAL_MAX_N] (larger values risk a sign overflow)" } return BINOMIAL[n] } fun binom(n: Double, k: Double) = factorial(n) / (factorial(k) * factorial(n - k)) fun binom(n: Complex, k: Complex) = factorial(n) / (factorial(k) * factorial(n - k)) @JvmStatic fun main(args: Array<String>) { for (n in 0..BINOMIAL_MAX_N) { val row = binomRow(n) println("row[%2d]: %s".format(n, row.contentToString())) } } }
0
Kotlin
1
0
c6ee97ab98115e044a46490ef3a26c51752ae6d6
1,797
fractal
Apache License 2.0
codeforces/round901/b_slow.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package codeforces.round901 private fun solve() { fun encode(a: Int, b: Int) = (a.toLong() shl 32) or b.toLong() val (a, b, c, d, m) = readIntArray() val source = encode(a, b) val dest = encode(c, d) val queue = mutableListOf<Long>() val dist = mutableMapOf<Long, Int>() queue.add(source) dist[source] = 0 var low = 0 while (low < queue.size && dest !in dist) { val v = queue[low] val di = dist[v]!! + 1 low++ fun move(xx: Int, yy: Int) { val u = encode(xx, yy) if (u in dist) return dist[u] = di queue.add(u) } val x = (v shr 32).toInt() val y = v.toInt() move(x and y, y) move(x or y, y) move(x, y xor x) move(x, y xor m) } val ans = dist[dest] ?: -1 out.appendLine(ans.toString()) } fun main() = repeat(readInt()) { solve() }.also { out.close() } private fun readInt() = readln().toInt() private fun readStrings() = readln().split(" ") private fun readInts() = readStrings().map { it.toInt() } private fun readIntArray() = readln().parseIntArray() private fun readLongs() = readStrings().map { it.toLong() } private fun String.parseIntArray(): IntArray { val result = IntArray(count { it == ' ' } + 1) var i = 0; var value = 0 for (c in this) { if (c != ' ') { value = value * 10 + c.code - '0'.code continue } result[i++] = value value = 0 } result[i] = value return result } private val `in` = System.`in`.bufferedReader() private val out = System.out.bufferedWriter() private fun readln() = `in`.readLine()
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
1,485
competitions
The Unlicense
src/main/adventofcode/Day14Solver.kt
eduardofandrade
317,942,586
false
null
package adventofcode import java.io.InputStream import java.math.BigInteger import java.util.* class Day14Solver(stream: InputStream) : Solver { private var instructions: ArrayList<Instruction> = arrayListOf() init { stream.bufferedReader().readLines().forEach { line: String -> if (line.startsWith("mask")) { instructions.add(Mask(line.replace("mask = ", ""))) } else { val writeData = line.replace("\\[|\\]|mem| ".toRegex(), "").split("=") instructions.add( WriteOperation(BigInteger.valueOf(writeData[0].toLong()), BigInteger.valueOf(writeData[1].toLong())) ) } } } override fun getPartOneSolution(): Long { val memory = hashMapOf<BigInteger, BigInteger>() var mask = "" instructions.forEach { instruction -> if (instruction is Mask) { mask = instruction.value } else if (instruction is WriteOperation) { memory[instruction.address] = BitMasker.applyMaskToValue(mask, instruction.value) } } return memory.values.reduce { sum, value -> sum + value }.toLong() } override fun getPartTwoSolution(): Long { val memory = hashMapOf<BigInteger, BigInteger>() var mask = "" instructions.forEach { instruction -> if (instruction is Mask) { mask = instruction.value } else if (instruction is WriteOperation) { BitMasker.applyMaskToAddress(mask, instruction.address).forEach { address -> memory[address] = instruction.value } } } return memory.values.reduce { sum, value -> sum + value }.toLong() } private interface Instruction private class Mask(var value: String) : Instruction private class WriteOperation(var address: BigInteger, var value: BigInteger) : Instruction private class BitMasker { companion object { fun applyMaskToValue(mask: String, value: BigInteger): BigInteger { val binaryValue = value.toString(2).padStart(mask.length, '0').toCharArray() for (i in (mask.length - 1) downTo 0) { val maskBit = mask[i] if (maskBit != 'X') { val pos = binaryValue.size - 1 - (mask.length - 1 - i) binaryValue[pos] = maskBit } } return BigInteger(String(binaryValue), 2) } fun applyMaskToAddress(mask: String, address: BigInteger): List<BigInteger> { var addresses = listOf("") val binaryAddress = address.toString(2).padStart(mask.length, '0').toCharArray() mask.forEachIndexed { i, maskBit -> addresses = when (maskBit) { 'X' -> addresses.flatMap { listOf(it + 0, it + 1) } '1' -> addresses.map { it + maskBit } else -> addresses.map { it + binaryAddress.getOrElse(binaryAddress.size - mask.length + i) { '0' } } } } return addresses.map { it.toBigInteger(2) } } } } }
0
Kotlin
0
0
147553654412ae1da4b803328e9fc13700280c17
3,345
adventofcode2020
MIT License
src/main/kotlin/g1301_1400/s1391_check_if_there_is_a_valid_path_in_a_grid/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1301_1400.s1391_check_if_there_is_a_valid_path_in_a_grid // #Medium #Array #Depth_First_Search #Breadth_First_Search #Matrix #Union_Find // #2023_06_06_Time_636_ms_(100.00%)_Space_64.1_MB_(100.00%) import java.util.LinkedList import java.util.Queue class Solution { private val dirs = arrayOf( arrayOf(intArrayOf(0, -1), intArrayOf(0, 1)), arrayOf(intArrayOf(-1, 0), intArrayOf(1, 0)), arrayOf( intArrayOf(0, -1), intArrayOf(1, 0) ), arrayOf(intArrayOf(0, 1), intArrayOf(1, 0)), arrayOf(intArrayOf(0, -1), intArrayOf(-1, 0)), arrayOf( intArrayOf(0, 1), intArrayOf(-1, 0) ) ) // the idea is you need to check port direction match, you can go to next cell and check whether // you can come back. fun hasValidPath(grid: Array<IntArray>): Boolean { val m = grid.size val n = grid[0].size val visited = Array(m) { BooleanArray(n) } val q: Queue<IntArray> = LinkedList() q.add(intArrayOf(0, 0)) visited[0][0] = true while (q.isNotEmpty()) { val cur = q.poll() val x = cur[0] val y = cur[1] val num = grid[x][y] - 1 for (dir in dirs[num]) { val nx = x + dir[0] val ny = y + dir[1] if (nx < 0 || nx >= m || ny < 0 || ny >= n || visited[nx][ny]) { continue } // go to the next cell and come back to orign to see if port directions are same for (backDir in dirs[grid[nx][ny] - 1]) { if (nx + backDir[0] == x && ny + backDir[1] == y) { visited[nx][ny] = true q.add(intArrayOf(nx, ny)) } } } } return visited[m - 1][n - 1] } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,928
LeetCode-in-Kotlin
MIT License
src/2021/Day05.kt
nagyjani
572,361,168
false
{"Kotlin": 369497}
package `2021` import common.Point import java.io.File import java.util.* import kotlin.math.abs fun main() { Day05().solve() } fun sign(a: Int): Int { if (a<0) { return -1 } if (a>0) { return 1 } return 0 } class Line(p1: Point, p2: Point) { private val leftTop: Point private val rightBottom: Point init { if (p1 < p2) { leftTop = p1 rightBottom = p2 } else { leftTop = p2 rightBottom = p1 } } fun points(): Sequence<Point> { return generateSequence(leftTop){ if (it == rightBottom) { null } else { val xGrad = sign(rightBottom.x-leftTop.x) val yGrad = sign(rightBottom.y-leftTop.y) Point(it.x + xGrad, it.y + yGrad) } } } fun isAligned2(): Boolean { return leftTop.x == rightBottom.x || leftTop.y == rightBottom.y } fun isAligned4(): Boolean { return isAligned2() || abs(leftTop.x - rightBottom.x) == abs(leftTop.y-rightBottom.y) } } class Bottom { val points = mutableMapOf<Point, Int>() fun drawLine(l: Line) { for (p in l.points()) { points[p] = points.getOrDefault(p, 0) + 1 } } } class Day05 { fun solve() { val f = File("src/2021/inputs/day05.in") val s = Scanner(f) val b2 = Bottom() val b4 = Bottom() while (s.hasNextLine()) { val ls = s.nextLine().trim() val cs = ls.split(" -> ").flatMap { it.split(",")}.filter { it.isNotEmpty() }.map { it.toInt() } val line = Line(Point(cs[0], cs[1]), Point(cs[2], cs[3])) if (line.isAligned2()) { b2.drawLine(line) } if (line.isAligned4()) { b4.drawLine(line) } } println("${b2.points.filter { it.value>1 }.count()} ${b4.points.filter { it.value>1 }.count()}") } }
0
Kotlin
0
0
f0c61c787e4f0b83b69ed0cde3117aed3ae918a5
1,968
advent-of-code
Apache License 2.0
src/Day21.kt
chasegn
573,224,944
false
{"Kotlin": 29978}
import java.lang.IllegalArgumentException /** * Day 21 for Advent of Code 2022 * https://adventofcode.com/2022/day/21 */ class Day21 : Day { override val inputFileName: String = "Day21" override val test1Expected: Long = 152 override val test2Expected: Long = 301 /** * Accepted solution: 110181395003396 * 135 ms */ override fun part1(input: List<String>): Long { val monkeys = buildMonkeys(input) while (!isNumeric(monkeys["root"]!!)) { for (monkey in monkeys) { if (!isNumeric(monkey.value)) { val parts = monkey.value.split("[+-/*]".toRegex()) val monkeyA = monkeys[parts[0].trim()] val monkeyB = monkeys[parts[1].trim()] val op = "[+-/*]".toRegex().find(monkey.value)!!.value if (isNumeric(monkeyA!!) && isNumeric(monkeyB!!)) { val monkeyAVal = monkeyA.toLong() val monkeyBVal = monkeyB.toLong() monkeys[monkey.key] = when(op) { "+" -> (monkeyAVal + monkeyBVal).toString() "-" -> (monkeyAVal - monkeyBVal).toString() "*" -> (monkeyAVal * monkeyBVal).toString() "/" -> (monkeyAVal / monkeyBVal).toString() else -> throw IllegalArgumentException("Did not recognize symbol $op") } println("remapped monkey ${monkey.key} to ${monkeys[monkey.key]}") } } } } return monkeys["root"]!!.toLong() } /** * Accepted solution: */ override fun part2(input: List<String>): Int { return input.size } private fun buildMonkeys(input: List<String>, isPart2: Boolean = false): MutableMap<String, String> { val monkeys = HashMap<String, String>() input.forEach { val tokens = it.split(':') if (!monkeys.containsKey(tokens[0])) { monkeys[tokens[0].trim()] = tokens[1].trim() } } if (isPart2) { monkeys["humn"] = "what" monkeys["root"] = "[+-/*]".toRegex().replace(monkeys["root"]!!, "==") } return monkeys } private fun isNumeric(toCheck: String): Boolean { return toCheck.all { c -> c.isDigit() } } }
0
Kotlin
0
0
2b9a91f083a83aa474fad64f73758b363e8a7ad6
2,485
advent-of-code-2022
Apache License 2.0
solver/src/commonMain/kotlin/org/hildan/sudoku/model/Cell.kt
joffrey-bion
9,559,943
false
{"Kotlin": 51198, "HTML": 187}
package org.hildan.sudoku.model import org.hildan.sudoku.solver.techniques.CellIndex /** * Represents one cell in a Sudoku [Grid]. */ class Cell( val row: Int, val col: Int, /** The digit set for this cell, or null if this cell is empty */ var value: Digit?, ) { /** True if this cell's digit was not found. */ val isEmpty: Boolean get() = value == null /** The possible digits for this cell. */ val candidates: MutableSet<Digit> = ALL_DIGITS.toMutableSet() /** The cells which are either in the same unit (row or column or box) as this cell. */ lateinit var sisters: Set<Cell> override fun toString(): String = "r${row + 1}c${col + 1} (${'A' + row}${col + 1})" } val Cell.index: CellIndex get() = Grid.SIZE * row + col val Cell.box: Int get() = (row / Grid.BOX_SIDE_SIZE) * 3 + col / Grid.BOX_SIDE_SIZE /** The number of empty cells which are sisters of this cell. */ val Cell.nbEmptySisters: Int get() = sisters.count { it.isEmpty } fun Set<Cell>.mapToIndices() = mapTo(HashSet()) { it.index } /** * Returns whether the given [digit] appears in the same unit as this cell */ fun Cell.sees(digit: Digit): Boolean = sisters.any { it.value == digit } /** * Remove this `Cell`'s current value from the list of possibilities of its sisters. * * @return `true` if success, `false` if one of the sisters has no more possible values. */ fun Cell.removeValueFromSistersCandidates(): Boolean { for (sister in sisters) { if (sister.isEmpty) { sister.candidates.remove(value) if (sister.candidates.isEmpty()) { return false } } } return true } /** * Put back the [value] in the list of possibilities of the sisters (only if the value is * consistent with the current grid). */ fun Cell.restoreValueInSisters(value: Digit) { for (sister in sisters) { if (sister.isEmpty && !sister.sees(value)) { sister.candidates.add(value) } } }
0
Kotlin
0
0
441fbb345afe89b28df9fe589944f40dbaccaec5
2,023
sudoku-solver
MIT License
src/algorithmsinanutshell/IntersectionOfLines.kt
realpacific
234,499,820
false
null
package algorithmsinanutshell import kotlin.math.abs import kotlin.math.max import kotlin.math.min import kotlin.test.assertFalse import kotlin.test.assertTrue /** * ``` * Two lines (P1, P2) and (P3,P4) intersect when orientation of: * * (P1 wrt P3,P4) and (P2 wrt P3,P4) * * (P3 wrt P1,P2) and (P4 wrt P1,P2) * * are different. * * A line (P1, P2) can be represented as vector P1P2 and orientation is the way (whether counter-clockwise or clockwise) * direction it makes fromTo move from P1P2 fromTo P3. * * P3 o * * P1 o----->---o P2 * * orientation of P3 wrt P1P2 is ACW. * * Special case is when (P1, P2) and (P3,P4) are collinear. * * * In case of non-intersecting case, orientation is 0 for both P3(P1P2) and P4(P1,P2) and vv. * * P1 o----->---o P2 P3 o----->---o P4 (Non-intersecting case) * * * In case of intersecting case, orientation is different for both P3(P1P2) and P4(P1,P2) and vv. * * P1 o----->--oP3-----P2o-->---o P4 (Intersecting case) * * * ``` * * [Link](https://www.youtube.com/watch?v=bbTqI0oqL5U) */ class IntersectionOfLines(val l1: Line, val l2: Line) { private fun getOrientation(p1: Point, p2: Point, other: Point): Orientation { return OrientationOf3Points(p1, p2, other).getOrientation() } /** * Find whether [other] lies in the line [p1] to [p2] */ private fun hasOverlap(p1: Point, p2: Point, other: Point): Boolean { return (other.x >= min(p1.x, p2.x) && other.x <= max(p1.x, p2.x)) .and(other.y >= min(p1.y, p2.y) && other.y <= max(p1.y, p2.y)) } fun hasIntersection(): Boolean { val o1 = getOrientation(l1.p1, l1.p2, l2.p1) val o2 = getOrientation(l1.p1, l1.p2, l2.p2) val o3 = getOrientation(l2.p1, l2.p2, l1.p1) val o4 = getOrientation(l2.p1, l2.p2, l1.p2) // Intersection when orientation are different if (o1 != o2 && o3 != o4) { return true } if (o1 == Orientation.COLINEAR && hasOverlap(l1.p1, l1.p2, l2.p1)) { return true } if (o2 == Orientation.COLINEAR && hasOverlap(l1.p1, l1.p2, l2.p2)) { return true } if (o3 == Orientation.COLINEAR && hasOverlap(l2.p1, l2.p2, l1.p1)) { return true } if (o4 == Orientation.COLINEAR && hasOverlap(l2.p1, l2.p2, l1.p2)) { return true } return false } } fun main() { run { val l1 = Line(6 fromTo 4, 9 fromTo 4) val l2 = Line(3 fromTo 2, 10 fromTo 3) val algorithm = IntersectionOfLines(l1, l2) assertFalse { algorithm.hasIntersection() } } run { val l1 = Line(5 fromTo 5, 10 fromTo 12) val l2 = Line(0 fromTo 0, 1 fromTo 1) val algorithm = IntersectionOfLines(l1, l2) assertFalse { algorithm.hasIntersection() } } run { val l1 = Line(0 fromTo 0, 5 fromTo 5) val l2 = Line(0 fromTo 5, 5 fromTo 0) val algorithm = IntersectionOfLines(l1, l2) assertTrue { algorithm.hasIntersection() } } run { val l1 = Line(0 fromTo 0, 5 fromTo 0) val l2 = Line(1 fromTo 0, 15 fromTo 0) val algorithm = IntersectionOfLines(l1, l2) assertTrue { algorithm.hasIntersection() } } run { val l1 = Line(6 fromTo 4, 9 fromTo 4) val l2 = Line(7 fromTo 1, 8 fromTo 1) val algorithm = IntersectionOfLines(l1, l2) assertFalse { algorithm.hasIntersection() } } }
4
Kotlin
5
93
22eef528ef1bea9b9831178b64ff2f5b1f61a51f
3,546
algorithms
MIT License
src/main/kotlin/Day03.kt
luluvia
576,815,205
false
{"Kotlin": 7130}
class Day03 { fun part1(input: List<String>): Int { var priorityScore = 0 for (line in input) { val matchingChar = getMatchingChar(line) priorityScore += getPriorityScore(matchingChar) } return priorityScore } fun part2(input: List<String>): Int { var priorityScore = 0 for (lines in input.chunked(3)) { priorityScore += getPriorityScore(getMatchingCharThreeLines(lines)) } return priorityScore } // Get char that matches across three lines private fun getMatchingCharThreeLines(lines: List<String>): Char { for (char in lines[0]) { if (lines[1].contains(char) && lines[2].contains(char)) { return char } } throw IllegalArgumentException("Lines do not contain matching char") } private fun getMatchingChar(line: String): Char { val firstRucksackRange = IntRange(0, line.length/2 - 1) val secondRucksackRange = IntRange(line.length/2, line.length - 1) for (char in line.substring(firstRucksackRange)) { if (char in line.substring(secondRucksackRange)) { return char } } throw IllegalArgumentException("Line does not contain matching character") } private fun getPriorityScore(matchingChar: Char): Int { return if (matchingChar.isLowerCase()) { matchingChar.code - 96 } else { matchingChar.code - 38 } } }
0
Kotlin
0
0
29ddde3b0d7acbe0ef1295ec743e7d0417cfef53
1,550
advent-of-code-22
Apache License 2.0
src/day12/d12_2.kt
svorcmar
720,683,913
false
{"Kotlin": 49110}
fun main() { val input = "" val obj = parseObj(input, 1, false) println(obj.sum()) } fun parseObj(input: String, from: Int, isArray: Boolean): ObjectFragment { val sb = StringBuilder() val arrSb = StringBuilder() val subObjects = mutableListOf<ObjectFragment>() var i = from while(true) { i += when(input[i]) { '[' -> { subObjects.add(parseObj(input, i + 1, true)) subObjects.last().length } ']' -> { if (isArray) return ObjectFragment(subObjects, sb.insert(0, '[').append(']').toString(), true) else { sb.append(input[i]) 1 } } '{' -> { subObjects.add(parseObj(input, i + 1, false)) subObjects.last().length } '}' -> { if (!isArray) return ObjectFragment(subObjects, sb.insert(0, '{').append('}').toString(), false) else { sb.append(input[i]) 1 } } else -> { sb.append(input[i]) 1 } } } } data class ObjectFragment(val subObjects: List<ObjectFragment>, val remainder: String, val isArray: Boolean) { val length: Int by lazy { subObjects.map { it.length }.sum() + remainder.length } fun sum(): Int { return if (!isArray && remainder.contains("\"red\"")) 0 else sumRemainder() + subObjects.map { it.sum() }.sum() } private fun sumRemainder(): Int = "(-?[0-9]+)".toRegex().findAll(remainder).map { it.groupValues[1].toInt() }.sum() }
0
Kotlin
0
0
cb097b59295b2ec76cc0845ee6674f1683c3c91f
1,523
aoc2015
MIT License
src/nl/davefranken/rosalind/P4FIB.kt
Davio
105,393,274
false
null
import java.io.File import java.math.BigInteger import java.util.stream.Stream /** * Problem A sequence is an ordered collection of objects (usually numbers), which are allowed to repeat. Sequences can be finite or infinite. Two examples are the finite sequence (π,−2–√,0,π)(π,−2,0,π) and the infinite sequence of odd numbers (1,3,5,7,9,…)(1,3,5,7,9,…). We use the notation anan to represent the nn-th term of a sequence. A recurrence relation is a way of defining the terms of a sequence with respect to the values of previous terms. In the case of Fibonacci's rabbits from the introduction, any given month will contain the rabbits that were alive the previous month, plus any new offspring. A key observation is that the number of offspring in any month is equal to the number of rabbits that were alive two months prior. As a result, if FnFn represents the number of rabbit pairs alive after the nn-th month, then we obtain the Fibonacci sequence having terms FnFn that are defined by the recurrence relation Fn=Fn−1+Fn−2Fn=Fn−1+Fn−2 (with F1=F2=1F1=F2=1 to initiate the sequence). Although the sequence bears Fibonacci's name, it was known to Indian mathematicians over two millennia ago. When finding the nn-th term of a sequence defined by a recurrence relation, we can simply use the recurrence relation to generate terms for progressively larger values of nn. This problem introduces us to the computational technique of dynamic programming, which successively builds up solutions by using the answers to smaller cases. Given: Positive integers n≤40n≤40 and k≤5k≤5. Return: The total number of rabbit pairs that will be present after nn months, if we begin with 1 pair and in each generation, every pair of reproduction-age rabbits produces a litter of kk rabbit pairs (instead of only 1 pair). */ fun main(args: Array<String>) { val fib = File("rosalind_fib.txt").readLines()[0]; val list = fib.split(" ") val n = list[0].toLong() val k = BigInteger(list[1]) Stream.iterate(Pair(BigInteger.ONE, BigInteger.ZERO), { pair -> Pair(pair.second * k, pair.first + pair.second) }) .skip(n - 1L) .findFirst() .ifPresent{pair -> println(pair.first + pair.second)} }
0
Kotlin
0
0
f5350b0bf4a2514044d69ece5420c5cb8f102889
2,235
rosalind
MIT License
src/main/kotlin/Day3.kt
d1snin
726,126,205
false
{"Kotlin": 14602}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ private const val INPUT = """ """ private data class Num( val line: String, val lineIndex: Int, val at: Int, val data: Int ) private data class Boundary( val line: String, val lineIndex: Int, val start: Int, val end: Int, val data: String ) private data class Gear( val at: Pair<Int, Int>, val first: Num, var second: Num? = null ) private val lines = INPUT.lines() .map { it.trim() } .filter { it.isNotEmpty() } private val gears = mutableListOf<Gear>() fun day3() { println("Running AoC Day 3 (1st part)...") firstPart() println() println("Running AoC Day 3 (2nd part)...") secondPart() } private fun firstPart() { val res = lines.numbers().sumOf { if (it.isAdjacentToSymbol()) it.data else 0 } println("res: $res") } private fun secondPart() { lines.numbers().forEach { it.gears() } val res = gears .filter { it.second != null } .sumOf { it.first.data * requireNotNull(it.second?.data) } println("res: $res") } private fun List<String>.numbers() = flatMapIndexed { lineIndex, line -> line.numbers(lineIndex) } private fun String.numbers(lineIndex: Int): List<Num> = buildList { var numString: String? = null var at: Int? = null this@numbers.forEachIndexed { index, char -> val isDigit = char.isDigit() if (isDigit) { numString = (numString ?: "") + char at = at ?: index } if (!isDigit || index == (length - 1)) { numString?.let { numStringNotNull -> at?.let { atNotNull -> val number = numStringNotNull.toInt() val num = Num( line = this@numbers, lineIndex = lineIndex, at = atNotNull, data = number ) add(num) numString = null at = null } } } } } private fun Num.isAdjacentToSymbol() = getBoundaries().any { boundary -> boundary.data.containsSymbol() } private fun Num.gears() { getBoundaries(excludeInt = false).forEach { boundary -> boundary.data.forEachIndexed { index, char -> if (char == '*') { val coords = boundary.lineIndex to (boundary.start + index) getOrPutGear(coords, this@gears) } } } } private fun Num.getBoundaries(excludeInt: Boolean = true): List<Boundary> { val length = data.toString().length val range = getBoundaryRange(length) fun String.substring(excludeInt: Boolean = false) = substring(range).let { substring -> if (excludeInt) substring.filterNot { it.isDigit() } else substring } val topLineIndex = lineIndex - 1 val topLineSub = lines.getOrNull(topLineIndex)?.substring() val currentLineSub = line.substring(excludeInt = excludeInt) val bottomLineIndex = lineIndex + 1 val bottomLineSub = lines.getOrNull(bottomLineIndex)?.substring() return listOfNotNull( topLineSub?.to(topLineIndex), currentLineSub to lineIndex, bottomLineSub?.to(bottomLineIndex) ).map { (data, dataLineIndex) -> Boundary( line = line, lineIndex = dataLineIndex, start = range.first, end = range.last, data = data ) } } private fun Num.getBoundaryRange(length: Int): IntRange { val start = if (at < 1) 0 else at - 1 val endCandidate = at + length val end = if (line.length <= endCandidate) endCandidate - 1 else endCandidate return start..end } private fun String.containsSymbol() = this.contains("[^\\d.]".toRegex()) private fun getOrPutGear(at: Pair<Int, Int>, num: Num): Gear { val foundGear = gears.find { it.at == at } foundGear?.second = num return foundGear ?: Gear(at, first = num).also { gears.add(it) } }
0
Kotlin
0
0
8b5b34c4574627bb3c6b1a12664cc6b4c9263e30
4,850
aoc-2023
Apache License 2.0
leetcode2/src/leetcode/remove-nth-node-from-end-of-list.kt
hewking
68,515,222
false
null
package leetcode import leetcode.structure.ListNode /** * 19. 删除链表的倒数第N个节点 * https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/ * 给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。 示例: 给定一个链表: 1->2->3->4->5, 和 n = 2. 当删除了倒数第二个节点后,链表变为 1->2->3->5. 说明: 给定的 n 保证是有效的。 进阶: 你能尝试使用一趟扫描实现吗? 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ object RemoveNthNodeFromEndOfList { class Solution { /** * 快慢指针法,当快指针到最后面时候,慢指针正好到中间。 * 如果我们给定一个index,这个值每次循环+1,然后,就可以通过与n的关系 * 删除一个节点即可 */ fun removeNthFromEnd(head: ListNode?, n: Int): ListNode? { val dummy = ListNode(-1) dummy.next = head var first = dummy var second = dummy for (i in 1 .. n) { first = first.next } while(first != null && first.next != null) { first = first.next second = second.next } second.next = second.next.next return dummy.next } } }
0
Kotlin
0
0
a00a7aeff74e6beb67483d9a8ece9c1deae0267d
1,485
leetcode
MIT License
src/main/Day20.kt
ssiegler
572,678,606
false
{"Kotlin": 76434}
package day20 import utils.readInput private const val filename = "Day20" fun part1(filename: String): Long = readEncrypted(filename).mix().grooveCoordinates().sum() fun readEncrypted(filename: String, key: Long = 1) = readInput(filename).map { it.toLong() * key } fun part2(filename: String): Long = readEncrypted(filename, 811589153).mix(10).grooveCoordinates().sum() fun List<Long>.grooveCoordinates(): List<Long> { val start = indexOf(0) return listOf(1000, 2000, 3000).map { this[(it + start) % size] } } fun List<Long>.mix(times: Int = 1): List<Long> = withIndex().toMutableList().apply { repeat(times) { mix() } }.map { it.value } private fun MutableList<IndexedValue<Long>>.mix() { indices.forEach { originalIndex -> val index = indexOfFirst { it.index == originalIndex } val element = removeAt(index) add((index + element.value).mod(size), element) } } fun main() { println(part1(filename)) println(part2(filename)) }
0
Kotlin
0
0
9133485ca742ec16ee4c7f7f2a78410e66f51d80
992
aoc-2022
Apache License 2.0
hoon/HoonAlgorithm/src/main/kotlin/programmers/lv02/Lv2_12951_JadenCase문자열만들기.kt
boris920308
618,428,844
false
{"Kotlin": 137657, "Swift": 35553, "Java": 1947, "Rich Text Format": 407}
package programmers.lv02 /** * * no.12951 * JadenCase 문자열 만들기 * https://school.programmers.co.kr/learn/courses/30/lessons/12951 * * JadenCase란 모든 단어의 첫 문자가 대문자이고, 그 외의 알파벳은 소문자인 문자열입니다. * 단, 첫 문자가 알파벳이 아닐 때에는 이어지는 알파벳은 소문자로 쓰면 됩니다. (첫 번째 입출력 예 참고) * 문자열 s가 주어졌을 때, s를 JadenCase로 바꾼 문자열을 리턴하는 함수, solution을 완성해주세요. * * 제한 조건 * s는 길이 1 이상 200 이하인 문자열입니다. * s는 알파벳과 숫자, 공백문자(" ")로 이루어져 있습니다. * 숫자는 단어의 첫 문자로만 나옵니다. * 숫자로만 이루어진 단어는 없습니다. * 공백문자가 연속해서 나올 수 있습니다. * 입출력 예 * s return * "3people unFollowed me" "3people Unfollowed Me" * "for the last week" "For The Last Week" */ fun main() { println(solution("3people unFollowed me")) println(solution("for the last week")) } private fun solution(s: String): String { var answer = "" val sArray = s.toCharArray() sArray.forEachIndexed { index, c -> if (index == 0) { sArray[index] = sArray[index].uppercaseChar() } if (c.isLetter() && index != 0) { if (sArray[index -1].toString() != " ") { sArray[index] = sArray[index].lowercaseChar() } else { sArray[index] = sArray[index].uppercaseChar() } } } answer = String(sArray) return answer }
1
Kotlin
1
2
88814681f7ded76e8aa0fa7b85fe472769e760b4
1,681
HoOne
Apache License 2.0
sbom-ort/scanner/src/main/kotlin/ScannerCriteria.kt
opensourceways
521,493,253
false
{"Kotlin": 4381819, "Go": 1396721, "JavaScript": 291650, "Shell": 163230, "HTML": 118849, "Python": 87335, "Haskell": 30438, "CSS": 25056, "Makefile": 21936, "FreeMarker": 20565, "Ruby": 13496, "Dockerfile": 12965, "Batchfile": 9453, "Roff": 7778, "Java": 6729, "Scala": 6656, "ANTLR": 1883, "Rust": 280, "Emacs Lisp": 191, "C": 107, "Vim Script": 16}
/* * Copyright (C) 2020 Bosch.IO GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * SPDX-License-Identifier: Apache-2.0 * License-Filename: LICENSE */ package org.ossreviewtoolkit.scanner import com.vdurmont.semver4j.Semver import org.ossreviewtoolkit.model.ScannerDetails /** * Definition of a predicate to check whether the configuration of a scanner is compatible with the requirements * specified by a [ScannerCriteria] object. * * When testing whether a scan result is compatible with specific criteria this function is invoked on the * scanner configuration data stored in the result. By having different, scanner-specific matcher functions, this * compatibility check can be made very flexible. * * TODO: Switch to a more advanced type than String to represent the scanner configuration. */ typealias ScannerConfigMatcher = (String) -> Boolean /** * A data class defining selection criteria for scanners. * * An instance of this class is passed to a [ScanResultsStorage] to define the criteria a scan result must match, * so that it can be used as a replacement for a result produced by an actual scanner. A scanner implementation * creates a criteria object with its exact properties. Users can override some or all of these properties to * state the criteria under which results from a storage are acceptable even if they deviate from the exact * properties of the scanner. That way it can be configured for instance, that results produced by an older * version of the scanner can be used. */ data class ScannerCriteria( /** * Criterion to match the scanner name. This string is interpreted as a regular expression. In the most basic * form, it can be an exact scanner name, but by using features of regular expressions, a more advanced * matching can be achieved. So it is possible for instance to select multiple scanners using an alternative ('|') * expression or an arbitrary one using a wildcard ('.*'). */ val regScannerName: String, /** * Criterion to match for the minimum scanner version. Results are accepted if they are produced from scanners * with at least this version. */ val minVersion: Semver, /** * Criterion to match for the maximum scanner version. Results are accepted if they are produced from scanners * with a version lower than this one. (This bound of the version range is excluding.) */ val maxVersion: Semver, /** * A function to check whether the configuration of a scanner is compatible with this criteria object. */ val configMatcher: ScannerConfigMatcher ) { companion object { /** * A matcher for scanner configurations that accepts all configurations passed in. This function can be * used if the concrete configuration of a scanner is irrelevant. */ val ALL_CONFIG_MATCHER: ScannerConfigMatcher = { true } /** * A matcher for scanner configurations that accepts only exact matches of the [originalConfig]. This * function can be used by scanners that are extremely sensitive about their configuration. */ fun exactConfigMatcher(originalConfig: String): ScannerConfigMatcher = { config -> originalConfig == config } /** * Generate a [ScannerCriteria] object that is compatible with the given [details] and versions that differ only * in the provided [versionDiff]. */ fun forDetails( details: ScannerDetails, versionDiff: Semver.VersionDiff = Semver.VersionDiff.NONE ): ScannerCriteria { val minVersion = Semver(details.version) val maxVersion = when (versionDiff) { Semver.VersionDiff.NONE, Semver.VersionDiff.SUFFIX, Semver.VersionDiff.BUILD -> minVersion.nextPatch() Semver.VersionDiff.PATCH -> minVersion.nextMinor() Semver.VersionDiff.MINOR -> minVersion.nextMajor() else -> throw IllegalArgumentException("Invalid version difference $versionDiff") } return ScannerCriteria( regScannerName = details.name, minVersion = minVersion, maxVersion = maxVersion, configMatcher = exactConfigMatcher(details.configuration) ) } } /** The regular expression to match for the scanner name. */ private val nameRegex: Regex by lazy { Regex(regScannerName) } init { require(minVersion < maxVersion) { "The `maxVersion` is exclusive and must be greater than the `minVersion`." } } /** * Check whether the [details] specified match the criteria stored in this object. Return true if and only if * the result described by the [details] fulfills all the requirements expressed by the properties of this * object. */ fun matches(details: ScannerDetails): Boolean { if (!nameRegex.matches(details.name)) return false val version = Semver(details.version) return minVersion <= version && version < maxVersion && configMatcher(details.configuration) } }
63
Kotlin
2
27
3e0f370e5c2d809257e0b8d7aa6b1ac3161c53a2
5,697
sbom-tools
Apache License 2.0
src/main/kotlin/days/Day25.kt
julia-kim
569,976,303
false
null
package days import readInput import kotlin.math.absoluteValue import kotlin.math.log import kotlin.math.pow import kotlin.math.roundToInt fun main() { fun Long.toSNAFU(): String { var snafu = "" var decimal = this.toDouble() var currentPlace = log(this.toDouble(), 5.0).roundToInt() while (currentPlace >= 0) { val currentPlaceValue = 5.0.pow(currentPlace) when ((decimal / currentPlaceValue).roundToInt()) { 1 -> { snafu += "1" decimal -= currentPlaceValue } 2 -> { snafu += "2" decimal -= currentPlaceValue * 2 } -1 -> { snafu += "-" decimal += currentPlaceValue } -2 -> { snafu += "=" decimal += currentPlaceValue * 2 } else -> { snafu += "0" } } currentPlace-- } return snafu } fun part1(input: List<String>): String { val decimalSum = input.map { snafu -> snafu.mapIndexed { i, c -> val nthPlace = 5.0.pow((i - snafu.lastIndex).absoluteValue).toLong() when (c) { '2' -> 2 * nthPlace '1' -> nthPlace '0' -> 0 '-' -> -nthPlace '=' -> -2 * nthPlace else -> { 0 } } }.sum() }.sum() return decimalSum.toSNAFU() } val testInput = readInput("Day25_test") check(part1(testInput) == "2=-1=0") val input = readInput("Day25") println(part1(input)) }
0
Kotlin
0
0
65188040b3b37c7cb73ef5f2c7422587528d61a4
1,882
advent-of-code-2022
Apache License 2.0
src/main/kotlin/com/marcdenning/adventofcode/day11/Day11b.kt
marcdenning
317,730,735
false
{"Kotlin": 87536}
package com.marcdenning.adventofcode.day11 import java.io.File private const val FLOOR = '.' private const val EMPTY = 'L' private const val OCCUPIED = '#' fun main(args: Array<String>) { val floorPlanMatrix = File(args[0]).readLines().map { it.toCharArray() }.toTypedArray() println("Number of occupied seats: ${countSeats(findSteadyFloorPlanByVisibility(floorPlanMatrix), OCCUPIED)}") } fun fillSeatsByVisibility(floorPlanMatrix: Array<CharArray>): Array<CharArray> { val outputFloorPlanMatrix = floorPlanMatrix.map { it.copyOf() }.toTypedArray() for ((rowIndex, row) in floorPlanMatrix.withIndex()) { for ((columnIndex, seat) in row.withIndex()) { if (seat == EMPTY && countVisibleSeats(floorPlanMatrix, rowIndex, columnIndex, OCCUPIED) == 0) { outputFloorPlanMatrix[rowIndex][columnIndex] = OCCUPIED } } } return outputFloorPlanMatrix } fun emptySeatsByVisibility(floorPlanMatrix: Array<CharArray>): Array<CharArray> { val outputFloorPlanMatrix = floorPlanMatrix.map { it.copyOf() }.toTypedArray() for ((rowIndex, row) in floorPlanMatrix.withIndex()) { for ((columnIndex, seat) in row.withIndex()) { if (seat == OCCUPIED && countVisibleSeats(floorPlanMatrix, rowIndex, columnIndex, OCCUPIED) >= 5) { outputFloorPlanMatrix[rowIndex][columnIndex] = EMPTY } } } return outputFloorPlanMatrix } fun findSteadyFloorPlanByVisibility(floorPlanMatrix: Array<CharArray>): Array<CharArray> { var lastFloorPlan = Array(floorPlanMatrix.size) { CharArray(floorPlanMatrix[0].size) } var currentFloorPlan = floorPlanMatrix.copyOf() var isFillTurn = true while (!lastFloorPlan.contentDeepEquals(currentFloorPlan)) { lastFloorPlan = currentFloorPlan if (isFillTurn) { currentFloorPlan = fillSeatsByVisibility(currentFloorPlan) isFillTurn = false } else { currentFloorPlan = emptySeatsByVisibility(currentFloorPlan) isFillTurn = true } } return currentFloorPlan } fun countVisibleSeats(floorPlanMatrix: Array<CharArray>, rowIndex: Int, columnIndex: Int, targetSeat: Char): Int { val directions = listOf( Pair(-1, 0), Pair(-1, 1), Pair(0, 1), Pair(1, 1), Pair(1, 0), Pair(1, -1), Pair(0, -1), Pair(-1, -1) ) var countOfSeats = 0 for (directionPair in directions) { if (findVisibleSeatInDirection(floorPlanMatrix, rowIndex, columnIndex, directionPair.first, directionPair.second) == targetSeat) { countOfSeats++ } } return countOfSeats } fun findVisibleSeatInDirection(floorPlanMatrix: Array<CharArray>, rowIndex: Int, columnIndex: Int, rowIncrement: Int, columnIncrement: Int): Char { if (rowIndex + rowIncrement < 0 || rowIndex + rowIncrement >= floorPlanMatrix.size || columnIndex + columnIncrement < 0 || columnIndex + columnIncrement >= floorPlanMatrix[rowIndex].size) { return ' ' } val cell = floorPlanMatrix[rowIndex + rowIncrement][columnIndex + columnIncrement] if (cell == EMPTY || cell == OCCUPIED) { return cell } return findVisibleSeatInDirection(floorPlanMatrix, rowIndex + rowIncrement, columnIndex + columnIncrement, rowIncrement, columnIncrement) }
0
Kotlin
0
0
b227acb3876726e5eed3dcdbf6c73475cc86cbc1
3,391
advent-of-code-2020
MIT License
advent2021/src/main/kotlin/year2021/Day07.kt
bulldog98
572,838,866
false
{"Kotlin": 132847}
package year2021 import AdventDay import kotlin.math.abs import kotlin.math.max import kotlin.math.min private fun addIfFirstMaxIsZero(a: Int, b: Int): Int = if (a == Int.MAX_VALUE) b else a + b private fun Collection<Int>.alignTo(i: Int, cost: (Int) -> Int = ::abs): Int = asSequence() .map { max(it, i) - min(it, i) } .filter { cost(it) > 0 } .map { cost(it) } .fold(Int.MAX_VALUE, ::addIfFirstMaxIsZero) fun increaseByStep(n: Int): Int = (n * (n+1)) / 2 object Day07 : AdventDay(2021, 7) { override fun part1(input: List<String>): Int = with(input[0].split(",").map(String::toInt)) { indices.minOfOrNull { this.alignTo(it) } ?: throw Error("no valid config") } override fun part2(input: List<String>): Int = with(input[0].split(",").map(String::toInt)) { indices.minOfOrNull { this.alignTo(it, ::increaseByStep) } ?: throw Error("no valid config") } } fun main() = Day07.run()
0
Kotlin
0
0
02ce17f15aa78e953a480f1de7aa4821b55b8977
999
advent-of-code
Apache License 2.0
kotlin/src/katas/kotlin/algorithms/RabinKarp.kt
dkandalov
2,517,870
false
{"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221}
package katas.kotlin.algorithms import datsok.shouldEqual import org.junit.Test class RollingHash( val s: CharSequence, val size: Int, val startIndex: Int = 0, val base: Int = 256, val modulus: Int = 101, val value: Int = s.subSequence(startIndex, startIndex + size).fold(0) { acc, c -> (acc * base + c.toInt()).rem(modulus) } ) { fun roll(): RollingHash { if (startIndex + size >= s.length) return this var prevMultiplier = 1 1.until(size).forEach { prevMultiplier = (prevMultiplier * base).rem(modulus) } val prevChar = s[startIndex] val newChar = s[startIndex + size] var newValue = value + modulus - (prevChar.toInt() * prevMultiplier) % modulus newValue = (newValue * base + newChar.toInt()).rem(modulus) return RollingHash(s, size, startIndex + 1, base, modulus, newValue) } } fun findIndexOf(s: String, text: String): Int { if (text.length < s.length) return -1 val hash = RollingHash(s, s.length) var textHash = RollingHash(text, s.length) 0.until(text.length - s.length + 1).forEach { i -> if (hash.value == textHash.value) return i textHash = textHash.roll() } return -1 } class RobinKarpTests { @Test fun `find index of a string in text`() { findIndexOf("", text = "") shouldEqual 0 findIndexOf("", text = "abc") shouldEqual 0 findIndexOf("abc", text = "") shouldEqual -1 findIndexOf("abc", text = "abc") shouldEqual 0 findIndexOf("ab", "abcdef") shouldEqual 0 findIndexOf("cd", "abcdef") shouldEqual 2 findIndexOf("ef", "abcdef") shouldEqual 4 } // https://en.wikipedia.org/wiki/Rabin%E2%80%93Karp_algorithm @Test fun `rolling hash example from wikipedia`() { val hash = RollingHash("abra", size = 3) hash.value shouldEqual 4 hash.roll().value shouldEqual 30 RollingHash("abra", startIndex = 1, size = 3).value shouldEqual 30 } @Test fun `rolling hash`() { val hash = RollingHash("hihi", size = 2) hash.value shouldEqual 65 hash.roll().value shouldEqual 17 hash.roll().roll().value shouldEqual 65 hash.roll().roll().roll().value shouldEqual 65 } }
7
Roff
3
5
0f169804fae2984b1a78fc25da2d7157a8c7a7be
2,296
katas
The Unlicense
src/main/kotlin/com/hj/leetcode/kotlin/problem1464/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem1464 import kotlin.math.max import kotlin.math.min /** * LeetCode page: [1464. Maximum Product of Two Elements in an Array](https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/); */ class Solution { /* Complexity: * Time O(N) and Space O(1) where N is the size of nums; */ fun maxProduct(nums: IntArray): Int { val (largest, secondLargest) = findTwoLargest(nums) return (largest - 1) * (secondLargest - 1) } private fun findTwoLargest(nums: IntArray): Pair<Int, Int> { var largest = max(nums[0], nums[1]) var secondLargest = min(nums[0], nums[1]) for (index in 2..<nums.size) { when { nums[index] > largest -> { secondLargest = largest largest = nums[index] } nums[index] > secondLargest -> { secondLargest = nums[index] } } } return Pair(largest, secondLargest) } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
1,067
hj-leetcode-kotlin
Apache License 2.0
src/main/kotlin/day21/Day21.kt
TheSench
572,930,570
false
{"Kotlin": 128505}
package day21 import runDay import stackOf import kotlin.RuntimeException fun main() { fun part1(input: List<String>): Long = input.map { it.toMonkey() } .processMonkeys() .let { it["root"]!!.number!! } fun part2(input: List<String>) = input.map { it.toMonkey() } .processMonkeys() .let { allMonkeys -> val root = allMonkeys["root"]!! val pathToHuman = root.findPath("humn", allMonkeys) allMonkeys.calculateHuman(root, pathToHuman) } (object {}).runDay( part1 = ::part1, part1Check = 152L, part2 = ::part2, part2Check = 301L, ) } private fun List<Monkey>.processMonkeys(): MutableMap<String, Monkey> = let { monkeys -> val seenMonkeys = mutableMapOf<String, Monkey>() val waitList = mutableMapOf<String, List<Monkey>>() fun Monkey.register() { seenMonkeys[name] = this } fun Monkey.tryRunOperation() { val otherMonkeys = waitingOn.map { it to seenMonkeys[it]?.number } if (otherMonkeys.any { it.second == null }) { otherMonkeys.forEach { (other, value) -> if (value == null) { val listForMonkey = waitList.computeIfAbsent(other) { emptyList() } waitList[other] = listForMonkey + this } } return } val numbers = otherMonkeys.map { it.second!! } number = when (operation) { "+" -> numbers[0] + numbers[1] "-" -> numbers[0] - numbers[1] "*" -> numbers[0] * numbers[1] "/" -> numbers[0] / numbers[1] else -> throw IllegalArgumentException("Operation $operation not supported") } removeFromWaitList(waitList) } fun Monkey.triggerWaiters() { if (number == null) return waitList[name]?.forEach { it.tryRunOperation() if (it.number != null) it.triggerWaiters() } } fun Monkey.process() { register() if (number == null) tryRunOperation() } monkeys.forEach { monkey -> monkey.process() monkey.triggerWaiters() val rootNumber = seenMonkeys["root"]?.number if (rootNumber != null) { return seenMonkeys } } throw RuntimeException("Did not find root number") } private fun Map<String, Monkey>.calculateHuman(monkey: Monkey, pathToHuman: Set<String>): Long { val left = monkey.waitingOn.first() val right = monkey.waitingOn.last() val leftMonkey = this[left]!! val rightMonkey = this[right]!! return if (left in pathToHuman) { calculateHuman(rightMonkey.number!!, leftMonkey, pathToHuman) } else { calculateHuman(leftMonkey.number!!, rightMonkey, pathToHuman) } } private fun Map<String, Monkey>.calculateHuman(value: Long, monkey: Monkey, pathToHuman: Set<String>): Long { val left = monkey.waitingOn.first() val right = monkey.waitingOn.last() val leftMonkey = this[left]!! val rightMonkey = this[right]!! if (left in pathToHuman) { val newValue = when (monkey.operation) { "+" -> value - rightMonkey.number!! "-" -> value + rightMonkey.number!! "*" -> value / rightMonkey.number!! "/" -> value * rightMonkey.number!! else -> throw IllegalArgumentException("Illegal operation ${monkey.operation}") } // println("/*(L)*/ ${value}L == ${newValue}L ${monkey.operation} ${rightMonkey.number}L") return if (left == "humn") { newValue } else { calculateHuman(newValue, leftMonkey, pathToHuman) } } else { val newValue = when (monkey.operation) { "+" -> value - leftMonkey.number!! "-" -> -(value - leftMonkey.number!!) "*" -> value / leftMonkey.number!! "/" -> leftMonkey.number!! / value else -> throw IllegalArgumentException("Illegal operation ${monkey.operation}") } // println("/*(R)*/ ${value}L == ${leftMonkey.number}L ${monkey.operation} ${newValue}L") return if (right == "humn") { newValue } else { calculateHuman(newValue, rightMonkey, pathToHuman) } } } private fun Monkey.findPath(targetKey: String, allMonkeys: Map<String, Monkey>): Set<String> { val paths = stackOf(this.waitingOn.map { listOf(it) }) while (paths.size > 0) { val path = paths.removeFirst() val key = path.last() if (key == targetKey) { return path.toSet() } else { allMonkeys[key]!!.waitingOn.forEach { paths.addLast(path + it) } } } throw RuntimeException("Did not find path") } private fun Monkey.toEquation( allMonkeys: Map<String, Monkey>, maxDepth: Int = Int.MAX_VALUE, currentDepth: Int = 0 ): String = when { this.operation == null -> this.number.toString() currentDepth == maxDepth -> this.number.toString() else -> { val first = allMonkeys[this.waitingOn[0]]!!.toEquation(allMonkeys, maxDepth, currentDepth + 1) val second = allMonkeys[this.waitingOn[1]]!!.toEquation(allMonkeys, maxDepth, currentDepth + 1) "($first $operation $second)" } } private fun Monkey.removeFromWaitList(waitList: MutableMap<String, List<Monkey>>) { this.waitingOn.forEach { if (waitList.containsKey(it)) { waitList[it] = waitList[it]!!.filter { waiter -> waiter != this } } } } class Monkey( val name: String, var number: Long? = null, val operation: String? = null, val originalWaitingOn: List<String> = emptyList(), ) { var waitingOn: List<String> = originalWaitingOn } fun String.toMonkey() = split(": ").let { nameValue -> val name = nameValue.first() nameValue.last().split(" ").let { when (it.size) { 1 -> NumberMonkey(name, it.first()) else -> OperationMonkey(name, it[0], it[1], it[2]) } } } fun NumberMonkey(name: String, value: String): Monkey { return Monkey( name = name, number = value.toLong() ) } fun OperationMonkey(name: String, firstMonkey: String, operation: String, secondMonkey: String): Monkey { return Monkey( name = name, operation = operation, originalWaitingOn = listOf(firstMonkey, secondMonkey) ) }
0
Kotlin
0
0
c3e421d75bc2cd7a4f55979fdfd317f08f6be4eb
5,900
advent-of-code-2022
Apache License 2.0
letcode/src/main/java/daily/LeetCode167.kt
chengw315
343,265,699
false
null
package daily fun main() { val solution = Solution167() //4,5 val twoSum4 = solution.twoSum(intArrayOf(1,2,3,4,4,8,9,75), 8) //2,3 val twoSum3 = solution.twoSum(intArrayOf(5,25,75), 100) //1,2 val twoSum = solution.twoSum(intArrayOf(2, 7, 11, 15), 9) //1,5 val twoSum2 = solution.twoSum(intArrayOf(-995, -856, 456, 7856, 65454), 64459) } /** * 两数之和——找到数组中两数之和等于目标的索引(索引以1开始),输出一个答案 */ class Solution167 { fun twoSum(numbers: IntArray, target: Int): IntArray { var a = 0 var b = 0 for (i in numbers.indices) { b = numbers.binarySearch(target - numbers[i]) if(b == i) b = numbers.binarySearch(target - numbers[i], b + 1) if(b > 0) { b++ a = i + 1 break } } return intArrayOf(a,b) } }
0
Java
0
2
501b881f56aef2b5d9c35b87b5bcfc5386102967
937
daily-study
Apache License 2.0
src/test/kotlin/dev/shtanko/algorithms/leetcode/SortByBitsTest.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.util.stream.Stream import org.assertj.core.api.Assertions import org.junit.jupiter.api.extension.ExtensionContext import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.Arguments import org.junit.jupiter.params.provider.ArgumentsProvider import org.junit.jupiter.params.provider.ArgumentsSource abstract class SortByBitsTest<out T : SortByBits>(private val strategy: T) { private class InputArgumentsProvider : ArgumentsProvider { override fun provideArguments(context: ExtensionContext?): Stream<out Arguments> = Stream.of( Arguments.of( intArrayOf(0, 1, 2, 3, 4, 5, 6, 7, 8), intArrayOf(0, 1, 2, 4, 8, 3, 5, 6, 7), ), Arguments.of( intArrayOf(1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1), intArrayOf(1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024), ), ) } @ParameterizedTest @ArgumentsSource(InputArgumentsProvider::class) fun `sort by bits test`(arr: IntArray, expected: IntArray) { val actual = strategy(arr) Assertions.assertThat(actual).isEqualTo(expected) } } class SortByBitsComparatorSolutionTest : SortByBitsTest<SortByBits>(SortByBitsStrategy.ComparatorSolution) class SortByBitsBitManipulationTest : SortByBitsTest<SortByBits>(SortByBitsStrategy.BitManipulation) class SortByBitsBrianKerninghansAlgorithmTest : SortByBitsTest<SortByBits>(SortByBitsStrategy.BrianKerninghansAlgorithm)
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,154
kotlab
Apache License 2.0
src/day04/Day04.kt
shiddarthbista
572,833,784
false
{"Kotlin": 9985}
package day04 import readInput fun main() { fun addToList(elf: String, roomList: MutableList<Int>) { for (i in elf.substringBefore("-").toInt()..elf.substringAfter("-").toInt()) { roomList.add(i) } } fun getElfRoomList(roomInfo: String): Pair<MutableList<Int>, MutableList<Int>> { val firstElf = roomInfo.substringBefore(",") val secondElf = roomInfo.substringAfter(",") val firstElfRoomList = mutableListOf<Int>() val secondElfRoomList = mutableListOf<Int>() addToList(firstElf, firstElfRoomList) addToList(secondElf, secondElfRoomList) return Pair(firstElfRoomList, secondElfRoomList) } fun part1(input: List<String>): Int { return input.count { val (firstElfRoomList, secondElfRoomList) = getElfRoomList(it) firstElfRoomList.containsAll(secondElfRoomList) || secondElfRoomList.containsAll(firstElfRoomList) } } fun part2(input: List<String>): Int { return input.count { it -> val (firstElfRoomList, secondElfRoomList) = getElfRoomList(it) firstElfRoomList.any { it in secondElfRoomList } } } val testInput = readInput("Day04_test") val input = readInput("Day04") check(part1(testInput) == 2) check(part2(testInput) == 4) println(part1(testInput)) println(part2(testInput)) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
ed1b6a132e201e98ab46c8df67d4e9dd074801fe
1,458
aoc-2022-kotlin
Apache License 2.0
src/main/kotlin/com/hj/leetcode/kotlin/problem59/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem59 /** * LeetCode page: [59. Spiral Matrix II](https://leetcode.com/problems/spiral-matrix-ii/); */ class Solution { /* Complexity: * Time O(n^2) and Auxiliary Space O(1); */ fun generateMatrix(n: Int): Array<IntArray> { val result = Array(n) { IntArray(n) } var currentValue = 1 result.spiralTraversal { row, column -> result[row][column] = currentValue currentValue++ } return result } private tailrec fun Array<IntArray>.spiralTraversal( fromLayer: Int = 0, atEachPosition: (row: Int, column: Int) -> Unit ) { require(fromLayer >= 0) // Check if the traversal is ended if (fromLayer > lastSpiralLayer()) { return } // Traverse the fromLayer spiralTraversalAt(fromLayer, atEachPosition) // Recursive call for the next layer spiralTraversal(fromLayer + 1, atEachPosition) } private fun Array<IntArray>.lastSpiralLayer(): Int { val indexLastRow = this.lastIndex val indexLastColumn = this[0].lastIndex val minLastIndex = minOf(indexLastRow, indexLastColumn) return minLastIndex / 2 } private fun Array<IntArray>.spiralTraversalAt( layer: Int, atEachPosition: (row: Int, column: Int) -> Unit ) { require(layer >= 0) val indexLastRow = this.lastIndex val indexLastColumn = this[0].lastIndex val top = layer val bottom = indexLastRow - layer val left = layer val right = indexLastColumn - layer check(top <= bottom) check(left <= right) // Traverse the top row for (column in left..right) { atEachPosition(top, column) } // Traverse the right column, except its first and last elements for (row in top + 1 until bottom) { atEachPosition(row, right) } // If bottom and top are different, traverse the bottom row in reversed order if (bottom != top) { for (column in right downTo left) { atEachPosition(bottom, column) } } /* If left and right are different, traverse the left column in reversed order, * except its first and last elements. */ if (left != right) { for (row in bottom - 1 downTo top + 1) { atEachPosition(row, left) } } } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
2,535
hj-leetcode-kotlin
Apache License 2.0
src/Day01.kt
marosseleng
573,498,695
false
{"Kotlin": 32754}
fun main() { fun part1(input: List<String>): Long { var currentMax = 0L var intermediateMax = 0L for (line in input) { if (line.isBlank()) { if (intermediateMax > currentMax) { currentMax = intermediateMax } intermediateMax = 0 } else { intermediateMax += line.toLong() } } return currentMax } fun part2(input: List<String>): Long { var first = 0L var second = 0L var third = 0L fun applyValue(value: Long) { if (value > first) { val oldFirst = first first = value applyValue(oldFirst) } else if (value > second) { val oldSecond = second second = value applyValue(oldSecond) } else if (value > third) { val oldThird = third third = value applyValue(oldThird) } } var intermediateMax = 0L for (line in input) { if (line.isBlank()) { applyValue(intermediateMax) intermediateMax = 0 } else { intermediateMax += line.toLong() } } return first+second+third } // test if implementation meets criteria from the description, like: // val testInput = readInput("Day01_test") // check(part1(testInput) == 1) val input = readInput("Day01") // println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
f13773d349b65ae2305029017490405ed5111814
1,635
advent-of-code-2022-kotlin
Apache License 2.0
leetcode2/src/leetcode/ValidAnagram.kt
hewking
68,515,222
false
null
package leetcode import java.util.* /** *242. 有效的字母异位词 * https://leetcode-cn.com/problems/valid-anagram/ * Created by test * Date 2019/6/4 1:06 * Description * 给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。 示例 1: 输入: s = "anagram", t = "nagaram" 输出: true 示例 2: 输入: s = "rat", t = "car" 输出: false 说明: 你可以假设字符串只包含小写字母。 进阶: 如果输入字符串包含 unicode 字符怎么办?你能否调整你的解法来应对这种情况? */ object ValidAnagram{ @JvmStatic fun main(args : Array<String>) { println(Solution().isAnagram2("anagram","nagaram")) } class Solution { /** * 思路 * 1.遍历s的char * 2.遍历过程中查找与t的char相等,如果相等 * 交换t对应s中的char并且和s遍历的i位置交换 * O(N2) */ fun isAnagram(s: String, t: String): Boolean { if (s.length != t.length) return false if (s == t) return true var flag = false val sa = s.toCharArray() val ta = t.toCharArray() for (i in sa.indices) { flag = false for (j in i until ta.size) { if (sa[i] == ta[j]) { val tmp = ta[j] ta[j] = ta[i] ta[i] = tmp flag = true break } } if (flag) { } else { return false } } return flag } /** * 对s,t进行排序,然后比较是偶相等 */ fun isAnagram2(s: String, t: String): Boolean { if (s.length != t.length) return false if (s == t) return true val sa = s.toCharArray() val ta = t.toCharArray() sa.sort() ta.sort() return Arrays.equals(sa,ta) } } }
0
Kotlin
0
0
a00a7aeff74e6beb67483d9a8ece9c1deae0267d
2,134
leetcode
MIT License
advent/src/test/kotlin/org/elwaxoro/advent/y2015/Dec03.kt
elwaxoro
328,044,882
false
{"Kotlin": 376774}
package org.elwaxoro.advent.y2015 import org.elwaxoro.advent.Coord import org.elwaxoro.advent.Dir import org.elwaxoro.advent.PuzzleDayTester /** * https://adventofcode.com/2015/day/3 * part 1: 2081 * part 2: 2341 */ class Dec03 : PuzzleDayTester(3, 2015) { data class Santa(val visits: List<Coord> = listOf(Coord(0, 0))) { fun visit(dir: Dir): Santa = Santa(visits + visits.last().move(dir)) } override fun part1(): Any = parse().fold(Santa()) { santa, dir -> santa.visit(dir) }.visits.distinct().count() // TWO SANTAAAAS? override fun part2(): Any = parse().foldIndexed(Pair(Santa(), Santa())) { idx, santas, dir -> if (idx % 2 == 0) { // santa moves Pair(santas.first.visit(dir), santas.second) } else { // robo santa moves Pair(santas.first, santas.second.visit(dir)) } }.let { listOf(it.first.visits, it.second.visits).flatten() }.distinct().count() private fun parse(): List<Dir> = load(delimiter = "").mapNotNull { when (it) { "^" -> Dir.N "v" -> Dir.S ">" -> Dir.E "<" -> Dir.W else -> null } } }
0
Kotlin
4
0
1718f2d675f637b97c54631cb869165167bc713c
1,214
advent-of-code
MIT License
src/Day01.kt
JohannesPtaszyk
573,129,811
false
{"Kotlin": 20483}
fun main() { fun getElvesCalories(input: List<String>) = input.fold(mutableListOf()) { elves: MutableList<Int>, s: String -> elves.apply { when { isEmpty() || s.isBlank() -> add(0) s.isNotBlank() -> this[lastIndex] += s.toInt() } } } fun part1(input: List<String>): Int { return getElvesCalories(input).max() } fun part2(input: List<String>): Int { return getElvesCalories(input).sortedDescending().take(3).sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 4) check(part2(testInput) == 9) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
6f6209cacaf93230bfb55df5d91cf92305e8cd26
840
advent-of-code-2022
Apache License 2.0
kotlin/src/katas/kotlin/leetcode/prison_cells/PrisonCells.kt
dkandalov
2,517,870
false
{"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221}
package katas.kotlin.leetcode.prison_cells import datsok.shouldEqual import org.junit.Test class PrisonCellsTests { @Test fun examples() { prisonAfterNDays(intArrayOf(0, 1, 0, 1, 1, 0, 0, 1), days = 0) shouldEqual intArrayOf(0, 1, 0, 1, 1, 0, 0, 1) prisonAfterNDays(intArrayOf(0, 1, 0, 1, 1, 0, 0, 1), days = 1) shouldEqual intArrayOf(0, 1, 1, 0, 0, 0, 0, 0) prisonAfterNDays(intArrayOf(0, 1, 0, 1, 1, 0, 0, 1), days = 2) shouldEqual intArrayOf(0, 0, 0, 0, 1, 1, 1, 0) prisonAfterNDays(intArrayOf(0, 1, 0, 1, 1, 0, 0, 1), days = 3) shouldEqual intArrayOf(0, 1, 1, 0, 0, 1, 0, 0) prisonAfterNDays(intArrayOf(0, 1, 0, 1, 1, 0, 0, 1), days = 4) shouldEqual intArrayOf(0, 0, 0, 0, 0, 1, 0, 0) prisonAfterNDays(intArrayOf(0, 1, 0, 1, 1, 0, 0, 1), days = 5) shouldEqual intArrayOf(0, 1, 1, 1, 0, 1, 0, 0) prisonAfterNDays(intArrayOf(0, 1, 0, 1, 1, 0, 0, 1), days = 6) shouldEqual intArrayOf(0, 0, 1, 0, 1, 1, 0, 0) prisonAfterNDays(intArrayOf(0, 1, 0, 1, 1, 0, 0, 1), days = 7) shouldEqual intArrayOf(0, 0, 1, 1, 0, 0, 0, 0) } @Test fun `cells after many days`() { prisonAfterNDays(intArrayOf(0, 1, 0, 1, 1, 0, 0, 1), days = 1_000_000_000) } } private fun prisonAfterNDays(cells: IntArray, days: Int): IntArray { return prisonAfterNDays(cells.toInt(), days).toIntArray() } private fun prisonAfterNDays(cells: Int, days: Int): Int { if (days == 0) return cells var dayCount = days var oldCells = cells var newCells = 0 while (dayCount-- > 0) { newCells = 0 if (oldCells.and(128) == oldCells.and(32).shl(2)) newCells = newCells.or(64) if (oldCells.and(64) == oldCells.and(16).shl(2)) newCells = newCells.or(32) if (oldCells.and(32) == oldCells.and(8).shl(2)) newCells = newCells.or(16) if (oldCells.and(16) == oldCells.and(4).shl(2)) newCells = newCells.or(8) if (oldCells.and(8) == oldCells.and(2).shl(2)) newCells = newCells.or(4) if (oldCells.and(4) == oldCells.and(1).shl(2)) newCells = newCells.or(2) oldCells = newCells } return newCells } private tailrec fun prisonAfterNDays_(cells: IntArray, days: Int): IntArray { if (days == 0) return cells val newCells = IntArray(8) { i -> when { i == 0 || i == 7 -> 0 cells[i - 1] == cells[i + 1] -> 1 else -> 0 } } return prisonAfterNDays_(newCells, days - 1) } private fun IntArray.toInt(): Int { return 0 .or(this[0]).shl(1) .or(this[1]).shl(1) .or(this[2]).shl(1) .or(this[3]).shl(1) .or(this[4]).shl(1) .or(this[5]).shl(1) .or(this[6]).shl(1) .or(this[7]) } private fun Int.toIntArray(): IntArray { return intArrayOf( and(128).shr(7), and(64).shr(6), and(32).shr(5), and(16).shr(4), and(8).shr(3), and(4).shr(2), and(2).shr(1), and(1) ) } class IntToIntArrayConversions { @Test fun `IntArray to Int`() { intArrayOf(0, 0, 0, 0, 0, 0, 0, 1).toInt() shouldEqual 1 intArrayOf(0, 0, 0, 0, 0, 0, 1, 0).toInt() shouldEqual 2 intArrayOf(0, 0, 0, 0, 0, 0, 1, 1).toInt() shouldEqual 3 intArrayOf(0, 0, 0, 0, 0, 1, 0, 0).toInt() shouldEqual 4 intArrayOf(0, 0, 0, 0, 1, 0, 0, 0).toInt() shouldEqual 8 intArrayOf(1, 0, 0, 0, 0, 0, 0, 1).toInt() shouldEqual 129 } @Test fun `Int to IntArray`() { 1.toIntArray() shouldEqual intArrayOf(0, 0, 0, 0, 0, 0, 0, 1) 2.toIntArray() shouldEqual intArrayOf(0, 0, 0, 0, 0, 0, 1, 0) 3.toIntArray() shouldEqual intArrayOf(0, 0, 0, 0, 0, 0, 1, 1) 4.toIntArray() shouldEqual intArrayOf(0, 0, 0, 0, 0, 1, 0, 0) 8.toIntArray() shouldEqual intArrayOf(0, 0, 0, 0, 1, 0, 0, 0) 129.toIntArray() shouldEqual intArrayOf(1, 0, 0, 0, 0, 0, 0, 1) } }
7
Roff
3
5
0f169804fae2984b1a78fc25da2d7157a8c7a7be
3,955
katas
The Unlicense
kotlin_from_scratch_solution/src/main/kotlin/ScheduleEntities.kt
thomasnield
106,970,692
false
null
import java.time.LocalDateTime /** A discrete, 15-minute chunk of time a class can be scheduled on */ data class Block(val range: ClosedRange<LocalDateTime>) { val timeRange = range.start.toLocalTime()..range.endInclusive.toLocalTime() /** indicates if this block is zeroed due to operating day/break constraints */ val withinOperatingDay get() = breaks.all { timeRange.start !in it } && timeRange.start in operatingDay && timeRange.endInclusive in operatingDay val affectingSlots by lazy { ScheduledClass.all.asSequence() .flatMap { it.affectingSlotsFor(this).asSequence() }.toSet() } companion object { /* All operating blocks for the entire week, broken up in 15 minute increments */ val all by lazy { generateSequence(operatingDates.start.atStartOfDay()) { dt -> dt.plusMinutes(15).takeIf { it.plusMinutes(15) <= operatingDates.endInclusive.atTime(23,59) } }.map { Block(it..it.plusMinutes(15)) } .toList() } /* only returns blocks within the operating times */ val allInOperatingDay by lazy { all.filter { it.withinOperatingDay } } } } data class ScheduledClass(val id: Int, val name: String, val hoursLength: Double, val recurrences: Int, val recurrenceGapDays: Int = 2) { /** the # of slots between each recurrence */ val gap = recurrenceGapDays * 24 * 4 /** the # of slots needed for a given occurrence */ val slotsNeededPerSession = (hoursLength * 4).toInt() /** yields slots for this given scheduled class */ val slots by lazy { Slot.all.asSequence().filter { it.scheduledClass == this }.toList() } /** yields slot groups for this scheduled class */ val recurrenceSlots by lazy { slots.affectedWindows(slotsNeeded = slotsNeededPerSession, gap = gap, recurrences = recurrences, mode = RecurrenceMode.FULL_ONLY).toList() } /** yields slots that affect the given block for this scheduled class */ fun affectingSlotsFor(block: Block) = recurrenceSlots.asSequence() .filter { blk -> blk.flatMap { it }.any { it.block == block } } .map { it.first().first() } /** These slots should be fixed to zero **/ val slotsFixedToZero by lazy { // broken recurrences slots.affectedWindows(slotsNeeded = slotsNeededPerSession, gap = gap, recurrences = recurrences, mode = RecurrenceMode.PARTIAL_ONLY ) .flatMap { it.asSequence() } .flatMap { it.asSequence() } // operating day breaks // affected slots that cross into non-operating day .plus( recurrenceSlots.asSequence() .flatMap { it.asSequence() } .filter { slot -> slot.any { !it.block.withinOperatingDay }} .map { it.first() } ) .distinct() .onEach { it.selected = 0 } .toList() } /** translates and returns the optimized start time of the class */ val start get() = slots.asSequence().filter { it.selected == 1 }.map { it.block.range.start }.min()!! /** translates and returns the optimized end time of the class */ val end get() = start.plusMinutes((hoursLength * 60.0).toLong()) /** returns the DayOfWeeks where recurrences take place */ val daysOfWeek get() = (0..(recurrences-1)).asSequence().map { start.dayOfWeek.plus(it.toLong() * recurrenceGapDays) }.sorted() companion object { val all by lazy { scheduledClasses } } } data class Slot(val block: Block, val scheduledClass: ScheduledClass) { var selected: Int? = null companion object { val all by lazy { Block.all.asSequence().flatMap { b -> ScheduledClass.all.asSequence().map { Slot(b,it) } }.toList() } } } enum class RecurrenceMode { PARTIAL_ONLY, FULL_ONLY, ALL } fun <T> List<T>.affectedWindows(slotsNeeded: Int, gap: Int, recurrences: Int, mode: RecurrenceMode = RecurrenceMode.FULL_ONLY) = (0..size).asSequence().map { i -> (1..recurrences).asSequence().map { (it - 1) * gap } .filter { it + i < size } .map { r -> subList(i + r, (i + r + slotsNeeded).let { if (it > size) size else it }) } .toList() }.filter { when (mode) { RecurrenceMode.ALL -> true RecurrenceMode.FULL_ONLY -> it.size == recurrences && it.all { it.size == slotsNeeded } RecurrenceMode.PARTIAL_ONLY -> it.size < recurrences || it.any { it.size < slotsNeeded } } } fun main(args: Array<String>) { (1..20).toList() .affectedWindows(slotsNeeded = 4, gap = 6, recurrences = 3, mode = RecurrenceMode.PARTIAL_ONLY ) .forEach { println(it) } }
3
Kotlin
7
37
e59e8c5a15fcc7e7baafbd31fc264da7f057b0e5
5,348
classroom-scheduling-demo
Apache License 2.0
src/iii_conventions/MyDate.kt
kacperkr90
92,478,724
false
{"Kotlin": 80910, "Java": 4315}
package iii_conventions data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int) : Comparable<MyDate> { override fun compareTo(other: MyDate): Int { return this.days().compareTo(other.days()) } } operator fun MyDate.rangeTo(other: MyDate): DateRange = DateRange(this, other) operator fun MyDate.inc(): MyDate { return this.nextDay() } operator fun MyDate.plus(interval: TimeInterval): MyDate = when (interval) { TimeInterval.DAY -> this.nextDay() TimeInterval.WEEK -> this.addTimeIntervals(TimeInterval.WEEK, 1) TimeInterval.YEAR -> this.addTimeIntervals(TimeInterval.YEAR, 1) } operator fun MyDate.plus(multipliedTimeInterval: MultipliedTimeInterval): MyDate = this.addTimeIntervals(multipliedTimeInterval.interval, multipliedTimeInterval.multiplier) class MultipliedTimeInterval(val interval: TimeInterval, val multiplier: Int) fun MyDate.days(): Int { return year * 365 + month * 31 + dayOfMonth } enum class TimeInterval { DAY, WEEK, YEAR } operator fun TimeInterval.times(multiplier: Int) : MultipliedTimeInterval = MultipliedTimeInterval(this, multiplier) class DateRange(val start: MyDate, val endInclusive: MyDate) : Iterable<MyDate> { override fun iterator(): Iterator<MyDate> { return object : Iterator<MyDate> { var currentDate: MyDate = start override fun next(): MyDate { return currentDate++ } override fun hasNext(): Boolean { return currentDate <= endInclusive } } } } operator fun DateRange.contains(other: MyDate): Boolean = start < other && other <= endInclusive
0
Kotlin
0
0
1bca2dfb13df09c97d917bfc6e69724f64b24b15
1,738
kotlin-tutorial
MIT License
src/cn/leetcode/codes/simple628/Simple628.kt
shishoufengwise1234
258,793,407
false
{"Java": 771296, "Kotlin": 68641}
package cn.leetcode.codes.simple628 import cn.leetcode.codes.out import java.util.* import kotlin.math.max fun main() { // val nums = intArrayOf(1,2,3) // val nums = intArrayOf(1,2,3,4) // val nums = intArrayOf(-1,-2,-3) val nums = intArrayOf(-100,-98,-1,2,3,4) out(maximumProduct(nums)) } /* 628. 三个数的最大乘积 给定一个整型数组,在数组中找出由三个数组成的最大乘积,并输出这个乘积。 示例 1: 输入: [1,2,3] 输出: 6 示例 2: 输入: [1,2,3,4] 输出: 24 注意: 给定的整型数组长度范围是[3,104],数组中所有的元素范围是[-1000, 1000]。 输入的数组中任意三个数的乘积不会超出32位有符号整数的范围。 */ fun maximumProduct(nums: IntArray): Int { if (nums.size < 3){ return 0 } Arrays.sort(nums) val size = nums.size return max(nums[0] * nums[1] * nums[size - 1],nums[size - 3] * nums[size - 2] * nums[size - 1]) }
0
Java
0
0
f917a262bcfae8cd973be83c427944deb5352575
965
LeetCodeSimple
Apache License 2.0
src/main/kotlin/year_2023/Day05.kt
krllus
572,617,904
false
{"Kotlin": 97314}
package year_2023 import Day import solve import year_2022.Command import year_2022.toCommand class Day05 : Day(day = 5, year = 2023, "If You Give A Seed A Fertilizer") { private val groups by lazy { inputAsString.split("\n\n") } private fun getSeeds(): List<Seed> { return groups.first() .split(": ").last() .split(" ").map { it.toSeed() } } private fun getSeedToSoil(): List<Coordinate> { return groups[1].split("\n") .drop(1) .toCoordinates() } private fun getSoilToFertilizer(): List<Coordinate> { return groups[2].split("\n") .drop(1) .toCoordinates() } private fun getFertilizerToWater(): List<Coordinate> { return groups[3].split("\n") .drop(1) .toCoordinates() } private fun getWaterToLight(): List<Coordinate> { return groups[4].split("\n") .drop(1) .toCoordinates() } private fun getLightToTemperature(): List<Coordinate> { return groups[5].split("\n") .drop(1) .toCoordinates() } private fun getTemperatureToHumidity(): List<Coordinate> { return groups[6].split("\n") .drop(1) .toCoordinates() } private fun getHumidityToLocation(): List<Coordinate> { return groups[7].split("\n") .drop(1) .toCoordinates() } override fun part1(): Int { val seedToLocation = mutableMapOf<Seed, Coordinate>() val seeds = getSeeds() val seedToSoil = getSeedToSoil() val soilToFertilizer = getSoilToFertilizer() val fertilizerToWater = getFertilizerToWater() val waterToLight = getWaterToLight() val lightToTemperature = getLightToTemperature() val temperatureToHumidity = getTemperatureToHumidity() val humidityToLocation = getHumidityToLocation() for(seed in seeds){ // val location = navigate() } return 0 } override fun part2(): Int { return 0 } } private typealias Seed = Long private typealias CoordinateAxis = Long private typealias CoordinateRange = LongRange fun List<String>.toCoordinates(): List<Coordinate> { return this.map { it.toCoordinate() } } fun String.toCoordinate(): Coordinate { val axis = this.split(" ").map { it.toCoordinateAxis() } return Coordinate( destination = axis[0], source = axis[1], length = axis[2] ) } data class Coordinate( val destinationRange: CoordinateRange, val sourceRange: CoordinateRange ) { constructor( destination: CoordinateAxis, source: CoordinateAxis, length: CoordinateAxis ) : this( destinationRange = CoordinateRange(start = destination, endInclusive = destination + length), sourceRange = CoordinateRange(start = source, endInclusive = source + length) ) } fun String.toSeed(): Seed { return this.toLong() } fun String.toCoordinateAxis(): CoordinateAxis { return this.toLong() } fun main() { solve<Day05>(offerSubmit = true) { """ seeds: 79 14 55 13 seed-to-soil map: 50 98 2 52 50 48 soil-to-fertilizer map: 0 15 37 37 52 2 39 0 15 fertilizer-to-water map: 49 53 8 0 11 42 42 0 7 57 7 4 water-to-light map: 88 18 7 18 25 70 light-to-temperature map: 45 77 23 81 45 19 68 64 13 temperature-to-humidity map: 0 69 1 1 0 69 humidity-to-location map: 60 56 37 56 93 4 """.trimIndent()(part1 = 35) } }
0
Kotlin
0
0
b5280f3592ba3a0fbe04da72d4b77fcc9754597e
3,872
advent-of-code
Apache License 2.0
app/src/main/kotlin/leetcode/0724_Find-Pivot-Index/FindPivotIndex.kt
chanphy
527,447,921
false
{"Kotlin": 13667}
package leetcode.`0724_Find-Pivot-Index` /** Given an array of integers nums, calculate the pivot index of this array. The pivot index is the index where the sum of all the numbers strictly to the left of the index is equal to the sum of all the numbers strictly to the index's right. If the index is on the left edge of the array, then the left sum is 0 because there are no elements to the left. This also applies to the right edge of the array. Return the leftmost pivot index. If no such index exists, return -1. Example 1: Input: nums = [1,7,3,6,5,6] Output: 3 Explanation: The pivot index is 3. Left sum = nums[0] + nums[1] + nums[2] = 1 + 7 + 3 = 11 Right sum = nums[4] + nums[5] = 5 + 6 = 11 Example 2: Input: nums = [1,2,3] Output: -1 Explanation: There is no index that satisfies the conditions in the problem statement. Example 3: Input: nums = [2,1,-1] Output: 0 Explanation: The pivot index is 0. Left sum = 0 (no elements to the left of index 0) Right sum = nums[1] + nums[2] = 1 + -1 = 0 Constraints: 1 <= nums.length <= 10⁴ -1000 <= nums[i] <= 1000 Note: This question is the same as 1991: https://leetcode.com/problems/find- the-middle-index-in-array/ Related Topics Array Prefix Sum 👍 4619 👎 499 */ class FindPivotIndex { companion object { fun pivotIndex(nums: IntArray): Int { var index = -1 val sum = nums.sum() var leftSum = 0 for (i in nums.indices) { if (leftSum *2== (sum - nums[i])){ return i } leftSum += nums[i] } return index } } }
0
Kotlin
0
0
3c1c49e0e6ab6e703dd123f942870c2c9801ee60
1,658
Algo-Kotlin
MIT License
utils/src/main/kotlin/de/skyrising/aoc/calc.kt
skyrising
317,830,992
false
{"Kotlin": 411565}
package de.skyrising.aoc import org.apache.commons.math3.util.ArithmeticUtils.gcd import kotlin.math.max infix fun Long.over(other: Long) = LongFraction(this, other).reduce() data class LongFraction(val numerator: Long, val denominator: Long) { init { require(denominator != 0L) } constructor(value: Long) : this(value, 1) operator fun plus(other: LongFraction): LongFraction { return numerator * other.denominator + other.numerator * denominator over denominator * other.denominator } operator fun minus(other: LongFraction): LongFraction { return numerator * other.denominator - other.numerator * denominator over denominator * other.denominator } operator fun times(other: LongFraction): LongFraction { return numerator * other.numerator over denominator * other.denominator } operator fun div(other: LongFraction): LongFraction { if (denominator == other.denominator) return numerator over other.numerator return numerator * other.denominator over denominator * other.numerator } operator fun unaryMinus(): LongFraction { return -numerator over denominator } operator fun compareTo(other: LongFraction): Int { return (numerator * other.denominator).compareTo(other.numerator * denominator) } override fun toString(): String { return if (denominator != 1L) "$numerator/$denominator" else "$numerator" } fun equals(value: Long) = denominator == 1L && numerator == value fun reduce(): LongFraction { val gcd = gcd(numerator, denominator) if (gcd == 1L) return this return numerator / gcd over denominator / gcd } } data class LongPolynomial(val coefficients: Array<LongFraction>) { constructor(constant: Long) : this(arrayOf(LongFraction(constant))) constructor(constant: LongFraction) : this(arrayOf(constant)) fun eval(x: LongFraction): LongFraction { var result = LongFraction(0) for (i in coefficients.indices) { result = result * x + coefficients[i] } return result } operator fun plus(other: LongPolynomial): LongPolynomial { val result = Array(max(coefficients.size, other.coefficients.size)) { LongFraction(0) } for (i in coefficients.indices) { result[i] += coefficients[i] } for (i in other.coefficients.indices) { result[i] += other.coefficients[i] } return LongPolynomial(result) } operator fun minus(other: LongPolynomial): LongPolynomial { val result = Array(max(coefficients.size, other.coefficients.size)) { LongFraction(0) } for (i in coefficients.indices) { result[i] += coefficients[i] } for (i in other.coefficients.indices) { result[i] -= other.coefficients[i] } return LongPolynomial(result) } operator fun times(other: LongPolynomial): LongPolynomial { val result = Array(coefficients.size + other.coefficients.size - 1) { LongFraction(0) } for (i in coefficients.indices) { for (j in other.coefficients.indices) { result[i + j] += coefficients[i] * other.coefficients[j] } } return LongPolynomial(result) } operator fun div(other: LongFraction): LongPolynomial { return LongPolynomial(coefficients.map { it / other }.toTypedArray()) } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as LongPolynomial if (!coefficients.contentDeepEquals(other.coefficients)) return false return true } override fun hashCode(): Int { return coefficients.contentDeepHashCode() } override fun toString(): String { return coefficients.indices.joinToString(" + ") { when (it) { 0 -> coefficients[it].toString() 1 -> if (coefficients[it].equals(1)) "x" else "${coefficients[it]}x" else -> if (coefficients[it].equals(1)) "x^$it" else "${coefficients[it]}x^$it" } } } fun rootNear(x: LongFraction): LongFraction? { when (coefficients.size) { 0 -> return null 1 -> return if (coefficients[0].equals(0)) x else null 2 -> { val a = coefficients[1] val b = coefficients[0] if (a.equals(0)) return if (b.equals(0)) x else null return -b / a } else -> TODO("Newton's method") } } companion object { val ZERO = LongPolynomial(0) val ONE = LongPolynomial(1) val X = LongPolynomial(arrayOf(LongFraction(0), LongFraction(1))) } }
0
Kotlin
0
0
19599c1204f6994226d31bce27d8f01440322f39
4,857
aoc
MIT License
src/main/kotlin/y2023/Day4.kt
juschmitt
725,529,913
false
{"Kotlin": 18866}
package y2023 import utils.Day import kotlin.math.pow class Day4 : Day(4, 2023, false) { override fun partOne(): Any { return inputList.mapToCards().calculatePointsPerCard().sum() } override fun partTwo(): Any { val cards = inputList.mapToCards() return IntArray(cards.size) { 1 }.apply { for (idx in cards.indices) { repeat(cards[idx].amountOfWinnings) { i -> this[idx + i + 1] += this[idx] } } }.sum() } } private fun List<String>.mapToCards(): List<Card> = map { line -> val (cardNum, tail) = line.split(": ") val (winningNums, myNums) = tail.split("|").map { it.mapToNumbers(" ") } Card(cardNum, myNums.intersect(winningNums.toSet()).size) } private fun List<Card>.calculatePointsPerCard(): List<Int> = map { card -> 2.0.pow(card.amountOfWinnings-1).toInt() } private fun String.mapToNumbers(splitter: String): List<Int> = trim().split(splitter).mapNotNull { it.toIntOrNull() } private data class Card( val cardNumber: String, val amountOfWinnings: Int )
0
Kotlin
0
0
b1db7b8e9f1037d4c16e6b733145da7ad807b40a
1,117
adventofcode
MIT License
src/Day01.kt
LukasAnda
572,878,230
false
{"Kotlin": 3190}
fun main() { check(getTopNLargestCalorieSum(readInput("Day01_test"), 1) == 24000L) check(getTopNLargestCalorieSum(readInput("Day01_test"), 3) == 45000L) println("Top 1 is: " + getTopNLargestCalorieSum(readInput("Day01"), 1)) println("Top 3 are: " + getTopNLargestCalorieSum(readInput("Day01"), 3)) } fun getTopNLargestCalorieSum(input: List<String>, n: Int): Long { val sum = input.fold(mutableListOf<MutableList<Long>>()) { list, item -> list.apply { if (item.isEmpty()) { add(mutableListOf()) } else if (this.isEmpty()) { add(mutableListOf(item.toLong())) } else { last().add(item.toLong()) } } }.map { it.sum() }.sortedDescending().take(n).sum() return sum }
0
Kotlin
0
0
20ccddd7b0517cbaf7590364333201e33bd5c0d6
806
AdventOfCode2022
Apache License 2.0
src/Day05.kt
anilkishore
573,688,256
false
{"Kotlin": 27023}
import java.util.* import java.util.regex.Pattern import kotlin.streams.toList fun main() { fun part1(input: List<String>, together: Boolean = false) { val (moves, colsExtra) = input.partition { it.startsWith("move") } val cols = colsExtra.dropLast(2).reversed() val n = (cols[0].length + 1) / 4 val stacks = Array<Stack<Char>>(n + 1) { Stack() } cols.forEach { it.chunkedSequence(4) .mapIndexed { i, s -> if (s[1] != ' ') stacks[i + 1].push(s[1]) }.toList() } val numPattern = Pattern.compile("\\d+") moves.forEach { val matcher = numPattern.matcher(it) val (cnt, from, to) = matcher.results().mapToInt { r -> r.group().toInt() }.toList() var fromStk = stacks[from] if (together) { fromStk = Stack() repeat(cnt) { fromStk.push(stacks[from].pop()) } } repeat(cnt) { stacks[to].push(fromStk.pop()) } } for (i in 1..n) print(if (stacks[i].isEmpty()) " " else stacks[i].peek()) println() } fun part2(input: List<String>) { part1(input, true) } val input = readInput("Day05") part1(input) part2(input) }
0
Kotlin
0
0
f8f989fa400c2fac42a5eb3b0aa99d0c01bc08a9
1,399
AOC-2022
Apache License 2.0
src/main/math/ModInt.kt
vamsi3
504,166,472
false
{"Kotlin": 10048}
package com.vamsi3.algorithm.math class ModInt private constructor( value: Long = 0, private val mod: Int, ) : Number() { private var value: Int = 0 init { this.value = (if (value !in -mod + 1..mod) value % mod else value).toInt() if (this.value < 0) this.value += mod } constructor(value: Number, mod: Int) : this(value.toLong(), mod) override fun toInt(): Int = value override fun toByte(): Byte = value.toByte() override fun toChar(): Char = value.toChar() override fun toShort(): Short = value.toShort() override fun toLong(): Long = value.toLong() override fun toFloat(): Float = value.toFloat() override fun toDouble(): Double = value.toDouble() operator fun unaryPlus() = this operator fun unaryMinus() = ModInt(-value, mod) operator fun inc() = this + 1 operator fun dec() = this - 1 operator fun plus(other: Number): ModInt = ModInt(value + other.toLong(), mod) operator fun minus(other: Number): ModInt = ModInt(value - other.toLong(), mod) operator fun times(other: Number): ModInt = ModInt(value * other.toLong(), mod) operator fun div(other: Number): ModInt = this * ModInt(other, mod).inverse val inverse: ModInt get() { var a1 = mod var a2 = value var v1 = 0 var v2 = 1 while (a2 != 0) { val q = a1 / a2 a1 -= q * a2 a1 = a2.also { a2 = a1 } v1 -= q * v2 v1 = v2.also { v2 = v1 } } return ModInt(v1, mod) } fun power(exponent: Int): ModInt = power(exponent.toLong()) fun power(exponent: Long): ModInt { var a = copy() var r = ModInt(1, mod) var b: Int = (exponent % (mod - 1)).toInt() while (b > 0) { if (b % 2 == 1) r *= a a *= a b /= 2 } return r } private fun copy(value: Number = this.value, mod: Int = this.mod) = ModInt(value, mod) } fun Number.toModInt(mod: Int) = ModInt(this, mod) operator fun Number.plus(other: ModInt) = other + this operator fun Number.minus(other: ModInt) = other - this operator fun Number.times(other: ModInt) = other * this operator fun Number.div(other: ModInt) = other / this
0
Kotlin
0
0
5eda4c454984866e00a5d26c73dfb6f2437017e7
2,320
algorithm-library
MIT License
src/main/kotlin/com/hj/leetcode/kotlin/problem1318/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem1318 /** * LeetCode page: [1318. Minimum Flips to Make a OR b Equal to c](https://leetcode.com/problems/minimum-flips-to-make-a-or-b-equal-to-c/); */ class Solution { /* Complexity: * Time O(LogN) and Space O(1) where N is the max of a, b and c; */ fun minFlips(a: Int, b: Int, c: Int): Int { // flipQueryTable[bit_a][bit_b][bit_c] ::= minimum required flips for that bit val flipQueryTable = Array(2) { Array(2) { IntArray(2) } }.apply { this[0][0][1] = 1 this[0][1][0] = 1 this[1][0][0] = 1 this[1][1][0] = 2 } var aWorking = a var bWorking = b var cWorking = c var maxWorking = maxOf(a, b, c) var result = 0 while (maxWorking != 0) { val aBit = aWorking and 1 val bBit = bWorking and 1 val cBit = cWorking and 1 result += flipQueryTable[aBit][bBit][cBit] aWorking = aWorking shr 1 bWorking = bWorking shr 1 cWorking = cWorking shr 1 maxWorking = maxWorking shr 1 } return result } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
1,183
hj-leetcode-kotlin
Apache License 2.0
kotlin/src/com/daily/algothrim/leetcode/MinWindow.kt
idisfkj
291,855,545
false
null
package com.daily.algothrim.leetcode /** * 76. 最小覆盖子串 * * 给你一个字符串 s 、一个字符串 t 。返回 s 中涵盖 t 所有字符的最小子串。如果 s 中不存在涵盖 t 所有字符的子串,则返回空字符串 "" 。 * * 注意:如果 s 中存在这样的子串,我们保证它是唯一的答案。 */ class MinWindow { companion object { @JvmStatic fun main(args: Array<String>) { println(MinWindow().minWindow("ADOBECODEBANC", "ABC")) } } // 输入:s = "ADOBECODEBANC", t = "ABC" // 输出:"BANC" fun minWindow(s: String, t: String): String { val tMap = hashMapOf<Char, Int>() val sMap = hashMapOf<Char, Int>() var fast = 0 var slow = 0 var l = -1 var r = -1 var minLen = Int.MAX_VALUE val len = s.length t.forEach { tMap[it] = tMap.getOrDefault(it, 0) + 1 } while (fast < len) { if (tMap.containsKey(s[fast])) { sMap[s[fast]] = sMap.getOrDefault(s[fast], 0) + 1 } while (check(tMap, sMap) && slow <= fast) { if (fast - slow + 1 < minLen) { minLen = fast - slow + 1 l = slow r = fast + 1 } if (tMap.containsKey(s[slow])) { sMap[s[slow]] = sMap.getOrDefault(s[slow], 0) - 1 } slow++ } fast++ } return if (l == -1) "" else s.substring(l, r) } private fun check(tMap: MutableMap<Char, Int>, sMap: MutableMap<Char, Int>): Boolean { tMap.iterator().forEach { if (sMap.getOrDefault(it.key, 0) < it.value) { return false } } return true } }
0
Kotlin
9
59
9de2b21d3bcd41cd03f0f7dd19136db93824a0fa
1,874
daily_algorithm
Apache License 2.0
src/day02/Code.kt
ldickmanns
572,675,185
false
{"Kotlin": 48227}
package day02 import readInput fun main() { val input = readInput("day02/input") println(part1(input)) println(part2(input)) } // A, X -> Rock, 1 // B, Y -> Paper, 2 // C, Z -> Scissors, 3 fun part1(input: List<String>): Int { var score = 0 input.forEach { score += when { "X" in it -> 1 "Y" in it -> 2 "Z" in it -> 3 else -> 0 } score += when(it) { "A X" -> 3 "A Y" -> 6 "B Y" -> 3 "B Z" -> 6 "C Z" -> 3 "C X" -> 6 else -> 0 } } return score } // A -> Rock, 1 // B -> Paper, 2 // C -> Scissors, 3 // X -> loose // Y -> draw // Z -> win fun part2(input: List<String>): Int { var score = 0 input.forEach { score += when { "X" in it -> 0 "Y" in it -> 3 "Z" in it -> 6 else -> 0 } score += when(it) { "A X" -> 3 "A Y" -> 1 "A Z" -> 2 "B X" -> 1 "B Y" -> 2 "B Z" -> 3 "C X" -> 2 "C Y" -> 3 "C Z" -> 1 else -> 0 } } return score }
0
Kotlin
0
0
2654ca36ee6e5442a4235868db8174a2b0ac2523
1,245
aoc-kotlin-2022
Apache License 2.0
src/main/kotlin/day9/EncryptedData.kt
lukasz-marek
317,632,409
false
{"Kotlin": 172913}
package day9 data class EncryptedData(val numbers: List<Long>, val preambleSize: Int) interface InvalidNumberFinder { fun findInvalidNumbers(encryptedData: EncryptedData): List<Long> } class InvalidNumberFinderImpl : InvalidNumberFinder { override fun findInvalidNumbers(encryptedData: EncryptedData): List<Long> { val preamble = with(encryptedData) { numbers.take(preambleSize) } val remainingMessage = with(encryptedData) { numbers.drop(preambleSize) } return scanForInvalidNumbers(preamble, remainingMessage, emptyList()) } private tailrec fun scanForInvalidNumbers( preamble: List<Long>, encryptedData: List<Long>, collected: List<Long> ): List<Long> { if (encryptedData.isEmpty()) { return collected } val testedNumber = encryptedData.first() val newCollected = if (testedNumber.isValidNumber(preamble)) collected else collected + testedNumber val newPreamble = preamble.drop(1) + testedNumber val newEncryptedData = encryptedData.drop(1) return scanForInvalidNumbers(newPreamble, newEncryptedData, newCollected) } private fun Long.isValidNumber(preamble: List<Long>): Boolean { val withIndex = preamble.withIndex().toList() return withIndex.asSequence() .map { indexed -> indexed to withIndex.filter { it.index != indexed.index } } .map { indexed -> indexed.first.value to indexed.second.map { it.value } } .any { pair -> val term = pair.first val terms = pair.second terms.any { term + it == this } } } } interface ContiguousSetFinder { fun findContiguousSet(sumEqualTo: Long, sequence: List<Long>): List<Long> } class ContiguousSetFinderImpl : ContiguousSetFinder { override fun findContiguousSet(sumEqualTo: Long, sequence: List<Long>): List<Long> { for (i in sequence.indices) { for (j in sequence.indices) { if (i < j) { val subset = sequence.subList(i, j + 1) if (subset.sum() == sumEqualTo) { return subset } } } } return emptyList() } }
0
Kotlin
0
0
a16e95841e9b8ff9156b54e74ace9ccf33e6f2a6
2,335
aoc2020
MIT License
codeforces/round626/c.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package codeforces.round626 import java.io.* private fun solve(): Long { val (n, m) = readInts() val c = readLongs() val nei = List(n) { mutableListOf<Int>() } repeat(m) { val (u, v) = readInts().map { it - 1 } nei[v].add(u) } val hashed = nei.map { it.sorted().fold(1L) { acc: Long, x: Int -> acc * 566239L + x } } val groups = hashed.indices.groupBy { hashed[it] }.map { if (it.key == 1L) 0L else it.value.map { i -> c[i] }.sum() } return groups.fold(0L, ::gcd) } private tailrec fun gcd(a: Long, b: Long): Long = if (a == 0L) b else gcd(b % a, a) fun main() = println(List(readInt()) { if (it > 0) readLn(); solve() }.joinToString("\n")) private val `in` = BufferedReader(InputStreamReader(System.`in`)) private fun readLn() = `in`.readLine() private fun readInt() = readLn().toInt() private fun readStrings() = readLn().split(" ") private fun readInts() = readStrings().map { it.toInt() } private fun readLongs() = readStrings().map { it.toLong() }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
973
competitions
The Unlicense
2015/src/main/kotlin/day3_func.kt
madisp
434,510,913
false
{"Kotlin": 388138}
import utils.Parser import utils.Solution import utils.Vec2i import utils.mapItems fun main() { Day3Func.run() } fun Char.toVec() = when (this) { '>' -> Vec2i(1, 0) '<' -> Vec2i(-1, 0) '^' -> Vec2i(0, -1) 'v' -> Vec2i(0, 1) else -> throw IllegalArgumentException("Unacceptable input char $this") } object Day3Func : Solution<List<Vec2i>>() { override val name = "day3" override val parser = Parser.chars.mapItems { it.toVec() } override fun part1(): Int { return getTrack(input).count() } override fun part2(): Number? { val (santa, roboSanta) = input.withIndex() .partition { value -> value.index % 2 == 0 } .toList() .map { list -> list.map { it.value } } return (getTrack(santa) + getTrack(roboSanta)).count() } private fun getTrack(input: List<Vec2i>) = input.runningFold(Vec2i(0, 0)) { location, vec -> location + vec } .toSet() }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
908
aoc_kotlin
MIT License
src/main/kotlin/problems/LongestConsecutiveArray.kt
amartya-maveriq
510,824,460
false
{"Kotlin": 42296}
package problems /** * Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence. * You must write an algorithm that runs in O(n) time. * * Input: nums = [100,4,200,1,3,2] * Output: 4 * Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4. */ object LongestConsecutiveArray { fun longestConsecutive(nums: IntArray): Int { var maxLength = 0 val set = nums.toHashSet() fun search(n: Int, len: Int = 0, greater: Boolean): Int { if (!set.contains(n)) { return len } set.remove(n) return if (greater) { search(n+1, len+1, true) } else { search(n-1, len+1, false) } } for (i in nums.indices) { if(set.contains(nums[i])) { maxLength = maxOf(maxLength, search(nums[i], greater=true) + search(nums[i]-1, greater=false)) } } return maxLength } }
0
Kotlin
0
0
2f12e7d7510516de9fbab866a59f7d00e603188b
1,062
data-structures
MIT License
app/src/main/kotlin/compiler/lexer/Lexer.kt
brzeczyk-compiler
545,707,939
false
{"Kotlin": 1167879, "C": 4004, "Shell": 3242, "Vim Script": 2238}
package compiler.lexer import compiler.dfa.AbstractDfa import compiler.dfa.isAccepting import compiler.diagnostics.Diagnostic import compiler.diagnostics.Diagnostics import compiler.input.Input import compiler.input.Location import compiler.input.LocationRange // Used to turn a sequence of characters into a sequence of tokens. // The DFAs given are used to recognize the corresponding token categories. // The priority of a DFA is given by its position in the list, with earlier positions having higher priority. class Lexer<TCat>( private val dfas: List<Pair<AbstractDfa<Char, Unit>, TCat>>, private val diagnostics: Diagnostics, private val contextErrorLength: Int = 3 ) { // Splits the given input into a sequence of tokens. // The input is read lazily as consecutive tokens are requested. // The matching is greedy - when multiple tokens match the input at a given location, the longest one is chosen. // Note that the complexity of this function is potentially quadratic if badly constructed DFAs are given. fun process(input: Input): Sequence<Token<TCat>> = sequence { var isErrorSegment = false var errorSegmentStart: Location? = null val errorSegment = StringBuilder() val context = ArrayDeque<String>(contextErrorLength) fun addToContext(content: String) { context.addLast(content) if (context.size > contextErrorLength) context.removeFirst() } while (input.hasNext()) { input.flush() // Tell the input source that previous characters can be discarded. val buffer = StringBuilder() // The content of a token currently attempted to be matched. val tokenStart = input.getLocation() // The start location of a token currently attempted to be matched. var tokenEnd: Location? = null // The end location of the last matched token, if any. var tokenCategory: TCat? = null // The category of the last matched token, if any. var excess = 0 // The number of characters added to the buffer after the last matched token, if any. val walks = dfas.map { it.first.newWalk() } while (input.hasNext() && walks.any { !it.isDead() }) { // Try to match as long a token as possible. val location = input.getLocation() val char = input.next() buffer.append(char) excess++ walks.forEach { it.step(char) } for ((index, walk) in walks.withIndex()) { if (walk.isAccepting()) { // Match a token with category corresponding to the first accepting DFA. if (isErrorSegment) { isErrorSegment = false diagnostics.report(Diagnostic.LexerError(errorSegmentStart!!, tokenStart, context.toList(), errorSegment.toString())) addToContext(errorSegment.toString()) errorSegment.clear() } tokenEnd = location tokenCategory = dfas[index].second excess = 0 break } } } input.rewind(excess) if (tokenEnd == null || tokenCategory == null) { if (!isErrorSegment) { isErrorSegment = true errorSegmentStart = tokenStart } errorSegment.append(input.next()) if (!input.hasNext()) { diagnostics.report(Diagnostic.LexerError(errorSegmentStart!!, null, context, errorSegment.toString())) } } else { val tokenContent = buffer.dropLast(excess).toString() addToContext(tokenContent) yield(Token(tokenCategory, tokenContent, LocationRange(tokenStart, tokenEnd))) } } } }
7
Kotlin
0
2
5917f4f9d0c13c2c87d02246da8ef8394499d33c
4,020
brzeczyk
MIT License
src/test/kotlin/aoc2018/day7/StepsTest.kt
arnab
75,525,311
false
null
package aoc2018.day7 import aoc.util.TestResourceReader import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test internal class StepsTest { @Test fun part1_StepOrder_Problem1() { val steps = parseData(TestResourceReader.readFile("aoc2018/day7/input.txt")) val stepsInOrder = Steps.calculateOrder(steps) Assertions.assertEquals("SCLPAMQVUWNHODRTGYKBJEFXZI", stepsInOrder.map(Step::id).joinToString("")) } @Test fun part1_StepOrder_Example1() { val steps = parseData(""" Step C must be finished before step A can begin. Step C must be finished before step F can begin. Step A must be finished before step B can begin. Step A must be finished before step D can begin. Step B must be finished before step E can begin. Step D must be finished before step E can begin. Step F must be finished before step E can begin. """.trimIndent()) val stepsInOrder = Steps.calculateOrder(steps) Assertions.assertEquals("CABDFE", stepsInOrder.map(Step::id).joinToString("")) } @Test fun part2_StepOrderByWorkers_Problem1() { val steps = parseData(TestResourceReader.readFile("aoc2018/day7/input.txt"), baseTimeTaken = 60) val (stepsInOrder, timeTaken) = Steps.calculateOrderWithWorkers(steps, numWorkers = 5) Assertions.assertEquals(1234, timeTaken) Assertions.assertEquals("SCLPAMQVWYNUHODTRGKBJEFXZI", stepsInOrder.map(Step::id).joinToString("")) } @Test fun part2_StepOrderByWorkers_Example1() { val steps = parseData(""" Step C must be finished before step A can begin. Step C must be finished before step F can begin. Step A must be finished before step B can begin. Step A must be finished before step D can begin. Step B must be finished before step E can begin. Step D must be finished before step E can begin. Step F must be finished before step E can begin. """.trimIndent(), baseTimeTaken = 0) val (stepsInOrder, timeTaken) = Steps.calculateOrderWithWorkers(steps, numWorkers = 2) Assertions.assertEquals("CABFDE", stepsInOrder.map(Step::id).joinToString("")) Assertions.assertEquals(15, timeTaken) } private fun parseData(data: String, baseTimeTaken: Int = 0): List<Pair<Step, Step>> { return data.split("\n") .filterNot(String::isEmpty) .map { parseDataLine(it, baseTimeTaken) } } // Matches: Step D must be finished before step E can begin. private val dataLineRegex = """Step (\w) must be finished before step (\w) can begin.""".toRegex() private fun parseDataLine(line: String, baseTimeTaken: Int): Pair<Step, Step> { val (stepOne, stepTwo) = dataLineRegex.find(line)!!.destructured return Pair(Step(stepOne, calculateTimeTaken(stepOne, baseTimeTaken)), Step(stepTwo, calculateTimeTaken(stepTwo, baseTimeTaken))) } private fun calculateTimeTaken(stepId: String, baseTimeTaken: Int): Int { return stepId.single().toInt() - ('A'.toInt() - 1) + baseTimeTaken } }
0
Kotlin
0
0
1d9f6bc569f361e37ccb461bd564efa3e1fccdbd
3,226
adventofcode
MIT License
src/main/kotlin/kr/co/programmers/P152995.kt
antop-dev
229,558,170
false
{"Kotlin": 695315, "Java": 213000}
package kr.co.programmers // https://github.com/antop-dev/algorithm/issues/486 class P152995 { fun solution(scores: Array<IntArray>): Int { var rank = 1 val me = scores[0] var maxScore = 0 // 근무태도 내림차순 정렬. // 근무태도 동점인 경우 동료평가 오름차순 정렬 scores.sortWith(Comparator { a, b -> if (a[0] == b[0]) a[1] - b[1] else b[0] - a[0] }) // 두 점수의 합이 다른 점수의 합보다 크다면 // 근무태도 또는 동료평가 둘 중 하나는 높다 for (score in scores) { if (score[1] < maxScore) { if (score.contentEquals(me)) { return -1 } } else { maxScore = maxOf(maxScore, score[1]) if (score[0] + score[1] > me[0] + me[1]) { rank++ } } } return rank } }
1
Kotlin
0
0
9a3e762af93b078a2abd0d97543123a06e327164
988
algorithm
MIT License
2020/day12/day12.kt
flwyd
426,866,266
false
{"Julia": 207516, "Elixir": 120623, "Raku": 119287, "Kotlin": 89230, "Go": 37074, "Shell": 24820, "Makefile": 16393, "sed": 2310, "Jsonnet": 1104, "HTML": 398}
/* * Copyright 2021 Google LLC * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ package day12 import java.lang.Math.floorMod import java.lang.Math.toDegrees import java.lang.Math.toRadians import kotlin.math.absoluteValue import kotlin.math.atan2 import kotlin.math.cos import kotlin.math.pow import kotlin.math.roundToInt import kotlin.math.sin import kotlin.math.sqrt import kotlin.time.ExperimentalTime import kotlin.time.TimeSource import kotlin.time.measureTimedValue /* Input: (operation)(number) instructions to move on a Cartesian grid. EWNS move in cardinal directions. LR rotate (always increments of 90). F moves in the current direction. */ operator fun Pair<Int, Int>.times(i: Int) = first * i to second * i operator fun Pair<Int, Int>.plus(p: Pair<Int, Int>) = first + p.first to second + p.second val Pair<Int, Int>.manhattanDistance get() = first.absoluteValue + second.absoluteValue val Pair<Int, Int>.crowDistance get() = sqrt(first.toDouble().pow(2) + second.toDouble().pow(2)) val pattern = Regex("""([NSEWLRF])(\d+)""") val headings = mapOf("E" to (+1 to 0), "W" to (-1 to 0), "N" to (0 to +1), "S" to (0 to -1)) /* Initial state: ship heading east. */ object Part1 { fun solve(input: Sequence<String>): String { val headingCycle = listOf("N", "W", "S", "E") // counterclockwise, like trig functions var heading = "E" var position = 0 to 0 input.map { pattern.matchEntire(it)!!.groups }.map { it[1]!!.value to it[2]!!.value.toInt() } .forEach { (op, value) -> when (op) { in headings -> position += headings.getValue(op) * value "F" -> position += headings.getValue(heading) * value "L", "R" -> { val factor = if (op == "R") -1 else 1 heading = with(headingCycle) { this[floorMod(indexOf(heading) + value * factor / 90, size)] } } else -> throw IllegalStateException("Unknown operation $op$value") } } return position.manhattanDistance.toString() } } /* Operations are relative to a waypoint. EWNS move the waypoint, F moves ship along waypoint vector and LR rotate the vector around the ship. */ object Part2 { fun solve(input: Sequence<String>): String { var waypoint = 10 to 1 // 10 east, 1 north var position = 0 to 0 input.map { pattern.matchEntire(it)!!.groups }.map { it[1]!!.value to it[2]!!.value.toInt() } .forEach { (op, value) -> when (op) { in headings -> waypoint += headings.getValue(op) * value "F" -> position += waypoint * value "L", "R" -> { val curAngle = toDegrees(atan2(waypoint.second.toDouble(), waypoint.first.toDouble())) val angle = toRadians((curAngle + value * (if (op == "R") -1 else 1)) % 360) val hypot = waypoint.crowDistance waypoint = (hypot * cos(angle)).roundToInt() to (hypot * sin(angle)).roundToInt() } else -> throw IllegalStateException("Unknown operation $op$value") } } return position.manhattanDistance.toString() } } @ExperimentalTime @Suppress("UNUSED_PARAMETER") fun main(args: Array<String>) { val lines = generateSequence(::readLine).toList() print("part1: ") TimeSource.Monotonic.measureTimedValue { Part1.solve(lines.asSequence()) }.let { println(it.value) System.err.println("Completed in ${it.duration}") } print("part2: ") TimeSource.Monotonic.measureTimedValue { Part2.solve(lines.asSequence()) }.let { println(it.value) System.err.println("Completed in ${it.duration}") } }
0
Julia
1
5
f2d6dbb67d41f8f2898dbbc6a98477d05473888f
3,703
adventofcode
MIT License
Retos/Reto #6 - PIEDRA, PAPEL, TIJERA, LAGARTO, SPOCK [Media]/kotlin/masdos.kt
mouredev
581,049,695
false
{"Python": 3866914, "JavaScript": 1514237, "Java": 1272062, "C#": 770734, "Kotlin": 533094, "TypeScript": 457043, "Rust": 356917, "PHP": 281430, "Go": 243918, "Jupyter Notebook": 221090, "Swift": 216751, "C": 210761, "C++": 164758, "Dart": 159755, "Ruby": 70259, "Perl": 52923, "VBScript": 49663, "HTML": 45912, "Raku": 44139, "Scala": 30892, "Shell": 27625, "R": 19771, "Lua": 16625, "COBOL": 15467, "PowerShell": 14611, "Common Lisp": 12715, "F#": 12710, "Pascal": 12673, "Haskell": 11051, "Assembly": 10368, "Elixir": 9033, "Visual Basic .NET": 7350, "Groovy": 7331, "PLpgSQL": 6742, "Clojure": 6227, "TSQL": 5744, "Zig": 5594, "Objective-C": 5413, "Apex": 4662, "ActionScript": 3778, "Batchfile": 3608, "OCaml": 3407, "Ada": 3349, "ABAP": 2631, "Erlang": 2460, "BASIC": 2340, "D": 2243, "Awk": 2203, "CoffeeScript": 2199, "Vim Script": 2158, "Brainfuck": 1550, "Prolog": 1342, "Crystal": 783, "Fortran": 778, "Solidity": 560, "Standard ML": 525, "Scheme": 457, "Vala": 454, "Limbo": 356, "xBase": 346, "Jasmin": 285, "Eiffel": 256, "GDScript": 252, "Witcher Script": 228, "Julia": 224, "MATLAB": 193, "Forth": 177, "Mercury": 175, "Befunge": 173, "Ballerina": 160, "Smalltalk": 130, "Modula-2": 129, "Rebol": 127, "NewLisp": 124, "Haxe": 112, "HolyC": 110, "GLSL": 106, "CWeb": 105, "AL": 102, "Fantom": 97, "Alloy": 93, "Cool": 93, "AppleScript": 85, "Ceylon": 81, "Idris": 80, "Dylan": 70, "Agda": 69, "Pony": 69, "Pawn": 65, "Elm": 61, "Red": 61, "Grace": 59, "Mathematica": 58, "Lasso": 57, "Genie": 42, "LOLCODE": 40, "Nim": 38, "V": 38, "Chapel": 34, "Ioke": 32, "Racket": 28, "LiveScript": 25, "Self": 24, "Hy": 22, "Arc": 21, "Nit": 21, "Boo": 19, "Tcl": 17, "Turing": 17}
/* * Crea un programa que calcule quien gana más partidas al juego piedra, papel, tijera, lagarto, * spock. * - El resultado puede ser: "Player 1", "Player 2", "Tie" (empate) * - La función recibe un listado que contiene pares, representando cada jugada. * - El par puede contener combinaciones de "🗿" (piedra), "📄" (papel), * "✂️" (tijera), "🦎" (lagarto) o "🖖" (spock). * - Ejemplo. Entrada: [("🗿","✂️"), ("✂️","🗿"), ("📄","✂️")]. Resultado: "Player 2". * - Debes buscar información sobre cómo se juega con estas 5 posibilidades. */ fun main() { val results2 = arrayOf( Round(Option.ROCK, Option.SCISSORS), Round(Option.SCISSORS, Option.ROCK), Round(Option.PAPER, Option.SCISSORS) ) val results1 = arrayOf( Round(Option.SPOCK, Option.ROCK), Round(Option.LIZARD, Option.SPOCK), Round(Option.ROCK, Option.LIZARD) ) val resultsTie = arrayOf( Round(Option.SPOCK, Option.ROCK), Round(Option.LIZARD, Option.SPOCK), Round(Option.ROCK, Option.SPOCK), Round(Option.SPOCK, Option.LIZARD) ) val game2 = Game(results2) game2.displayResult() val game1 = Game(results1) game1.displayResult() val gameTie = Game(resultsTie) gameTie.displayResult() } enum class Result(val value: String) { PLAYER1("Player 1"), PLAYER2("Player 2"), TIE("Tie"), } enum class Option(val value: String) { SCISSORS("✂️"), ROCK("🗿"), PAPER("📄"), LIZARD("🦎"), SPOCK("🖖") } data class Round(val player1: Option, val player2: Option) class Game(private val results: Array<Round>) { private fun calculateResult(): Result { var scorePlayer1 = 0 var scorePlayer2 = 0 results.forEach { when (whoWins(it.player1, it.player2)) { Result.PLAYER1 -> scorePlayer1++ Result.PLAYER2 -> scorePlayer2++ Result.TIE -> { scorePlayer1++ scorePlayer2++ } } } return when { scorePlayer1 > scorePlayer2 -> Result.PLAYER1 scorePlayer1 < scorePlayer2 -> Result.PLAYER2 else -> Result.TIE } } private fun whoWins(player1: Option, player2: Option): Result { if (player1 == player2) return Result.TIE val roll = "$player1$player2" val winningOption = when { """^(${Option.ROCK}${Option.SCISSORS}|${Option.SCISSORS}${Option.ROCK})$""" .toRegex() .matches(roll) -> Option.ROCK """^(${Option.ROCK}${Option.LIZARD}|${Option.LIZARD}${Option.ROCK})$""" .toRegex() .matches(roll) -> Option.ROCK """^(${Option.PAPER}${Option.SPOCK}|${Option.SPOCK}${Option.PAPER})$""" .toRegex() .matches(roll) -> Option.PAPER """^(${Option.PAPER}${Option.ROCK}|${Option.ROCK}${Option.PAPER})$""" .toRegex() .matches(roll) -> Option.PAPER """^(${Option.SCISSORS}${Option.PAPER}|${Option.PAPER}${Option.SCISSORS})$""" .toRegex() .matches(roll) -> Option.SCISSORS """^(${Option.SCISSORS}${Option.LIZARD}|${Option.LIZARD}${Option.SCISSORS})$""" .toRegex() .matches(roll) -> Option.SCISSORS """^(${Option.LIZARD}${Option.SPOCK}|${Option.SPOCK}${Option.LIZARD})$""" .toRegex() .matches(roll) -> Option.LIZARD """^(${Option.LIZARD}${Option.PAPER}|${Option.PAPER}${Option.LIZARD})$""" .toRegex() .matches(roll) -> Option.LIZARD """^(${Option.SPOCK}${Option.SCISSORS}|${Option.SCISSORS}${Option.SPOCK})$""" .toRegex() .matches(roll) -> Option.SPOCK else -> { Option.SPOCK } } return if (winningOption == player1) Result.PLAYER1 else Result.PLAYER2 } fun displayResult() { println(calculateResult().value) } }
4
Python
2,929
4,661
adcec568ef7944fae3dcbb40c79dbfb8ef1f633c
3,841
retos-programacion-2023
Apache License 2.0
src/main/kotlin/shared.kt
reitzig
318,492,753
false
null
import kotlin.math.absoluteValue data class Either<T, U>(val t: T? = null, val u: U? = null) { init { assert((t == null) != (u == null)) { "Exactly one parameter must be null" } } override fun toString(): String = "${t ?: ""}${u ?: ""}" } fun <T> List<T>.split(splitEntry: T): List<List<T>> = this.fold(mutableListOf(mutableListOf<T>())) { acc, line -> if (line == splitEntry) { acc.add(mutableListOf()) } else { acc.last().add(line) } return@fold acc } fun <T> List<T>.replace(index: Int, newElement: T): List<T> = mapIndexed { i, elem -> if (i == index) { newElement } else { elem } } fun <T> List<T>.replace(index: Int, replacer: (T) -> T): List<T> = mapIndexed { i, elem -> if (i == index) { replacer(elem) } else { elem } } fun <T> List<List<T>>.replace(index: Pair<Int, Int>, newElement: T): List<List<T>> = replace(index.first) { it.replace(index.second, newElement) } fun <T> (MutableList<T>).removeAllAt(indices: IntRange): List<T> { val result = this.subList(indices.first, indices.last + 1).toList() indices.forEach { _ -> removeAt(indices.first) } return result } fun <T> (MutableList<T>).rotateLeft(by: Int) { for (i in 1..(by % size)) { add(removeAt(0)) } } fun <T, U> List<T>.combinationsWith(other: List<U>): List<Pair<T, U>> = flatMap { left -> other.map { right -> Pair(left, right) } } fun <T> List<T>.combinations(): List<Pair<T, T>> = combinationsWith(this) fun <T> List<T>.combinations(times: Int): List<List<T>> = when (times) { 0 -> listOf() 1 -> map { listOf(it) } else -> combinations(times - 1).let { tails -> tails.flatMap { tail -> this.map { head -> tail + head } } } } fun <T : Comparable<T>> List<T>.indexOfMaxOrNull(): Int? = mapIndexed { i, e -> Pair(i, e) }.maxByOrNull { it.second }?.first fun <T, R : Comparable<R>> List<T>.indexOfMaxByOrNull(selector: (T) -> R): Int? = mapIndexed { i, e -> Pair(i, selector(e)) }.maxByOrNull { it.second }?.first fun <S, T, U> Pair<S, Pair<T, U>>.flatten(): Triple<S, T, U> = Triple(this.first, this.second.first, this.second.second) //fun <S, T, U> Pair<Pair<S, T>, U>.flatten(): Triple<S, T, U> = // Triple(this.first.first, this.first.second, this.second) operator fun Pair<Int, Int>.plus(other: Pair<Int, Int>): Pair<Int, Int> = Pair(first + other.first, second + other.second) operator fun Pair<Int, Int>.times(factor: Int): Pair<Int, Int> = Pair(first * factor, second * factor) fun Pair<Int, Int>.manhattanFrom(origin: Pair<Int, Int> = Pair(0, 0)): Int = (origin.first - this.first).absoluteValue + (origin.second - this.second).absoluteValue //fun Pair<Int, Int>.projectRay(): Sequence<Pair<Int, Int>> = // generateSequence(this) { it + this } fun Pair<Int, Int>.projectRay( direction: Pair<Int, Int>, isInBounds: (Pair<Int, Int>).() -> Boolean = { true } ): Sequence<Pair<Int, Int>> = generateSequence(this) { (it + direction).takeIf(isInBounds) } data class Quadruple<out A, out B, out C, out D>( public val first: A, public val second: B, public val third: C, public val fourth: D ) { override fun toString(): String = "($first, $second, $third, $fourth)" } fun <T> Quadruple<T, T, T, T>.toList(): List<T> = listOf(first, second, third, fourth)
0
Kotlin
0
0
f17184fe55dfe06ac8897c2ecfe329a1efbf6a09
3,511
advent-of-code-2020
The Unlicense
src/Day14.kt
HylkeB
573,815,567
false
{"Kotlin": 83982}
import java.lang.IllegalArgumentException fun main() { class Scan( private val top: Int, private val left: Int, private val bottom: Int, private val right: Int, ) { private val width = (right - left) + 1 private val height = (bottom - top) + 1 private val grid = Array(height) { Array(width) { '.' } } init { setGridValue(0, 0, '+') } private fun Int.normalizeX(): Int = width - ((right - this) + 1) private fun Int.normalizeY(): Int = top + this fun setGridValue(x: Int, y: Int, value: Char) { grid[y.normalizeY()][x.normalizeX()] = value } fun getGridValue(x: Int, y: Int): Char? { if (x !in left..right || y !in top..bottom) return null return grid[y.normalizeY()][x.normalizeX()] } fun addRock(x: Int, y: Int) { setGridValue(x, y, '#') } fun debugDraw() { val canvas = grid.joinToString("\n") { it.joinToString("") } println(canvas) } } // top left, bottom right fun List<List<Pair<Int, Int>>>.getBounds(): Pair<Pair<Int, Int>, Pair<Int, Int>> { var left = Int.MAX_VALUE var right = Int.MIN_VALUE var top = 0 var bottom = Int.MIN_VALUE forEach { scanLine -> scanLine.forEach { (x, y) -> left = minOf(left, x) right = maxOf(right, x) top = minOf(top, y) bottom = maxOf(bottom, y) } } return (top to left) to (bottom to right) } fun List<String>.parseInput(): Scan { val scanLines = map { line -> line.split(" -> ") .map { val splitted = it.split(",") splitted[0].toInt() to splitted[1].toInt() } .map { (x, y) -> x - 500 to y } // normalize } val (topLeft, bottomRight) = scanLines.getBounds() val (top, left) = topLeft val (bottom, right) = bottomRight val scan = Scan(top, left, bottom, right) scanLines.forEach { scanLine -> scanLine.forEachIndexed { index, (curX, curY) -> if (index > 0) { val (prevX, prevY) = scanLine[index - 1] if (curX == prevX) { // vertical line val minY = minOf(curY, prevY) val maxY = maxOf(curY, prevY) val yRange = minY..maxY val x = curX yRange.forEach { y -> scan.addRock(x, y) } } else if (curY == prevY) { val minX = minOf(curX, prevX) val maxX = maxOf(curX, prevX) val xRange = minX..maxX val y = curY xRange.forEach { x -> scan.addRock(x, y) } } else { throw IllegalArgumentException("No support for diagonal lines") } } } } return scan } fun part1(input: List<String>): Int { val scan = input.parseInput() tailrec fun Scan.simulate(x: Int, y: Int): Boolean { val oneDown = getGridValue(x, y + 1) ?: return false // outside canvas if (oneDown == '.') return simulate(x, y + 1) val downLeft = getGridValue(x - 1, y + 1) ?: return false // outside canvas if (downLeft == '.') return simulate(x - 1, y + 1) val downRight = getGridValue(x + 1, y + 1) ?: return false // outside canvas if (downRight == '.') return simulate(x + 1, y + 1) setGridValue(x, y, 'O') return true } var counter = 0 while (scan.simulate(0, 0)) { counter++ } return counter } fun part2(input: List<String>): Int { val maxY = input.map { line -> line.split(" -> ") .map { val splitted = it.split(",") splitted[0].toInt() to splitted[1].toInt() } .map { (x, y) -> x - 500 to y } // normalize }.flatten().maxBy { (x, y) -> y }.second + 2 val scan = (input + "-10000,$maxY -> 10000,$maxY").parseInput() tailrec fun Scan.simulate(x: Int, y: Int) { val oneDown = getGridValue(x, y + 1) ?: throw IllegalStateException("Outside canvas, bottom line not wide enough") if (oneDown == '.') return simulate(x, y + 1) val downLeft = getGridValue(x - 1, y + 1) ?: throw IllegalStateException("Outside canvas, bottom line not wide enough") if (downLeft == '.') return simulate(x - 1, y + 1) val downRight = getGridValue(x + 1, y + 1) ?: throw IllegalStateException("Outside canvas, bottom line not wide enough") if (downRight == '.') return simulate(x + 1, y + 1) setGridValue(x, y, 'O') } var counter = 0 do { scan.simulate(0, 0) counter++ } while (scan.getGridValue(0, 0) == '+') return counter } // test if implementation meets criteria from the description, like: val dayNumber = 14 val testInput = readInput("Day${dayNumber}_test") val testResultPart1 = part1(testInput) val testAnswerPart1 = 24 check(testResultPart1 == testAnswerPart1) { "Part 1: got $testResultPart1 but expected $testAnswerPart1" } val testResultPart2 = part2(testInput) val testAnswerPart2 = 93 check(testResultPart2 == testAnswerPart2) { "Part 2: got $testResultPart2 but expected $testAnswerPart2" } val input = readInput("Day$dayNumber") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
8649209f4b1264f51b07212ef08fa8ca5c7d465b
6,117
advent-of-code-2022-kotlin
Apache License 2.0
src/day13/Day13.kt
Ciel-MC
572,868,010
false
{"Kotlin": 55885}
package day13 import day13.ListNode.Companion.toListNode import day13.Value.Companion.toValue import readInput import java.io.File val file = File("AAA.txt") fun log(message: Any?) { file.appendText("$message\n") println(message) } sealed interface Value { fun isCorrect(other: Value): Boolean? companion object { fun String.toValue(): Value { // day13.log("Parsing for day13.Value: $this") toIntOrNull()?.let { return IntValue(it) } return this.toListNode() } } } data class ListNode(val value: Value? = null, val next: ListNode? = null): Iterable<ListNode>, Value { override fun iterator() = generateSequence(this) { it.next }.iterator() override fun isCorrect(other: Value): Boolean? { return when (other) { is IntValue -> { log("This is a list, but the other is an int, wrap the int in a list and compare") this.isCorrect(ListNode(IntValue(other.value))) } is ListNode -> { log("Both are lists, compare them") this.isCorrect(other) } } } override fun toString(): String { return "[${this.joinToString(" -> ") { it.value.toString() }}]" } companion object { private fun fromValues(values: List<Value>): ListNode { var current: ListNode? = null for (value in values.reversed()) { current = ListNode(value, current) } return current ?: ListNode() } fun CharSequence.indexOfMatching(open: Char, close: Char, start: Int = 0): Int { var openCount = 0 for (i in start..lastIndex) { when (this[i]) { open -> openCount++ close -> openCount-- } if (openCount == 0) return i } return -1 } fun String.toListNode(): ListNode { // day13.log("Parsing `$this`") val removeBrackets = this.removeSurrounding("[", "]") if (removeBrackets.isEmpty()) return ListNode() val segments = mutableListOf<String>() run { val current = StringBuilder() var index = 0 while (index <= removeBrackets.lastIndex) { when (val char = removeBrackets[index]) { ',' -> { segments.add(current.toString()) current.clear() } '[' -> { check(current.isEmpty()) { "Unexpected '[' at index $index" } val closeBracket = index + removeBrackets.substring(index).indexOfMatching('[', ']') segments.add(removeBrackets.substring(index..closeBracket)) index = closeBracket + 1 } else -> { current.append(char) } } // day13.log("Current: $current, segments: $segments") index++ } if (current.isNotEmpty()) segments.add(current.toString()) } // day13.log("Segments: $segments") return fromValues(segments.map { it.toValue() }) } } fun isCorrect(other: ListNode): Boolean? { log("Compare $this vs $other") if (this.value == null) { return if (other.value == null) { log("Neither item has a value, undecided") null } else { log("This item has ended, but the other hasn't, so it's correct") true } } if (other.value == null) { log("The other ended, but this didn't, so it's incorrect") return false } val valueResult = this.value.isCorrect(other.value) if (valueResult != null) { log("Values has a result: $valueResult") return valueResult } if (this.next == null) { return if (other.next == null) { log("Both ended, it's undecided") null } else { log("This ended, but the other didn't, so it's correct") true } } if (other.next == null) { log("The other ended, but this didn't, so it's incorrect") return false } log("Still undecided, checking the next item") return this.next.isCorrect(other.next) } } data class IntValue(val value: Int): Value { override fun isCorrect(other: Value): Boolean? { log("Compare $this vs $other") return when (other) { is IntValue -> { when (value.compareTo(other.value)) { -1 -> { log("This is less than the other, so it's correct") true } 0 -> { log("Two values are equal, so it's undecided") null } 1 -> { log("This is greater than the other, so it's incorrect") false } else -> { throw IllegalStateException("Unexpected comparison result") } } } is ListNode -> { log("This is an int, but the other is a list, wrap the int in a list and compare") ListNode(IntValue(value)).isCorrect(other) } } } override fun toString(): String { return value.toString() } } fun ListNode.isDivider(i: Int): Boolean { if (this.next != null) return false val inner = this.value as? ListNode ?: return false if (inner.next != null) return false val value = inner.value as? IntValue ?: return false return value.value == i } fun <T> MutableList<T>.booleanSort(compare: (T, T) -> Boolean): MutableList<T> { var index = 0 while (index < lastIndex) { if (compare(this[index], this[index + 1])) { index++ } else { swap(index, index + 1) // index = 0 index = maxOf(0, index - 1) } } return this } fun <T> MutableList<T>.swap(index1: Int, index2: Int) { this[index1] = this[index2].also { this[index2] = this[index1] } } fun main() { fun part1(input: List<String>): Int { // day13.log("[[[]]]".toListNode()) // day13.log("[[]]".toListNode()) // return 0 return input.asSequence().chunked(2).map { (a, b) -> (a to b) //.also { day13.log("Building: $it") } }.map { (a, b) -> a.toListNode() to b.toListNode() }.withIndex().filter { (_, v) -> // day13.log("Compare:") // day13.log(v.first) // day13.log(v.second) v.first.isCorrect(v.second).also { log(it) }!! //.also { day13.log("day02.Result: $it\n") } }.sumOf { it.index + 1 } } fun part2(input: List<String>): Int { return input .map { it.toListNode() }.toMutableList() .booleanSort { a, b -> a.isCorrect(b)!! } // .onEach { // file.appendText("$it\n") // } .asSequence().withIndex() .filter { it.value.isDivider(2) || it.value.isDivider(6) } // .onEach { day13.log(it.value) } .map { it.index + 1 }.take(2).reduce { a, b -> a * b } } // val testInput = readInput(13, true) // part1(testInput).let { check(it == 13) { println(it) } } // part2(testInput).also { println(it) } // if (readlnOrNull() == "y") { // day13.log("Tests passed") val input = readInput(13) // println(part1(input)) println(part2(input)) // } }
0
Kotlin
0
0
7eb57c9bced945dcad4750a7cc4835e56d20cbc8
8,012
Advent-Of-Code
Apache License 2.0
2022/src/day25/day25.kt
Bridouille
433,940,923
false
{"Kotlin": 171124, "Go": 37047}
package day25 import GREEN import RESET import printTimeMillis import readInput fun String.toDecimal() = fold(0L) { acc, c -> acc * 5L + ("=-012".indexOf(c) - 2) } fun Long.toSNAFU(): String { val base = listOf('0', '1', '2', '=', '-') val digits = listOf(0, 1, 2, -2, -1) val sb = StringBuilder() var nb = this while (nb != 0L) { val rest = (nb % 5).toInt() sb.append(base[rest]) nb = (nb - digits[rest]) / 5L } return sb.toString().reversed() } fun part1(input: List<String>) = input.map { it.toDecimal() }.sum().let { println(it) it.toSNAFU() } fun main() { val testInput = readInput("day25_example.txt") printTimeMillis { print("part1 example = $GREEN" + part1(testInput) + RESET) } val input = readInput("day25.txt") printTimeMillis { print("part1 input = $GREEN" + part1(input) + RESET) } }
0
Kotlin
0
2
8ccdcce24cecca6e1d90c500423607d411c9fee2
881
advent-of-code
Apache License 2.0
Kotlin/5 kyu Josephus Survivor.kt
MechaArms
508,384,440
false
{"Kotlin": 22917, "Python": 18312}
/* In this kata you have to correctly return who is the "survivor", ie: the last element of a Josephus permutation. Basically you have to assume that n people are put into a circle and that they are eliminated in steps of k elements, like this: josephus_survivor(7,3) => means 7 people in a circle; one every 3 is eliminated until one remains [1,2,3,4,5,6,7] - initial sequence [1,2,4,5,6,7] => 3 is counted out [1,2,4,5,7] => 6 is counted out [1,4,5,7] => 2 is counted out [1,4,5] => 7 is counted out [1,4] => 5 is counted out [4] => 1 counted out, 4 is the last element - the survivor! The above link about the "base" kata description will give you a more thorough insight about the origin of this kind of permutation, but basically that's all that there is to know to solve this kata. Notes and tips: using the solution to the other kata to check your function may be helpful, but as much larger numbers will be used, using an array/list to compute the number of the survivor may be too slow; you may assume that both n and k will always be >=1. */ //My Solution //=========== fun josephusSurvivor(n: Int, k: Int): Int { return (1..n).reduce { x, ni -> (x + k - 1) % ni + 1 } } //Best Solution //============= fun josephusSurvivor(n: Int, k: Int): Int = (1..n).fold(1){ i, j -> (i + k) % j } + 1
0
Kotlin
0
1
b23611677c5e2fe0f7e813ad2cfa21026b8ac6d3
1,311
My-CodeWars-Solutions
MIT License
Kotlin/src/UniqueBinarySearchTreesII.kt
TonnyL
106,459,115
false
null
/** * Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1...n. * * For example, * Given n = 3, your program should return all 5 unique BST's shown below. * * 1 3 3 2 1 * \ / / / \ \ * 3 2 1 1 3 2 * / / \ \ * 2 1 2 3 * * Accepted. */ class UniqueBinarySearchTreesII { fun generateTrees(n: Int): List<TreeNode?> { val list = mutableListOf<TreeNode>() return if (n <= 0) { list } else gen(1, n) } private fun gen(start: Int, end: Int): List<TreeNode?> { val list = mutableListOf<TreeNode?>() if (start > end) { list.add(null) return list } if (start == end) { list.add(TreeNode(start)) return list } for (i in start..end) { for (m in gen(start, i - 1)) { gen(i + 1, end).mapTo(list) { TreeNode(i).apply { left = m right = it } } } } return list } data class TreeNode( var `val`: Int, var left: TreeNode? = null, var right: TreeNode? = null ) }
1
Swift
22
189
39f85cdedaaf5b85f7ce842ecef975301fc974cf
1,369
Windary
MIT License
src/Day10.kt
msernheim
573,937,826
false
{"Kotlin": 32820}
import kotlin.math.sign fun main() { fun evalSignalStrengthOrZero(clock: Int, x: Int): Int { if (clock % 40 == 20) { return x * clock } return 0 } fun part1(input: List<String>): Int { var clock = 1 var signalStrength = 0 var x = 1 input.forEach { instruction -> if (instruction.startsWith("addx")) { clock++ signalStrength += evalSignalStrengthOrZero(clock, x) x += instruction.split(" ").last().toInt() } clock++ signalStrength += evalSignalStrengthOrZero(clock, x) } return signalStrength } fun crtPrint(pixelToWrite: Int, crt: List<MutableList<Char>>, spritePos: Int) { val crtX = pixelToWrite % 40 if (spritePos - 1 <= crtX && crtX <= spritePos + 1) { val crtY = (pixelToWrite - (pixelToWrite % 40)) / 40 crt[crtY][crtX] = '#' } } fun part2(input: List<String>): Int{ val crt = List(6) { MutableList(40) {'.'} } var clock = 1 var x = 1 input.forEach { instruction -> crtPrint(clock - 1, crt, x) if (instruction.startsWith("addx")) { clock++ crtPrint(clock - 1, crt, x) x += instruction.split(" ").last().toInt() } clock++ } crt.forEach { row -> println(row.joinToString("")) } return 0 } val input = readInput("Day10") val part1 = part1(input) println("Result part1: $part1") println("Result part2:") part2(input) }
0
Kotlin
0
3
54cfa08a65cc039a45a51696e11b22e94293cc5b
1,664
AoC2022
Apache License 2.0
2023/3/solve-1.kts
gugod
48,180,404
false
{"Raku": 170466, "Perl": 121272, "Kotlin": 58674, "Rust": 3189, "C": 2934, "Zig": 850, "Clojure": 734, "Janet": 703, "Go": 595}
import java.io.File class EngineSchemata( val engineSchematic: List<String>, ) { private fun CharSequence.indicesOfNextNumOrNull ( startIndex: Int, ) : IntRange? { if (startIndex > this.lastIndex) throw IllegalStateException("Your index is not my index.") val begin = (startIndex..this.lastIndex).firstOrNull { this[it].isDigit() } if (begin == null) return null val end = (begin..this.lastIndex).firstOrNull { ! this[it].isDigit() } ?: this.lastIndex+1 return IntRange(begin,end-1) } private fun surroundingChars( lineIndex: Int, colIndices: IntRange, ) : CharArray { val w = engineSchematic.lastIndex val h = engineSchematic[0].lastIndex var chars = mutableListOf<Char>() (maxOf(0,lineIndex-1)..minOf(h,lineIndex+1)).forEach { j -> (maxOf(0, colIndices.start-1)..minOf(w, colIndices.endInclusive+1)).forEach { i -> if (! engineSchematic[j][i].isDigit()) { chars.add(engineSchematic[j][i]) } } } return chars.toCharArray() } fun play1 () { var sumOfAllPartNumbers = 0 (0..engineSchematic.lastIndex).forEach { j -> val line = engineSchematic[j] var col = 0 while (col < line.lastIndex) { val indices = line.indicesOfNextNumOrNull(col) if (indices == null) break col = indices.endInclusive + 1 if (surroundingChars(j, indices).any { it != '.' }) { val partNum = line.substring(indices).toInt() sumOfAllPartNumbers += partNum } } } println("$sumOfAllPartNumbers") } } val machine = EngineSchemata( File("input").readLines().toList<String>() ) machine.play1()
0
Raku
1
5
ca0555efc60176938a857990b4d95a298e32f48a
1,934
advent-of-code
Creative Commons Zero v1.0 Universal
src/main/kotlin/dev/shtanko/algorithms/leetcode/ThreeSumMulti.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2021 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import dev.shtanko.algorithms.MOD private const val LIMIT = 100 private const val ARR_SIZE = LIMIT + 1 fun interface ThreeSumMulti { operator fun invoke(arr: IntArray, target: Int): Int } /** * Approach 1: Three Pointer * Time Complexity: O(N^2), where NN is the length of arr. * Space Complexity: O(1). */ class TSMThreePointer : ThreeSumMulti { override operator fun invoke(arr: IntArray, target: Int): Int { var ans: Long = 0 arr.sort() for (i in arr.indices) { val t: Int = target - arr[i] var j = i + 1 var k: Int = arr.size - 1 while (j < k) { when { arr[j] + arr[k] < t -> { j++ } arr[j] + arr[k] > t -> { k-- } arr[j] != arr[k] -> { var left = 1 var right = 1 while (j + 1 < k && arr[j] == arr[j + 1]) { left++ j++ } while (k - 1 > j && arr[k] == arr[k - 1]) { right++ k-- } ans += (left * right).toLong() ans %= MOD.toLong() j++ k-- } else -> { ans += ((k - j + 1) * (k - j) / 2).toLong() ans %= MOD.toLong() break } } } } return ans.toInt() } } /** * Approach 2: Counting with Cases * Time Complexity: O(N + W^2). * Space Complexity: O(W). */ class TSMCountingCases : ThreeSumMulti { override operator fun invoke(arr: IntArray, target: Int): Int { val count = LongArray(ARR_SIZE) for (x in arr) count[x]++ var ans: Long = 0 for (x in 0..LIMIT) for (y in x + 1..LIMIT) { val z: Int = target - x - y if (z in y.plus(1)..LIMIT) { ans += count[x] * count[y] * count[z] ans %= MOD.toLong() } } for (x in 0..LIMIT) { val z: Int = target - 2 * x if (z in x.plus(1)..LIMIT) { ans += count[x] * (count[x] - 1) / 2 * count[z] ans %= MOD.toLong() } } for (x in 0..LIMIT) { if (target % 2 == x % 2) { val y: Int = (target - x) / 2 if (y in x.plus(1)..LIMIT) { ans += count[x] * count[y] * count[y].minus(1) / 2 ans %= MOD.toLong() } } } if (target % 3 == 0) { val x: Int = target / 3 if (x in 0..LIMIT) { ans += count[x] * (count[x] - 1) * (count[x] - 2) / 6 ans %= MOD.toLong() } } return ans.toInt() } } /** * Approach 3: Adapt from Three Sum * Time Complexity: O(N^2), where N is the length of A. * Space Complexity: O(1). */ class TSMAdapt : ThreeSumMulti { override operator fun invoke(arr: IntArray, target: Int): Int { val count = LongArray(ARR_SIZE) var uniq = 0 for (x in arr) { count[x]++ if (count[x] == 1L) uniq++ } val keys = IntArray(uniq) var t = 0 for (i in 0..LIMIT) if (count[i] > 0) keys[t++] = i var ans: Long = 0 for (i in keys.indices) { val x = keys[i] var j = i var k = keys.size - 1 val a = target - x while (j <= k) { val y = keys[j] val z = keys[k] when { y + z < a -> { j++ } y + z > a -> { k-- } else -> { ans += when { j in i.plus(1) until k -> { count[x] * count[y] * count[z] } i == j && j < k -> { count[x] * (count[x] - 1) / 2 * count[z] } i < j && j == k -> { count[x] * count[y] * (count[y] - 1) / 2 } else -> { count[x] * (count[x] - 1) * (count[x] - 2) / 6 } } ans %= MOD.toLong() j++ k-- } } } } return ans.toInt() } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
5,623
kotlab
Apache License 2.0
src/main/kotlin/com/hj/leetcode/kotlin/problem347/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem347 /** * LeetCode page: [347. Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/); */ class Solution { /* Complexity: * Time O(N) and Space O(N) where N is the size of nums; */ fun topKFrequent(nums: IntArray, k: Int): IntArray { val result = IntArray(k) val numbersByFrequency = numbersGroupByFrequency(nums) var numCollected = 0 // Collect the k elements by searching in a decreasing frequency order search@ for (frequency in nums.size downTo 1) { val numbers = numbersByFrequency[frequency] ?: continue for (number in numbers) { result[numCollected] = number numCollected++ if (numCollected == k) { break@search } } } return result } private fun numbersGroupByFrequency(numbers: IntArray): Map<Int, List<Int>> { val result = hashMapOf<Int, MutableList<Int>>() for ((number, frequency) in numberFrequency(numbers)) { result .computeIfAbsent(frequency) { mutableListOf() } .add(number) } return result } private fun numberFrequency(numbers: IntArray): Map<Int, Int> { val result = hashMapOf<Int, Int>() for (number in numbers) { result[number] = (result[number] ?: 0) + 1 } return result } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
1,501
hj-leetcode-kotlin
Apache License 2.0
src/main/kotlin/org/flightofstairs/ctci/treesAndGraphs/Heap.kt
FlightOfStairs
509,587,102
false
{"Kotlin": 38930}
package org.flightofstairs.ctci.treesAndGraphs // The main thing I learned from this is that it's way easier to implement a heap using an array or list than a // classic tree. A lot of effort here is spent on pathing to the last element, which is trivial with array. class Heap<T : Comparable<T>>(private val comparator: Comparator<T> = naturalOrder()) { private var root: BTreeNode<T>? = null var size = 0 private set fun peek(): T = root?.item ?: throw RetrieveFromEmptyHeapException() fun insert(item: T) { size++ val path = pathFromIndex(size) if (path.isEmpty()) { assert(root == null) root = BTreeNode(item, null, null) } else { root!!.insertAndHeapify(path, item, comparator) } } fun remove(): T { val item = peek() val path = pathFromIndex(size) if (path.isEmpty()) { assert(size == 1) root = null } else { root!!.item = root!!.deleteAt(path) root!!.heapifyDown(comparator) } size-- return item } } class RetrieveFromEmptyHeapException : Exception() private enum class Direction { LEFT, RIGHT } private fun pathFromIndex(i: Int) = i.toString(2).map { if (it == '0') Direction.LEFT else Direction.RIGHT }.drop(1) private fun <T> BTreeNode<T>.insertAndHeapify(path: List<Direction>, newItem: T, comparator: Comparator<T>) { check(path.isNotEmpty()) val direction = path.first() if (path.size == 1) { val newNode = BTreeNode(newItem, null, null) when (direction) { Direction.LEFT -> left = newNode Direction.RIGHT -> right = newNode } } else { when (direction) { Direction.LEFT -> left!!.insertAndHeapify(path.drop(1), newItem, comparator) Direction.RIGHT -> right!!.insertAndHeapify(path.drop(1), newItem, comparator) } } val heapifyNode = when (direction) { Direction.LEFT -> left!! Direction.RIGHT -> right!! } if (comparator.compare(this.item, heapifyNode.item) > 0) { val oldItem = this.item this.item = heapifyNode.item heapifyNode.item = oldItem } } private fun <T> BTreeNode<T>.deleteAt(path: List<Direction>): T { check(path.isNotEmpty()) val direction = path.first() return if (path.size == 1) { when(direction) { Direction.LEFT -> left!!.item.also { left = null } Direction.RIGHT -> right!!.item.also { right = null } } } else { when(direction) { Direction.LEFT -> left!!.deleteAt(path.drop(1)) Direction.RIGHT -> right!!.deleteAt(path.drop(1)) } } } private fun <T> BTreeNode<T>.heapifyDown(comparator: Comparator<T>) { if (left == null) return val smallestChild = if (right == null || comparator.compare(left!!.item, right!!.item) <= 0 ) left else right if (comparator.compare(this.item, smallestChild!!.item) > 0) { val oldItem = this.item this.item = smallestChild.item smallestChild.item = oldItem smallestChild.heapifyDown(comparator) } }
0
Kotlin
0
0
5f4636ac342f0ee5e4f3517f7b5771e5aabe5992
3,221
FlightOfStairs-ctci
MIT License
gcj/y2022/round1b/b.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package gcj.y2022.round1b import kotlin.math.abs private fun solve(): Long { val (n, _) = readInts() val lists = List(n) { readInts() } var pLow = 0 var pHigh = 0 var costLow = 0L var costHigh = 0L for (list in lists) { val pLowNew = list.minOrNull()!! val pHighNew = list.maxOrNull()!! val costLowNew = minOf(costLow + abs(pLow - pHighNew), costHigh + abs(pHigh - pHighNew)) + pHighNew - pLowNew val costHighNew = minOf(costLow + abs(pLow - pLowNew), costHigh + abs(pHigh - pLowNew)) + pHighNew - pLowNew pLow = pLowNew; pHigh = pHighNew; costLow = costLowNew; costHigh = costHighNew } return minOf(costLow, costHigh) } fun main() { repeat(readInt()) { println("Case #${it + 1}: ${solve()}") } } private fun readLn() = readLine()!! private fun readInt() = readLn().toInt() private fun readStrings() = readLn().split(" ") private fun readInts() = readStrings().map { it.toInt() }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
904
competitions
The Unlicense
src/deselby/fockSpace/BinomialBasis.kt
deselby-research
166,023,166
false
null
package deselby.fockSpace import deselby.fockSpace.extensions.join import deselby.std.FallingFactorial import deselby.std.extensions.fallingFactorial import org.apache.commons.math3.distribution.BinomialDistribution import org.apache.commons.math3.special.Gamma import java.io.Serializable import kotlin.math.ln import kotlin.math.max import kotlin.math.min import kotlin.math.pow class BinomialBasis<AGENT>(val pObserve: Double, val observations: Map<AGENT,Int>): Serializable { val pNotObserve = 1.0 - pObserve // calculates the (unnormalised) monteCarloPrior probability of the observations // which is the product over i of ((1-pObserve)lambda_i)^m_i // fun times(D0: DeselbyGround<AGENT>): DeselbyGround<AGENT> { val newLambdas = HashMap<AGENT,Double>() D0.lambdas.mapValuesTo(newLambdas) { (_,lambda) -> pNotObserve * lambda } return DeselbyGround(newLambdas) } fun map(transform: (AGENT) -> AGENT): BinomialBasis<AGENT> { return BinomialBasis(pObserve, observations.mapKeys { transform(it.key) }) } // finds the basis that minimises the KL divergence with this likelihood times prior fun timesApproximate(prior: GroundedVector<AGENT,DeselbyGround<AGENT>>): GroundedBasis<AGENT,DeselbyGround<AGENT>> { // val filteredMap = HashMap<CreationBasis<AGENT>,Double>() // monteCarloPrior.creationVector.filterTo(filteredMap) {abs(it.value) < 1e-5} // val filteredPrior = HashCreationVector(filteredMap) val cPrimes = reweight(prior) val basisFit = calcBasisFit(prior.creationVector) val newLambdas = HashMap<AGENT,Double>() prior.ground.lambdas.mapValuesTo(newLambdas) { (agent, lambda) -> val mj = observations[agent]?:0 val lambdap = lambda*pNotObserve val newLambda = mj + lambdap - (basisFit.creations[agent]?:0) + meanSum(cPrimes, mj, lambdap, agent) if(newLambda < 0.0) println("Got -ve lambda: $newLambda") max(newLambda, 1e-8) } return basisFit.asGroundedBasis(DeselbyGround(newLambdas)) } private fun reweight(prior: GroundedVector<AGENT,DeselbyGround<AGENT>>): CreationVector<AGENT> { val reweighted = HashCreationVector<AGENT>() var sumOfWeights = 0.0 prior.creationVector.mapValuesTo(reweighted) { (priorBasis, priorWeight) -> var newWeight = priorWeight priorBasis.creations.forEach { (agent, deltai) -> val mi = observations[agent]?:0 val lambdap = prior.ground.lambda(agent)*pNotObserve newWeight *= pNotObserve.pow(deltai) newWeight *= binomialSum(mi, deltai, lambdap) } sumOfWeights += newWeight newWeight } reweighted *= 1.0/sumOfWeights return reweighted } private fun meanSum(cPrimes: CreationVector<AGENT>, mj: Int, lambdaj: Double, j: AGENT): Double { var sum = 0.0 cPrimes.forEach {(basis, cPrime) -> val deltai = basis[j] sum += cPrime * (deltai - binomialFraction(mj, deltai, lambdaj)) } return sum } private fun calcBasisFit(prior: CreationVector<AGENT>): CreationBasis<AGENT> { val minOrder = HashMap<AGENT,Int>(observations) prior.join().creations.forEach { (agent, order) -> minOrder.merge(agent, order) {a,b -> max(a,b)} } return CreationBasis(minOrder) } // Calculates the log probability of concreteState given the observations in this // Where there is no observation, assume a prior poisson distribution given in 'priors' // uses the identity that B_r(k,m)D_0(k,lambda) \propto D_m(k,(1-r)lambda) // so P(k|m) = D_m(k,(1-r)lambda) fun logProb(concreteState: Map<AGENT,Int>, priors: Map<AGENT,Double>) : Double { var l = 0.0 priors.forEach {(agent,lambda )-> val kReal = concreteState[agent]?:0 val kObserved = observations[agent] if(kObserved != null) { if(kReal < kObserved) return Double.NEGATIVE_INFINITY val k = kReal - kObserved val lambdap = (1.0-pObserve)*lambda l += k*ln(lambdap) - lambdap - Gamma.logGamma(k+1.0) } else { l += kReal*ln(lambda) - lambda - Gamma.logGamma(kReal+1.0) } } return l } // Calculates the log likelihood of the observations in this // for the supplied 'concreteState', assuming that absent observations // are observed to be zero fun logLikelihood(concreteState: CreationBasis<AGENT>, allAgents: Iterable<AGENT>) : Double { var l = 0.0 // val allAgents = observations.keys.times(concreteState.creations.keys) allAgents.forEach {agent -> l += BinomialDistribution(null, concreteState[agent], pObserve).logProbability(observations[agent]?:0) + ln(pObserve) } return l } // Calculates the log-probability of 'concreteState' on the // re-normalised product of this and 'prior' fun posteriorProbability(prior: GroundedVector<AGENT,DeselbyGround<AGENT>>, concreteState: CreationBasis<AGENT>): Double { var l = 0.0 var normalisation = 0.0 var prob = 0.0 prior.creationVector.forEach { (priorBasis, priorWeight) -> var basisNormalisation = 1.0 var basisProb = 1.0 prior.ground.lambdas.forEach { (agent, lambda) -> val k = concreteState[agent] val m = observations[agent]?:0 val delta = priorBasis[agent] val pm1d = pNotObserve.pow(delta) val lambdap = pNotObserve*lambda basisProb *= pm1d * k.fallingFactorial(m) * DeselbyGround.probability(k, delta, lambdap) basisNormalisation *= pm1d * binomialSum(m, delta, lambdap, lambdap.pow(m)) } normalisation += priorWeight*basisNormalisation prob += priorWeight*basisProb } return prob / normalisation } // calculates the sum over k of B_m D_d,lambda fun binomialSum(m: Int, d: Int, lambda: Double, c0: Double = 1.0): Double { var c = c0 var sum = c for(q in 1..min(d,m)) { val qm1 = q-1 c *= (m-qm1)*(d-qm1)/(q*lambda) sum += c } return sum } fun binomialFraction(m: Int,n: Int,lambda: Double): Double { var c = 1.0 var sumq = 0.0 var sum = c for(q in 1..min(n,m)) { val qm1 = q-1 c *= (m-qm1)*(n-qm1)/(q*lambda) sum += c sumq += c*q } return sumq/sum } override fun toString(): String { return buildString { append("p=$pObserve ") append(observations.toString()) } } }
0
Kotlin
1
8
6c76a9a18e2caafc1ff00ab970d0df4d703f0119
6,971
ProbabilisticABM
MIT License
src/Day03.kt
rromanowski-figure
573,003,468
false
{"Kotlin": 35951}
object Day03 : Runner<Int, Int>(3, 157, 70) { override fun part1(input: List<String>): Int { val priorities = input.map { contents -> val half = contents.length / 2 val left = contents.substring(0, half) val right = contents.substring(half, contents.length) val overlap = left.toCharArray().intersect(right.toCharArray().toSet()).single() overlap.priority() } return priorities.sum() } override fun part2(input: List<String>): Int { val groups = input.chunked(3) val priorities = groups.map { val overlap = it[0].toCharArray() .intersect(it[1].toCharArray().toSet()) .intersect(it[2].toCharArray().toSet()) .single() overlap.priority() } return priorities.sum() } private fun Char.priority() = code - if (this.isUpperCase()) 38 else 96 }
0
Kotlin
0
0
6ca5f70872f1185429c04dcb8bc3f3651e3c2a84
952
advent-of-code-2022-kotlin
Apache License 2.0
solutions/aockt/util/Collections.kt
Jadarma
624,153,848
false
{"Kotlin": 435090}
package aockt.util /** * Generate a [Sequence] of permutations of this collection. * For obvious reasons, will throw if the collection is too large. */ fun <T> Collection<T>.generatePermutations(): Sequence<List<T>> = when (size) { !in 0 .. 9 -> throw Exception("Too many permutations. This is probably not what you want to use.") 0 -> emptySequence() 1 -> sequenceOf(this.toList()) else -> { val first = first() drop(1) .generatePermutations() .flatMap { perm -> (0..perm.size).map { perm.toMutableList().apply { add(it, first) } } } } } /** * Returns the power set of the collection (all possible unordered combinations) except it's a [List] and not a [Set] * because repeated values are allowed. */ fun <T> Collection<T>.powerSet(): List<List<T>> = when (size) { 0 -> listOf(emptyList()) else -> { val first = listOf(first()) val next = drop(1).powerSet() next.map { first + it } + next } }
0
Kotlin
0
3
19773317d665dcb29c84e44fa1b35a6f6122a5fa
998
advent-of-code-kotlin-solutions
The Unlicense
src/main/kotlin/dev/shtanko/algorithms/leetcode/CountTheRepetitions.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 CountTheRepetitionsStrategy { operator fun invoke(s1: String, n1: Int, s2: String, n2: Int): Int } class CountTheRepetitionsBruteForce : CountTheRepetitionsStrategy { override operator fun invoke(s1: String, n1: Int, s2: String, n2: Int): Int { if (n2 == 0) return 0 var index = 0 var repeatCount = 0 val s1Size: Int = s1.length val s2Size: Int = s2.length for (i in 0 until n1) { for (j in 0 until s1Size) { if (s1[j] == s2[index]) ++index if (index == s2Size) { index = 0 ++repeatCount } } } return repeatCount / n2 } } class CountTheRepetitionsBetterBruteForce : CountTheRepetitionsStrategy { override operator fun invoke(s1: String, n1: Int, s2: String, n2: Int): Int { val reps = IntArray(ARRAY_SIZE) val rests = IntArray(ARRAY_SIZE) var posRest = 0 var repTime = 0 var i = 0 var k = 0 if (n1 <= 0) return 0 while (k == i) { i++ for (j in s1.indices) { if (s2[posRest] == s1[j]) { posRest++ if (posRest == s2.length) { repTime++ posRest = 0 } } } if (i >= n1) return repTime / n2 k = 0 while (k < i) { if (posRest == rests[k]) break k++ } reps[i] = repTime rests[i] = posRest } val interval = i - k val repeatCount = n1.plus(k) / interval val repeatTimes = repeatCount * reps[i].minus(reps[k]) val remainTimes = reps[n1.minus(k) % interval + k] return repeatTimes.plus(remainTimes) / n2 } companion object { private const val ARRAY_SIZE = 102 } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,616
kotlab
Apache License 2.0
src/main/kotlin/g0301_0400/s0395_longest_substring_with_at_least_k_repeating_characters/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0301_0400.s0395_longest_substring_with_at_least_k_repeating_characters // #Medium #Top_Interview_Questions #String #Hash_Table #Sliding_Window #Divide_and_Conquer // #2022_11_28_Time_274_ms_(66.67%)_Space_34_MB_(100.00%) class Solution { fun longestSubstring(s: String, k: Int): Int { return helper(s, k, 0, s.length) } private fun helper(s: String, k: Int, start: Int, end: Int): Int { if (end - start < k) { return 0 } val nums = IntArray(26) for (i in start until end) { nums[s[i].code - 'a'.code]++ } for (i in start until end) { if (nums[s[i].code - 'a'.code] < k) { var j = i + 1 while (j < s.length && nums[s[j].code - 'a'.code] < k) { j++ } return Math.max(helper(s, k, start, i), helper(s, k, j, end)) } } return end - start } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
970
LeetCode-in-Kotlin
MIT License
code-sample-kotlin/algorithms/src/main/kotlin/com/codesample/leetcode/medium/394_decodeString.kt
aquatir
76,377,920
false
{"Java": 674809, "Python": 143889, "Kotlin": 112192, "Haskell": 57852, "Elixir": 33284, "TeX": 20611, "Scala": 17065, "Dockerfile": 6314, "HTML": 4714, "Shell": 387, "Batchfile": 316, "Erlang": 269, "CSS": 97}
package com.codesample.leetcode.medium fun main() { val s = Solution1() println(s.decodeString("3[a]2[bc]")) // "aaabcbc" println(s.decodeString("3[a2[c]]")) // "accaccacc" println(s.decodeString("2[abc]3[cd]ef")) // "abcabccdcdcdef" println(s.decodeString("abc3[cd]xyz")) // "abccdcdcdxyz" } /** 394. Decode String * Given an encoded string, return its decoded string. * The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer. * You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc. * Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won't be input like 3a or 2[4]. * */ class Solution1 { fun decodeString(s: String): String { val finalResultStringBuilder = StringBuilder() var currentStringBuilder = StringBuilder() var currentNumberOfRepeats = 0 var i = 0 while (i < s.length) { val char = s[i] if (char == ']') { // skip -> nothing to process } else if (char == '[') { val endOfRepeat = findCorrespondingClosingBracketFrom(s, i + 1) val leftOfString = decodeString(s.substring(i + 1, endOfRepeat)) for (j in 1..currentNumberOfRepeats) { finalResultStringBuilder.append(leftOfString) } currentNumberOfRepeats = 0 i = endOfRepeat // this will be traversed by 1 at the end of the while } else if (char.isLetter()) { currentStringBuilder.append(char) } else if (char.isDigit()) { finalResultStringBuilder.append(currentStringBuilder) currentStringBuilder = StringBuilder() if (currentNumberOfRepeats != 0) { currentNumberOfRepeats = currentNumberOfRepeats * 10 + (char.toInt() - '0'.toInt()) } else { currentNumberOfRepeats = char.toInt() - '0'.toInt() } } i++ } return finalResultStringBuilder.append(currentStringBuilder).toString() } /** if another opening bracket is met along the way, we should continue until we close both of them. * i will point to ']' at the end of function */ private fun findCorrespondingClosingBracketFrom(s: String, startIndex: Int): Int { var closedBracketsToFind = 1; for (i in startIndex..s.length - 1) { val char = s[i] if (char == '[') { closedBracketsToFind++ } if (char == ']') { closedBracketsToFind-- } if (closedBracketsToFind == 0) { return i } } return 0 // never reached } }
1
Java
3
6
eac3328ecd1c434b1e9aae2cdbec05a44fad4430
3,038
code-samples
MIT License
Day2_02/src/main/kotlin/Main.kt
mepants
574,131,679
false
{"Kotlin": 17592}
import java.io.File enum class Move(val value: Int) { ROCK(1) { override fun scoreAgainst(opponentMove: Move): Int { return when (opponentMove) { ROCK -> 3 PAPER -> 0 SCISSORS -> 6 } } override fun losesAgainst() = PAPER override fun winsAgainst() = SCISSORS }, PAPER(2){ override fun scoreAgainst(opponentMove: Move): Int { return when (opponentMove) { ROCK -> 6 PAPER -> 3 SCISSORS -> 0 } } override fun losesAgainst() = SCISSORS override fun winsAgainst() = ROCK }, SCISSORS(3){ override fun scoreAgainst(opponentMove: Move): Int { return when (opponentMove) { ROCK -> 0 PAPER -> 6 SCISSORS -> 3 } } override fun losesAgainst() = ROCK override fun winsAgainst() = PAPER }; abstract fun scoreAgainst(opponentMove: Move) : Int abstract fun losesAgainst() : Move abstract fun winsAgainst() : Move companion object { fun fromLetter(letter: Char): Move { return when (letter) { 'A' -> Move.ROCK 'B' -> Move.PAPER 'C' -> Move.SCISSORS else -> throw Exception("Unknown move $letter") } } } } fun main(args: Array<String>) { val FILENAME = "c:\\Users\\micro\\code\\Advent-Of-Code-2022\\Day2_02\\input.txt" fun scoreRound(oppLetter: Char, myLetter: Char) : Int { val opponentMove = Move.fromLetter(oppLetter) val myMove = when (myLetter) { 'X' -> opponentMove.winsAgainst() 'Z' -> opponentMove.losesAgainst() else -> opponentMove } return myMove.value + myMove.scoreAgainst(opponentMove) } var score = 0 val file = File(FILENAME) file.forEachLine { score += scoreRound(it[0], it[2]) } println("My total score is $score") }
0
Kotlin
0
0
3b42381c10f3990b5a92cc6e41af04cb67a4fbd4
2,095
Advent-Of-Code-2022
Creative Commons Zero v1.0 Universal
src/main/java/challenges/educative_grokking_coding_interview/two_heaps/_2/MedianOfAStream.kt
ShabanKamell
342,007,920
false
null
package challenges.educative_grokking_coding_interview.two_heaps._2 import challenges.util.PrintHyphens import java.util.* /** Our task is to implement a data structure that will store a dynamically growing list of integers and provide access to their median in O(1). https://www.educative.io/courses/grokking-coding-interview-patterns-java/7Xx1Y64gADA */ class MedianOfAStream { var maxHeapForSmallNum //containing first half of numbers : PriorityQueue<Int> = PriorityQueue { a: Int, b: Int -> b - a } var minHeapForLargeNum //containing second half of numbers : PriorityQueue<Int> = PriorityQueue { a: Int, b: Int -> a - b } fun insertNum(num: Int) { if (maxHeapForSmallNum.isEmpty() || maxHeapForSmallNum.peek() >= num) maxHeapForSmallNum.add(num) else minHeapForLargeNum.add( num ) // either both the heaps will have equal number of elements or max-heap will have one // more element than the min-heap if (maxHeapForSmallNum.size > minHeapForLargeNum.size + 1) minHeapForLargeNum.add(maxHeapForSmallNum.poll()) else if (maxHeapForSmallNum.size < minHeapForLargeNum.size) maxHeapForSmallNum.add( minHeapForLargeNum.poll() ) } fun findMedian(): Double { return if (maxHeapForSmallNum.size == minHeapForLargeNum.size) { // we have even number of elements, take the average of middle two elements maxHeapForSmallNum.peek() / 2.0 + minHeapForLargeNum.peek() / 2.0 } else maxHeapForSmallNum.peek().toDouble() // because max-heap will have one more element than the min-heap } companion object { @JvmStatic fun main(args: Array<String>) { // Driver code val nums = intArrayOf(35, 22, 30, 25, 1) var medianOfAges: MedianOfAStream? = null for (i in nums.indices) { print(i + 1) print(".\tData stream: [") medianOfAges = MedianOfAStream() for (j in 0..i) { print(nums[j]) if (j != i) print(", ") medianOfAges.insertNum(nums[j]) } println("]") println("\t\tThe median for the given numbers is: " + medianOfAges.findMedian()) println(PrintHyphens.repeat("-", 100)) } } } }
0
Kotlin
0
0
ee06bebe0d3a7cd411d9ec7b7e317b48fe8c6d70
2,437
CodingChallenges
Apache License 2.0
src/main/kotlin/com/rtarita/days/Day12.kt
RaphaelTarita
570,100,357
false
{"Kotlin": 79822}
package com.rtarita.days import com.rtarita.structure.AoCDay import com.rtarita.util.day import com.rtarita.util.ds.graph.Graph import com.rtarita.util.ds.graph.MutableGraph import com.rtarita.util.ds.graph.buildGraph import kotlinx.datetime.LocalDate import java.util.LinkedList import java.util.Queue object Day12 : AoCDay { private data class Coord(val x: Int, val y: Int) override val day: LocalDate = day(12) private fun List<List<Char>>.atLocation(coord: Coord): Char = this[coord.y][coord.x] private fun MutableGraph<Coord>.processNode( origin: Coord, node: Coord, gridval: Int, grid: List<List<Char>>, visited: MutableSet<Coord> ) { if (node == origin) return if (node !in adjacentVertices(origin) && grid.atLocation(node).code - 1 <= gridval) { addEdge(origin, node) if (node !in visited) { processNeighbours(node, grid, visited) } } } private fun MutableGraph<Coord>.processNeighbours( location: Coord, grid: List<List<Char>>, visited: MutableSet<Coord> ) { visited += location val gridval = grid.atLocation(location).code val left = Coord((location.x - 1).coerceAtLeast(0), location.y) val up = Coord(location.x, (location.y - 1).coerceAtLeast(0)) val right = Coord((location.x + 1).coerceAtMost(grid[location.y].lastIndex), location.y) val down = Coord(location.x, (location.y + 1).coerceAtMost(grid.lastIndex)) processNode(location, left, gridval, grid, visited) processNode(location, up, gridval, grid, visited) processNode(location, right, gridval, grid, visited) processNode(location, down, gridval, grid, visited) } private fun parseGraph(input: String): Triple<Graph<Coord>, Coord, Coord> { val grid = input.lineSequence() .map { it.toMutableList() }.toMutableList() val start = grid.mapIndexed { y, line -> Coord(line.indexOf('S'), y) }.single { (x, _) -> x != -1 } val dest = grid.mapIndexed { y, line -> Coord(line.indexOf('E'), y) }.single { (x, _) -> x != -1 } grid[start.y][start.x] = 'a' grid[dest.y][dest.x] = 'z' return Triple(buildGraph { processNeighbours(start, grid, mutableSetOf()) }, start, dest) } private fun bfs(graph: Graph<Coord>, initial: Coord, target: Coord): Int { val queue: Queue<Coord> = LinkedList() val visited = mutableSetOf<Coord>() val prev = mutableMapOf<Coord, Coord?>() queue.add(initial) visited.add(initial) prev[initial] = null while (queue.isNotEmpty()) { val node = queue.poll() if (node == target) { val path = mutableListOf<Coord>() var current: Coord? = target while (current != null) { path += current current = prev[current] } return path.size - 1 } for (v in graph.adjacentVertices(node)) { if (v !in visited) { visited.add(v) queue.add(v) prev[v] = node } } } return Int.MAX_VALUE } override fun executePart1(input: String): Int { val (graph, start, dest) = parseGraph(input) return bfs(graph, start, dest) } override fun executePart2(input: String): Int { val possibleStartingPoints = input.lineSequence() .flatMapIndexed { y, line -> line.mapIndexedNotNull { x, elem -> if (elem != 'a' && elem != 'S') null else Coord(x, y) } } val (graph, _, dest) = parseGraph(input) return possibleStartingPoints.minOf { bfs(graph, it, dest) } } }
0
Kotlin
0
9
491923041fc7051f289775ac62ceadf50e2f0fbe
4,012
AoC-2022
Apache License 2.0
src/main/kotlin/me/giacomozama/adventofcode2023/days/Day03.kt
giacomozama
725,810,476
false
{"Kotlin": 12023}
package me.giacomozama.adventofcode2023.days import java.io.File class Day03 : Day() { private lateinit var input: List<String> override fun parseInput(inputFile: File) { input = inputFile.readLines() } override fun solveFirstPuzzle(): Int { fun isAdjacentToSymbol(y: Int, startX: Int, endX: Int): Boolean { fun checkLine(line: String): Boolean { if (startX > 0 && line[startX - 1] != '.') return true if (endX < input[y].length && line[endX] != '.') return true for (x in startX until endX) { if (line[x] != '.') return true } return false } if (startX > 0 && input[y][startX - 1] != '.') return true if (endX < input[y].length && input[y][endX] != '.') return true return y > 0 && (checkLine(input[y - 1])) || y < input.lastIndex && checkLine(input[y + 1]) } var result = 0 for ((y, line) in input.withIndex()) { var acc = 0 var startX = -1 for ((x, c) in line.withIndex()) { if (c.isDigit()) { if (startX == -1) { startX = x acc = c.digitToInt() } else { acc = acc * 10 + c.digitToInt() } } else { if (startX != -1) { if (isAdjacentToSymbol(y, startX, x)) result += acc acc = 0 startX = -1 } } } if (startX != -1 && isAdjacentToSymbol(y, startX, line.length)) result += acc } return result } override fun solveSecondPuzzle(): Int { val gearNumbers = hashMapOf<Int, MutableList<Int>>() fun mapStarNumber(y: Int, x: Int, value: Int) { gearNumbers.getOrPut(y * 1000 + x) { mutableListOf() }.add(value) } fun mapNearbyStars(y: Int, startX: Int, endX: Int, value: Int) { fun checkLine(lineY: Int) { val line = input[lineY] if (startX > 0 && line[startX - 1] == '*') mapStarNumber(lineY, startX - 1, value) if (endX < input[y].length && line[endX] == '*') mapStarNumber(lineY, endX, value) for (x in startX until endX) { if (line[x] == '*') mapStarNumber(lineY, x, value) } } if (startX > 0 && input[y][startX - 1] == '*') mapStarNumber(y, startX - 1, value) if (endX < input[y].length && input[y][endX] == '*') mapStarNumber(y, endX, value) if (y > 0) checkLine(y - 1) if (y < input.lastIndex) checkLine(y + 1) } for ((y, line) in input.withIndex()) { var acc = 0 var startX = -1 for ((x, c) in line.withIndex()) { if (c.isDigit()) { if (startX == -1) { startX = x acc = c.digitToInt() } else { acc = acc * 10 + c.digitToInt() } } else { if (startX != -1) { mapNearbyStars(y, startX, x, acc) acc = 0 startX = -1 } } } if (startX != -1) mapNearbyStars(y, startX, line.length, acc) } var result = 0 for (values in gearNumbers.values) { if (values.size == 2) result += values[0] * values[1] } return result } }
0
Kotlin
0
0
a86e9757288c63778e1f8f1f3fa5a2cfdaa6dcdd
3,753
aoc2023
MIT License
src/Day05.kt
elliaoster
573,666,162
false
{"Kotlin": 14556}
fun main() { fun moveBoxes(input: List<String>, multipleBoxMove: Boolean): String { var tops = "" //read the file to figure out how many stacks var numStacks = 0 for (line in input) { if (line[1] == '1') { numStacks = line.split(" ").last().toInt() break } } //make an array for that many stacks //var stacks:MutableList<MutableList<Char>>=mutableListOf(mutableListOf()) val stacks = MutableList(numStacks) { mutableListOf<Char>() } var readingCrates = true //read the file to put boxes in stacks for (line in input) { var spaceCounter = 0 var stackCounter = 0 if (readingCrates) { if (line.isEmpty()) { readingCrates = false continue } for (c in line.toCharArray()) { if (c == ' ') { spaceCounter++ if (spaceCounter == 4) { stackCounter++ spaceCounter = 0 } } else if (c == '[') { spaceCounter = 0 } else if (c == ']') { stackCounter++ } else if (c.isLetter()) { spaceCounter = 0 stacks[stackCounter].add(c) } } } else { //read the instructions val split = line.split(' ') var moveItems = split[1].toInt() val from = split[3].toInt() val to = split[5].toInt() //and move the boxes as they say if (!multipleBoxMove) { for (i in 1..moveItems) { stacks[to - 1].add(0, stacks[from - 1][0]) stacks[from - 1].removeFirst() //println(split) } } else { for (i in 1..moveItems) { stacks[to - 1].add(0, stacks[from - 1][moveItems-1]) stacks[from - 1].removeAt(moveItems-1) moveItems-- } } //println("Done processing line: ${line}") } } //read the first letter of all the stacks into its own string for (i in 0..stacks.lastIndex) { tops += stacks[i][0] } return tops } fun part1(input: List<String>): String { return moveBoxes(input, false) } fun part2(input: List<String>): String { return moveBoxes(input, true) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day05_test") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readInput("Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
27e774b133f9d5013be9a951d15cefa8cb01a984
3,102
advent-of-code-2022
Apache License 2.0
src/main/kotlin/Day11.kt
Walop
573,012,840
false
{"Kotlin": 53630}
import java.io.InputStream data class Monkey( val items: MutableList<Long>, val operation: (Long) -> Long, val test: Long, val trueReceiver: Int, val falseReceiver: Int, var inspectionCount: Long = 0 ) class Day11 { companion object { private fun createOperation(operator: String, other: Long?): (Long) -> Long { return when (operator) { "+" -> { old: Long -> old + (other ?: old) } else -> { old: Long -> old * (other ?: old) } } } private fun privateProcess(input: InputStream?, rounds: Int, worryDivider: Long): Long { if (input == null) { throw Exception("Input missing") } val numRegex = "\\d+".toRegex() val operatorRegex = "[+*]".toRegex() val monkeys = input.bufferedReader().useLines { lines -> lines.chunked(7) .map { monkeyDesc -> val items = numRegex.findAll(monkeyDesc[1]).map { it.value.toLong() }.toMutableList() //println(monkeyDesc) Monkey( items, createOperation( operatorRegex.find(monkeyDesc[2])!!.value, numRegex.find(monkeyDesc[2])?.value?.toLong() ), numRegex.find(monkeyDesc[3])!!.value.toLong(), numRegex.find(monkeyDesc[4])!!.value.toInt(), numRegex.find(monkeyDesc[5])!!.value.toInt(), ) }.toList() } val mod = monkeys.map { it.test }.fold(1L) { acc, it -> acc * it } for (i in 1..rounds) { for (monkey in monkeys) { monkey.items.map { monkey.operation(it) / worryDivider }.forEach { monkey.inspectionCount++ val reveiver = if ((it) % monkey.test == 0L) monkey.trueReceiver else monkey.falseReceiver val converted = it % mod monkeys[reveiver].items.add(converted) } monkey.items.clear() } // if (i == 1 || i % 1000 == 0) { // monkeys.forEachIndexed { index, it -> println("$index: ${it.items}, ${it.inspectionCount}") } // println() // } } return monkeys.sortedByDescending { it.inspectionCount }.take(2).map { it.inspectionCount } .fold(1L) { acc, count -> acc * count } } fun process(input: InputStream?): Long { return privateProcess(input, 20, 3L) } fun process2(input: InputStream?): Long { return privateProcess(input, 10_000, 1L) } } }
0
Kotlin
0
0
7a13f6500da8cb2240972fbea780c0d8e0fde910
3,024
AdventOfCode2022
The Unlicense
y2021/src/main/kotlin/adventofcode/y2021/Day19.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2021 import adventofcode.io.AdventSolution import adventofcode.util.collections.cartesian import adventofcode.util.vector.Vec3 object Day19 : AdventSolution(2021, 19, "Beacon Scanner") { override fun solvePartOne(input: String): Any { val scanners = parse(input) val closed = alignScanners(scanners) return closed.flatMap { it.key.beacons }.distinct().size } override fun solvePartTwo(input: String): Int { val scanners = parse(input) val closed = alignScanners(scanners) return closed.values.cartesian().maxOf { (a, b) -> a.manhattanDistanceTo(b) } } private fun alignScanners(scanners: List<Scanner>): Map<Scanner, Vec3> { val closed = mutableMapOf(scanners[0] to Vec3(0, 0, 0)) val openScanners = mutableListOf(scanners[0]) var unmatched = scanners.drop(1) while (unmatched.isNotEmpty()) { val placed = openScanners.removeLast() val matched: Map<Scanner, Scanner?> = unmatched.associateWith { current -> current.rotations.find { scanner -> (scanner.fingerprint.keys intersect placed.fingerprint.keys).size >= 66 } } unmatched = matched.filterValues { it == null }.keys.toList() matched.values.filterNotNull().map { scanner -> val matchingDistances = placed.fingerprint.keys intersect scanner.fingerprint.keys val (delta, count) = matchingDistances.map { k -> placed.fingerprint.getValue(k) - scanner.fingerprint.getValue(k) } .groupingBy { it } .eachCount() .maxByOrNull { it.value }!! require(count >= 66) val shifted = Scanner(scanner.beacons.map { it + delta }) openScanners += shifted closed += shifted to delta } } return closed } } private val rotationFns: List<(Vec3) -> Vec3> = listOf( { (x, y, z) -> Vec3(x, y, z) }, { (x, y, z) -> Vec3(x, z, -y) }, { (x, y, z) -> Vec3(x, -y, -z) }, { (x, y, z) -> Vec3(x, -z, y) }, { (x, y, z) -> Vec3(-x, z, y) }, { (x, y, z) -> Vec3(-x, y, -z) }, { (x, y, z) -> Vec3(-x, -z, -y) }, { (x, y, z) -> Vec3(-x, -y, z) }, { (x, y, z) -> Vec3(y, z, x) }, { (x, y, z) -> Vec3(y, x, -z) }, { (x, y, z) -> Vec3(y, -z, -x) }, { (x, y, z) -> Vec3(y, -x, z) }, { (x, y, z) -> Vec3(-y, x, z) }, { (x, y, z) -> Vec3(-y, z, -x) }, { (x, y, z) -> Vec3(-y, -x, -z) }, { (x, y, z) -> Vec3(-y, -z, x) }, { (x, y, z) -> Vec3(z, x, y) }, { (x, y, z) -> Vec3(z, y, -x) }, { (x, y, z) -> Vec3(z, -x, -y) }, { (x, y, z) -> Vec3(z, -y, x) }, { (x, y, z) -> Vec3(-z, y, x) }, { (x, y, z) -> Vec3(-z, x, -y) }, { (x, y, z) -> Vec3(-z, -y, -x) }, { (x, y, z) -> Vec3(-z, -x, y) } ) private data class Scanner(val beacons: List<Vec3>) { //het verschil tussen alle paren van punten is een soort van fingerprint voor de hele beacon //Om een match te zijn van tenminste 12 punten, moeten de verschillen ook matchen. Dus tenminste 12*11/2 matches //best wel wat aannames: // Geen paren van punten met hetzelfde verschil // als er genoeg matches tussen verschillen zijn, dan zal het wel kloppen. (hier zit wel een controle op) // de key is om te matchen, de value is om snel de translatie uit te voeren. val fingerprint: Map<Vec3, Vec3> by lazy { buildMap { for (a in beacons.indices) { for (b in a + 1..beacons.lastIndex) { put(beacons[a] - beacons[b], beacons[a]) } } } } val rotations: List<Scanner> by lazy { rotationFns.map { fn -> beacons.map { fn(it) }.sortedWith(compareBy(Vec3::x).thenComparing(Vec3::y).thenComparing(Vec3::z)) .let(::Scanner) } } } private fun parse(input: String) = input.split("\n\n").map { parseScanner(it) } private fun parseScanner(input: String) = input.lines().drop(1).map(::parseVector) .sortedWith(compareBy(Vec3::x).thenComparing(Vec3::y).thenComparing(Vec3::z)) .let(::Scanner) private fun parseVector(it: String) = it.split(',').map(String::toInt).let { (x, y, z) -> Vec3(x, y, z) }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
4,404
advent-of-code
MIT License
aoc2022/day10.kt
davidfpc
726,214,677
false
{"Kotlin": 127212}
package aoc2022 import utils.InputRetrieval fun main() { Day10.execute() } object Day10 { fun execute() { val input = readInput() println("Part 1: ${part1(input)}") println("Part 2:") part2(input) } private val CYCLES = listOf(20, 60, 100, 140, 180, 220) private fun part1(input: List<String>): Int { return processInstructions(input, 220).mapIndexed { index, value -> if (CYCLES.contains(index)) { index * value } else { 0 } }.sum() } private fun part2(input: List<String>) { val spritePositions = processInstructions(input, 240) (1..240).forEach { val currentSpritePos = spritePositions[it] // print twice as many pixels to make it more readable if (((it - 1) % 40) in (currentSpritePos - 1..currentSpritePos + 1)) { print("##") } else { print("..") } if ((it % 40) == 0) { println() } } } private fun processInstructions(input: List<String>, maxCycles: Int): List<Int> { var x = 1 // initial signal strength val result = mutableListOf(1) var instructionPointer = 0 var processing = false // run 220 cycles for (it in 1..maxCycles) { result.add(x) // process instruction if (instructionPointer == input.size) { continue } val instruction = input[instructionPointer] when (instruction.substring(0..3)) { "noop" -> instructionPointer++ "addx" -> if (processing) { processing = false instructionPointer++ x += instruction.substringAfter("addx ").toInt() } else { processing = true } } } return result } private fun readInput(): List<String> = InputRetrieval.getFile(2022, 10).readLines() }
0
Kotlin
0
0
8dacf809ab3f6d06ed73117fde96c81b6d81464b
2,124
Advent-Of-Code
MIT License
src/year2022/01/Day01.kt
Vladuken
573,128,337
false
{"Kotlin": 327524, "Python": 16475}
package year2022.`01` import readInput fun main() { fun prepareListOfElfsWithCalories(input: List<String>): List<List<Int>> { return input // Null is for empty strings that are separators. .map { it.toIntOrNull() } .fold(mutableListOf(mutableListOf<Int>())) { listOfElfs, product -> if (product == null) { listOfElfs.add(mutableListOf()) } else { listOfElfs.last().add(product) } listOfElfs } } fun part1(input: List<String>): Int { return prepareListOfElfsWithCalories(input) .maxOfOrNull { it.sum() } ?: error("Illegal state") } fun part2(input: List<String>): Int { return prepareListOfElfsWithCalories(input) .map { it.sum() } .sortedDescending() .take(3) .sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part2(testInput) == 45000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
5
c0f36ec0e2ce5d65c35d408dd50ba2ac96363772
1,191
KotlinAdventOfCode
Apache License 2.0
kotlin/src/main/kotlin/AoC_Day6.kt
sviams
115,921,582
false
null
object AoC_Day6 { data class State(val steps: Int, val work: Array<Byte>, val mem: MutableList<Array<Byte>>) { fun repeats() : Boolean = mem.count { it contentEquals work } > 1 } fun solve2(input: Array<Byte>) : State { val width = input.size return generateSequence(State(0, input, mutableListOf(input.copyOf()))) { (steps, work, mem) -> val startIndex = work.indexOfFirst { it == work.max() } val toBeMovedValue = work[startIndex] work[startIndex] = 0 (toBeMovedValue downTo 1).fold((startIndex+1) % width) { index, _ -> work[index]++ (index + 1) % width } mem.add(work.copyOf()) State(steps + 1, work, mem) }.takeWhileInclusive { !it.repeats() }.last() } fun solvePt1(work: Array<Byte>) : Int = solve2(work).steps fun solvePt2(work: Array<Byte>) : Int { val endState = solve2(work) return endState.mem.size - endState.mem.indexOfFirst { it contentEquals endState.mem.last() } - 1 } }
0
Kotlin
0
0
19a665bb469279b1e7138032a183937993021e36
1,086
aoc17
MIT License
src/Day01.kt
esteluk
572,920,449
false
{"Kotlin": 29185}
fun main() { fun part1(input: List<String>): Int { var i = 0 val arr = IntArray(input.size) input.forEach { if (it.isEmpty()) { i += 1 } else { arr[i] += it.toInt() } } return arr.max() } fun part2(input: List<String>): Int { var i = 0 val arr = IntArray(input.size) input.forEach { if (it.isEmpty()) { i += 1 } else { arr[i] += it.toInt() } } arr.sortDescending() return arr[0]+arr[1]+arr[2] } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
5d1cf6c32b0c76c928e74e8dd69513bd68b8cb73
918
adventofcode-2022
Apache License 2.0
src/main/kotlin/com/kishor/kotlin/algo/algorithms/graph/RemoveIslands.kt
kishorsutar
276,212,164
false
null
package com.kishor.kotlin.algo.algorithms.graph import java.util.* class RemoveIslands { fun removeIsland(matrix: List<MutableList<Int>>): List<MutableList<Int>> { for (row in 0 until matrix.size) { val rowBorder = row == 0 || row == matrix.size - 1 for (col in 0 until matrix[row].size) { val colBorder = col == 0 || col == matrix[row].size - 1 val isBorder = rowBorder || colBorder if (!isBorder) continue if (matrix[row][col] != 1) continue dfsAndMarkTwo(matrix, Pair(row, col)) } } for (row in 0 until matrix.size) { for (col in 0 until matrix[row].size) { if (matrix[row][col] > 0) { matrix[row][col] -= 1 } } } return matrix } fun dfsAndMarkTwo(matrix: List<MutableList<Int>>, position: Pair<Int, Int>) { val stack = Stack<Pair<Int, Int>>() stack.push(position) while (stack.isNotEmpty()) { val currentPosition = stack.pop() val (currentRow, currentCol) = currentPosition matrix[currentRow][currentCol] = 2 val itemsNeighbourList = getItemNeighbour(matrix, currentPosition) for (neighbour in itemsNeighbourList) { val (row, col) = neighbour if (matrix[row][col] != 1) continue stack.add(Pair(row, col)) } } } fun getItemNeighbour(matrix: List<MutableList<Int>>, item: Pair<Int, Int>): List<Pair<Int, Int>> { val neighbours = mutableListOf<Pair<Int, Int>>() val (row, col) = item val numRows = matrix.size val numCols = matrix[row].size if (row - 1 >= 0) neighbours.add(Pair(row - 1, col)) if (row + 1 < numRows) neighbours.add(Pair(row + 1, col)) if (col - 1 >= 0) neighbours.add(Pair(row, col - 1)) if (col + 1 < numCols) neighbours.add(Pair(row, col + 1)) return neighbours } }
0
Kotlin
0
0
6672d7738b035202ece6f148fde05867f6d4d94c
2,085
DS_Algo_Kotlin
MIT License
src/Day04.kt
konclave
573,548,763
false
{"Kotlin": 21601}
fun main() { fun solve1(input: List<String>): Int { return input.filter { val (fstStart, fstEnd, sndStart, sndEnd) = it.split(Regex("[-,]")).map{ it.toInt() } sndStart >= fstStart && sndEnd <= fstEnd || fstStart >= sndStart && fstEnd <= sndEnd }.size } fun solve2(input: List<String>): Int { return input.filter { val (fstStart, fstEnd, sndStart, sndEnd) = it.split(Regex("[-,]")).map{ it.toInt() } sndStart in fstStart..fstEnd || fstStart in sndStart..sndEnd }.size } val input = readInput("Day04") println(solve1(input)) println(solve2(input)) }
0
Kotlin
0
0
337f8d60ed00007d3ace046eaed407df828dfc22
650
advent-of-code-2022
Apache License 2.0
src/main/kotlin/days/y23/Day01.kt
kezz
572,635,766
false
{"Kotlin": 20772}
package days.y23 import util.Day import util.debug import util.mapInner public fun main() { Day01().run() } public class Day01 : Day(23, 1) { private val replacements = 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, ) private val matchRegex = replacements .entries .map { (word, digit) -> listOf(word, digit.toString()) } .flatten() .joinToString(separator = "|") .toRegex() override fun part1(input: List<String>): Any = input .map(String::toCharArray) .mapInner(Char::digitToIntOrNull) .map(List<Int?>::filterNotNull) .map { list -> Pair(list.first(), list.last()) } .sumOf { (tens, units) -> (tens * 10) + units } override fun part2(input: List<String>): Any = input .map { string -> string.indices.mapNotNull { index -> matchRegex.find(string, index) } } .mapInner(MatchResult::value) .mapInner { value -> (value.toIntOrNull() ?: replacements[value])?.toString()?.debug() ?: value } .map(List<String>::joinToString) .let(::part1) }
0
Kotlin
0
0
1cef7fe0f72f77a3a409915baac3c674cc058228
1,234
aoc
Apache License 2.0
src/main/kotlin/io/undefined/IntervalListIntersections.kt
jffiorillo
138,075,067
false
{"Kotlin": 434399, "Java": 14529, "Shell": 465}
package io.undefined import io.utils.runTests // https://leetcode.com/problems/interval-list-intersections/ class IntervalListIntersections { fun execute(input0: Array<IntArray>, input1: Array<IntArray>): Array<IntArray> { var index0 = 0 var index1 = 0 val result = mutableListOf<IntArray>() while (index0 in input0.indices && index1 in input1.indices) { val (start0, end0) = input0[index0] val (start1, end1) = input1[index1] when { start0 in start1..end1 || start1 in start0..end0 -> { result.add(intArrayOf(maxOf(start0, start1), minOf(end0, end1))) } } if (end0 > end1) index1++ else index0++ } return result.toTypedArray() } } fun main() { runTests(listOf( Triple(arrayOf(intArrayOf(0, 2), intArrayOf(5, 10), intArrayOf(13, 23), intArrayOf(24, 25)), arrayOf(intArrayOf(1, 5), intArrayOf(8, 12), intArrayOf(15, 24), intArrayOf(25, 26)), listOf(listOf(1, 2), listOf(5, 5), listOf(8, 10), listOf(15, 23), listOf(24, 24), listOf(25, 25))) )) { (input0, input1, value) -> value to IntervalListIntersections().execute(input0, input1).map { it.toList() } } }
0
Kotlin
0
0
f093c2c19cd76c85fab87605ae4a3ea157325d43
1,176
coding
MIT License
2023/src/main/kotlin/org/suggs/adventofcode/Day08HauntedWasteland.kt
suggitpe
321,028,552
false
{"Kotlin": 156836}
package org.suggs.adventofcode import org.slf4j.LoggerFactory object Day08HauntedWasteland { private val log = LoggerFactory.getLogger(this::class.java) fun countHopsInDataMap(data: List<String>): Long = countHopsToFinsh("AAA", data.first(), buildHopsDataMapFrom(data), 0) .also { log.debug("Part 1: $it") } private tailrec fun countHopsToFinsh(key: String, indicator: String, hopMap: Map<String, Hop>, accumulator: Long): Long = if (key == "ZZZ") accumulator else countHopsToFinsh(hopMap[key]!!.get(indicator.first()), shuffleIndicators(indicator), hopMap, accumulator + 1L) fun countHopsInDataMapForMultiHop(data: List<String>): Long { val hopMap = buildHopsDataMapFrom(data) return hopMap.keys.filter { it.endsWith("A") } .map { countHopsToFinshEndingZ(it, data.first(), buildHopsDataMapFrom(data), 0) } .reduce { acc, next -> lcm(acc, next) } .also { log.debug("Part 2: $it") } } private tailrec fun countHopsToFinshEndingZ(key: String, indicator: String, hopMap: Map<String, Hop>, accumulator: Long): Long = if (key.endsWith("Z")) accumulator else countHopsToFinshEndingZ(hopMap[key]!!.get(indicator.first()), shuffleIndicators(indicator), hopMap, accumulator + 1L) private fun lcm(a: Long, b: Long) = a / gcd(a, b) * b private fun gcd(a: Long, b: Long): Long = if (b == 0L) a else gcd(b, a % b) private fun shuffleIndicators(indicator: String) = indicator.drop(1) + indicator.first() private fun buildHopsDataMapFrom(data: List<String>) = data.last().split("\n").associate { it.split(" ").first() to Hop(it) } } data class Hop(val left: String, val right: String) { companion object { operator fun invoke(hopData: String): Hop = Hop( hopData.split("(")[1].split(",").first().trim(), hopData.split("(")[1].split(",")[1].split(")").first().trim() ) } fun get(indicator: Char) = if (indicator == 'L') left else right }
0
Kotlin
0
0
9485010cc0ca6e9dff447006d3414cf1709e279e
2,103
advent-of-code
Apache License 2.0
src/day04/Day04.kt
gagandeep-io
573,585,563
false
{"Kotlin": 9775}
package day04 import readInput fun main() { fun List<String>.ranges() = map { val (firstElf, secondElf) = it.split(",") Pair(firstElf.toRange(), secondElf.toRange()) } fun part1(input: List<String>): Int = input.ranges().count { it.first in it.second || it.second in it.first } fun part2(input: List<String>): Int = input.ranges().count { it.first overlaps it.second || it.second overlaps it.first } val input = readInput("day04/Day04_test") //val input = readInput("day04/Day04") println(part1(input)) println(part2(input)) } private fun String.toRange(): IntRange { val (start, end) = this.split("-") return IntRange(start.toInt(), end.toInt()) } private operator fun IntRange.contains(other: IntRange): Boolean = other.first in this && other.last in this private infix fun IntRange.overlaps(other: IntRange): Boolean = other.first in this || other.last in this
0
Kotlin
0
0
952887dd94ccc81c6a8763abade862e2d73ef924
954
aoc-2022-kotlin
Apache License 2.0
src/Day21.kt
MarkTheHopeful
572,552,660
false
{"Kotlin": 75535}
private sealed interface MathMonkey { fun initLeftRight(information: Map<String, MathMonkey>) fun isConcrete(): Boolean fun eval(): Long } private class JustYell(val name: String, val value: Long) : MathMonkey { override fun initLeftRight(information: Map<String, MathMonkey>) {} override fun isConcrete(): Boolean = true override fun eval(): Long = value } private class Human(val name: String, val value: Long) : MathMonkey { override fun initLeftRight(information: Map<String, MathMonkey>) {} override fun isConcrete(): Boolean = false override fun eval(): Long = value } private class WithChildren( val name: String, val leftName: String, val rightName: String, val f: ((Long, Long) -> Long), val revFL: ((Long, Long) -> Long), val revFR: ((Long, Long) -> Long) ) : MathMonkey { var left: MathMonkey? = null var right: MathMonkey? = null var concrete: Boolean? = null var storedValue: Long? = null override fun initLeftRight(information: Map<String, MathMonkey>) { left = information[leftName] right = information[rightName] } fun getLeftOrFail(): MathMonkey = left ?: error("Child not initialized") fun getRightOrFail(): MathMonkey = right ?: error("Child not initialized") override fun isConcrete(): Boolean { if (concrete != null) return concrete!! concrete = getLeftOrFail().isConcrete() && getRightOrFail().isConcrete() return concrete!! } override fun eval(): Long { return storedValue ?: if (isConcrete()) { storedValue = f(getLeftOrFail().eval(), getRightOrFail().eval()) storedValue!! } else { f(getLeftOrFail().eval(), getRightOrFail().eval()) } } fun whatNeedFromNotConcreteToEqual(needed: Long): Pair<MathMonkey, Long> { assert(!isConcrete()) if (getLeftOrFail().isConcrete()) { assert(!getRightOrFail().isConcrete()) return getRightOrFail() to revFR(needed, getLeftOrFail().eval()) } assert(getRightOrFail().isConcrete()) return getLeftOrFail() to revFL(needed, getRightOrFail().eval()) } } fun main() { val mathMap: Map<Char, Pair<MathOp, Pair<MathOp, MathOp>>> = mapOf( '/' to Pair( { x, y -> x / y }, Pair({ result: Long, known: Long -> result * known }, { result: Long, known: Long -> known / result }) ), '*' to Pair( { x, y -> x * y }, Pair({ result: Long, known: Long -> result / known }, { result: Long, known: Long -> result / known }) ), '+' to Pair( { x, y -> x + y }, Pair({ result: Long, known: Long -> result - known }, { result: Long, known: Long -> result - known }) ), '-' to Pair( { x, y -> x - y }, Pair({ result: Long, known: Long -> result + known }, { result: Long, known: Long -> known - result }) ), ) fun getMonkeyMap(input: List<String>): Map<String, MathMonkey> { val monkeyMap: MutableMap<String, MathMonkey> = mutableMapOf() input.map { it.split(':') }.forEach { (name, def) -> val parts = def.trim().split(' ') monkeyMap[name] = if (parts.size == 1) { if (name == "humn") { Human(name, parts[0].toLong()) } else { JustYell(name, parts[0].toLong()) } } else { val (f, pairRevFLR) = mathMap[parts[1][0]]!! WithChildren(name, parts[0], parts[2], f, pairRevFLR.first, pairRevFLR.second) } } monkeyMap.forEach { it.value.initLeftRight(monkeyMap) } return monkeyMap } fun part1(input: List<String>): Long { val monkeyMap = getMonkeyMap(input) return monkeyMap["root"]?.eval() ?: error("No root?") } fun part2(input: List<String>): Long { val monkeyMap = getMonkeyMap(input) val root: WithChildren = (monkeyMap["root"] ?: error("No root?")) as WithChildren val left = root.getLeftOrFail() val right = root.getRightOrFail() var currentValueNeeded = if (left.isConcrete()) { left.eval() } else { assert(right.isConcrete()) right.eval() } var currentNode = if (left.isConcrete()) right else left while (currentNode !is Human) { require(currentNode is WithChildren) val nodeAndValue = currentNode.whatNeedFromNotConcreteToEqual(currentValueNeeded) currentNode = nodeAndValue.first currentValueNeeded = nodeAndValue.second } return currentValueNeeded } // test if implementation meets criteria from the description, like: val testInput = readInput("Day21_test") check(part1(testInput) == 152L) check(part2(testInput) == 301L) val input = readInput("Day21") println(part1(input)) println(part2(input)) } private typealias MathOp = (Long, Long) -> Long
0
Kotlin
0
0
8218c60c141ea2d39984792fddd1e98d5775b418
5,116
advent-of-kotlin-2022
Apache License 2.0