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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
day06/part2.kts | bmatcuk | 726,103,418 | false | {"Kotlin": 214659} | // --- Part Two ---
// As the race is about to start, you realize the piece of paper with race
// times and record distances you got earlier actually just has very bad
// kerning. There's really only one race - ignore the spaces between the
// numbers on each line.
//
// So, the example from before:
//
// Time: 7 15 30
// Distance: 9 40 200
//
// ...now instead means this:
//
// Time: 71530
// Distance: 940200
//
// Now, you have to figure out how many ways there are to win this single race.
// In this example, the race lasts for 71530 milliseconds and the record
// distance you need to beat is 940200 millimeters. You could hold the button
// anywhere from 14 to 71516 milliseconds and beat the record, a total of 71503
// ways!
//
// How many ways can you beat the record in this one much longer race?
import java.io.*
import kotlin.math.*
val (time, distance) = File("input.txt").readLines().map {
it.dropWhile { !it.isDigit() }.filterNot { it.isWhitespace() }.toDouble()
}
// If total time is `T`, winning distance is `D`, and time spent holding the
// button is `x`, `(T - x)` would be the remaining time where the boat is
// moving, and `(T - x) * x` would be the distance moved. Therefore, we want to
// solve the equation `(T - x) * x > D`. This can be done with the quadratic
// formula, giving us: `(-T ± √(T² - 4D)) / -2`. Or, basically, the ceiling in
// the plus case, and the floor in the minus case. If the results of the
// calculation are an integer (meaning ceiling or floor doesn't change the
// answer), then nudge the result one higher for ceiling, or one lower for
// floor using a tiny fudge factor.
val sqrtTerm = sqrt(time.pow(2) - 4.0 * distance)
val minimum = ceil((-time + sqrtTerm) / -2.0 + 0.00001)
val maximum = floor((-time - sqrtTerm) / -2.0 - 0.00001)
val result = maximum - minimum + 1.0
println(result.toLong())
| 0 | Kotlin | 0 | 0 | a01c9000fb4da1a0cd2ea1a225be28ab11849ee7 | 1,881 | adventofcode2023 | MIT License |
src/Day10.kt | catcutecat | 572,816,768 | false | {"Kotlin": 53001} | import kotlin.system.measureTimeMillis
fun main() {
measureTimeMillis {
Day10.run {
solve1(13140) // 14760
solve2(0) // "EFGERURE"
}
}.let { println("Total: $it ms") }
}
object Day10 : Day.LineInput<List<Day10.Data>, Int>("10") {
data class Data(val isAdd: Boolean, val num: Int)
override fun parse(input: List<String>) = input.map {
"$it 0".split(" ").let { (command, num) ->
Data(command == "addx", num.toInt())
}
}
override fun part1(data: List<Data>): Int {
var res = 0
var nextCheck = 20
var x = 1
var cycle = 0
for ((isAdd, num) in data) {
cycle += if (isAdd) 2 else 1
if (cycle >= nextCheck) {
res += x * nextCheck
nextCheck += 40
}
x += num
}
return res
}
override fun part2(data: List<Data>): Int {
val res = mutableListOf(BooleanArray(40))
var x = 1
var curr = 0
for ((isAdd, num) in data) {
repeat(if (isAdd) 2 else 1) {
res.last()[curr] = curr in x - 1 .. x + 1
if (++curr == 40) {
res.add(BooleanArray(40))
curr = 0
}
}
x += num
}
for (row in res) row.joinToString("") { if (it) "⚽" else "⚫" }.let(::println)
return 0
}
} | 0 | Kotlin | 0 | 2 | fd771ff0fddeb9dcd1f04611559c7f87ac048721 | 1,466 | AdventOfCode2022 | Apache License 2.0 |
src/main/kotlin/gal/usc/citius/processmining/dfgfiltering/filtering/TwoWaysEdmonds.kt | david-chapela | 322,881,845 | false | null | package gal.usc.citius.processmining.dfgfiltering.filtering
import gal.usc.citius.processmining.dfgfiltering.graph.DirectedGraph
import gal.usc.citius.processmining.dfgfiltering.graph.Edge
import gal.usc.citius.processmining.dfgfiltering.graph.Vertex
import java.util.Deque
import java.util.LinkedList
/**
* Given a connected digraph with one source and one sink vertices, and where all vertices are in, at least, a path from
* root to sink (i.e., a Directly Follows Graph), obtains an approximation to the maximally filtered directly follows
* graph (MF-DFG) maximizing (or minimizing) the total weight of the DFG by combining two arborescence with maximum
* (or minimum weight) using Edmonds' Algorithm.
*
* @param minimum if set to true search for the minimum equivalent graph with the lowest overall weight.
*
* @return an approximation to the MF-DFG problem with a maximum total weight (minimum if [minimum] is true).
*/
fun DirectedGraph.filterEdgesTWE(minimum: Boolean = false): DirectedGraph {
this.checkDFGCorrectness()
val digraph = this.removeSelfCycles()
.let { if (minimum) it.invertWeights() else it }
// Call Edmond's algorithm forward
val root = digraph.vertices.first { vertex ->
vertex !in this.edges.map { it.to }
}
val fwMSA = digraph.getSpanningArborescence(root)
// Call Edmond's algorithm backwards
val sink = digraph.vertices.first { vertex ->
vertex !in this.edges.map { it.from }
}
val bwMSA = digraph.reverse().getSpanningArborescence(sink).reverse()
// Merge
val meg = DirectedGraph(
vertices = digraph.vertices,
edges = fwMSA.edges + bwMSA.edges
)
return if (minimum) meg.invertWeights() else meg
}
/**
* Edmonds' Algorithm: get the spanning arborescence with the maximum weight (the sum of all edge weights). An
* arborescence is a directed graph in which, for a vertex u called root and any other vertex v, there is exactly one
* directed path from u to v. An arborescence is thus the directed-graph form of a rooted tree.
*
* @param root vertex from the graph to be the root of the arborescence.
* @param minimum if set to true search for the minimum spanning arborescence with the lowest overall weight.
*
* @return the spanning arborescence rooted in [root] and with a maximum total weight (minimum if [minimum] is set to
* true).
*/
fun DirectedGraph.getSpanningArborescence(root: Vertex, minimum: Boolean = false): DirectedGraph {
var arborescence: DirectedGraph
// If we search for the minimum invert the edge weights
var digraph = if (minimum) this.invertWeights() else this
val cyclesLIFO: Deque<Pair<Vertex, DirectedGraph>> = LinkedList()
val edgesHistoryLIFO: Deque<MutableMap<Edge, Edge>> = LinkedList()
var cycleCounter = 0
// Iterative arborescence construction until no cycles remaining
do {
// Get, for each vertex except the root, the incoming edge with more weight
arborescence = digraph.copy(
edges = digraph.vertices
.filter { it != root }
.mapNotNull { currentVertex ->
digraph.edges
.filter { it.to == currentVertex }
.maxByOrNull { it.weight }
}
)
// Detect cycles
val cycles = arborescence.getArborescenceCycles()
// If there is any cycle, copy the current digraph collapsing the cycles into
// single vertices, and updating the weights of the edges entering the cycle
cycles.forEach { cycle ->
// Vertex to collapse the cycle
val collapsedCycle = Vertex("cycle${cycleCounter++}")
// Save the cycle to re-expand it later
cyclesLIFO.push(collapsedCycle to cycle)
// Edges renaming history for this cycle
val edgesHistory = mutableMapOf<Edge, Edge>()
// Edge inside the cycle with minimum weight
val minEdge = cycle.edges.minByOrNull { it.weight }!!
// Update digraph collapsing the cycle
digraph = DirectedGraph(
vertices = digraph.vertices - cycle.vertices + collapsedCycle,
edges = digraph.edges.mapNotNull { edge ->
when {
edge.from !in cycle.vertices && edge.to !in cycle.vertices -> {
// Edge outside the cycle
edge
}
edge.from !in cycle.vertices && edge.to in cycle.vertices -> {
// Edge entering the cycle
val newEdge = edge.copy(
to = collapsedCycle,
weight = edge.weight + minEdge.weight - cycle.edges.find { it.to == edge.to }!!.weight
)
edgesHistory += newEdge to edge
newEdge
}
edge.from in cycle.vertices && edge.to !in cycle.vertices -> {
// Edge leaving the cycle
val newEdge = edge.copy(
from = collapsedCycle
)
edgesHistory += newEdge to edge
newEdge
}
else -> {
// Edge inside the cycle
null
}
}
}
)
// Save this edge renaming history
edgesHistoryLIFO.push(edgesHistory)
}
} while (cycles.isNotEmpty())
// Re-expand the cycles
while (cyclesLIFO.isNotEmpty()) {
// Retrieve last collapsed cycle
val (collapsedCycle, cycle) = cyclesLIFO.pop()
// Retrieve edge renaming history for this cycle
val edgesHistory = edgesHistoryLIFO.pop()
// Update the edges in the arborescence going to/from the collapsed cycle
val newEdges = arborescence.edges.map { edge ->
when (edge) {
in edgesHistory.keys -> edgesHistory[edge]!!
else -> edge
}
}
// Update the arborescence including the re-expanded cycle, and removing
// the edge going to the same vertex as the new edge entering the cycle
arborescence = arborescence.copy(
vertices = arborescence.vertices - collapsedCycle + cycle.vertices,
edges = newEdges + cycle.edges.filter { edge ->
edge.to !in newEdges.map { it.to }
}
)
}
return if (minimum) arborescence.invertWeights() else arborescence
}
/**
* Given an arborescence, a directed graph where each vertex contains only one incoming edge, except for the root which
* contains no incoming edges, search the cycles, if any.
*
* For this, the vertices with no incoming or outgoing edges are removed iteratively, along with the edges connected to
* them. Once there are no more vertices without incoming or outgoing edges, the remaining structures are the cycles, if
* any.
*
* @return a set with the cycles in the arborescence, if any.
*/
private fun DirectedGraph.getArborescenceCycles(): Set<DirectedGraph> {
var digraph = this.copy()
// Remove iteratively the edges of those vertices with no incoming or outgoing edges
do {
val fullyConnectedVertices = digraph.edges.map { it.from }.intersect(digraph.edges.map { it.to })
digraph = DirectedGraph(
vertices = fullyConnectedVertices,
edges = digraph.edges.filter { it.from in fullyConnectedVertices && it.to in fullyConnectedVertices }
)
// Check if there is still orphan vertices remaining
val orphanRemaining = fullyConnectedVertices.any { vertex ->
vertex !in digraph.edges.map { it.from } ||
vertex !in digraph.edges.map { it.to }
}
} while (orphanRemaining)
// Retrieve each connected component, i.e., each cycle
val visitedVertices = mutableSetOf<Vertex>()
val cycles = mutableSetOf<DirectedGraph>()
while (visitedVertices != digraph.vertices) {
// get one unvisited vertex and get the vertices reaching it
val unvisitedVertex = digraph.vertices.first { it !in visitedVertices }
val cycle = digraph.getSubgraphConnectedTo(unvisitedVertex)
// mark all cycle vertices as visited
visitedVertices += cycle.vertices
// save the cycle
cycles += cycle
}
return cycles
}
| 0 | Kotlin | 0 | 0 | d73d1f3f3462f9ef3d699d8fafb1435084b472ef | 8,689 | dfg-edge-filtering | MIT License |
src/main/kotlin/cloud/dqn/leetcode/self/MyHeap.kt | aviuswen | 112,305,062 | false | null | package cloud.dqn.leetcode.self
import java.util.Comparator
class MyHeap<T> {
private var heap: ArrayList<T> = ArrayList()
private var comparator: Comparator<T>
constructor(comparator: Comparator<T>) {
this.comparator = comparator
}
// add to the end of the tree; heapUp
fun push(t: T) {
heap.add(t)
heapUp(heap.size - 1)
}
// copy element from 0; switch last to top; heapDown
fun pop(): T? {
if (heap.isEmpty()) {
return null
}
swap(0, heap.size - 1)
val result = heap.removeAt(heap.size - 1)
heapDown(0)
return result
}
private fun heapUp(index: Int) {
var i = index
var parentI = parentIndex(i)
var parent = parentI?.let { heap[it] }
// possible boolean error (>= 0 ? instead)
while (parent != null && comparator.compare(parent, heap[i]) > 0) {
// swap
parentI = parentI?.let {
swap(it, i)
i = it
parentIndex(it)
}
parent = parentI?.let { heap[it] }
}
}
private fun heapDown(index: Int) {
var i = index
var lowest = lowestOfChildren(i)
while (lowest != null && comparator.compare(heap[i], heap[lowest]) > 0) {
swap(i, lowest)
i = lowest
lowest = lowestOfChildren(i)
}
}
private fun lowestOfChildren(index: Int?): Int? {
return index?.let {
childLeft(index)?.let { lowestIndex ->
var result = lowestIndex
childRight(index)?.let { rightIndex ->
// possible boolean error (<= 0 ? instead)
if (comparator.compare(heap[lowestIndex], heap[rightIndex]) > 0) {
result = rightIndex
}
}
result
}
}
}
/**
* 0
* / \
* 1 2
* / \ / \
* 3 4 5 6
* 7 8 9 10
*/
private fun parentIndex(index: Int): Int? {
val i = (index - 1) / 2
return if (inHeap(i)) i else null
}
private fun childLeft(index: Int): Int? {
val i = index * 2 + 1
return if (inHeap(i)) i else null
}
private fun childRight(index: Int): Int? {
val i = index * 2 + 2
return if (inHeap(i)) i else null
}
private fun inHeap(index: Int) = (index >= 0 && index < heap.size)
private fun swap(i: Int, j: Int) {
val temp = heap[i]
heap[i] = heap[j]
heap[j] = temp
}
companion object {
val DEFAULT_CAPACITY = 10
}
} | 0 | Kotlin | 0 | 0 | 23458b98104fa5d32efe811c3d2d4c1578b67f4b | 2,764 | cloud-dqn-leetcode | No Limit Public License |
src/main/kotlin/ctci/chaptersixteen/EnglishInt.kt | amykv | 538,632,477 | false | {"Kotlin": 169929} | package ctci.chaptersixteen
// 16.8 - page 182
// Given any integer, print an English phrase that describes the integer (e.g., "One Thousand, Two Hundred
// Thirty Four").
fun main() {
val num = 123456
println(numberToWords(num))
}
fun numberToWords(num: Int): String {
if (num == 0) return "Zero"
val words = arrayOf("", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven",
"Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen", "Twenty")
val tens = arrayOf("", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety")
var n = num
var result = ""
if (n >= 1000000000) {
result += numberToWords(n / 1000000000) + " Billion "
n %= 1000000000
}
if (n >= 1000000) {
result += numberToWords(n / 1000000) + " Million "
n %= 1000000
}
if (n >= 1000) {
result += numberToWords(n / 1000) + " Thousand "
n %= 1000
}
if (n >= 100) {
result += numberToWords(n / 100) + " Hundred "
n %= 100
}
if (n >= 20) {
result += tens[n / 10] + " "
n %= 10
}
result += words[n]
return result.trim()
}
//The space complexity of this algorithm is O(1), since we're using constant additional memory. The time complexity
// is O(log n), where n is the size of the input number.
| 0 | Kotlin | 0 | 2 | 93365cddc95a2f5c8f2c136e5c18b438b38d915f | 1,417 | dsa-kotlin | MIT License |
kotlin/src/main/kotlin/dev/mikeburgess/euler/problems/Problem006.kt | mddburgess | 261,028,925 | false | null | package dev.mikeburgess.euler.problems
/**
* Problem 6
*
* The sum of the squares of the first ten natural numbers is,
*
* 1^2 + 2^2 + ... + 10^2 = 385
*
* The square of the sum of the first ten natural numbers is,
* (1 + 2 + ... + 10)^2 = 552 = 3025
*
* Hence the difference between the sum of the squares of the first ten natural numbers and the
* square of the sum is 3025 − 385 = 2640.
*
* Find the difference between the sum of the squares of the first one hundred natural numbers and
* the square of the sum.
*/
class Problem006 : Problem {
private fun Long.square(): Long =
this * this
override fun solve(): Long {
val sumOfSquares = (1..100L).map { it.square() }.sum()
val squareOfSums = (1..100L).sum().square()
return squareOfSums - sumOfSquares
}
}
| 0 | Kotlin | 0 | 0 | 86518be1ac8bde25afcaf82ba5984b81589b7bc9 | 824 | project-euler | MIT License |
src/org/prime/util/Converter.kt | bozhnyukAlex | 429,572,343 | false | {"Kotlin": 18468} | package org.prime.util
import org.prime.util.machines.Direction
import org.prime.util.machines.TapeMachine
interface Converter {
fun machineToGrammar(machine: TapeMachine): Grammar
}
object Constants {
const val EPSILON = "epsilon"
const val RIGHT = ">"
const val COMMENT = "//"
const val BLANK = "_"
const val COMMA_DELIM = ","
}
class ConverterT0 : Converter {
override fun machineToGrammar(machine: TapeMachine): Grammar {
val sigmaStrings = machine.sigma
val initStr = machine.startState
val gammaStrings = machine.gamma
val acceptStr = machine.acceptState
val nonTerminals = ArrayList<String>()
(sigmaStrings + listOf(Constants.EPSILON)).forEach { X ->
gammaStrings.forEach { Y ->
nonTerminals.add(getBracketSymbol(X, Y))
}
}
nonTerminals.addAll(listOf("A1", "A2", "A3"))
nonTerminals.addAll(machine.states)
val productions = ArrayList<Production>()
// following Martynenko: https://core.ac.uk/download/pdf/217165386.pdf
// (1)
productions.add(Production(listOf("A1"), listOf(initStr, "A2")))
// (2)
sigmaStrings.forEach {
productions.add(Production(listOf("A2"), listOf(getBracketSymbol(it, it), "A2")))
}
// (3)
productions.add(Production(listOf("A2"), listOf("A3")))
// (4)
productions.add(Production(listOf("A3"), listOf(getBracketSymbol(Constants.EPSILON, Constants.BLANK), "A3")))
// (5)
productions.add(Production(listOf("A3"), listOf(Constants.EPSILON)))
val (deltasRight, deltasLeft) = machine.deltaTransitions.partition {
it.direction == Direction.RIGHT
}
// (6)
deltasRight.forEach { delta ->
(sigmaStrings + listOf(Constants.EPSILON)).forEach {
productions.add(Production(listOf(delta.currentState, getBracketSymbol(it, delta.readSymbol)),
listOf(getBracketSymbol(it, delta.writeSymbol), delta.nextState)))
}
}
// (7)
deltasLeft.forEach { delta ->
(sigmaStrings + listOf(Constants.EPSILON)).forEach { a ->
(sigmaStrings + listOf(Constants.EPSILON)).forEach { b ->
gammaStrings.forEach { E ->
productions.add(Production(listOf(getBracketSymbol(b, E), delta.currentState, getBracketSymbol(a, delta.readSymbol)),
listOf(delta.nextState, getBracketSymbol(b, E), getBracketSymbol(a, delta.writeSymbol))))
}
}
}
}
// (8)
(sigmaStrings + listOf(Constants.EPSILON)).forEach { a ->
gammaStrings.forEach { C ->
productions.add(
Production(listOf(getBracketSymbol(a, C), acceptStr), listOf(acceptStr, a, acceptStr))
)
productions.add(
Production(listOf(acceptStr, getBracketSymbol(a, C)), listOf(acceptStr, a, acceptStr))
)
productions.add(
Production(listOf(acceptStr), listOf(Constants.EPSILON))
)
}
}
return Grammar(sigmaStrings, nonTerminals, "A1", productions.distinct())
}
private fun getBracketSymbol(left: String, right: String) = "($left|$right)"
}
class ConverterT1 : Converter {
override fun machineToGrammar(machine: TapeMachine): Grammar {
TODO("Not yet implemented")
}
} | 0 | Kotlin | 1 | 0 | b1e4afe3b0d4292d202492f2271ffd7b378a371c | 3,576 | primary-numbers-grammar | MIT License |
src/main/kotlin/org/vaccineimpact/api/models/expectations/CountryOutcomeExpectations.kt | vimc | 88,746,413 | false | {"Kotlin": 35433} | package org.vaccineimpact.api.models.expectations
import org.vaccineimpact.api.models.*
import org.vaccineimpact.api.models.helpers.FlexibleProperty
data class CountryOutcomeExpectations(
override val id: Int,
override val description: String,
override val years: IntRange,
override val ages: IntRange,
override val cohorts: CohortRestriction,
val countries: List<Country>,
override val outcomes: List<Outcome>): Expectations
{
private fun Int.withinCohortRange(): Boolean
{
return (cohorts.minimumBirthYear == null || this >= cohorts.minimumBirthYear)
&& (cohorts.maximumBirthYear == null || this <= cohorts.maximumBirthYear)
}
data class RowDeterminer(val year: Int, val age: Int, val country: Country)
fun expectedCentralRows(disease: String) = expectedRows()
.map { mapCentralRow(disease, it.year, it.age, it.country) }
fun expectedStochasticRows(disease: String) = expectedRows()
.map { mapStochasticRow(disease, it.year, it.age, it.country) }
private fun expectedRows(): Sequence<RowDeterminer> = sequence {
for (age in ages)
{
for (country in countries)
{
yieldAll(years
.filter { (it - age).withinCohortRange() }
.map { RowDeterminer(it, age, country) })
}
}
}
fun expectedRowLookup(): RowLookup
{
val map = RowLookup()
for (country in countries)
{
val ageMap = AgeLookup()
for (age in ages)
{
val yearMap = YearLookup()
years.map { if ((it - age).withinCohortRange()) yearMap[it.toShort()] = false }
ageMap[age.toShort()] = yearMap
}
map[country.id] = ageMap
}
return map
}
private fun outcomesMap() = outcomes.associateBy({ it }, { null })
private fun mapCentralRow(disease: String, year: Int, age: Int, country: Country): ExpectedCentralRow
{
return ExpectedCentralRow(disease, year, age, country.id, country.name, null, outcomesMap())
}
private fun mapStochasticRow(disease: String, year: Int, age: Int, country: Country): ExpectedStochasticRow
{
return ExpectedStochasticRow(disease, null, year, age, country.id, country.name, null, outcomesMap())
}
}
data class CohortRestriction(
val minimumBirthYear: Short? = null,
val maximumBirthYear: Short? = null
)
data class ExpectedCentralRow(
val disease: String,
val year: Int,
val age: Int,
val country: String,
val countryName: String,
val cohortSize: Float?,
@FlexibleProperty
val outcomes: Map<Outcome, Float?>
) : ExpectedRow
data class ExpectedStochasticRow(
val disease: String,
val runId: Int?,
val year: Int,
val age: Int,
val country: String,
val countryName: String,
val cohortSize: Float?,
@FlexibleProperty
val outcomes: Map<Outcome, Float?>
) : ExpectedRow
interface ExpectedRow
| 0 | Kotlin | 0 | 0 | 999369f9ad88f3141b208fe3308c8575fc8899b3 | 3,184 | montagu-webmodels | MIT License |
src/main/kotlin/day1/Day1.kt | Wicked7000 | 573,552,409 | false | {"Kotlin": 106288} | package day1
import Day
import checkWithMessage
import parserCombinators.*
import parserCombinators.newLine
import readInput
import readInputString
import runTimedPart
@Suppress("unused")
class Day1(): Day() {
private fun parseInput(input: String): List<List<Int>> {
val parseTree = parseTillEnd(sequenceOf(group(oneOrMoreTimes(sequenceOf(number(Int::class), optional(newLine())))), optional(newLine())))
val result = parseTree(BaseParser(input))
if(result.hasError){
throw Error(result.error)
}
return result.results as List<List<Int>>
}
private fun part1(input: String): Int {
val elves = parseInput(input)
var currentMaxCalories = Int.MIN_VALUE;
for(elf in elves){
val summedVal = elf.sum()
if(summedVal > currentMaxCalories){
currentMaxCalories = summedVal
}
}
return currentMaxCalories
}
private fun part2(input: String): Int {
val elves = parseInput(input)
val currentTopThree = MutableList(3) { _: Int -> Int.MIN_VALUE }
for(elf in elves){
val summedVal = elf.sum()
for(topThreeIdx in currentTopThree.size-1 downTo 0){
val topAmount = currentTopThree[topThreeIdx]
if(topAmount <= summedVal){
if(topThreeIdx + 1 < currentTopThree.size){
val tempVal = currentTopThree[topThreeIdx]
currentTopThree[topThreeIdx] = summedVal
currentTopThree[topThreeIdx+1] = tempVal
} else {
currentTopThree[topThreeIdx] = summedVal
}
}
}
}
return currentTopThree.sum()
}
override fun run(){
val testInput = readInputString(1, "test")
val p1Input = readInputString(1, "input")
val testResult1 = part1(testInput)
checkWithMessage(testResult1, 24000)
runTimedPart(1, { part1(it) }, p1Input)
val testResult2 = part2(testInput)
checkWithMessage(testResult2,45000)
runTimedPart(2, { part2(it) }, p1Input)
}
}
| 0 | Kotlin | 0 | 0 | 7919a8ad105f3b9b3a9fed048915b662d3cf482d | 2,218 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/com/hj/leetcode/kotlin/problem295/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem295
import java.util.*
/**
* LeetCode page: [295. Find Median from Data Stream](https://leetcode.com/problems/find-median-from-data-stream/);
*/
class MedianFinder() {
private val leftHalf = PriorityQueue<Int>(reverseOrder())
private val rightHalf = PriorityQueue<Int>()
/* Complexity of N calls:
* Time O(NLogN) and Space O(N);
*/
fun addNum(num: Int) {
val shouldInsertLeft = shouldInsertLeft(num)
if (shouldInsertLeft) leftHalf.offer(num) else rightHalf.offer(num)
balance()
}
private fun shouldInsertLeft(newNum: Int): Boolean {
return leftHalf.peek()
?.let { it >= newNum }
?: true
}
private fun balance() {
when {
leftHalf.size > rightHalf.size + 1 -> {
val pop = leftHalf.poll()
rightHalf.offer(pop)
}
leftHalf.size < rightHalf.size -> {
val pop = rightHalf.poll()
leftHalf.offer(pop)
}
}
}
/* Complexity:
* Time O(1) and Space O(1);
*/
fun findMedian(): Double {
val size = leftHalf.size + rightHalf.size
val isEvenSize = size and 1 == 0
return if (isEvenSize) findMedianWhenEvenSize() else findMedianWhenOddSize()
}
private fun findMedianWhenOddSize(): Double {
val leftPeek = checkNotNull(leftHalf.peek())
return leftPeek.toDouble()
}
private fun findMedianWhenEvenSize(): Double {
val leftPeek = checkNotNull(leftHalf.peek())
val rightPeek = checkNotNull(rightHalf.peek())
return (leftPeek + rightPeek) / 2.0
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 1,705 | hj-leetcode-kotlin | Apache License 2.0 |
leetcode2/src/leetcode/binary-tree-zigzag-level-order-traversal.kt | hewking | 68,515,222 | false | null | package leetcode
import leetcode.structure.TreeNode
import java.util.*
/**
* 103. 二叉树的锯齿形层次遍历
* https://leetcode-cn.com/problems/binary-tree-zigzag-level-order-traversal/
* @program: leetcode
* @description: ${description}
* @author: hewking
* @create: 2019-10-22 10:43
* 给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
例如:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回锯齿形层次遍历如下:
[
[3],
[20,9],
[15,7]
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-zigzag-level-order-traversal
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
**/
object BinaryTreeZigzagLevelOrderTraversal {
fun zigzagLevelOrder(root: TreeNode?): List<List<Int>> {
root?: return mutableListOf()
val list = mutableListOf<List<Int>>()
val queue = ArrayDeque<TreeNode?>()
queue.add(root)
var isLeft = true
while (queue.size > 0) {
var len = queue.size
val values = mutableListOf<Int>()
while (len > 0) {
val node = queue.poll()
if (node?.left != null) {
queue.add(node?.left)
}
if (node?.right != null) {
queue.add(node?.right)
}
len --
values.add(node!!.`val`)
}
if (!isLeft) {
values.reverse()
}
list.add(values)
isLeft = !isLeft
}
return list
}
} | 0 | Kotlin | 0 | 0 | a00a7aeff74e6beb67483d9a8ece9c1deae0267d | 1,766 | leetcode | MIT License |
app/src/main/kotlin/aoc2022/day03/Day03.kt | dbubenheim | 574,231,602 | false | {"Kotlin": 18742} | package aoc2022.day03
import aoc2022.toFile
object Day03 {
fun part1(): Int {
return "input-day03.txt"
.toFile()
.readLines()
.sumOf { it.calc() }
}
fun part2(): Int {
return "input-day03.txt"
.toFile()
.readLines()
.chunked(3)
.sumOf { it.calc2() }
}
private fun List<String>.calc2(): Int {
val char = this[0].toSet().intersect(this[1].toSet()).intersect(this[2].toSet()).single()
return char.code - if (char.isLowerCase()) 96 else 38
}
private fun String.calc(): Int {
val halfIndex = this.length / 2
val first = this.substring(0, halfIndex)
val second = this.substring(halfIndex)
val char = first.toSet().intersect(second.toSet()).single()
return char.code - if (char.isLowerCase()) 96 else 38
}
}
fun main() {
println(Day03.part1())
println(Day03.part2())
}
| 8 | Kotlin | 0 | 0 | ee381bb9820b493d5e210accbe6d24383ae5b4dc | 965 | advent-of-code-2022 | MIT License |
src/main/kotlin/me/grison/aoc/y2020/Day11.kt | agrison | 315,292,447 | false | {"Kotlin": 267552} | package me.grison.aoc.y2020
import me.grison.aoc.*
import kotlin.reflect.KFunction2
class Day11 : Day(11, 2020) {
override fun title() = "Seating System"
override fun partOne(): Int = evolve(4, this::adjacent)
override fun partTwo(): Int = evolve(5, this::firstSeen)
private fun evolve(tolerance: Int, strategy: KFunction2<AllSeats, SeatPosition, Int>): Int {
var seats = loadSeats()
while (true)
when (val copy = evolve(seats, tolerance, strategy)) {
seats -> return seats.occupied()
else -> seats = copy
}
}
private fun adjacent(seats: AllSeats, pos: SeatPosition): Int {
return listOf(p(-1, -1), p(-1, 0), p(-1, 1), p(0, -1), p(0, 1), p(1, -1), p(1, 0), p(1, 1))
.count { seats[it + pos] == "#" }
}
private fun firstSeen(s: AllSeats, pos: SeatPosition): Int {
val adj = mutableSetOf<SeatPosition>()
/*N*/ (pos.first - 1 downTo 0).firstOrNull { s.isSeat(it, pos.second) }?.let { adj.add(p(it, pos.second)) }
/*S*/ (pos.first + 1..inputList.size).firstOrNull { s.isSeat(it, pos.second) }?.let { adj.add(p(it, pos.second)) }
/*E*/ (pos.second + 1..inputList[0].length).firstOrNull { s.isSeat(pos.first, it) }?.let { adj.add(p(pos.first, it)) }
/*W*/ (pos.second - 1 downTo 0).firstOrNull { s.isSeat(pos.first, it) }?.let { adj.add(p(pos.first, it)) }
/*NE*/ (1..5).firstOrNull { s.isSeat(pos + p(-it, it)) }?.let { adj.add(pos + p(-it, it)) }
/*NW*/ (1..5).firstOrNull { s.isSeat(pos + p(-it, -it)) }?.let { adj.add(pos + p(-it, -it)) }
/*SE*/ (1..5).firstOrNull { s.isSeat(pos + p(it, it)) }?.let { adj.add(pos + p(it, it)) }
/*SW*/ (1..5).firstOrNull { s.isSeat(pos + p(it, -it)) }?.let { adj.add(pos + p(it, -it)) }
return adj.filter { s.occupied(it) }.count()
}
private fun evolve(s: AllSeats, tolerance: Int, strategy: KFunction2<AllSeats, SeatPosition, Int>): AllSeats {
return s.toMutableMap().let { copy ->
s.entries.forEach { (seat, state) ->
if (state == "L" && strategy(s, seat) == 0)
copy.replace(seat, "#")
else if (state == "#" && strategy(s, seat) >= tolerance)
copy.replace(seat, "L")
}
copy
}
}
private fun loadSeats(): AllSeats {
var (i, seats) = p(0, mutableMapOf<SeatPosition, String>())
inputList.forEach { row ->
var j = 0
row.toCharArray().forEach { seat ->
seats[p(i, j)] = seat.toString()
j++
}
i++
}
return seats.toSortedMap { p1, p2 ->
if (p1.first == p2.first) p1.second.compareTo(p2.second)
else p1.first.compareTo(p2.first)
}
}
}
typealias SeatPosition = Pair<Int, Int>
typealias AllSeats = MutableMap<SeatPosition, String>
fun AllSeats.occupied() = entries.count { it.value == "#" }
fun AllSeats.occupied(p: Pair<Int, Int>) = get(p) == "#"
fun AllSeats.isSeat(i: Int, j: Int) = isSeat(Pair(i, j))
fun AllSeats.isSeat(p: Pair<Int, Int>) = get(p) != "." | 0 | Kotlin | 3 | 18 | ea6899817458f7ee76d4ba24d36d33f8b58ce9e8 | 3,194 | advent-of-code | Creative Commons Zero v1.0 Universal |
implementation/src/main/kotlin/io/github/tomplum/aoc/game/QuantumDie.kt | TomPlum | 431,391,240 | false | {"Kotlin": 114607} | package io.github.tomplum.aoc.game
/**
* A quantum die has 3 sides numbered 1, 2 & 3.
* Each time it is rolled, a new parallel universe is created for
* each of the possible outcomes.
*/
class QuantumDie {
/**
* In a game of [DiracDice], the die is rolled 3 times per turn.
* Rolling this quantum dice has only a small set of possible outcomes
* for the summation of those 3 values.
*
* For example, the smallest roll sum is (1, 1, 1) = 3.
* And the highest is (3, 3, 3) = 9.
*
* There are also sums that can be achieved in different ways.
* For example, a sum of 4 can be achieved with (1, 1, 2), (1, 2, 1) and (2, 1, 1).
* The sums are therefore paired with a multiplier for the number of permutations of that sum.
*
* A list of every roll sum permutation is iterated over and the given roll [function]
* is invoked. The value of the die roll is passed in for the game simulation and
* the number of winning games is added to the total.
*
* @param function The game simulation function.
* @return A pair of values for the number of wins for players 1 and 2 respectively.
*/
fun forEachRollPossibility(function: (value: Int) -> Pair<Long, Long>): Pair<Long, Long> = listOf(
Pair(9, 1), Pair(8, 3), Pair(7, 6), Pair(6, 7), Pair(5, 6), Pair(4, 3), Pair(3, 1)
).fold(Pair(0L, 0L)) { total, (value, multiplier) ->
val wins = function(value)
val playerOneWins = total.first + (wins.first * multiplier)
val playerTwoWins = (total.second + wins.second) * multiplier
Pair(playerOneWins, playerTwoWins)
}
}
| 0 | Kotlin | 0 | 0 | cccb15593378d0bb623117144f5b4eece264596d | 1,650 | advent-of-code-2021 | Apache License 2.0 |
src/main/kotlin/kt/kotlinalgs/app/graph/CycleDetectionUnionFind.ws.kts | sjaindl | 384,471,324 | false | null | package com.sjaindl.kotlinalgsandroid.graph
/*
https://www.geeksforgeeks.org/union-find/
*/
class CycleDetection {
fun hasCycle(graph: Graph): Boolean {
//val unionFind = Array(graph.vertices.size) { -1 }
val unionFind: MutableMap<Int, Int> = mutableMapOf()
val counts: MutableMap<Int, Int> = mutableMapOf()
graph.vertices.forEach {
unionFind[it.value] = it.value
counts[it.value] = 1
}
// O((E+V) * log V):
graph.vertices.forEach {
graph.neighbours(it).forEach { neighbour ->
val srcGroup = find(unionFind, it) //O(log V)
val destGroup = find(unionFind, neighbour) //O(log V)
if (srcGroup == destGroup) return true
union(unionFind, counts, it, neighbour) //O(1)
}
}
return false
}
private fun find(unionFind: MutableMap<Int, Int>, vertice: Vertice): Int {
var group = vertice.value
while (unionFind[group] != group) {
group = unionFind[group]!!
}
return group
}
private fun union(
unionFind: MutableMap<Int, Int>,
counts: MutableMap<Int, Int>,
src: Vertice,
dst: Vertice
) {
// union by rank (size, but could also be depth) -> O(log N)!
if (counts[src.value]!! < counts[dst.value]!!) {
unionFind[src.value] = unionFind[dst.value]!!
counts[dst.value] = counts[dst.value]!!.plus(counts[src.value]!!)
} else {
unionFind[dst.value] = unionFind[src.value]!!
counts[src.value] = counts[dst.value]!!.plus(counts[src.value]!!)
}
}
}
class Graph(val vertices: List<Vertice>) {
private var adjList: MutableMap<Int, MutableList<Vertice>> = mutableMapOf()
fun addEdge(from: Vertice, to: Vertice) {
val list = adjList.getOrDefault(from.value, mutableListOf())
list.add(to)
adjList[from.value] = list
}
fun neighbours(vertice: Vertice): List<Vertice> {
return adjList.getOrDefault(vertice.value, listOf())
}
}
data class Vertice(
val value: Int
)
val vertice0 = Vertice(0)
val vertice1 = Vertice(1)
val vertice2 = Vertice(2)
val vertice3 = Vertice(3)
val vertices = listOf(
vertice0, vertice1, vertice2, vertice3
)
val graph = Graph(vertices)
graph.addEdge(vertice0, vertice1)
graph.addEdge(vertice0, vertice2)
graph.addEdge(vertice1, vertice2)
graph.addEdge(vertice2, vertice0)
graph.addEdge(vertice3, vertice3)
println(CycleDetection().hasCycle(graph))
| 0 | Java | 0 | 0 | e7ae2fcd1ce8dffabecfedb893cb04ccd9bf8ba0 | 2,591 | KotlinAlgs | MIT License |
calendar/day04/Day4.kt | polarene | 572,886,399 | false | {"Kotlin": 17947} | package day04
import Day
import Lines
class Day4 : Day() {
override fun part1(input: Lines): Any {
return input.map(::parseAssignments)
.count { it.fullyOverlaps() }
}
override fun part2(input: Lines): Any {
return input.map(::parseAssignments)
.count { it.overlaps() }
}
}
fun parseAssignments(line: String): ElvesPair {
return line.split(",")
.map(::getSections)
.let { ElvesPair(it[0], it[1]) }
}
private fun getSections(sectionIdsRange: String) = sectionIdsRange.split("-")
.let {
val (start, end) = it
start.toInt()..end.toInt()
}
class ElvesPair(private val assignment1: IntRange, private val assignment2: IntRange) {
fun fullyOverlaps(): Boolean {
return assignment1 fullyContains assignment2
|| assignment2 fullyContains assignment1
}
fun overlaps(): Boolean {
return assignment1.first <= assignment2.last
&& assignment1.last >= assignment2.first
}
private infix fun IntRange.fullyContains(other: IntRange) =
first <= other.first && last >= other.last
} | 0 | Kotlin | 0 | 0 | 0b2c769174601b185227efbd5c0d47f3f78e95e7 | 1,145 | advent-of-code-2022 | Apache License 2.0 |
Problem Solving/Data Structures/Left Rotation.kt | MechaArms | 525,331,223 | false | {"Kotlin": 30017} | /*
A left rotation operation on an array of size n shifts each of the array's elements 1 unit to the left. Given an integer, d, rotate the array that many steps left and return the result.
Example
d=2
arr=[1,2,3,4,5]
After 2 rotations, arr'=[3,4,5,1,2].
Function Description
Complete the rotateLeft function in the editor below.
rotateLeft has the following parameters:
int d: the amount to rotate by
int arr[n]: the array to rotate
Returns
int[n]: the rotated array
Input Format
The first line contains two space-separated integers that denote n, the number of integers, and d, the number of left rotations to perform.
The second line contains n space-separated integers that describe arr[].
Sample Input
5 4
1 2 3 4 5
Sample Output
5 1 2 3 4
Explanation
To perform d=4 left rotations, the array undergoes the following sequence of changes:
[1,2,3,4,5] -> [2,3,4,5,1] -> [3,4,5,1,2] -> [4,5,1,2,3] -> [5,1,2,3,4]
*/
import java.io.*
import java.math.*
import java.security.*
import java.text.*
import java.util.*
import java.util.concurrent.*
import java.util.function.*
import java.util.regex.*
import java.util.stream.*
import kotlin.collections.*
import kotlin.comparisons.*
import kotlin.io.*
import kotlin.jvm.*
import kotlin.jvm.functions.*
import kotlin.jvm.internal.*
import kotlin.ranges.*
import kotlin.sequences.*
import kotlin.text.*
/*
* Complete the 'rotateLeft' function below.
*
* The function is expected to return an INTEGER_ARRAY.
* The function accepts following parameters:
* 1. INTEGER d
* 2. INTEGER_ARRAY arr
*/
fun rotateLeft(d: Int, arr: Array<Int>): Array<Int> {
// Write your code here
var rotate = arr.toMutableList()
for (i in 0 until d){
rotate.add(arr[i]) // add the first value of the Array and put in the end of the list
rotate.removeAt(0) // remove the first value of the list
}
return rotate.toTypedArray()
}
fun main(args: Array<String>) {
val first_multiple_input = readLine()!!.trimEnd().split(" ")
val n = first_multiple_input[0].toInt()
val d = first_multiple_input[1].toInt()
val arr = readLine()!!.trimEnd().split(" ").map{ it.toInt() }.toTypedArray()
val result = rotateLeft(d, arr)
println(result.joinToString(" "))
}
| 0 | Kotlin | 0 | 1 | eda7f92fca21518f6ee57413138a0dadf023f596 | 2,264 | My-HackerRank-Solutions | MIT License |
src/main/kotlin/adventofcode/y2021/Day17.kt | Tasaio | 433,879,637 | false | {"Kotlin": 117806} | import adventofcode.*
fun main() {
val testInput = """
target area: x=20..30, y=-10..-5
""".trimIndent()
runDay(
day = Day17::class,
testInput = testInput,
testAnswer1 = 45,
testAnswer2 = 112
)
}
open class Day17(staticInput: String? = null) : Y2021Day(17, staticInput) {
private val input = fetchInput()
val target = hashSetOf<Coordinate>()
val minMax: MinMaxXY
init {
val list = input[0].parseNumbersToIntList()
for (x in list[0]..list[1]) {
for (y in list[2]..list[3]) {
target.add(Coordinate(x, y))
}
}
minMax = target.getMinMaxValues()
}
override fun part1(): Number? {
val high = MaxValue()
for (x in 0..50) {
for (y in 0..200) {
var probe = Coordinate.ORIGIN
var vx = x
var vy = y
val max = MaxValue()
while (true) {
probe = probe.move(vx, vy)
max.next(probe.y)
if (target.contains(probe)) {
high.next(max.get())
continue
} else if (probe.x > minMax.maxX || probe.y < minMax.minY) {
break
}
if (vx > 0) {
vx--
}
vy--
}
}
}
return high.get()
}
override fun part2(): Number? {
val found = hashSetOf<Coordinate>()
for (x in 0..minMax.maxX.toInt()) {
for (y in -minMax.minY.abs().toInt()..minMax.maxY.abs().toInt() * 2) {
var probe = Coordinate.ORIGIN
var vx = x
var vy = y
while (true) {
probe = probe.move(vx, vy)
if (target.contains(probe)) {
found.add(Coordinate(x, y))
break
} else if (probe.x > minMax.maxX || probe.y < minMax.minY) {
break
}
if (vx > 0) {
vx--
}
vy--
}
}
}
return found.size
}
}
| 0 | Kotlin | 0 | 0 | cc72684e862a782fad78b8ef0d1929b21300ced8 | 2,366 | adventofcode2021 | The Unlicense |
src/test/kotlin/com/github/michaelbull/advent2021/day10/Day10Test.kt | michaelbull | 433,565,311 | false | {"Kotlin": 162839} | package com.github.michaelbull.advent2021.day10
import com.github.michaelbull.advent2021.day10.Day10.part1
import com.github.michaelbull.advent2021.day10.Day10.part2
import kotlin.test.Test
import kotlin.test.assertEquals
class Day10Test {
@Test
fun `example 1`() {
val input = """
[({(<(())[]>[[{[]{<()<>>
[(()[<>])]({[<{<<[]>>(
{([(<{}[<>[]}>{[]{[(<()>
(((({<>}<{<{<>}{[]{[]{}
[[<[([]))<([[{}[[()]]]
[{[{({}]{}}([{[{{{}}([]
{<[[]]>}<{[{[{[]{()[[[]
[<(<(<(<{}))><([]([]()
<{([([[(<>()){}]>(<<{{
<{([{{}}[<[[[<>{}]]]>[]]
"""
assertEquals(26397, Day10.solve(::part1, input))
}
@Test
fun `answer 1`() {
assertEquals(341823, Day10.solve(::part1))
}
@Test
fun `example 2`() {
val input = """
[({(<(())[]>[[{[]{<()<>>
[(()[<>])]({[<{<<[]>>(
{([(<{}[<>[]}>{[]{[(<()>
(((({<>}<{<{<>}{[]{[]{}
[[<[([]))<([[{}[[()]]]
[{[{({}]{}}([{[{{{}}([]
{<[[]]>}<{[{[{[]{()[[[]
[<(<(<(<{}))><([]([]()
<{([([[(<>()){}]>(<<{{
<{([{{}}[<[[[<>{}]]]>[]]
"""
assertEquals(288957, Day10.solve(::part2, input))
}
@Test
fun `answer 2`() {
assertEquals(2801302861, Day10.solve(::part2))
}
}
| 0 | Kotlin | 0 | 4 | 7cec2ac03705da007f227306ceb0e87f302e2e54 | 1,440 | advent-2021 | ISC License |
src/day17/Day17Alternative.kt | gautemo | 317,316,447 | false | null | package day17
import shared.DimensionMap
import shared.getText
fun cubeStateAlt(input: String, cycles: Int, dimension: Int = 3): Int{
var map = DimensionMap(input, dimension)
for(i in 1..cycles) map = tickAlt(map)
return map.countChar('#')
}
fun tickAlt(map: DimensionMap): DimensionMap{
val copyMap = map.copy()
fun forPoints(points: List<Int>){
println(points)
if(points.size == map.ranges.size){
val state = map.getAt(*points.toIntArray())
val activeNeighbors = map.countAdjacent('#', *points.toIntArray())
if(state == '#' && !listOf(2, 3).contains(activeNeighbors)) copyMap.setAt('.', *points.toIntArray())
if(state != '#' && activeNeighbors == 3) copyMap.setAt('#', *points.toIntArray())
}else{
for(d in map.ranges[points.size]!!){
forPoints(points + d)
}
}
}
forPoints(listOf())
return copyMap
}
fun main(){
val input = getText("day17.txt")
val active = cubeStateAlt(input, 6)
println(active)
val active4d = cubeStateAlt(input, 6, 4)
println(active4d)
}
| 0 | Kotlin | 0 | 0 | ce25b091366574a130fa3d6abd3e538a414cdc3b | 1,139 | AdventOfCode2020 | MIT License |
src/main/kotlin/dev/sirch/aoc/y2022/days/Day01.kt | kristofferchr | 573,549,785 | false | {"Kotlin": 28399, "Mustache": 1231} | package dev.sirch.aoc.y2022.days
import dev.sirch.aoc.Day
class Day01(testing: Boolean = false): Day(2022, 1, testing) {
override fun part1(): Int {
val allElves = parseElves(inputLines)
return allElves.maxBy { it.totalCalories }.totalCalories
}
override fun part2(): Int {
val allElves = parseElves(inputLines)
return allElves.sortedByDescending { it.totalCalories }.take(3).sumOf { it.totalCalories }
}
fun parseElves(input: List<String>): List<Elf> {
return input.joinToString(",") {
if (it == "") "|" else it
}.split("|")
.mapIndexed { elfNumber, elfCalories ->
Elf(elfNumber, elfCalories)
}
}
}
data class Elf(
val elfNumber: Int,
val calories: List<Int> = emptyList()
) {
constructor(elfIndex: Int, caloriesString: String) : this(
elfNumber = elfIndex + 1,
calories = caloriesString.split(",")
.filter { it != "" }
.map { it.toInt() })
val totalCalories = calories.sum()
}
| 0 | Kotlin | 0 | 0 | 867e19b0876a901228803215bed8e146d67dba3f | 1,051 | advent-of-code-kotlin | Apache License 2.0 |
src/test/kotlin/ch/ranil/aoc/aoc2022/Day25.kt | stravag | 572,872,641 | false | {"Kotlin": 234222} | package ch.ranil.aoc.aoc2022
import ch.ranil.aoc.AbstractDay
import org.junit.jupiter.api.Test
import kotlin.math.pow
import kotlin.test.assertEquals
class Day25 : AbstractDay() {
@Test
fun part1Test() {
assertEquals("2=-1=0", compute1(testInput))
}
@Test
fun part1Puzzle() {
assertEquals("2=2-1-010==-0-1-=--2", compute1(puzzleInput))
}
@Test
fun toDecimalTests() {
assertEquals(1747, "1=-0-2".toDecimal())
assertEquals(906, "12111".toDecimal())
assertEquals(198, "2=0=".toDecimal())
assertEquals(201, "2=01".toDecimal())
}
@Test
fun toSnafuTests() {
assertEquals("1", 1L.toSNAFU())
assertEquals("2", 2L.toSNAFU())
assertEquals("1=", 3L.toSNAFU())
assertEquals("1-", 4L.toSNAFU())
assertEquals("10", 5L.toSNAFU())
assertEquals("11", 6L.toSNAFU())
assertEquals("12", 7L.toSNAFU())
assertEquals("2=", 8L.toSNAFU())
assertEquals("2-", 9L.toSNAFU())
assertEquals("20", 10L.toSNAFU())
assertEquals("1-0---0", 12345L.toSNAFU())
assertEquals("1121-1110-1=0", 314159265L.toSNAFU())
}
private fun compute1(input: List<String>): String {
return input
.sumOf { it.toDecimal() }
.toSNAFU()
}
private fun SNAFU.toDecimal(): Long {
return this.reversed().mapIndexed { index, char ->
val value = 5.0.pow(index).toLong()
val number = when (char) {
'2' -> 2
'1' -> 1
'0' -> 0
'-' -> -1
'=' -> -2
else -> throw IllegalArgumentException("unexpected char $char")
}
number * value
}.sum()
}
private fun Long.toSNAFU(): SNAFU {
var numberToConvert = this
var result = ""
while (numberToConvert != 0L) {
val (snafuDigit, carry) = when (numberToConvert % 5) {
0L -> "0" to 0
1L -> "1" to 0
2L -> "2" to 0
3L -> "=" to 1
4L -> "-" to 1
else -> throw RuntimeException()
}
numberToConvert = (numberToConvert / 5) + carry
result = snafuDigit + result
}
return result
}
}
typealias SNAFU = String
| 0 | Kotlin | 1 | 0 | dbd25877071cbb015f8da161afb30cf1968249a8 | 2,371 | aoc | Apache License 2.0 |
2017/src/main/kotlin/Day25.kt | dlew | 498,498,097 | false | {"Kotlin": 331659, "TypeScript": 60083, "JavaScript": 262} | import grid.Turn
import utils.splitNewlines
import java.util.regex.Matcher
import java.util.regex.Pattern
object Day25 {
fun part1(input: String): Int {
val blueprint = parseBlueprint(input)
val states = blueprint.states.associateBy { it.name }
var tape = mutableSetOf<Int>()
var position = 0
var state = blueprint.initialState
for (step in 0 until blueprint.checksumSteps) {
val stateInstructions = states[state]!!
val isOne = tape.contains(position)
val instruction = if (isOne) stateInstructions.ifOne else stateInstructions.ifZero
// Write
if (instruction.write) {
tape.add(position)
}
else if (!instruction.write) {
tape.remove(position)
}
// Move
position += if (instruction.move == Turn.LEFT) -1 else 1
// Next state
state = instruction.nextState
}
return tape.size
}
data class Blueprint(val initialState: Char, val checksumSteps: Int, val states: List<State>)
data class State(val name: Char, val ifZero: Instruction, val ifOne: Instruction)
data class Instruction(val write: Boolean, val move: Turn, val nextState: Char)
private fun parseBlueprint(input: String): Blueprint {
val lines = input.splitNewlines()
val initialState = BEGIN_PATTERN.extract(lines[0]).group(1)[0]
val checksum = CHECKSUM_PATTERN.extract(lines[1]).group(1).toInt()
val states = mutableListOf<State>()
lines.forEachIndexed { index, line ->
val stateMatcher = IN_PATTERN.matcher(line)
if (stateMatcher.matches()) {
var name = stateMatcher.group(1)[0]
val ifZero = Instruction(
write = WRITE_PATTERN.extract(lines[index + 2].trim()).group(1) == "1",
move = if (MOVE_PATTERN.extract(lines[index + 3].trim()).group(1) == "left") Turn.LEFT else Turn.RIGHT,
nextState = CONTINUE_PATTERN.extract(lines[index + 4].trim()).group(1)[0]
)
val ifOne = Instruction(
write = WRITE_PATTERN.extract(lines[index + 6].trim()).group(1) == "1",
move = if (MOVE_PATTERN.extract(lines[index + 7].trim()).group(1) == "left") Turn.LEFT else Turn.RIGHT,
nextState = CONTINUE_PATTERN.extract(lines[index + 8].trim()).group(1)[0]
)
states.add(Day25.State(name, ifZero, ifOne))
}
}
return Blueprint(initialState, checksum, states)
}
private fun Pattern.extract(input: CharSequence): Matcher {
val matcher = matcher(input)
matcher.matches()
return matcher
}
private val BEGIN_PATTERN = Pattern.compile("Begin in state (\\w)\\.")
private val CHECKSUM_PATTERN = Pattern.compile("Perform a diagnostic checksum after (\\d+) steps\\.")
private val IN_PATTERN = Pattern.compile("In state (\\w):")
private val WRITE_PATTERN = Pattern.compile("- Write the value (0|1)\\.")
private val MOVE_PATTERN = Pattern.compile("- Move one slot to the (right|left)\\.")
private val CONTINUE_PATTERN = Pattern.compile("- Continue with state (\\w)\\.")
} | 0 | Kotlin | 0 | 0 | 6972f6e3addae03ec1090b64fa1dcecac3bc275c | 3,032 | advent-of-code | MIT License |
src/main/kotlin/io/undefined/FindAllAnagramsInAString.kt | jffiorillo | 138,075,067 | false | {"Kotlin": 434399, "Java": 14529, "Shell": 465} | package io.undefined
import io.utils.runTests
// https://leetcode.com/problems/find-all-anagrams-in-a-string/
class FindAllAnagramsInAString {
fun execute(input: String, anagram: String): List<Int> {
if (input.isEmpty() || anagram.length > input.length) return emptyList()
val result = mutableListOf<Int>()
val current = mutableMapOf<Char, Int>()
val anagramMap = anagram.fold(mutableMapOf<Char, Int>()) { acc, value -> acc.apply { acc[value] = acc.getOrDefault(value, 0) + 1 } }
for (index in anagram.indices) {
val key = input[index]
current[key] = current.getOrDefault(key, 0) + 1
}
for (index in anagram.length..input.length) {
if (current == anagramMap) result.add(index - anagram.length)
val startWord = input[index - anagram.length]
when {
current.getOrDefault(startWord, 0) == 1 -> current.remove(startWord)
current.containsKey(startWord) -> current[startWord] = current.getValue(startWord) - 1
}
if (index < input.length) {
val element = input[index]
if (anagramMap.keys.contains(element)) current[element] = current.getOrDefault(element, 0) + 1
}
}
return result
}
}
fun main() {
runTests(listOf(
Triple("cbaebabacd", "abc", listOf(0, 6)),
Triple("abab", "ba", listOf(0, 1, 2))
)) { (input, anagram, value) -> value to FindAllAnagramsInAString().execute(input, anagram) }
} | 0 | Kotlin | 0 | 0 | f093c2c19cd76c85fab87605ae4a3ea157325d43 | 1,424 | coding | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/AddOneRowToTree.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import java.util.LinkedList
import java.util.Queue
import java.util.Stack
/**
* 623. Add One Row to Tree
* @see <a href="https://leetcode.com/problems/add-one-row-to-tree/">Source</a>
*/
fun interface AddOneRowToTree {
operator fun invoke(root: TreeNode?, v: Int, d: Int): TreeNode?
}
/**
* Approach #1 Using Recursion(DFS)
*/
class AddOneRowToTreeRec : AddOneRowToTree {
/**
* Adds a row with a specified value to a binary tree at a specified depth.
*
* @param root The root of the binary tree.
* @param v The value to be inserted in the new nodes.
* @param d The depth at which the new row should be inserted.
* @return The modified binary tree with the new row inserted.
*/
override operator fun invoke(root: TreeNode?, v: Int, d: Int): TreeNode? {
if (d == 1) {
return TreeNode(v).apply {
left = root
right = null
}
}
return insert(root, v, d - 1, 1)
}
/**
* Inserts a node into a binary tree at a specified depth with a specified value.
*
* @param node The root of the binary tree or sub-tree.
* @param value The value to be inserted in the new nodes.
* @param depth The depth at which the new nodes should be inserted.
* @param n The current depth of the tree.
* @return The modified binary tree with the new nodes inserted.
*/
private fun insert(node: TreeNode?, value: Int, depth: Int, n: Int): TreeNode? {
if (node == null) {
return node
}
if (depth == n) {
node.left = TreeNode(value).apply {
left = node.left
right = null
}
node.right = TreeNode(value).apply {
left = null
right = node.right
}
}
node.left = insert(node.left, value, depth, n + 1)
node.right = insert(node.right, value, depth, n + 1)
return node
}
}
/**
* Approach #2 Using stack(DFS)
*/
class AddOneRowToTreeStack : AddOneRowToTree {
data class Node(val node: TreeNode?, val depth: Int)
override operator fun invoke(root: TreeNode?, v: Int, d: Int): TreeNode? {
if (d == 1) {
return TreeNode(v).apply {
left = root
}
}
val stack = Stack<Node>()
stack.push(Node(root, 1))
while (stack.isNotEmpty()) {
val n = stack.pop()
if (n.node == null) {
continue
}
if (n.depth == d - 1) {
var tmp = n.node.left
n.node.left = TreeNode(v)
n.node.left?.left = tmp
tmp = n.node.right
n.node.right = TreeNode(v)
n.node.right?.right = tmp
} else {
stack.push(Node(n.node.left, n.depth + 1))
stack.push(Node(n.node.right, n.depth + 1))
}
}
return root
}
}
/**
* Approach #3 Using queue(BFS)
*/
class AddOneRowToTreeQueue : AddOneRowToTree {
override operator fun invoke(root: TreeNode?, v: Int, d: Int): TreeNode? {
if (d == 1) {
return TreeNode(v).apply {
left = root
}
}
var queue: Queue<TreeNode?> = LinkedList()
queue.add(root)
var depth = 1
while (depth < d - 1) {
val temp: Queue<TreeNode?> = LinkedList()
while (queue.isNotEmpty()) {
val node = queue.remove()
if (node?.left != null) {
temp.add(node.left)
}
if (node?.right != null) {
temp.add(node.right)
}
}
queue = temp
depth++
}
while (queue.isNotEmpty()) {
val node = queue.remove()
var tmp = node?.left
node?.left = TreeNode(v)
node?.left?.left = tmp
tmp = node?.right
node?.right = TreeNode(v)
node?.right?.right = tmp
}
return root
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 4,798 | kotlab | Apache License 2.0 |
kotlin/src/main/kotlin/com/github/jntakpe/aoc2021/days/day2/Day2.kt | jntakpe | 433,584,164 | false | {"Kotlin": 64657, "Rust": 51491} | package com.github.jntakpe.aoc2021.days.day2
import com.github.jntakpe.aoc2021.shared.Day
import com.github.jntakpe.aoc2021.shared.readInputLines
import kotlin.math.abs
object Day2 : Day {
override val input: List<Move> = readInputLines(2).map { it.parseMove() }
override fun part1() = input.fold(Position()) { acc, cur -> acc.apply { move(cur) } }.result()
override fun part2() = input.fold(Position()) { acc, cur -> acc.apply { aim(cur) } }.result()
private fun String.parseMove() = split(' ').let { Move(Direction.valueOf(it.first().uppercase()), it.last().toInt()) }
enum class Direction {
FORWARD,
DOWN,
UP
}
data class Move(val direction: Direction, val units: Int)
class Position {
private var horizontal: Int = 0
private var depth: Int = 0
private var aim: Int = 0
fun move(move: Move) {
when (move.direction) {
Direction.FORWARD -> horizontal += move.units
Direction.UP -> depth += move.units
Direction.DOWN -> depth -= move.units
}
}
fun aim(move: Move) {
when (move.direction) {
Direction.FORWARD -> {
horizontal += move.units
depth += aim * move.units
}
Direction.UP -> {
aim -= move.units
}
Direction.DOWN -> {
aim += move.units
}
}
}
fun result() = abs(horizontal * depth)
}
}
| 0 | Kotlin | 1 | 5 | 230b957cd18e44719fd581c7e380b5bcd46ea615 | 1,600 | aoc2021 | MIT License |
src/main/kotlin/days/Day3.kt | couturierb | 728,250,155 | false | {"Kotlin": 27134} | package days
import kotlin.math.log
class Day3 : Day(3) {
val lineLength = inputList[0].length + 1
val numbers: Sequence<MatchResult> = Regex("\\d+").findAll(inputString)
val symbols: Sequence<MatchResult> = Regex("[^\\d.\\w\\s]").findAll(inputString)
val gears: Sequence<MatchResult> = Regex("\\*").findAll(inputString)
override fun partOne(): Any {
return numbers
.filter { isIntersect(it, symbols.map{ it.range }) }
.map { it.value.toInt() }
.reduce { acc, t -> acc + t }
}
override fun partTwo(): Any {
return gears
.map{ it.range }
.map { numbers.filter { number -> isIntersect(number, sequenceOf(it)) } }
.filter { it.count() == 2}
.map { it.first().value.toInt() * it.last().value.toInt() }
.reduce { acc, t -> acc + t }
}
private fun isIntersect(numberRange : MatchResult, symbols : Sequence<IntRange>): Boolean {
return symbols.any {
val target = it.first
numberRange.range.contains(target-1)
|| numberRange.range.contains(target+1)
|| numberRange.range.contains(target-lineLength)
|| numberRange.range.contains(target-lineLength-1)
|| numberRange.range.contains(target-lineLength+1)
|| numberRange.range.contains(target+lineLength)
|| numberRange.range.contains(target+lineLength-1)
|| numberRange.range.contains(target+lineLength+1)
}
}
} | 0 | Kotlin | 0 | 0 | eb48e810592beaf221b9a8620c8ebc19282ac059 | 1,588 | adventofcode2023 | Creative Commons Zero v1.0 Universal |
src/nativeMain/kotlin/com.qiaoyuang.algorithm/special/Questions80.kt | qiaoyuang | 100,944,213 | false | {"Kotlin": 338134} | package com.qiaoyuang.algorithm.special
fun test80() {
printlnResult(3, 2)
}
/**
* Questions 80: Input integers n and k, find all sets that size is k and be combined by integers in 1...n
*/
private fun allSets(n: Int, k: Int): List<List<Int>> {
require(n > 0) { "The n must grater than 0" }
if (k == 0)
return listOf(listOf())
val nums = IntArray(n) { it + 1 }
return buildList {
nums.backtrack(0, this, mutableListOf(), k)
}
}
private fun IntArray.backtrack(index: Int, results: MutableList<List<Int>>, subset: MutableList<Int>, k: Int) {
if (subset.size == k)
results.add(ArrayList(subset))
else if (index < size) {
backtrack(index + 1, results, subset, k)
subset.add(this[index])
backtrack(index + 1, results, subset, k)
subset.removeLast()
}
}
private fun printlnResult(n: Int, k: Int) =
println("Input n = $n, k = $k, the all subsets are: ${allSets(n, k)}") | 0 | Kotlin | 3 | 6 | 66d94b4a8fa307020d515d4d5d54a77c0bab6c4f | 964 | Algorithm | Apache License 2.0 |
cryptonote/src/test/kotlin/io/pnyx/bubu/cryptonote/boo/EcAlgebra.kt | pnyxio | 133,630,013 | false | null | package io.pnyx.bubu.cryptonote.boo
import org.junit.Assert
import org.junit.Test
import java.math.BigInteger
import java.math.BigInteger.ONE
import java.math.BigInteger.ZERO
class Test {
@Test
fun dotest() {
val _29 = Fe(i(29), i(99))
val _87 = Fe(i(87), i(99))
val sum = _29 + _87
println(sum.v)
println(Fe(i(7), i(9)) * Fe(i(8), i(9)))
println(Fe(i(8), i(9)) * Fe(i(7), i(9)))
// for (i in 0..16)
// println(Fe(i(2), i(17)).pow(i))
println("============")
for (i in 0..16)
println(Fe(i(i), i(17)).mulInverse())
}
}
fun gcd(x: BigInteger, y: BigInteger): BigInteger = when {
x == ZERO -> y.abs()
y == ZERO -> x.abs()
x == y -> x.abs()
x < y -> gcd(y, x)
else -> gcd(y, mod(x, y))
}
fun mod(x: BigInteger, n: BigInteger) : BigInteger {
Assert.assertTrue(n > ZERO)
val rem = x % n
val res = if(rem >= ZERO) rem else n + rem
Assert.assertTrue(res >= ZERO)
Assert.assertTrue(res < n)
return res
}
class Fe(xx: BigInteger, val q: BigInteger) {
val v : BigInteger
init {
v = if(xx > q || xx < ZERO) mod(xx, q) else xx
}
/////
operator fun plus(fe: Fe): Fe {
Assert.assertEquals(q, fe.q)
val x = q - v//assert >= 0
return if(x > fe.v) {
Fe(fe.v + v, q)
} else {
Fe(fe.v - x, q)
}
}
operator fun times(fe: Fe): Fe {
Assert.assertEquals(q, fe.q)
val a: Fe
val b: Fe
if(this < fe) {
a = this
b = fe
} else {
a = fe
b = this
}
var s = b
var r = Fe(ZERO, q)
for(bit in a.v.toString(2).reversed()) {
if(bit == '1') r = r + s
s += s
}
return r
}
fun pow(exp: Int): Fe {
if(exp == 0) return Fe(ONE, q)
Assert.assertTrue(exp > 0)
var m = this
var r = Fe(ONE, q)
for(bit in BigInteger.valueOf(exp.toLong()).toString(2).reversed()) {
if(bit == '1') r = r * m
m *= m
}
return r
}
@Throws
fun mulInverse(): Fe {
// if(gcd(v, q) > ONE) throw IllegalStateException()
if (q.isProbablePrime(1)) {
return pow(q.longValueExact().toInt() - 2)
}
var _r = ZERO
var _r1 = ONE
var _q = q
var _q1 = v
while (_r1 != ZERO) {
val quotient = _q / _q1
val _r1tmp = _r1
_r1 = _r - quotient * _r1
_r = _r1tmp
val _q1tmp = _q1
_q1 = _q - quotient * _q1
_q = _q1tmp
}
if (_q <= ONE) {
return if (_r < ZERO) Fe( _r + q, q) else Fe( _r, q)
} else {
throw IllegalStateException()
}
}
private operator fun compareTo(fe: Fe): Int {
Assert.assertEquals(q, fe.q)
return v.compareTo(fe.v)
}
override fun toString(): String {
return "${v.toString(10)} mod ${q.toString(10)}"
}
}
class Ge {
}
class Point {
} | 0 | Kotlin | 0 | 0 | 2929362a2fabcc342aba450ebf9b5129eb6dfe17 | 3,148 | bubu | Apache License 2.0 |
src/main/kotlin/day13.kt | p88h | 317,362,882 | false | null | internal fun inv(a0: Long, m0: Long): Long {
var m = m0; var a = a0; var x0 = 0L; var x1 = 1L
while (a > 1) {
val q = a / m;
val t0 = m; m = a % m; a = t0
val t1 = x0; x0 = x1 - q * x0; x1 = t1
}
return if (x1 < 0) x1 + m0 else x1
}
fun main(args: Array<String>) {
val input = allLines(args, "day13.in").toList()
val start = input.first().toLong()
val sched = input.last().split(',').mapIndexed { p, v -> v to p }
.filter { it.first != "x" }.map { it.first.toLong() to it.second }.toList()
val bus = sched.map { it.first }.map { it to (it - (start % it)) % it }.minByOrNull { it.second }
println(bus!!.first * bus.second)
val prod = sched.map { it.first }.reduce { a, b -> a * b }
println(sched.map {
val rem = (it.first - it.second) % it.first
val pp = prod / it.first
( rem * inv(pp, it.first) * pp )
}.sum() % prod)
} | 0 | Kotlin | 0 | 5 | 846ad4a978823563b2910c743056d44552a4b172 | 925 | aoc2020 | The Unlicense |
src/main/kotlin/day6.kt | gautemo | 433,582,833 | false | {"Kotlin": 91784} | import shared.getText
fun simulateLanternfishGrowth(input: String, times: Int = 80): Long{
val map = mutableMapOf(
Pair(0, input.count { it == '0' }.toLong()),
Pair(1, input.count { it == '1' }.toLong()),
Pair(2, input.count { it == '2' }.toLong()),
Pair(3, input.count { it == '3' }.toLong()),
Pair(4, input.count { it == '4' }.toLong()),
Pair(5, input.count { it == '5' }.toLong()),
Pair(6, input.count { it == '6' }.toLong()),
Pair(7, input.count { it == '7' }.toLong()),
Pair(8, input.count { it == '8' }.toLong()),
)
for(i in 1..times){
val zeros = map[0]!!
map[0] = map[1]!!
map[1] = map[2]!!
map[2] = map[3]!!
map[3] = map[4]!!
map[4] = map[5]!!
map[5] = map[6]!!
map[6] = map[7]!! + zeros
map[7] = map[8]!!
map[8] = zeros
}
return map.values.sumOf { it }
}
fun main(){
val input = getText("day6.txt").trim()
val task1 = simulateLanternfishGrowth(input)
println(task1)
val task2 = simulateLanternfishGrowth(input, 256)
println(task2)
} | 0 | Kotlin | 0 | 0 | c50d872601ba52474fcf9451a78e3e1bcfa476f7 | 1,136 | AdventOfCode2021 | MIT License |
src/main/kotlin/com/psmay/exp/advent/y2021/Day12.kt | psmay | 434,705,473 | false | {"Kotlin": 242220} | @file:Suppress("unused")
package com.psmay.exp.advent.y2021
import com.psmay.exp.advent.y2021.util.asSet
object Day12 {
data class CaveNode(val name: String, val isSmall: Boolean) {
override fun toString() = "<$name>"
}
fun String.toCaveNode(): CaveNode {
val name = this
val isSmall = when {
allLowerCaseRegex.matches(name) -> true
allUpperCaseRegex.matches(name) -> false
else -> throw IllegalArgumentException("Name '$name' cannot be classified as big or small.")
}
return CaveNode(name, isSmall)
}
class CaveSystem {
private var graph: Map<CaveNode, Set<CaveNode>>
constructor(bidirectionalSegments: Sequence<Pair<CaveNode, CaveNode>>) {
graph = bidirectionalSegments
.onEach { (a, b) ->
if (a == b)
throw IllegalArgumentException("Node cannot direct to self.")
else if (!a.isSmall && !b.isSmall)
throw IllegalArgumentException("Bidirectional path cannot exist between two big nodes.")
}
.flatMap { (a, b) -> listOf((a to b), (b to a)) }
.distinct()
.groupBy({ (from, _) -> from }, { (_, to) -> to })
.map { (from, tos) -> from to tos.toHashSet() }
.associate { it }
}
constructor(bidirectionalSegments: Iterable<Pair<CaveNode, CaveNode>>)
: this(bidirectionalSegments.asSequence())
private fun availableExitsUsingInitialLogic(path: List<CaveNode>): Set<CaveNode> {
val head = path.last()
val visited = path.toHashSet().asSet()
val avoid = visited.filter { it.isSmall }.toHashSet().asSet()
val exits = graph[head] ?: emptySet()
return exits - avoid
}
private fun availableExitsUsingNewLogic(path: List<CaveNode>): Set<CaveNode> {
val head = path.last()
val allPossibleExits = graph[head] ?: emptySet()
val pathSmallNodes = path.filter { it.isSmall }
val visitedSmallNodes = pathSmallNodes.toHashSet().asSet()
val smallNodesToAvoid = if (pathSmallNodes.size > visitedSmallNodes.size) {
// At least one small node was visited twice
visitedSmallNodes
} else {
// No small nodes are off limits yet
emptySet()
}
// In this version, revisiting the start node is not allowed ever.
val avoid = smallNodesToAvoid + startNode
return allPossibleExits - avoid
}
private tailrec fun traversePathsToEnd(
paths: List<List<CaveNode>>,
getExits: (List<CaveNode>) -> Set<CaveNode>,
): List<List<CaveNode>> {
return if (paths.all { it.last() == endNode }) {
paths
} else {
traversePathsToEnd(
paths.flatMap { path ->
if (path.last() == endNode) {
listOf(path)
} else {
getExits(path).sortedBy { it.name }.map { path + it }
}
}, getExits)
}
}
private fun traverseStartToEnd(getExits: (List<CaveNode>) -> Set<CaveNode>): List<List<CaveNode>> {
return traversePathsToEnd(listOf(listOf(startNode))) { getExits(it) }
}
fun traverseStartToEndUsingInitialLogic(): List<List<CaveNode>> =
traverseStartToEnd { availableExitsUsingInitialLogic(it) }
fun traverseStartToEndUsingNewLogic(): List<List<CaveNode>> =
traverseStartToEnd { availableExitsUsingNewLogic(it) }
}
// FIXME: Should be ^[[:upper:]]+$ and ^[[:lower:]]+$, but it was recognizing "h" as neither upper nor lower
private val allUpperCaseRegex = """^[A-Z]+$""".toRegex()
private val allLowerCaseRegex = """^[a-z]+$""".toRegex()
val startNode = "start".toCaveNode()
val endNode = "end".toCaveNode()
} | 0 | Kotlin | 0 | 0 | c7ca54612ec117d42ba6cf733c4c8fe60689d3a8 | 4,168 | advent-2021-kotlin | Creative Commons Zero v1.0 Universal |
kotlin/486.Predict the Winner(预测赢家).kt | learningtheory | 141,790,045 | false | {"Python": 4025652, "C++": 1999023, "Java": 1995266, "JavaScript": 1990554, "C": 1979022, "Ruby": 1970980, "Scala": 1925110, "Kotlin": 1917691, "Go": 1898079, "Swift": 1827809, "HTML": 124958, "Shell": 7944} | /**
<p>Given an array of scores that are non-negative integers. Player 1 picks one of the numbers from either end of the array followed by the player 2 and then player 1 and so on. Each time a player picks a number, that number will not be available for the next player. This continues until all the scores have been chosen. The player with the maximum score wins. </p>
<p>Given an array of scores, predict whether player 1 is the winner. You can assume each player plays to maximize his score. </p>
<p><b>Example 1:</b><br />
<pre>
<b>Input:</b> [1, 5, 2]
<b>Output:</b> False
<b>Explanation:</b> Initially, player 1 can choose between 1 and 2. <br/>If he chooses 2 (or 1), then player 2 can choose from 1 (or 2) and 5. If player 2 chooses 5, then player 1 will be left with 1 (or 2). <br/>So, final score of player 1 is 1 + 2 = 3, and player 2 is 5. <br/>Hence, player 1 will never be the winner and you need to return False.
</pre>
</p>
<p><b>Example 2:</b><br />
<pre>
<b>Input:</b> [1, 5, 233, 7]
<b>Output:</b> True
<b>Explanation:</b> Player 1 first chooses 1. Then player 2 have to choose between 5 and 7. No matter which number player 2 choose, player 1 can choose 233.<br />Finally, player 1 has more score (234) than player 2 (12), so you need to return True representing player1 can win.
</pre>
</p>
<p><b>Note:</b><br>
<ol>
<li>1 <= length of the array <= 20. </li>
<li>Any scores in the given array are non-negative integers and will not exceed 10,000,000.</li>
<li>If the scores of both players are equal, then player 1 is still the winner.</li>
</ol>
</p><p>给定一个表示分数的非负整数数组。 玩家1从数组任意一端拿取一个分数,随后玩家2继续从剩余数组任意一端拿取分数,然后玩家1拿,……。每次一个玩家只能拿取一个分数,分数被拿取之后不再可取。直到没有剩余分数可取时游戏结束。最终获得分数总和最多的玩家获胜。</p>
<p>给定一个表示分数的数组,预测玩家1是否会成为赢家。你可以假设每个玩家的玩法都会使他的分数最大化。</p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong> [1, 5, 2]
<strong>输出:</strong> False
<strong>解释:</strong> 一开始,玩家1可以从1和2中进行选择。
如果他选择2(或者1),那么玩家2可以从1(或者2)和5中进行选择。如果玩家2选择了5,那么玩家1则只剩下1(或者2)可选。
所以,玩家1的最终分数为 1 + 2 = 3,而玩家2为 5。
因此,玩家1永远不会成为赢家,返回 False。
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong> [1, 5, 233, 7]
<strong>输出:</strong> True
<strong>解释:</strong> 玩家1一开始选择1。然后玩家2必须从5和7中进行选择。无论玩家2选择了哪个,玩家1都可以选择233。
最终,玩家1(234分)比玩家2(12分)获得更多的分数,所以返回 True,表示玩家1可以成为赢家。
</pre>
<p><strong>注意:</strong></p>
<ol>
<li>1 <= 给定的数组长度 <= 20.</li>
<li>数组里所有分数都为非负数且不会大于10000000。</li>
<li>如果最终两个玩家的分数相等,那么玩家1仍为赢家。</li>
</ol>
<p>给定一个表示分数的非负整数数组。 玩家1从数组任意一端拿取一个分数,随后玩家2继续从剩余数组任意一端拿取分数,然后玩家1拿,……。每次一个玩家只能拿取一个分数,分数被拿取之后不再可取。直到没有剩余分数可取时游戏结束。最终获得分数总和最多的玩家获胜。</p>
<p>给定一个表示分数的数组,预测玩家1是否会成为赢家。你可以假设每个玩家的玩法都会使他的分数最大化。</p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong> [1, 5, 2]
<strong>输出:</strong> False
<strong>解释:</strong> 一开始,玩家1可以从1和2中进行选择。
如果他选择2(或者1),那么玩家2可以从1(或者2)和5中进行选择。如果玩家2选择了5,那么玩家1则只剩下1(或者2)可选。
所以,玩家1的最终分数为 1 + 2 = 3,而玩家2为 5。
因此,玩家1永远不会成为赢家,返回 False。
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong> [1, 5, 233, 7]
<strong>输出:</strong> True
<strong>解释:</strong> 玩家1一开始选择1。然后玩家2必须从5和7中进行选择。无论玩家2选择了哪个,玩家1都可以选择233。
最终,玩家1(234分)比玩家2(12分)获得更多的分数,所以返回 True,表示玩家1可以成为赢家。
</pre>
<p><strong>注意:</strong></p>
<ol>
<li>1 <= 给定的数组长度 <= 20.</li>
<li>数组里所有分数都为非负数且不会大于10000000。</li>
<li>如果最终两个玩家的分数相等,那么玩家1仍为赢家。</li>
</ol>
**/
class Solution {
fun PredictTheWinner(nums: IntArray): Boolean {
}
} | 0 | Python | 1 | 3 | 6731e128be0fd3c0bdfe885c1a409ac54b929597 | 5,010 | leetcode | MIT License |
src/main/kotlin/com/hj/leetcode/kotlin/problem1339/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem1339
import com.hj.leetcode.kotlin.common.model.TreeNode
/**
* LeetCode page: [1339. Maximum Product of Splitted Binary Tree](https://leetcode.com/problems/maximum-product-of-splitted-binary-tree/description/);
*/
class Solution {
/* Complexity:
* Time O(N) and Space O(H) where N and H are the number of nodes and height of root;
*/
fun maxProduct(root: TreeNode?): Int {
val sum = root.sum {}
var maxProduct = Long.MIN_VALUE
val updateMaxProduct = { subTreeSum: Long ->
maxProduct = maxOf(maxProduct, subTreeSum * (sum - subTreeSum))
}
root?.left.sum(updateMaxProduct)
root?.right.sum(updateMaxProduct)
return toOutput(maxProduct)
}
private fun TreeNode?.sum(sideEffect: (subTreeSum: Long) -> Unit): Long {
if (this == null) return 0L
val sum = `val` + left.sum(sideEffect) + right.sum(sideEffect)
sideEffect(sum)
return sum
}
private fun toOutput(maxProduct: Long): Int {
val modulo = 1_000_000_007
return (maxProduct % modulo).toInt()
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 1,140 | hj-leetcode-kotlin | Apache License 2.0 |
domain/src/main/java/com/jacekpietras/zoo/domain/business/Dijkstra.kt | JacekPietrasSpotOn | 472,234,427 | true | {"Kotlin": 402237, "Java": 7306} | package com.jacekpietras.zoo.domain.business
internal class Dijkstra(
vertices: Set<Node>,
private val start: Node,
private val end: Node,
technicalAllowed: Boolean = false,
) {
private val previous: MutableMap<Node, Node?> = vertices.map { it to null }.toMutableMap()
init {
// shortest distances
val delta = vertices.map { it to Double.MAX_VALUE }.toMutableMap()
delta[start] = 0.0
// subset of vertices, for which we know true distance
val s: MutableSet<Node> = mutableSetOf()
var outsideTechnical = technicalAllowed
while (s != vertices) {
// closest vertex that has not yet been visited
val v: Node = delta
.asSequence()
.filter { !s.contains(it.key) }
.minByOrNull { it.value }!!
.key
v.edges.forEach { neighbor ->
if (neighbor.node !in s &&
(technicalAllowed || !outsideTechnical || !neighbor.technical)
) {
val newPath = delta.getValue(v) + neighbor.length
if (!neighbor.technical) {
outsideTechnical = true
}
if (newPath < delta.getValue(neighbor.node)) {
delta[neighbor.node] = newPath
previous[neighbor.node] = v
}
}
}
if (v == end) break
s.add(v)
}
}
private fun pathTo(start: Node, end: Node): List<Node> {
val path = previous[end] ?: return listOf(end)
return listOf(pathTo(start, path), listOf(end)).flatten()
}
fun getPath(): List<Node> {
return pathTo(start, end)
}
private fun <T, R> List<Pair<T, R>>.toMutableMap(): MutableMap<T, R> =
this.toMap().toMutableMap()
}
| 0 | null | 0 | 0 | 07474546a9dbfc0263126b59933086b38d41b7e1 | 1,919 | ZOO | MIT License |
archive/src/main/kotlin/com/grappenmaker/aoc/year22/Day13.kt | 770grappenmaker | 434,645,245 | false | {"Kotlin": 409647, "Python": 647} | package com.grappenmaker.aoc.year22
import com.grappenmaker.aoc.PuzzleSet
import com.grappenmaker.aoc.asList
import com.grappenmaker.aoc.asPair
import kotlinx.serialization.json.*
import kotlin.math.min
fun PuzzleSet.day13() = puzzle {
val pairs = input.split("\n\n").map { p -> p.lines().map { parseValue(it) }.asPair() }
partOne = pairs.mapIndexed { idx, (a, b) -> a.inOrderWith(b) to idx + 1 }
.filter { (a) -> a == 1 }.sumOf { (_, idx) -> idx }.s()
val flat = pairs.flatMap { it.asList() }
val div1 = ValueList(listOf(ValueList(listOf(LiteralValue(2)))))
val div2 = ValueList(listOf(ValueList(listOf(LiteralValue(6)))))
val sorted = (flat + div1 + div2).sortedDescending()
partTwo = ((sorted.indexOf(div1) + 1) * (sorted.indexOf(div2) + 1)).s()
}
// Coding under pressure is not fun
fun JsonArray.parse(): ValueList = ValueList(
map {
when (it) {
is JsonPrimitive -> LiteralValue(it.int)
is JsonArray -> it.parse()
else -> error("Invalid value")
}
}
)
fun parseValue(str: String) = Json.parseToJsonElement(str).jsonArray.parse()
sealed interface Value : Comparable<Value> {
override operator fun compareTo(other: Value): Int = when {
this is LiteralValue && other is LiteralValue -> -value.compareTo(other.value)
this is ValueList && other is ValueList -> inOrderWith(other)
else -> toList().compareTo(other.toList())
}
}
@JvmInline
value class ValueList(val values: List<Value>) : Value
fun ValueList.inOrderWith(other: ValueList): Int {
values.zip(other.values).forEach { (a, b) ->
val cmp = a.compareTo(b)
if (cmp != 0) return cmp
}
val mSize = min(values.size, other.values.size)
return when {
mSize == values.size && mSize < other.values.size -> 1
mSize == other.values.size && mSize < values.size -> -1
else -> 0
}
}
fun Value.toList() = when (this) {
is ValueList -> this
is LiteralValue -> ValueList(listOf(this))
}
@JvmInline
value class LiteralValue(val value: Int) : Value | 0 | Kotlin | 0 | 7 | 92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585 | 2,094 | advent-of-code | The Unlicense |
numbers/src/main/kotlin/mathtools/numbers/primes/PrimeCacheBase.kt | RishiKumarRay | 467,793,819 | true | {"Kotlin": 182604, "Java": 53276} | package mathtools.numbers.primes
import mathtools.numbers.factors.BitFactoring.isProductOf2
/** Common to Prime Number Caches */
abstract class PrimeCacheBase(
/** The highest index that this Cache can store */
val maxIndex: Int,
/** The maximum value that small data type arrays can hold */
val maxValue: Int,
) {
/** The range of indexed prime numbers serviced by this cache */
val indexRange: IntRange = 0 .. maxIndex
/** Obtain the index of the highest prime number in the cache */
abstract fun highestCachedIndex(): Int
/** Request a prime number by it's index
* @param idx The index of the requested prime number
* @return The prime number at idx */
abstract fun getPrime(idx: Int): Int
/** Merge existing data structures, and find new primes
* @param add Try to find this many primes beyond highest cached index
* @return The highest prime that has been recently added */
protected abstract fun consolidate(add: Int = 1): Int
/** Clear saved prime numbers in this cache */
abstract fun clear()
/** Skip checking if 2 is a factor, assume number is odd */
private fun quickIsPrime(
number: Int,
) : Boolean? {
var prevPrime = 2
for (i in 1 .. 15) {
val testPrime = initArray[i].toInt()
if (number % testPrime == 0) return false
if (testPrime * prevPrime > number) return true
prevPrime = testPrime
}
for (i in 16 .. maxIndex) {
val testPrime = getPrime(i)
if (number % testPrime == 0) return false
if (testPrime * prevPrime > number) return true
prevPrime = testPrime
}
return null
}
/** Determine if a number is prime. Zero and one are prime.
* @param number The number to check for prime status
* @return True if it is a prime, false if not. Null if undetermined. */
fun isPrime(
number: Int,
) : Boolean? {
when {
// Basic Primes: 0, 1, 2, 3
number in 0 .. 3 -> return true
// Invert the number if it is negative
number < 0 -> return isPrime(-number)
// Check if it is in the initial prime array
number <= initArray.last() -> {
return initArray.binarySearch(number.toByte(), 2) > 0
}
isProductOf2(number) -> return false
}
// Check current cache size, and maximum prime number
val cacheIndex = highestCachedIndex()
var highestPrime = getPrime(cacheIndex)
// Check factor break condition
var maxProduct = highestPrime * getPrime(cacheIndex - 1)
if (maxProduct > number) return quickIsPrime(number)
if (maxProduct == number) return false
// Potential Improvement: Check static primes before expanding cache
// Expand the cache, assume more primes will be required
var availablePrimes = (maxIndex - cacheIndex).coerceAtMost(24)
while (availablePrimes > 0) { // Can be expanded
highestPrime = consolidate(availablePrimes)
maxProduct = highestPrime * getPrime(cacheIndex - 1)
if (maxProduct > number) return quickIsPrime(number)
if (maxProduct == number) return false
// The given number is still larger than the break condition
availablePrimes = (maxIndex - cacheIndex).coerceAtMost(48)
}
return null
}
/** Find the next prime using the given number as a starting point
* @param testNum The first number to test for prime status */
internal fun findPrime(
testNum: Int,
) : Int? {
if (testNum <= 0) return null
for (n in testNum .. maxValue step 2) {
when (quickIsPrime(n)) {
true -> return n
null -> return null
else -> {}
}
}
return null
}
companion object {
/** The first 16 useful primes */
internal val initArray: ByteArray = byteArrayOf(
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53,
)
}
} | 0 | Kotlin | 0 | 0 | a7c4887a2ac37756b5a1c71265b6c006cf22ccb9 | 4,087 | MathTools | Apache License 2.0 |
kotlin/src/com/s13g/aoc/aoc2020/Day8.kt | shaeberling | 50,704,971 | false | {"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245} | package com.s13g.aoc.aoc2020
import com.s13g.aoc.Result
import com.s13g.aoc.Solver
/**
* --- Day 8: Handheld Halting ---
* https://adventofcode.com/2020/day/8
*/
class Day8 : Solver {
override fun solve(lines: List<String>): Result {
val input = lines.map { it.split(" ") }.map { Instr(it[0], it[1].toInt()) }
return Result("${runA(VM(input))}", "${runB(input)}")
}
private fun runA(vm: VM): Int {
while (vm.step()) if (vm.hasLooped()) return vm.acc
error("No loop detected")
}
private fun runB(program: List<Instr>): Int {
for (x in program.indices) {
// Clone the list.
val variant = program.toMutableList()
// Swap the instruction if it matches.
if (variant[x].cmd == "jmp") variant[x] = Instr("nop", variant[x].value)
else if (variant[x].cmd == "nop") variant[x] = Instr("jmp", variant[x].value)
// Create a Vm an run it until it either ends or loops.
val vm = VM(variant)
while (vm.step() && !vm.hasLooped());
// If the program has ended normally, we found the fix!
if (vm.hasEnded()) return vm.acc
}
error("Could not find a solution for Part B")
}
private class VM(val program: List<Instr>) {
var acc = 0
var pc = 0
private val history = mutableSetOf<Int>()
/** Returns whether the program is still running. False if it has finished. */
fun step(): Boolean {
history.add(pc)
when (program[pc].cmd) {
"nop" -> pc++
"acc" -> {
acc += program[pc].value; pc++
}
"jmp" -> pc += program[pc].value
}
return !hasEnded()
}
/** Whether the instruction to be executed has already been executed before. */
fun hasLooped() = history.contains(pc)
/** Whether this program has terminated normally .*/
fun hasEnded() = pc >= program.size
}
private data class Instr(val cmd: String, val value: Int)
} | 0 | Kotlin | 1 | 2 | 7e5806f288e87d26cd22eca44e5c695faf62a0d7 | 1,918 | euler | Apache License 2.0 |
src/main/kotlin/days/Day13.kt | sicruse | 315,469,617 | false | null | package days
class Day13 : Day(13) {
data class Bus(val departure: Int, val frequency: Long)
private val earliestPossibleDeparture: Long by lazy {
inputList[0].toLong()
}
private val busses: List<Bus> by lazy {
inputList[1].split(",").mapIndexedNotNull {
departure, frequency -> if (frequency == "x") null else Bus(departure, frequency.toLong())
}
}
private fun nextBusDepartureAfter(interval: Long): Long {
val priorDeparture = interval * (earliestPossibleDeparture / interval)
return if (priorDeparture == earliestPossibleDeparture) priorDeparture else priorDeparture + interval
}
override fun partOne(): Any {
val departures = busses.map { nextBusDepartureAfter(it.frequency) }
val best = departures.withIndex().minByOrNull { (_ , f) -> f }?.index!!
return busses[best].frequency * (departures[best] - earliestPossibleDeparture)
}
override fun partTwo(): Any {
var stepSize = busses.first().frequency
var time = 0L
busses.drop(1).forEach { (departure, frequency) ->
while ((time + departure) % frequency != 0L) time += stepSize
stepSize *= frequency
}
return time
}
}
| 0 | Kotlin | 0 | 0 | 9a07af4879a6eca534c5dd7eb9fc60b71bfa2f0f | 1,265 | aoc-kotlin-2020 | Creative Commons Zero v1.0 Universal |
src/main/kotlin/biz/koziolek/adventofcode/year2021/day16/day16.kt | pkoziol | 434,913,366 | false | {"Kotlin": 715025, "Shell": 1892} | package biz.koziolek.adventofcode.year2021.day16
import biz.koziolek.adventofcode.*
fun main() {
val inputFile = findInput(object {})
val line = inputFile.bufferedReader().readLine()
val packet = parseBitsPacket(line)
println("Version numbers sum: ${sumAllVersions(packet)}")
println("Packet value: ${packet.evaluate()}")
}
sealed interface Packet {
val version: Int
val type: Int
fun evaluate(): Long
fun toString(evaluate: Boolean, indent: Int = 0): String
}
data class LiteralValuePacket(
override val version: Int,
override val type: Int,
val value: Long
) : Packet {
override fun evaluate() = value
override fun toString(evaluate: Boolean, indent: Int) =
buildString {
append(" ".repeat(indent))
append("$value (v$version)")
}
}
sealed interface OperatorPacket : Packet {
val children: List<Packet>
override fun toString(evaluate: Boolean, indent: Int) =
buildString {
append(" ".repeat(indent))
append(this@OperatorPacket.javaClass.simpleName.replace("OperatorPacket", ""))
append(" (v$version)")
if (evaluate) {
append(" = ${evaluate()}")
}
append(children.joinToString(prefix = "\n", separator = "\n") {
it.toString(evaluate, indent + 2)
})
}
}
data class SumOperatorPacket(
override val version: Int,
override val type: Int,
override val children: List<Packet>
) : OperatorPacket {
override fun evaluate() = children.sumOf { it.evaluate() }
}
data class ProductOperatorPacket(
override val version: Int,
override val type: Int,
override val children: List<Packet>
) : OperatorPacket {
override fun evaluate() = children.fold(1L) { product, packet -> product * packet.evaluate() }
}
data class MinimumOperatorPacket(
override val version: Int,
override val type: Int,
override val children: List<Packet>
) : OperatorPacket {
override fun evaluate() = children.minOf { it.evaluate() }
}
data class MaximumOperatorPacket(
override val version: Int,
override val type: Int,
override val children: List<Packet>
) : OperatorPacket {
override fun evaluate() = children.maxOf { it.evaluate() }
}
data class GreaterThanOperatorPacket(
override val version: Int,
override val type: Int,
override val children: List<Packet>
) : OperatorPacket {
override fun evaluate() = if (children[0].evaluate() > children[1].evaluate()) 1L else 0L
}
data class LessThanOperatorPacket(
override val version: Int,
override val type: Int,
override val children: List<Packet>
) : OperatorPacket {
override fun evaluate() = if (children[0].evaluate() < children[1].evaluate()) 1L else 0L
}
data class EqualToOperatorPacket(
override val version: Int,
override val type: Int,
override val children: List<Packet>
) : OperatorPacket {
override fun evaluate() = if (children[0].evaluate() == children[1].evaluate()) 1L else 0L
}
fun parseBitsPacket(hexString: String): Packet {
return BitsParser(hexString).readNextPacket()
}
private class BitsParser(hexString: String) {
private val bitSet = hexString.hexStringToBitSet()
private var index = 0
fun readNextPacket(): Packet {
val version = readVersion()
return when (val type = readType()) {
4 -> readLiteralValuePacket(version, type)
else -> readOperatorPacket(version, type)
}
}
private fun readVersion(): Int {
return readRawInt(3)
}
private fun readType(): Int {
return readRawInt(3)
}
private fun readLiteralValuePacket(version: Int, type: Int): LiteralValuePacket {
val value = readLiteralValue()
return LiteralValuePacket(version, type, value)
}
private fun readLiteralValue(): Long {
var isNotLastGroup = true
var value = 0L
while (isNotLastGroup) {
isNotLastGroup = (readRawInt(1) == 1)
val groupValue = readRawInt(4)
value = value * 16 + groupValue
}
return value
}
private fun readOperatorPacket(version: Int, type: Int): Packet {
val children = readChildren()
return when (type) {
0 -> SumOperatorPacket(version, type, children)
1 -> ProductOperatorPacket(version, type, children)
2 -> MinimumOperatorPacket(version, type, children)
3 -> MaximumOperatorPacket(version, type, children)
5 -> GreaterThanOperatorPacket(version, type, children)
6 -> LessThanOperatorPacket(version, type, children)
7 -> EqualToOperatorPacket(version, type, children)
else -> throw IllegalArgumentException("Unknown type: $type")
}
}
private fun readChildren(): List<Packet> {
val lengthTypeId = readRawInt(1)
val children = mutableListOf<Packet>()
when (lengthTypeId) {
0 -> {
val totalLength = readRawInt(15)
val childrenEndIndex = index + totalLength
while (index < childrenEndIndex) {
children.add(readNextPacket())
}
}
1 -> {
val numberOfSubPackets = readRawInt(11)
for (i in 1..numberOfSubPackets) {
children.add(readNextPacket())
}
}
else -> throw IllegalArgumentException("Unknown length type ID: $lengthTypeId")
}
return children
}
private fun readRawInt(bits: Int): Int {
val int = bitSet.toInt(index, index + bits)
index += bits
return int
}
}
fun sumAllVersions(packet: Packet): Int =
packet.version + when (packet) {
is LiteralValuePacket -> 0
is OperatorPacket -> packet.children.sumOf { sumAllVersions(it) }
}
| 0 | Kotlin | 0 | 0 | 1b1c6971bf45b89fd76bbcc503444d0d86617e95 | 5,978 | advent-of-code | MIT License |
src/main/kotlin/com/nlkprojects/neuralnet/math/rational/Rational.kt | leokash | 264,928,399 | false | null | package com.nlkprojects.neuralnet.math.rational
import java.lang.RuntimeException
data class Rational(val numerator: Long, val denominator: Long): Number(), Comparable<Rational> {
constructor(num: Int): this(num, num)
constructor(num: Long): this(num, num)
constructor(num: Int, den: Int): this(num.toLong(), den.toLong())
operator fun div(that: Rational): Rational {
return from(numerator * that.denominator, denominator * that.numerator)
}
operator fun plus(that: Rational): Rational {
return from((numerator * that.denominator) + (denominator + that.numerator), denominator * that.denominator)
}
operator fun minus(that: Rational): Rational {
return from((numerator * that.denominator) - (denominator + that.numerator), denominator * that.denominator)
}
operator fun times(that: Rational): Rational {
return from(numerator * that.numerator, denominator * that.denominator)
}
override fun toInt(): Int {
return (if (denominator == 0L) 0L else numerator / denominator).toInt()
}
override fun toByte(): Byte {
return (if (denominator == 0L) 0L else numerator / denominator).toByte()
}
override fun toChar(): Char {
throw RuntimeException("Rational does not fit into a Char")
}
override fun toLong(): Long {
return if (denominator == 0L) 0L else numerator / denominator
}
override fun toShort(): Short {
return (if (denominator == 0L) 0L else numerator / denominator).toShort()
}
override fun toFloat(): Float {
return if (denominator == 0L) .0f else numerator / denominator.toFloat()
}
override fun toDouble(): Double {
return if (denominator == 0L) .0 else numerator / denominator.toDouble()
}
override fun compareTo(other: Rational): Int {
if (this == other)
return 0
val lhs = numerator * other.denominator
val rhs = denominator * other.numerator
return if (lhs < rhs) -1 else 1
}
override fun toString(): String {
return "($numerator/$denominator)"
}
companion object {
val ONE = Rational(1, 1)
val ZERO = Rational(0, 0)
val EMPTY = Rational(0, 1)
fun from(num: Float): Rational {
return if (num == .0f) return ZERO else from(num.toString())
}
fun from(num: Double): Rational {
return if (num == .0) return ZERO else from(num.toString())
}
fun from(lhs: Int, rhs: Int): Rational {
return from(lhs.toLong(), rhs.toLong())
}
fun from(lhs: Long, rhs: Long): Rational {
if (rhs == 0L)
return ZERO
if (lhs == 0L)
return Rational(0L, rhs)
val d = gcd(lhs, rhs)
return Rational(lhs / d, rhs / d)
}
private fun from(string: String): Rational {
val arr = string.split(".").map { it.trim() }
val clean = arr[1].dropLastWhile { it == '0' }
if (clean.isEmpty())
return Rational(arr[0].toLong(), 1L)
val num = clean.toLong()
val exc = arr[0].toLong()
val den = clean.indices.fold("1") { acc, _ -> "${acc}0" }.toLong()
val gcd = gcd(num, den)
val nDen = den / gcd
return Rational((exc * nDen) + (num / gcd), den / gcd)
}
fun gcd(lhs: Int, rhs: Int): Long {
return gcd(lhs.toLong(), rhs.toLong())
}
fun gcd(lhs: Long, rhs: Long): Long {
var a = lhs
var b = rhs
var t: Long
while (b != 0L) {
t = a % b
a = b
b = t
}
return if (a < 0L) -a else a
}
}
}
fun main() {
println(Rational.from(3/7.0).toDouble())
}
| 0 | Kotlin | 0 | 0 | d243588ef4f66e71294d486ffbfecfb88372a69e | 3,889 | neuralnet | Apache License 2.0 |
src/main/kotlin/math/Prime.kt | yx-z | 106,589,674 | false | null | package math
import java.util.*
fun main(args: Array<String>) {
val LIMIT = 100000
println(time { sievePrime(LIMIT) })
println(time { listPrime(LIMIT) })
println(time { listByIsPrime(LIMIT) })
println(5.thPrime()) // 5th prime = 11
println(Arrays.toString(5.thPrimes())) // first 5 primes = [2, 3, 5, 7, 11]
}
/**
* return a list of sievePrime numbers (>= 2) <= i (i >= 2)
*/
fun sievePrime(i: Int): List<Int> {
val p = ArrayList<Int>()
if (i <= 1) {
return p
}
// b[i] = whether i is prime (true) or not (false)
// ex. b[2] = true since 2 is a prime number
// ex. b[4] = false since 4 = 2 * 2
val b = Array(i) { false }
for (n in 2 until i) {
if (!b[n]) {
p.add(n)
var mult = 2
while (n * mult < i) {
b[n * mult] = true
mult++
}
}
}
return p
}
// alternative method
// slower
fun listPrime(i: Int): List<Int> {
val p = ArrayList<Int>()
if (i <= 1) {
return p
}
p.add(2)
for (n in 2 until i) {
if (p.all { n % it != 0 }) {
p.add(n)
}
}
return p
}
// alternative method
// call isPrime() for each number
fun listByIsPrime(i: Int) = if (i <= 1) {
ArrayList()
} else {
(2..i).filter { it.isPrime() }.toList()
}
fun Int.isPrime() = (2..Math.sqrt(this.toDouble()).toInt()).all { this % it != 0 }
fun time(f: () -> Unit): Long {
val start = System.currentTimeMillis()
f()
return System.currentTimeMillis() - start
}
fun Int.thPrime(): Int {
if (this < 1) {
return -1
}
var count = 0
var num = 2
while (count < this) {
while (!num.isPrime()) {
num++
}
count++
num++
}
return num - 1
}
fun Int.thPrimes(): IntArray {
if (this < 1) {
return IntArray(0)
}
val primes = IntArray(this) { 1 }
primes[0] = 2
var num = 3
(1 until this).forEach {
while (primes.filterIndexed { idx, _ -> idx < it }.any { num % it == 0 }) {
num++
}
primes[it] = num
num++
}
return primes
} | 0 | Kotlin | 0 | 1 | 15494d3dba5e5aa825ffa760107d60c297fb5206 | 1,879 | AlgoKt | MIT License |
contest1907/src/main/kotlin/CFixed.kt | austin226 | 729,634,548 | false | {"Kotlin": 23837} | import kotlin.streams.toList
// https://codeforces.com/contest/1907/problem/C
private fun readInt(): Int = readln().toInt()
private fun <T> List<T>.counts(): Map<T, Int> = this.groupingBy { it }.eachCount()
private fun solve(n: Int, s: String): Int {
// https://codeforces.com/blog/entry/123012
// The final string will always have all of the same characters.
// If a character appears more than n/2 times, the final string will consist only of that character.
val charCounts = s.chars().toList().counts().toMutableMap()
var dominantChar: Int? = null
var dominantCharCount: Int? = null
for (charCount in charCounts) {
if (charCount.value > n / 2) {
// One char dominates
dominantChar = charCount.key
dominantCharCount = charCount.value
break
}
}
if (dominantChar == null || dominantCharCount == null) {
// No character dominates - all pairs can be deleted
return n % 2
}
charCounts.remove(dominantChar)
return dominantCharCount - charCounts.values.sum()
}
private fun testcase() {
val n = readInt()
val s = readln()
val min = solve(n, s)
println(min)
}
fun main() {
// val min = solve(20000, "abacd".repeat(20000 / 5))
// val min = solve(2000, "aaacd".repeat(2000 / 5))
// println(min)
// return
val t = readInt()
for (i in 0..<t) {
testcase()
}
} | 0 | Kotlin | 0 | 0 | 4377021827ffcf8e920343adf61a93c88c56d8aa | 1,428 | codeforces-kt | MIT License |
src/main/kotlin/g1001_1100/s1073_adding_two_negabinary_numbers/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1001_1100.s1073_adding_two_negabinary_numbers
// #Medium #Array #Math #2023_05_31_Time_187_ms_(100.00%)_Space_40.9_MB_(100.00%)
class Solution {
fun addNegabinary(arr1: IntArray, arr2: IntArray): IntArray {
val len1 = arr1.size
val len2 = arr2.size
val reverseArr1 = IntArray(len1)
for (i in len1 - 1 downTo 0) {
reverseArr1[len1 - i - 1] = arr1[i]
}
val reverseArr2 = IntArray(len2)
for (i in len2 - 1 downTo 0) {
reverseArr2[len2 - i - 1] = arr2[i]
}
val sumArray = IntArray(len1.coerceAtLeast(len2) + 2)
System.arraycopy(reverseArr1, 0, sumArray, 0, len1)
for (i in sumArray.indices) {
if (i < len2) {
sumArray[i] += reverseArr2[i]
}
if (sumArray[i] > 1) {
sumArray[i] -= 2
sumArray[i + 1]--
} else if (sumArray[i] == -1) {
sumArray[i] = 1
sumArray[i + 1]++
}
}
var resultLen = sumArray.size
for (i in sumArray.indices.reversed()) {
if (sumArray[i] == 0) {
resultLen--
} else {
break
}
}
if (resultLen == 0) {
return intArrayOf(0)
}
val result = IntArray(resultLen)
for (i in resultLen - 1 downTo 0) {
result[resultLen - i - 1] = sumArray[i]
}
return result
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,508 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/org/kotrix/test.kt | JarnaChao09 | 285,169,397 | false | {"Kotlin": 446442, "Jupyter Notebook": 26378} | package org.kotrix
import kotlin.system.measureTimeMillis
import kotlin.math.absoluteValue
/*
https://users.wpi.edu/~walker/MA510/HANDOUTS/w.gander,w.gautschi,Adaptive_Quadrature,BIT_40,2000,84-101.pdf
chapter 3 adaptive simpsons
*/
fun integralScan(a: Double, b: Double, eps: Double, f: (Double) -> Double): Double /*List<Double>*/ {
val m = (a + b) / 2
val fa = f(a)
val fm = f(m)
val fb = f(b)
var i = (b - a) / 8 * (
fa + fm + fb +
f(a + 0.9501 * (b - a)) +
f(a + 0.2311 * (b - a)) +
f(a + 0.6068 * (b - a)) +
f(a + 0.4860 * (b - a)) +
f(a + 0.8913 * (b - a))
)
if (i == 0.0) {
i = b - a
}
i *= eps / Math.ulp(1.0)
// val values = mutableListOf(0.0)
// val sums = mutableListOf(0.0)
var sum = 0.0
fun helper(a: Double, m: Double, b: Double, fa: Double, fm: Double, fb: Double) {
val h = (b - a) / 4
val ml = a + h
val mr = b - h
val fml = f(ml)
val fmr = f(mr)
var i1 = h / 1.5 * (fa + 4 * fm + fb)
val i2 = h / 3 * (fa + 4 * (fml + fmr) + 2 * fm + fb)
i1 = (16 * i2 - i1) / 15
if (i + (i1 - i2) == i || m <= a || b <= m) {
// values.add(b)
// sums.add(sums.last() + i1)
sum += i1
} else {
helper(a, ml, m, fa, fml, fm)
helper(m, mr, b, fm, fmr, fb)
}
}
helper(a, m, b, fa, fm, fb)
return sum
}
private fun quadSimpsonsMemory(
a: Double,
fa: Double,
b: Double,
fb: Double,
function: (Double) -> Double
): Triple<Double, Double, Double> {
val m = (a + b) / 2.0
val fm = function(m)
return Triple(m, fm, (b - a).absoluteValue / 6 * (fa + 4 * fm + fb))
}
private fun quadASR(
a: Double,
fa: Double,
b: Double,
fb: Double,
eps: Double,
whole: Double,
m: Double,
fm: Double,
f: (Double) -> Double
): Double {
val (lm, flm, left) = quadSimpsonsMemory(a, fa, m, fm, f)
val (rm, frm, right) = quadSimpsonsMemory(m, fm, b, fb, f)
val delta = left + right - whole
return if (delta.absoluteValue <= 15 * eps) {
left + right + delta / 15
} else {
quadASR(a, fa, m, fm, eps / 2.0, left, lm, flm, f) + quadASR(m, fm, b, fb, eps / 2.0, right, rm, frm, f)
}
}
fun adaptiveSimpsonMethod(
from: Number,
to: Number,
eps: Double = 1E-15,
function: (Double) -> Double
): Double {
val a = from.toDouble()
val b = to.toDouble()
val (fa, fb) = function(a) to function(b)
val (m, fm, whole) = quadSimpsonsMemory(a, fa, b, fb, function)
return quadASR(a, fa, b, fb, eps, whole, m, fm, function)
}
fun main() {
println("Testing")
// var res1: List<Double>
var res1: Double
var res2: Double
var totalDuration1 = 0.0
var totalDuration2 = 0.0
var totalError1 = 0.0
var totalError2 = 0.0
var totalCalls1 = 0
var totalCalls2 = 0
val f = { x: Double ->
kotlin.math.sqrt(x)
// kotlin.math.sin(x*x)
}
val eps = 1e-8
val a = 0.0
val b = 1.0
// val actualAns = -0.022318845283755027
val actualAns = 2.0 / 3.0
repeat(100) {
totalDuration1 += measureTimeMillis {
res1 = integralScan(a, b, eps) { x -> totalCalls1++; f(x) }
}
totalDuration2 += measureTimeMillis {
res2 = adaptiveSimpsonMethod(a, b, eps=eps) { x -> totalCalls2++; f(x) }
}
totalError1 += (res1 - (actualAns)).absoluteValue
totalError2 += (res2 - (actualAns)).absoluteValue
}
println("total(ms): ${totalDuration1}, avg(ms): ${totalDuration1 / 100}, avg err: ${totalError1 / 100} avg calls: ${totalCalls1 / 100}")
println("total(ms): ${totalDuration2}, avg(ms): ${totalDuration2 / 100}, avg err: ${totalError2 / 100} avg calls: ${totalCalls2 / 100}")
} | 0 | Kotlin | 1 | 5 | c5bb19457142ce1f3260e8fed5041a4d0c77fb14 | 3,964 | Kotrix | MIT License |
src/main/kotlin/com/hj/leetcode/kotlin/problem7/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem7
/**
* LeetCode page: [7. Reverse Integer](https://leetcode.com/problems/reverse-integer/);
*/
class Solution {
private val digitsOfIntMax = intArrayOf(2, 1, 4, 7, 4, 8, 3, 6, 4, 7)
/* Complexity:
* Time O(LogN) and Space (LogN) where N equals x;
*/
fun reverse(x: Int): Int {
val reversedDigits = getDigitsInReversedOrder(x)
if (isNumberOverflow(reversedDigits)) return 0
val abs = reversedDigits.fold(0) { acc, i -> acc * 10 + i }
return if (x > 0) abs else -abs
}
private fun getDigitsInReversedOrder(number: Int): List<Int> {
if (number == 0) return mutableListOf(0)
val reversedDigits = mutableListOf<Int>()
var num = Math.abs(number)
while (num > 0) {
reversedDigits.add(num % 10)
num /= 10
}
return reversedDigits
}
private fun isNumberOverflow(digits: List<Int>): Boolean {
if (digits.size < digitsOfIntMax.size) return false
for (index in digits.indices) {
when {
digits[index] < digitsOfIntMax[index] -> return false
digits[index] > digitsOfIntMax[index] -> return true
}
}
return false
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 1,282 | hj-leetcode-kotlin | Apache License 2.0 |
kotlin/src/com/daily/algothrim/leetcode/ReorderList.kt | idisfkj | 291,855,545 | false | null | package com.daily.algothrim.leetcode
import com.daily.algothrim.linked.LinkedNode
/**
* 143. 重排链表
*
* 给定一个单链表 L:L0→L1→…→Ln-1→Ln ,
* 将其重新排列后变为: L0→Ln→L1→Ln-1→L2→Ln-2→…
*
* 你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
*
* 示例 1:
*
* 给定链表 1->2->3->4, 重新排列为 1->4->2->3.
* 示例 2:
*
* 给定链表 1->2->3->4->5, 重新排列为 1->5->2->4->3.
*
* */
class ReorderList {
companion object {
@JvmStatic
fun main(args: Array<String>) {
val head = LinkedNode(
1,
LinkedNode(
2, LinkedNode(
3,
LinkedNode(4, LinkedNode(5))
)
)
)
ReorderList().solution(head)
head.printAll()
}
}
fun solution(head: LinkedNode<Int>?) {
if (head == null) return
val middleNode = middleNode(head)
var l2 = middleNode?.next
middleNode?.next = null
l2 = reverseList(l2)
mergeList(head, l2)
}
private fun middleNode(head: LinkedNode<Int>?): LinkedNode<Int>? {
var slow = head
var fast = head
while (fast?.next != null && fast.next?.next != null) {
slow = slow?.next
fast = fast.next?.next
}
return slow
}
private fun reverseList(head: LinkedNode<Int>?): LinkedNode<Int>? {
var prev: LinkedNode<Int>? = null
var curr = head
while (curr != null) {
val temp = curr.next
curr.next = prev
prev = curr
curr = temp
}
return prev
}
private fun mergeList(l1: LinkedNode<Int>?, l2: LinkedNode<Int>?) {
var node1: LinkedNode<Int>? = l1
var node2: LinkedNode<Int>? = l2
while (node1 != null && node2 != null) {
val temp1 = node1.next
val temp2 = node2.next
node1.next = node2
node1 = temp1
node2.next = node1
node2 = temp2
}
}
} | 0 | Kotlin | 9 | 59 | 9de2b21d3bcd41cd03f0f7dd19136db93824a0fa | 2,207 | daily_algorithm | Apache License 2.0 |
jvm_sandbox/projects/advent_of_code/src/main/kotlin/year2018/Day7.kt | jduan | 166,515,850 | false | {"Rust": 876461, "Kotlin": 257167, "Java": 139101, "Python": 114308, "Vim Script": 100117, "Shell": 96665, "C": 67784, "Starlark": 23497, "JavaScript": 20939, "HTML": 12920, "Ruby": 5087, "Thrift": 4518, "Nix": 2919, "HCL": 1069, "Lua": 926, "CSS": 826, "Assembly": 761, "Makefile": 591, "Haskell": 585, "Dockerfile": 501, "Scala": 322, "Smalltalk": 270, "CMake": 252, "Smarty": 97, "Clojure": 91} | package year2018.day7
import java.io.File
import java.lang.RuntimeException
class Node(val name: String) {
var nexts: MutableList<Node> = mutableListOf()
private var incoming: Int = 0
fun addNext(next: Node) {
nexts.add(next)
next.incoming += 1
}
fun decrement() {
incoming--
}
fun isReady() = incoming == 0
override fun toString(): String {
return "Node(name: $name, incoming: $incoming)"
}
}
class Worker {
var node: Node? = null
private var remainingLoad: Int? = null
fun start(node: Node, baseSeconds: Int) {
this.node = node
remainingLoad = node.name.first().toUpperCase() - 'A' + 1 + baseSeconds
}
fun decrement() {
if (remainingLoad != null) {
remainingLoad = remainingLoad!! - 1
}
}
fun isDone() = remainingLoad == 0
}
// part 1
fun topsort(path: String): String {
val nodes = parseFile(path).toMutableList()
val order = StringBuffer()
while (nodes.isNotEmpty()) {
val node = nodes.sortedBy { it.name }.first()
nodes.remove(node)
order.append(node.name)
for (next in node.nexts) {
next.decrement()
if (next.isReady()) {
nodes.add(next)
}
}
}
return order.toString()
}
// part 2
class Solution2(path: String, private val workerNum: Int,
private val baseSeconds: Int = 0) {
private val nodes = parseFile(path).toMutableList()
private val order = StringBuffer()
private val busyWorkers = mutableListOf<Worker>()
private val idleWorkers = mutableListOf<Worker>()
fun topsort(): Int {
for (i in 0 until workerNum) {
idleWorkers.add(Worker())
}
var seconds = 0
while (true) {
seconds++
assignWork()
tick()
// println("tick, order: $order")
if (nodes.isEmpty() && busyWorkers.isEmpty()) {
break
}
}
return seconds
}
// time passes by 1 second
private fun tick() {
for (i in 0 until busyWorkers.size) {
val worker = busyWorkers.removeAt(0)
worker.decrement()
if (worker.isDone()) {
// println("worker is done: ${worker.node!!.name}")
order.append(worker.node!!.name.first())
for (next in worker.node!!.nexts) {
next.decrement()
if (next.isReady()) {
// println("adding next ${next.name}")
nodes.add(next)
}
}
idleWorkers.add(worker)
} else {
// add it back
busyWorkers.add(worker)
}
}
// println("after tick, nodes: $nodes, idleWorkers: $idleWorkers, busyWorkers: $busyWorkers")
}
private fun assignWork() {
nodes.sortBy { it.name }
while (nodes.isNotEmpty() && idleWorkers.isNotEmpty()) {
val node = nodes.removeAt(0)
val worker = idleWorkers.removeAt(0)
worker.start(node, baseSeconds)
busyWorkers.add(worker)
}
// println("after assignWork, nodes: $nodes, idleWorkers: $idleWorkers, busyWorkers: $busyWorkers")
}
}
// Return a list of nodes with no incoming edges
fun parseFile(path: String): List<Node> {
val nodes: MutableMap<String, Node> = mutableMapOf()
File(path).forEachLine { line ->
val pair = parseLine(line)
val name1 = pair.first
val name2 = pair.second
val node1 = nodes.getOrDefault(name1, Node(name1))
val node2 = nodes.getOrDefault(name2, Node(name2))
node1.addNext(node2)
nodes[name1] = node1
nodes[name2] = node2
}
return nodes.values.filter { it.isReady() }
}
// Step A must be finished before step L can begin.
fun parseLine(line: String): Pair<String, String> {
val regex = """Step (\S+) must be finished before step (\S+) can begin.""".toRegex()
if (regex.matches(line)) {
val (_, name1, name2) = regex.find(line)!!.groupValues
return Pair(name1, name2)
} else {
throw RuntimeException("Invalid input line: $line")
}
}
| 58 | Rust | 1 | 0 | d5143e89ce25d761eac67e9c357620231cab303e | 4,302 | cosmos | MIT License |
src/Day02.kt | gischthoge | 573,509,147 | false | {"Kotlin": 5583} | fun main() {
fun part1(input: List<String>): Int {
return input.map { it.toCharArray().first().lowercaseChar() to it.toCharArray().last().lowercaseChar() }
.sumOf { (a, b) -> b - 'x' + 1 + ((b + ('a' - 'x') - a + 1).mod(3)) * 3 }
}
fun part2(input: List<String>): Int {
return input.map { it.toCharArray().first() to it.toCharArray().last() }
.sumOf { (a,b) -> (b - 'X') * 3 + ((a + (b - 'Y') - 'A').mod(3) + 1) }
}
val input = readInput("Day02")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | e403f738572360d4682f9edb6006d81ce350ff9d | 570 | aock | Apache License 2.0 |
hierarchy/src/commonMain/kotlin/io/data2viz/hierarchy/pack/Enclose.kt | data2viz | 89,368,762 | false | null | /*
* Copyright (c) 2018-2021. data2viz sàrl.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package io.data2viz.hierarchy.pack
import io.data2viz.hierarchy.CircleValues
import io.data2viz.hierarchy.PackNode
import kotlin.math.sqrt
private data class Circle(
override var x: Double = .0,
override var y: Double = .0,
override var r: Double = .0
) : CircleValues
/**
* Computes the smallest circle that encloses the specified array of circles, each of which must have a circle.r
* property specifying the circle’s radius, and circle.x and circle.y properties specifying the circle’s center.
* The enclosing circle is computed using the Matoušek-Sharir-Welzl algorithm.
*/
public fun enclose(circles: List<CircleValues>): CircleValues? {
var i = 0
val shuffledCircles = circles.shuffled()
val n = shuffledCircles.size
var B = listOf<CircleValues>()
var e: CircleValues? = null
while (i < n) {
val p = shuffledCircles[i]
if (e != null && enclosesWeak(e, p)) i++
else {
B = extendBasis(B, p)
e = encloseBasis(B)
i = 0
}
}
return e
}
private fun enclosesWeak(a: CircleValues, b: CircleValues): Boolean {
val dr = a.r - b.r + epsilon
val dx = b.x - a.x
val dy = b.y - a.y
return (dr > 0) && ((dr * dr) > ((dx * dx) + (dy * dy)))
}
private fun enclosesWeakAll(a: CircleValues, B: List<CircleValues>): Boolean {
for (i in 0 until B.size) {
if (!enclosesWeak(a, B[i])) {
return false
}
}
return true
}
private fun enclosesNot(a: CircleValues, b: CircleValues): Boolean {
val dr = a.r - b.r
val dx = b.x - a.x
val dy = b.y - a.y
return (dr < 0) || ((dr * dr) < ((dx * dx) + (dy * dy)))
}
private fun encloseBasis(B:List<CircleValues>): CircleValues {
when (B.size) {
1 -> return encloseBasis1(B[0])
2 -> return encloseBasis2(B[0], B[1])
else -> return encloseBasis3(B[0], B[1], B[2])
}
}
private fun encloseBasis1(a: CircleValues) = Circle(a.x, a.y, a.r)
private fun encloseBasis2(a: CircleValues, b: CircleValues): CircleValues {
val x1 = a.x
val y1 = a.y
val r1 = a.r
val x2 = b.x
val y2 = b.y
val r2 = b.r
val x21 = x2 - x1
val y21 = y2 - y1
val r21 = r2 - r1
val l = sqrt(x21 * x21 + y21 * y21)
return Circle((x1 + x2 + x21 / l * r21) / 2, (y1 + y2 + y21 / l * r21) / 2, (l + r1 + r2) / 2)
}
private fun encloseBasis3(a: CircleValues, b: CircleValues, c: CircleValues): CircleValues {
val x1 = a.x
val y1 = a.y
val r1 = a.r
val x2 = b.x
val y2 = b.y
val r2 = b.r
val x3 = c.x
val y3 = c.y
val r3 = c.r
val a2 = x1 - x2
val a3 = x1 - x3
val b2 = y1 - y2
val b3 = y1 - y3
val c2 = r2 - r1
val c3 = r3 - r1
val d1 = x1 * x1 + y1 * y1 - r1 * r1
val d2 = d1 - x2 * x2 - y2 * y2 + r2 * r2
val d3 = d1 - x3 * x3 - y3 * y3 + r3 * r3
val ab = a3 * b2 - a2 * b3
val xa = (b2 * d3 - b3 * d2) / (ab * 2) - x1
val xb = (b3 * c2 - b2 * c3) / ab
val ya = (a3 * d2 - a2 * d3) / (ab * 2) - y1
val yb = (a2 * c3 - a3 * c2) / ab
val A = xb * xb + yb * yb - 1
val B = 2 * (r1 + xa * xb + ya * yb)
val C = xa * xa + ya * ya - r1 * r1
val r = -(if (A != .0) (B + sqrt(B * B - 4 * A * C)) / (2 * A) else C / B)
return Circle(x1 + xa + xb * r, y1 + ya + yb * r, r)
}
private fun extendBasis(B: List<CircleValues>, p: CircleValues): List<CircleValues> {
if (enclosesWeakAll(p, B)) return listOf(p)
// If we get here then B must have at least one element.
for (i in 0 until B.size) {
if (enclosesNot(p, B[i])
&& enclosesWeakAll(encloseBasis2(B[i], p), B)
) {
return listOf(B[i], p)
}
}
// If we get here then B must have at least two elements.
for (i in 0 until B.size - 1) {
for (j in (i + 1) until B.size) {
if (enclosesNot(encloseBasis2(B[i], B[j]), p)
&& enclosesNot(encloseBasis2(B[i], p), B[j])
&& enclosesNot(encloseBasis2(B[j], p), B[i])
&& enclosesWeakAll(encloseBasis3(B[i], B[j], p), B)
) {
return listOf(B[i], B[j], p)
}
}
}
// If we get here then something is very wrong.
throw RuntimeException("Unable to compute enclosing circle for PackLayout.")
}
| 79 | Kotlin | 29 | 389 | 5640d3e8f1ce4cd4e5d651431726869e329520fc | 4,953 | data2viz | Apache License 2.0 |
src/main/kotlin/algorithms/CandyCount.kt | AgentKnopf | 240,955,745 | false | null | package algorithms
/**
* There are N children standing in a line. Each child is assigned a rating value.
* You are giving candies to these children subjected to the following requirements:
*
* Each child must have at least one candy.
* Children with a higher rating get more candies than their neighbors.
* What is the minimum candies you must give?
*
* Note: The steps to the approach implemented here are as follows:
*
* #1 Fill candy array with 1 candy for each cell
* #2 Go from left to right > update candy
* #3 Go from right to left > update candy
*/
internal fun candyCount(ratings: IntArray): Int {
val maxIndex = ratings.size - 1
if (maxIndex < 0) {
return 0
}
val candies = IntArray(maxIndex + 1) { 1 }
//Left to right, skipping the first element as we only compare left-hand neighbors
for (i in 1..maxIndex) {
if (ratings[i] > ratings[i - 1]) {
candies[i] = candies[i - 1] + 1
}
}
var sum = candies[maxIndex]
//Right to left, skipping the last element as we only compare right-hand neighbors
for (i in maxIndex - 1 downTo 0) {
if (ratings[i] > ratings[i + 1]) {
candies[i] = Math.max(candies[i], candies[i + 1] + 1)
}
sum += candies[i]
}
return sum
} | 0 | Kotlin | 1 | 0 | 5367ce67e54633e53b2b951c2534bf7b2315c2d8 | 1,297 | technical-interview | MIT License |
src/main/kotlin/solver/model.kt | toukovk | 256,759,841 | false | null | package solver
import java.lang.RuntimeException
import kotlin.math.abs
interface ExpressionItem
enum class Operator : ExpressionItem {
ADD { override fun apply(a1: Double, a2: Double) = a1 + a2 },
MINUS { override fun apply(a1: Double, a2: Double) = a1 - a2 },
TIMES { override fun apply(a1: Double, a2: Double) = a1 * a2 },
DIVIDE { override fun apply(a1: Double, a2: Double) = a1 / a2 };
abstract fun apply(a1: Double, a2: Double): Double
}
data class Scalar(
val value: Double
): ExpressionItem
fun evalPrefixExpression(expression: List<ExpressionItem>): Double {
var index = 0
fun evalNext(): Double {
return when (val current = expression[index++]) {
is Scalar -> current.value
is Operator -> current.apply(evalNext(), evalNext())
else -> throw RuntimeException("Unexpected type: $current")
}
}
return evalNext()
}
fun solve(values: List<Double>, target: Double): List<ExpressionItem>? {
fun recur(expressionSoFar: List<ExpressionItem>, remainingComponents: List<Double>): List<ExpressionItem>? {
if (remainingComponents.isEmpty()) {
return if (abs(evalPrefixExpression(expressionSoFar) - target) < 0.001) {
expressionSoFar
} else {
null
}
}
val numbersSoFar = expressionSoFar.filterIsInstance<Scalar>().count()
val operatorsSoFar = expressionSoFar.filterIsInstance<Operator>().count()
// Try out all operators if operator can be added
if (operatorsSoFar < values.size - 1) {
for (op in Operator.values()) {
val result = recur(expressionSoFar + op, remainingComponents)
if (result != null) {
return result
}
}
}
// Try out all operators if number can be added
if (numbersSoFar < operatorsSoFar || (numbersSoFar == operatorsSoFar && remainingComponents.size == 1)) {
for (number in remainingComponents) {
val result = recur(
expressionSoFar + Scalar(number),
remainingComponents - number
)
if (result != null) {
return result
}
}
}
return null
}
return recur(listOf(), values)
}
| 0 | Kotlin | 0 | 0 | 2c878978b6b9edbaac961dccb82418c504cec7f3 | 2,393 | 24-solver | Apache License 2.0 |
src/main/kotlin/days/Day3.kt | jgrgt | 433,952,606 | false | {"Kotlin": 113705} | package days
class Day3 : Day(3) {
override fun partOne(): Any {
return p1(inputList)
}
override fun partTwo(): Any {
return p2(inputList)
}
fun p1(l: List<String>): Int {
val total = l.size
val first = l[0]
val amountOfBits = first.length
val ones = mutableListOf<Int>()
repeat(amountOfBits) {
ones.add(0)
}
l.map {
it.forEachIndexed { i, s ->
when (s) {
'1' -> ones[i]++
'0' -> {
}
else -> error("Unexpected character $s")
}
}
}
var (gamma, epsilon) = buildGammaAndEpsilon(ones, total)
return gamma * epsilon
}
fun p2(l: List<String>): Int {
val oxString = oxygen(l)
val ox = oxString.toInt(2)
val co2String = co2scrubber(l)
val co2 = co2String.toInt(2)
return ox * co2
}
fun buildGammaAndEpsilon(
ones: List<Int>,
total: Int
): Pair<Int, Int> {
var gamma = 0
var epsilon = 0
ones.forEach { amountOfOnes ->
gamma = gamma.shl(1)
epsilon = epsilon.shl(1)
if (amountOfOnes > (total / 2)) {
gamma += 1
} else {
epsilon += 1
}
}
return Pair(gamma, epsilon)
}
fun oxygen(l: List<String>, index: Int = 0): String {
if (l.size == 1) {
return l[0]
}
if (index >= l[0].length) {
return l[0]
}
val (zeroes, ones) = l.partition {
it[index] == '0'
}
return if (zeroes.size > ones.size) {
oxygen(zeroes, index + 1)
} else {
oxygen(ones, index + 1)
}
}
fun co2scrubber(l: List<String>, index: Int = 0): String {
if (l.size == 1) {
return l[0]
}
if (index >= l[0].length) {
return l[0]
}
val (zeroes, ones) = l.partition {
it[index] == '0'
}
return if (zeroes.size <= ones.size) {
co2scrubber(zeroes, index + 1)
} else {
co2scrubber(ones, index + 1)
}
}
}
| 0 | Kotlin | 0 | 0 | 6231e2092314ece3f993d5acf862965ba67db44f | 2,314 | aoc2021 | Creative Commons Zero v1.0 Universal |
src/test/kotlin/Day5Test.kt | FredrikFolkesson | 320,692,155 | false | null | import org.junit.jupiter.api.Test
import kotlin.test.assertEquals
class Day5Test {
@Test
fun test_real_input() {
println(getHighestSeatNumber(readFileAsLinesUsingUseLines("/Users/fredrikfolkesson/git/advent-of-code/src/test/kotlin/input-day5.txt")))
}
@Test
fun test_real_input_part_2() {
println(findMissingBoardingPass(readFileAsLinesUsingUseLines("/Users/fredrikfolkesson/git/advent-of-code/src/test/kotlin/input-day5.txt")))
}
private fun findMissingBoardingPass(boardingpasses: List<String>): Int {
val sortedBoardingPassSeatIds =
boardingpasses.map { boardingpass -> getSeatId(getRow(boardingpass), getColumn(boardingpass)) }.sorted()
return (sortedBoardingPassSeatIds[0]..sortedBoardingPassSeatIds[sortedBoardingPassSeatIds.size - 1]).filter { !(it in sortedBoardingPassSeatIds) }
.first()
}
private fun getHighestSeatNumber(boardingpasses: List<String>): Int {
return boardingpasses.maxOf { boardingpass -> getSeatId(getRow(boardingpass), getColumn(boardingpass)) }
}
@Test
fun test_seat_id() {
assertEquals(567, getSeatId(70, 7))
assertEquals(119, getSeatId(14, 7))
assertEquals(820, getSeatId(102, 4))
}
@Test
fun test_seat_id_with_boarding_pass() {
assertEquals(567, getSeatId(getRow("BFFFBBFRRR"), getColumn("BFFFBBFRRR")))
assertEquals(119, getSeatId(getRow("FFFBBBFRRR"), getColumn("FFFBBBFRRR")))
assertEquals(820, getSeatId(getRow("BBFFBBFRLL"), getColumn("BBFFBBFRLL")))
}
@Test
fun test_row() {
assertEquals(44, getRow("FBFBBFFRLR"))
assertEquals(70, getRow("BFFFBBFRRR"))
assertEquals(14, getRow("FFFBBBFRRR"))
assertEquals(102, getRow("BBFFBBFRLL"))
}
@Test
fun test_column() {
assertEquals(5, getColumn("FBFBBFFRLR"))
assertEquals(7, getColumn("BFFFBBFRRR"))
assertEquals(7, getColumn("FFFBBBFRRR"))
assertEquals(4, getColumn("BBFFBBFRLL"))
}
private fun getColumn(input: String): Int {
val columnPart = input.substring(7)
return doBinarySpacePartitioning(columnPart, 0, 7, 'L')
}
private fun getRow(input: String): Int {
val rowPart = input.substring(0, 7)
val rowBinaryString = rowPart.replace("F", "0").replace("L", "1").replace("L", "0").replace("B", "1")
return rowBinaryString.toInt(2)
//return doBinarySpacePartitioning(rowPart, 0,127, 'F')
}
private fun doBinarySpacePartitioning(input: String, initialMin: Int, initialMax: Int, lowerHalfChar: Char): Int {
return input.fold(Pair(initialMin, initialMax)) { (min, max), char ->
if (char == lowerHalfChar) {
Pair(min, min + (max - min) / 2)
} else {
Pair(min + (max - min) / 2, max)
}
}.second
}
private fun getSeatId(row: Int, column: Int): Int = row * 8 + column
} | 0 | Kotlin | 0 | 0 | 79a67f88e1fcf950e77459a4f3343353cfc1d48a | 2,984 | advent-of-code | MIT License |
src/main/kotlin/me/grison/aoc/y2017/Day24.kt | agrison | 315,292,447 | false | {"Kotlin": 267552} | package me.grison.aoc.y2017
import me.grison.aoc.Day
import me.grison.aoc.allInts
import me.grison.aoc.pair
import me.grison.aoc.sum
class Day24 : Day(24, 2017) {
override fun title() = "Electromagnetic Moat"
val elements = inputList.map { it.allInts().pair() }
// 1656
override fun partOne() = buildBridge(0, listOf(), elements, compareBy(Bridge::value)).value()
// 1642
override fun partTwo() =
buildBridge(0, listOf(), elements, compareBy(Bridge::size) then compareBy(Bridge::value)).value()
private fun load() = inputList.map { it.allInts().pair() }
}
typealias Bridge = List<Pair<Int, Int>>
fun Bridge.value() = this.sumOf { it.sum() }
fun buildBridge(x: Int, bridge: Bridge, remaining: Bridge, comparator: Comparator<Bridge>): Bridge {
return remaining.filter { it.first == x || it.second == x }
.map { buildBridge(if (it.first == x) it.second else it.first, bridge + it, remaining - it, comparator) }
.maxWithOrNull(comparator) ?: bridge
}
| 0 | Kotlin | 3 | 18 | ea6899817458f7ee76d4ba24d36d33f8b58ce9e8 | 1,012 | advent-of-code | Creative Commons Zero v1.0 Universal |
js/js.translator/testFiles/webDemoExamples2/cases/maze.kt | chirino | 3,596,099 | true | null | /**
* Let's Walk Through a Maze.
*
* Imagine there is a maze whose walls are the big 'O' letters.
* Now, I stand where a big 'I' stands and some cool prize lies
* somewhere marked with a '$' sign. Like this:
*
* OOOOOOOOOOOOOOOOO
* O O
* O$ O O
* OOOOO O
* O O
* O OOOOOOOOOOOOOO
* O O I O
* O O
* OOOOOOOOOOOOOOOOO
*
* I want to get the prize, and this program helps me do so as soon
* as I possibly can by finding a shortest path through the maze.
*/
import java.util.*
/**
* This function looks for a path from max.start to maze.end through
* free space (a path does not go through walls). One can move only
* straightly up, down, left or right, no diagonal moves allowed.
*/
fun findPath(maze : Maze) : List<#(Int, Int)>? {
val previous = HashMap<#(Int, Int), #(Int, Int)>
val queue = LinkedList<#(Int, Int)>
val visited = HashSet<#(Int, Int)>
queue.offer(maze.start)
visited.add(maze.start)
while (!queue.isEmpty()) {
val cell = queue.poll()
if (cell == maze.end) break
for (newCell in maze.neighbors(cell._1, cell._2)) {
if (newCell in visited) continue
previous[newCell] = cell
queue.offer(newCell)
visited.add(cell)
}
}
if (previous[maze.end] == null) return null
val path = ArrayList<#(Int, Int)>()
var current = previous[maze.end]
while (current != maze.start) {
path.add(0, current)
current = previous[current]
}
return path
}
/**
* Find neighbors of the (i, j) cell that are not walls
*/
fun Maze.neighbors(i : Int, j : Int) : List<#(Int, Int)> {
val result = ArrayList<#(Int, Int)>
addIfFree(i - 1, j, result)
addIfFree(i, j - 1, result)
addIfFree(i + 1, j, result)
addIfFree(i, j + 1, result)
return result
}
fun Maze.addIfFree(i : Int, j : Int, result : List<#(Int, Int)>) {
if (i !in 0..height-1) return
if (j !in 0..width-1) return
if (walls[i][j]) return
result.add(#(i, j))
}
/**
* A data class that represents a maze
*/
class Maze(
// Number or columns
val width : Int,
// Number of rows
val height : Int,
// true for a wall, false for free space
val walls : Array<out Array<out Boolean>>,
// The starting point (must not be a wall)
val start : #(Int, Int),
// The target point (must not be a wall)
val end : #(Int, Int)
) {
}
/** A few maze examples here */
fun main(args : Array<String>) {
printMaze("I $")
printMaze("I O $")
printMaze("""
O $
O
O
O
O I
""")
printMaze("""
OOOOOOOOOOO
O $ O
OOOOOOO OOO
O O
OOOOO OOOOO
O O
O OOOOOOOOO
O OO
OOOOOO IO
""")
printMaze("""
OOOOOOOOOOOOOOOOO
O O
O$ O O
OOOOO O
O O
O OOOOOOOOOOOOOO
O O I O
O O
OOOOOOOOOOOOOOOOO
""")
}
// UTILITIES
fun printMaze(str : String) {
val maze = makeMaze(str)
println("Maze:")
val path = findPath(maze)
for (i in 0..maze.height - 1) {
for (j in 0..maze.width - 1) {
val cell = #(i, j)
print(
if (maze.walls[i][j]) "O"
else if (cell == maze.start) "I"
else if (cell == maze.end) "$"
else if (path != null && path.contains(cell)) "~"
else " "
)
}
println("")
}
println("Result: " + if (path == null) "No path" else "Path found")
println("")
}
/**
* A maze is encoded in the string s: the big 'O' letters are walls.
* I stand where a big 'I' stands and the prize is marked with
* a '$' sign.
*
* Example:
*
* OOOOOOOOOOOOOOOOO
* O O
* O$ O O
* OOOOO O
* O O
* O OOOOOOOOOOOOOO
* O O I O
* O O
* OOOOOOOOOOOOOOOOO
*/
fun makeMaze(s : String) : Maze {
val lines = s.split("\n").sure()
val w = max<String?>(lines.toList(), comparator<String?> {o1, o2 ->
val l1 : Int = o1?.size ?: 0
val l2 = o2?.size ?: 0
l1 - l2
}).sure()
val data = Array<Array<Boolean>>(lines.size) {Array<Boolean>(w.size) {false}}
var start : #(Int, Int)? = null
var end : #(Int, Int)? = null
for (line in lines.indices) {
for (x in lines[line].indices) {
val c = lines[line].sure()[x]
data[line][x] = c == 'O'
when (c) {
'I' -> start = #(line, x)
'$' -> end = #(line, x)
else -> {}
}
}
}
if (start == null) {
throw IllegalArgumentException("No starting point in the maze (should be indicated with 'I')")
}
if (end == null) {
throw IllegalArgumentException("No goal point in the maze (should be indicated with a '$' sign)")
}
return Maze(w.size, lines.size, data, start.sure(), end.sure())
}
// An excerpt from the Standard Library
val String?.indices : IntRange get() = IntRange(0, this.sure().size)
fun <K, V> Map<K, V>.set(k : K, v : V) { put(k, v) }
fun comparator<T> (f : (T, T) -> Int) : Comparator<T> = object : Comparator<T> {
override fun compare(o1 : T, o2 : T) : Int = f(o1, o2)
override fun equals(p : Any?) : Boolean = false
}
fun <T, C: Collection<T>> Array<T>.to(result: C) : C {
for (elem in this)
result.add(elem)
return result
}
| 0 | Java | 28 | 70 | ac434d48525a0e5b57c66b9f61b388ccf3d898b5 | 5,423 | kotlin | Apache License 2.0 |
src/Day01.kt | mertceyhan | 573,013,476 | false | {"Kotlin": 4804} | fun main() {
fun getTotalCaloriesByOrder(input: List<String>): List<Int> {
val totalCalories = mutableListOf<Int>()
var currentTotalCalorie = 0
input.forEachIndexed { index, string ->
if (string != "") {
currentTotalCalorie += string.toInt()
} else {
totalCalories.add(currentTotalCalorie)
currentTotalCalorie = 0
}
if (index == input.lastIndex) {
totalCalories.add(currentTotalCalorie)
currentTotalCalorie = 0
}
}
totalCalories.sortDescending()
return totalCalories
}
fun part1(input: List<String>): Int {
return getTotalCaloriesByOrder(input).first()
}
fun part2(input: List<String>): Int {
return getTotalCaloriesByOrder(input).subList(0, 3).sum()
}
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | e079082b70ae459fa1068653d11c54399265b8c8 | 978 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day09.kt | mvmlisb | 572,859,923 | false | {"Kotlin": 14994} | private data class Coords(var x: Int, var y: Int)
private class Rope {
private var head = Coords(0, 0)
private var tail = Coords(0, 0)
val visitedCordsByTail = mutableSetOf<Coords>()
init {
visitedCordsByTail += tail.copy()
}
fun move(string: String) {
val split = string.split(" ")
val direction = split.first()
val count = split.last().toInt()
when (direction) {
"U" -> {
repeat(count) {
head.y ++
if (head.y - tail.y > 1) {
tail.x = head.x
tail.y++
visitedCordsByTail += tail.copy()
}
}
}
"D" -> {
repeat(count) {
head.y--
if (tail.y - head.y > 1) {
tail.x = head.x
tail.y--
visitedCordsByTail += tail.copy()
}
}
}
"R" -> {
repeat(count) {
head.x++
if (head.x - tail.x > 1) {
tail.y = head.y
tail.x++
visitedCordsByTail += tail.copy()
}
}
}
"L" -> {
repeat(count) {
head.x--
if (tail.x - head.x > 1) {
tail.y = head.y
tail.x--
visitedCordsByTail += tail.copy()
}
}
}
}
}
override fun toString() = "Head : $head :::: Tail : $tail"
}
fun main() {
val input = readInput("Day09_test")
val rope = Rope()
input.forEach(rope::move)
println(rope.visitedCordsByTail.size)
println(rope.toString())
}
| 0 | Kotlin | 0 | 0 | 648d594ec0d3b2e41a435b4473b6e6eb26e81833 | 1,957 | advent_of_code_2022 | Apache License 2.0 |
src/aoc2022/day03/AoC03.kt | Saxintosh | 576,065,000 | false | {"Kotlin": 30013} | package aoc2022.day03
import readLines
fun main() {
fun part1(list: List<String>): Int {
return list.map {
val len = it.length
val a = it.substring(0, len / 2).toSet()
val b = it.substring(len / 2).toSet()
val x = (a intersect b).first()
if (x.isLowerCase())
x - 'a' + 1
else
x - 'A' + 27
}.sum()
}
fun part2(list: List<String>): Int {
return list.windowed(3, 3) {
val (l1, l2, l3) = it
val x = ((l1.toSet() intersect l2.toSet()) intersect l3.toSet()).first()
if (x.isLowerCase())
x - 'a' + 1
else
x - 'A' + 27
}.sum()
}
readLines(157, 70, ::part1, ::part2)
}
| 0 | Kotlin | 0 | 0 | 877d58367018372502f03dcc97a26a6f831fc8d8 | 625 | aoc2022 | Apache License 2.0 |
src/main/kotlin/dwt/Dwt33.kt | sssemil | 268,084,789 | false | null | package dwt
import com.marcinmoskala.math.combinations
import utils.Rational
import kotlin.math.max
import kotlin.math.min
class Dwt33 {
fun main() {
val nodes = setOf(1, 2, 3, 4)
val edges = mutableSetOf<Pair<Int, Int>>()
nodes.forEach { a ->
nodes.forEach { b ->
//if (a != b) {
edges.add(Pair(min(a, b), max(a, b)))
//}
}
}
val pss = (0..edges.size).flatMap {
edges.combinations(it)
}
val bro = pss.map { list: Set<Pair<Int, Int>> ->
var buckets = nodes.map { mutableSetOf(it) }
list.forEach { (a, b) ->
val theBucket = buckets.filter {
it.contains(a) || it.contains(b)
}.fold(mutableSetOf<Int>(), { acc, mutableSet ->
acc.addAll(mutableSet)
acc
})
buckets = buckets.filter { !it.contains(a) && !it.contains(b) }
theBucket.add(a)
theBucket.add(b)
buckets = buckets.toMutableList().also { it.add(theBucket) }
}
Pair(buckets.size, list)
}.groupBy { it.first }
val e1 = Rational(bro.entries.fold(0, { acc, entry ->
acc + entry.key * entry.key * entry.value.size
}).toLong(), bro.entries.sumBy { it.value.size }.toLong())
val e2 = Rational(bro.entries.fold(0, { acc, entry ->
acc + entry.key * entry.value.size
}).toLong(), bro.entries.sumBy { it.value.size }.toLong())
println("E[X^2] = $e1 = ${e1.toDouble()}")
println("E[X] = $e2 = ${e2.toDouble()}")
println("E[X]^2 = ${e2 * e2} = ${(e2 * e2).toDouble()}")
}
}
fun main() {
Dwt33().main()
} | 0 | Kotlin | 0 | 0 | 02d951b90e0225bb1fa36f706b19deee827e0d89 | 1,815 | math_playground | MIT License |
src/Day04.kt | daividssilverio | 572,944,347 | false | {"Kotlin": 10575} |
private fun extractRange(stringRange: String): IntRange = stringRange.split("-").let { it[0].toInt()..it[1].toInt() }
private fun IntRange.contains(other: IntRange) = this.first <= other.first && other.last <= this.last
private fun IntRange.overlap(other: IntRange) =
this.first in other || this.last in other || other.first in this || other.last in this
fun main() {
val rawPairs = readInput("Day04_test")
val rangePairs = rawPairs.map { pair -> pair.split(",").let { extractRange(it[0]) to extractRange(it[1]) } }
val pairsWithOneCompleteOverlap = rangePairs.count { it.first.contains(it.second) || it.second.contains(it.first) }
val pairsWithAnyOverlap = rangePairs.count { it.first.overlap(it.second) }
println(pairsWithOneCompleteOverlap)
println(pairsWithAnyOverlap)
} | 0 | Kotlin | 0 | 0 | 141236c67fe03692785e0f3ab90248064a1693da | 804 | advent-of-code-kotlin-2022 | Apache License 2.0 |
app/src/main/kotlin/day05/Point.kt | StylianosGakis | 434,004,245 | false | {"Kotlin": 56380} | package day05
import kotlin.math.abs
import kotlin.math.min
data class Point(val x: Int, val y: Int) {
operator fun rangeTo(end: Point): List<Point> {
return if (x == end.x) {
val startingIndex = min(y, end.y)
val length = abs(y - end.y)
val endingIndex = startingIndex + length
(startingIndex..endingIndex).map { y ->
Point(this.x, y)
}
} else if (y == end.y) {
val startingIndex = min(x, end.x)
val length = abs(x - end.x)
val endingIndex = startingIndex + length
(startingIndex..endingIndex).map { x ->
Point(x, this.y)
}
} else if (abs(x - end.x) == abs(y - end.y)) {
val start = this
val xRange = if (start.x < end.x) {
start.x..end.x
} else {
start.x downTo end.x
}
val yRange = if (start.y < end.y) {
start.y..end.y
} else {
start.y downTo end.y
}
(xRange zip yRange).map { (x, y) ->
Point(x, y)
}
} else {
emptyList()
}
}
companion object {
fun fromCommaSeparatedInput(input: String): Point {
return input
.split(",")
.map(String::toInt)
.let { Point(it[0], it[1]) }
}
}
}
| 0 | Kotlin | 0 | 0 | a2dad83d8c17a2e75dcd00651c5c6ae6691e881e | 1,468 | advent-of-code-2021 | Apache License 2.0 |
src/commonMain/kotlin/eu/yeger/cyk/model/CYKModel.kt | DerYeger | 302,742,119 | false | null | package eu.yeger.cyk.model
public data class CYKModel
internal constructor(
val word: Word,
val grammar: Grammar,
val grid: List<List<Set<NonTerminalSymbol>>>,
) {
internal constructor(
word: Word,
grammar: Grammar,
) : this(
word,
grammar,
List(word.size) { rowIndex ->
List(word.size - rowIndex) {
setOf<NonTerminalSymbol>()
}
},
)
override fun toString(): String {
return with(grid) {
val maxRuleSetLength = maxOf { row ->
row.maxOf { set ->
set.joinToString(", ").length
}
}
val maxTerminalSymbolLength = word.maxOf { terminalSymbol ->
terminalSymbol.toString().length
}
val maxLength = maxOf(maxRuleSetLength, maxTerminalSymbolLength)
val columnPadding = " | "
val wordRowString = word.joinToString(columnPadding, prefix = "| ", postfix = " |") { nonTerminalSymbol ->
nonTerminalSymbol.toString().padEnd(maxLength, ' ')
}.plus("\n")
val wordRowSeparator = "".padEnd(size * maxLength + (size - 1) * columnPadding.length + 4, '-').plus("\n")
wordRowSeparator + wordRowString + wordRowSeparator.repeat(2) + joinToString(separator = "") { row ->
row.joinToString(columnPadding, prefix = "| ", postfix = " |") { set ->
set.joinToString(", ") { it.toString() }.padEnd(maxLength, ' ')
}.plus("\n")
.plus("-".repeat(row.size * maxLength + (row.size - 1) * columnPadding.length + 4))
.plus("\n")
}
}
}
}
public val CYKModel.result: Boolean
get() = grid.last().first().contains(grammar.startSymbol)
public operator fun CYKModel.get(rowIndex: Int, columnIndex: Int): Set<NonTerminalSymbol> {
return grid[rowIndex][columnIndex]
}
public fun CYKModel.containsSymbolAt(nonTerminalSymbol: NonTerminalSymbol, rowIndex: Int, columnIndex: Int): Boolean {
return get(rowIndex, columnIndex).contains(nonTerminalSymbol)
}
internal fun CYKModel.allowsNonTerminalRuleAt(
nonTerminatingRule: NonTerminatingRule,
l: Int,
s: Int,
p: Int,
): Boolean {
return this.containsSymbolAt(nonTerminatingRule.right.first, p - 1, s - 1) &&
this.containsSymbolAt(nonTerminatingRule.right.second, l - p - 1, s + p - 1)
}
internal fun CYKModel.withSymbolAt(nonTerminalSymbol: NonTerminalSymbol, rowIndex: Int, columnIndex: Int): CYKModel {
return grid.mapIndexed { gridRowIndex, gridRow ->
when (gridRowIndex) {
rowIndex -> gridRow.mapIndexed { gridColumnIndex, nonTerminalSymbolSet ->
when (gridColumnIndex) {
columnIndex -> nonTerminalSymbolSet + nonTerminalSymbol
else -> nonTerminalSymbolSet
}
}
else -> gridRow
}
}.let { newGrid -> copy(grid = newGrid) }
}
| 0 | Kotlin | 0 | 2 | 76b895e3e8ea6b696b3ad6595493fda9ee3da067 | 3,052 | cyk-algorithm | MIT License |
src/main/kotlin/net/varionic/mcbinpack/BinPacking.kt | patonw | 213,552,659 | false | null | package net.varionic.mcbinpack
import io.vavr.collection.List
sealed class Node
object Empty : Node()
data class Item(val width: Int, val height: Int) : Node() {
/**
* Transpose item
*/
fun t() = Item(height, width)
}
data class HSplit(val pos: Int, val top: Node, val bottom: Node) : Node()
data class VSplit(val pos: Int, val left: Node, val right: Node) : Node()
data class Vacancy(val width: Int, val height: Int) : Node(), Comparable<Vacancy> {
companion object {
fun make(width:Int, height:Int) = if (width * height > 0) Vacancy(width, height) else Empty
}
val area get() = width * height
override fun compareTo(other: Vacancy): Int {
return (area).compareTo(other.area)
}
override fun equals(other: Any?): Boolean {
return this === other
}
override fun toString(): String {
return "Vacancy($width, $height, ***)"
}
}
data class Bin(val width: Int, val height: Int, val root: Node = Empty, val vacancies: List<Vacancy> = List.of(Vacancy(width, height)), val rejects: List<Item> = List.empty()) {
companion object {
fun empty(width: Int, height: Int) = Vacancy(width, height).let { Bin(width, height, it, List.of(it) ) }
}
fun reject(item: Item) = this.copy(rejects = rejects.prepend(item))
}
fun Bin.toEndpoint() = Point(width, height)
/**
* Traverses the bin with a visitor lambda.
*
* Runs [block] on each node of the receiver and combines results from each subtree.
*
* @receiver Bin the object to traverse
* @param block Lambda to execute on each node
* @param combine Binary function to combine the results of executing [block] on each subtree
*/
fun <T> Bin.traverse(block: (Point, Point, Node) -> T, combine: (T, T) -> T): T {
fun helper(start: Point, end: Point, node: Node): T {
val result = block(start, end, node)
when (node) {
is HSplit -> {
val mid = start.y + node.pos
val tops = helper(start, Point(end.x, mid), node.top)
val bottoms = helper(Point(start.x, mid), end, node.bottom)
return combine(result, combine(tops, bottoms))
}
is VSplit -> {
val mid = start.x + node.pos
val lefts = helper(start, Point(mid, end.y), node.left)
val rights = helper(Point(mid, start.y), end, node.right)
return combine(result, combine(lefts, rights))
}
else -> return result
}
}
return helper(Point(0, 0), this.toEndpoint(), this.root)
}
fun Bin.getItems() = traverse({ _, _, node ->
if (node is Item) listOf(node) else emptyList()
}, { a, b ->
a + b
})
fun Bin.countItems() = traverse({ _, _, node ->
if (node is Item) 1 else 0
}, { a, b ->
a + b
})
/**
* Computes a score based on the area of rejected items.
*
*/
//fun computeScore(bin: Bin) = bin.rejects.map { it.height * it.width }.sum().toInt()
val vacancyArea: (Point, Point, Node) -> Int = { _,_,node -> when(node) {
is Vacancy -> node.width * node.height
else -> 0
}}
// Wasted space per bin
fun computeScore(bin: Bin) = bin.traverse(vacancyArea) { a, b -> a + b }
| 0 | Kotlin | 1 | 0 | b0fbaa526881c7f651dc6edac21f65de50d45c0b | 3,218 | mcbinpack | MIT License |
src/main/kotlin/algorithms/sorting/heap_sort/Heapsort.kt | AANikolaev | 273,465,105 | false | {"Java": 179737, "Kotlin": 13961} | package algorithms.sorting.heap_sort
import algorithms.sorting.InplaceSort
import java.util.*
class Heapsort : InplaceSort {
override fun sort(values: IntArray) {
heapsort(values)
}
private fun heapsort(ar: IntArray?) {
if (ar == null) return
val n = ar.size
// Heapify, converts array into binary heap O(n), see:
// http://www.cs.umd.edu/~meesh/351/mount/lectures/lect14-heapsort-analysis-part.pdf
for (i in Math.max(0, n / 2 - 1) downTo 0) {
sink(ar, n, i)
}
// Sorting bit
for (i in n - 1 downTo 0) {
swap(ar, 0, i)
sink(ar, i, 0)
}
}
private fun sink(ar: IntArray, n: Int, i: Int) {
var tmp = i
while (true) {
val left = 2 * tmp + 1 // Left node
val right = 2 * tmp + 2 // Right node
var largest = tmp
// Right child is larger than parent
if (right < n && ar[right] > ar[largest]) largest = right
// Left child is larger than parent
if (left < n && ar[left] > ar[largest]) largest = left
// Move down the tree following the largest node
tmp = if (largest != tmp) {
swap(ar, largest, tmp)
largest
} else break
}
}
private fun swap(ar: IntArray, i: Int, j: Int) {
val tmp = ar[i]
ar[i] = ar[j]
ar[j] = tmp
}
} | 0 | Java | 0 | 0 | f9f0a14a5c450bd9efb712b28c95df9a0d7d589b | 1,471 | Algorithms | MIT License |
app/src/main/java/eu/kanade/tachiyomi/util/ChapterExtensions.kt | nekomangaorg | 182,704,531 | false | {"Kotlin": 3454839} | package eu.kanade.tachiyomi.util
import kotlin.math.floor
import org.nekomanga.domain.chapter.ChapterItem
data class MissingChapterHolder(
val count: String? = null,
val estimatedChapters: String? = null,
)
fun List<ChapterItem>.getMissingChapters(): MissingChapterHolder {
var count = 0
val estimateChapters = mutableListOf<String>()
if (this.isNotEmpty()) {
val chapterNumberArray =
this.asSequence()
.distinctBy {
if (it.chapter.chapterText.isNotEmpty()) {
it.chapter.volume + it.chapter.chapterText
} else {
it.chapter.name
}
}
.sortedBy { it.chapter.chapterNumber }
.mapNotNull {
when (it.chapter.chapterText.isEmpty() && !it.chapter.isMergedChapter()) {
true -> null
false -> floor(it.chapter.chapterNumber).toInt()
}
}
.toList()
.toIntArray()
if (chapterNumberArray.isNotEmpty()) {
if (chapterNumberArray.first() > 1) {
while (count != (chapterNumberArray[0] - 1)) {
estimateChapters.add("Chp. $count")
count++
if (count > 5000) {
break
}
}
}
chapterNumberArray.forEachIndexed { index, chpNum ->
val lastIndex = index - 1
if (
lastIndex >= 0 &&
(chpNum - 1) > chapterNumberArray[lastIndex] &&
chapterNumberArray[lastIndex] > 0
) {
count += (chpNum - chapterNumberArray[lastIndex]) - 1
val beginningChp = (chapterNumberArray[lastIndex] + 1)
val endChap = chpNum - 1
when (beginningChp == endChap) {
true -> estimateChapters.add("Ch.$beginningChp")
false -> estimateChapters.add("Ch.$beginningChp ? Ch.$endChap")
}
}
}
}
}
val actualCount =
if (count <= 0) {
null
} else {
count.toString()
}
val estimateChapterString =
when (estimateChapters.isEmpty()) {
true -> null
false -> estimateChapters.joinToString(" ⋅ ")
}
return MissingChapterHolder(
count = actualCount,
estimatedChapters = estimateChapterString,
)
}
| 85 | Kotlin | 111 | 1,985 | 4dc7daf0334499ca72c7f5cbc7833f38a9dfa2c3 | 2,683 | Neko | Apache License 2.0 |
src/main/java/com/luckystar/advent2020/Advent4.kt | alexeymatveevp | 48,393,486 | false | {"Java": 199293, "Kotlin": 8971} | package com.luckystar.advent2020
fun main() {
val file = object {}.javaClass.getResource("/2020/input_4.txt").readText()
val passports = file.split("\r\n\r\n")
val data = passports.map { p ->
val split = p
.split("\r\n")
.reduce { acc, s -> "$acc $s" }
.split(" ")
val parts = split
.map { part ->
val pair = part.split(":")
Pair(pair[0], pair[1])
}
.associateBy({ pair -> pair.first }, { pair -> pair.second })
Passport(parts["byr"]?.toInt(), parts["iyr"]?.toInt(), parts["eyr"]?.toInt(), parts["hgt"], parts["hcl"], parts["ecl"], parts["pid"], parts["cid"])
}
// part 1
println(data.filter { passport ->
passport.byr != null
&& passport.iyr != null
&& passport.eyr != null
&& passport.hgt != null
&& passport.hcl != null
&& passport.ecl != null
&& passport.pid != null
}.count())
// part 2
val hgtRegex = """(\d+)(cm|in)""".toRegex()
val hclRegex = """#[0-9a-f]{6}""".toRegex()
val eclRegex = """^(amb|blu|brn|gry|grn|hzl|oth)$""".toRegex()
val pidRegex = """^(\d){9}$""".toRegex()
fun validate(passport: Passport): Boolean {
if (passport.byr != null
&& passport.iyr != null
&& passport.eyr != null
&& passport.hgt != null
&& passport.hcl != null
&& passport.ecl != null
&& passport.pid != null) {
if (passport.byr !in 1920..2002) {
return false
}
if (passport.iyr !in 2010..2020) {
return false
}
if (passport.eyr !in 2020..2030) {
return false
}
val hgtMatch = hgtRegex.find(passport.hgt) ?: return false
val ( value, type ) = hgtMatch.destructured
val hgtValue = value.toInt()
if (type == "cm" && (hgtValue !in 150..193)
|| type == "in" && (hgtValue !in 59..76)) {
return false
}
if (hclRegex.find(passport.hcl) == null) {
return false
}
if (eclRegex.find(passport.ecl) == null) {
return false
}
if (pidRegex.find(passport.pid) == null) {
return false
}
return true
} else {
return false
}
}
println(data.filter(::validate).count())
}
data class Passport(
val byr: Int?,
val iyr: Int?,
val eyr: Int?,
val hgt: String?,
val hcl: String?,
val ecl: String?,
val pid: String?,
val cid: String?
) | 0 | Java | 0 | 1 | d140ee8328003e79fbd2e0997cc7a8adf0e59ab2 | 2,872 | adventofcode | Apache License 2.0 |
js/js.translator/testData/webDemoExamples/maze.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // MAIN_ARGS: []
/**
* Let's Walk Through a Maze.
*
* Imagine there is a maze whose walls are the big 'O' letters.
* Now, I stand where a big 'I' stands and some cool prize lies
* somewhere marked with a '$' sign. Like this:
*
* OOOOOOOOOOOOOOOOO
* O O
* O$ O O
* OOOOO O
* O O
* O OOOOOOOOOOOOOO
* O O I O
* O O
* OOOOOOOOOOOOOOOOO
*
* I want to get the prize, and this program helps me do so as soon
* as I possibly can by finding a shortest path through the maze.
*/
fun <E> MutableList<E>.offer(element: E) = this.add(element)
fun <E> MutableList<E>.poll() = this.removeAt(0)
/**
* This function looks for a path from max.start to maze.end through
* free space (a path does not go through walls). One can move only
* straightly up, down, left or right, no diagonal moves allowed.
*/
fun findPath(maze: Maze): List<Pair<Int, Int>>? {
val previous = HashMap<Pair<Int, Int>, Pair<Int, Int>>()
val queue = ArrayDeque<Pair<Int, Int>>()
val visited = HashSet<Pair<Int, Int>>()
queue.offer(maze.start)
visited.add(maze.start)
while (!queue.isEmpty()) {
val cell = queue.poll()
if (cell == maze.end) break
for (newCell in maze.neighbors(cell.first, cell.second)) {
if (newCell in visited) continue
previous[newCell] = cell
queue.offer(newCell)
visited.add(cell)
}
}
if (previous[maze.end] == null) return null
val path = ArrayList<Pair<Int, Int>>()
var current = previous[maze.end]
while (current != maze.start) {
path.add(0, current!!)
current = previous[current]
}
return path
}
/**
* Find neighbors of the (i, j) cell that are not walls
*/
fun Maze.neighbors(i: Int, j: Int): List<Pair<Int, Int>> {
val result = ArrayList<Pair<Int, Int>>()
addIfFree(i - 1, j, result)
addIfFree(i, j - 1, result)
addIfFree(i + 1, j, result)
addIfFree(i, j + 1, result)
return result
}
fun Maze.addIfFree(i: Int, j: Int, result: MutableList<Pair<Int, Int>>) {
if (i !in 0..height - 1) return
if (j !in 0..width - 1) return
if (walls[i][j]) return
result.add(Pair(i, j))
}
/**
* A data class that represents a maze
*/
class Maze(
// Number or columns
val width: Int,
// Number of rows
val height: Int,
// true for a wall, false for free space
val walls: Array<out Array<out Boolean>>,
// The starting point (must not be a wall)
val start: Pair<Int, Int>,
// The target point (must not be a wall)
val end: Pair<Int, Int>
) {
}
/** A few maze examples here */
fun main(args: Array<String>) {
printMaze("I $")
printMaze("I O $")
printMaze("""
O $
O
O
O
O I
""".trimIndent())
printMaze("""
OOOOOOOOOOO
O $ O
OOOOOOO OOO
O O
OOOOO OOOOO
O O
O OOOOOOOOO
O OO
OOOOOO IO
""".trimIndent())
printMaze("""
OOOOOOOOOOOOOOOOO
O O
O$ O O
OOOOO O
O O
O OOOOOOOOOOOOOO
O O I O
O O
OOOOOOOOOOOOOOOOO
""".trimIndent())
}
// UTILITIES
fun printMaze(str: String) {
val maze = makeMaze(str)
println("Maze:")
val path = findPath(maze)
for (i in 0..maze.height - 1) {
for (j in 0..maze.width - 1) {
val cell = Pair(i, j)
print(
if (maze.walls[i][j]) "O"
else if (cell == maze.start) "I"
else if (cell == maze.end) "$"
else if (path != null && path.contains(cell)) "~"
else " "
)
}
println("")
}
println("Result: " + if (path == null) "No path" else "Path found")
println("")
}
/**
* A maze is encoded in the string s: the big 'O' letters are walls.
* I stand where a big 'I' stands and the prize is marked with
* a '$' sign.
*
* Example:
*
* OOOOOOOOOOOOOOOOO
* O O
* O$ O O
* OOOOO O
* O O
* O OOOOOOOOOOOOOO
* O O I O
* O O
* OOOOOOOOOOOOOOOOO
*/
fun makeMaze(s: String): Maze {
val lines = s.split("\n")!!
val w = lines.maxWithOrNull(Comparator { o1, o2 ->
val l1: Int = o1?.length ?: 0
val l2 = o2?.length ?: 0
l1 - l2
})!!
val data = Array<Array<Boolean>>(lines.size) { Array<Boolean>(w.length) { false } }
var start: Pair<Int, Int>? = null
var end: Pair<Int, Int>? = null
for (line in lines.indices) {
for (x in lines[line].indices) {
val c = lines[line]!![x]
data[line][x] = c == 'O'
when (c) {
'I' -> start = Pair(line, x)
'$' -> end = Pair(line, x)
else -> {
}
}
}
}
if (start == null) {
throw IllegalArgumentException("No starting point in the maze (should be indicated with 'I')")
}
if (end == null) {
throw IllegalArgumentException("No goal point in the maze (should be indicated with a '$' sign)")
}
return Maze(w.length, lines.size, data, start!!, end!!)
}
// An excerpt from the Standard Library
val String?.indices: IntRange get() = IntRange(0, this!!.length)
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 5,454 | kotlin | Apache License 2.0 |
aoc21/day_20/main.kt | viktormalik | 436,281,279 | false | {"Rust": 227300, "Go": 86273, "OCaml": 82410, "Kotlin": 78968, "Makefile": 13967, "Roff": 9981, "Shell": 2796} | import java.io.File
data class Pixel(val r: Int, val c: Int)
fun area(rows: IntRange, cols: IntRange): List<Pixel> =
rows.flatMap { r -> cols.map { c -> Pixel(r, c) } }
class Picture(var pixels: Set<Pixel>) {
var min = Pixel(-1, -1)
var max = Pixel(
pixels.map { it.r }.maxOrNull()!! + 1,
pixels.map { it.c }.maxOrNull()!! + 1,
)
var outerOnes = false
fun outer(p: Pixel): Boolean = p.r <= min.r || p.r >= max.r || p.c <= min.c || p.c >= max.c
fun pixelId(p: Pixel): Int =
area(p.r - 1..p.r + 1, p.c - 1..p.c + 1)
.map { if (pixels.contains(it) || (outer(it) && outerOnes)) '1' else '0' }
.joinToString("")
.toInt(radix = 2)
fun enhance(algo: CharArray) {
pixels = area(min.r..max.r, min.c..max.c)
.filter { p -> algo[pixelId(p)] == '#' }
.toSet()
min = Pixel(min.r - 1, min.c - 1)
max = Pixel(max.r + 1, max.c + 1)
outerOnes = !outerOnes
}
}
fun main() {
val input = File("input").readLines()
val algo = input[0].toCharArray()
val picture = Picture(
input.drop(2).withIndex().flatMap { (r, row) ->
row.withIndex().filter { (_, x) -> x == '#' }.map { (c, _) -> Pixel(r, c) }
}.toSet()
)
repeat(2) { picture.enhance(algo) }
println("First: ${picture.pixels.size}")
repeat(48) { picture.enhance(algo) }
println("Second: ${picture.pixels.size}")
}
| 0 | Rust | 1 | 0 | f47ef85393d395710ce113708117fd33082bab30 | 1,467 | advent-of-code | MIT License |
src/main/kotlin/com/adventofcode/Day.kt | reactivedevelopment | 574,006,668 | false | {"Kotlin": 2241, "Dockerfile": 379} | package com.adventofcode
import com.adventofcode.Day.process
import com.adventofcode.Day.solution
import java.util.*
object Day {
private var script = false
private val scheme = mutableListOf<String>()
private val stackedColumns = mutableListOf<LinkedList<Char>>()
fun process(line: String) {
if (script) {
return processCode(line)
}
if (line.isBlank()) {
processScheme()
script = true
return
}
scheme.add(line)
}
private fun processScheme() {
val columns = scheme.last().split(" ").last().trim().toInt()
for (x in 0 until columns) {
stackedColumns.add(LinkedList())
}
for (line in scheme.dropLast(1).asReversed()) {
line.windowed(3, 4).forEachIndexed { idx, crateEncoded ->
if (crateEncoded.isNotBlank()) {
check(crateEncoded.length == 3 && crateEncoded.first() == '[' && crateEncoded.last() == ']')
val crate = crateEncoded[1]
stackedColumns[idx].push(crate)
}
}
}
}
private fun processCode(line: String) {
val (crates, from, to) = line.split("move ", " from ", " to ").filterNot(String::isBlank).map(String::toInt)
val fromColumn = stackedColumns[from - 1]
val toColumn = stackedColumns[to - 1]
if(crates == 1) {
fromColumn.pop().let(toColumn::push)
} else {
val buffered = fromColumn.take(crates)
for(x in buffered.asReversed()) {
fromColumn.removeFirst()
toColumn.push(x)
}
}
}
fun solution(): String {
return stackedColumns.map(LinkedList<Char>::getFirst).joinToString("")
}
}
fun main() {
::main.javaClass
.getResourceAsStream("/input")!!
.bufferedReader()
.forEachLine(::process)
println(solution())
}
| 0 | Kotlin | 0 | 0 | f9f78bc2fab16660c5e3602e09bc43b6da029e4f | 1,754 | aoc-2022-5 | MIT License |
day3/src/main/kotlin/aoc2015/day3/Day3.kt | sihamark | 581,653,112 | false | {"Kotlin": 263428, "Shell": 467, "Batchfile": 383} | package aoc2015.day3
/**
* [https://adventofcode.com/2015/day/3]
*/
object Day3 {
fun countHouses(): Int {
val houses = HouseMap()
val santa = Santa()
input.forEach { direction ->
santa.move(direction)
houses.visitHouse(santa.position)
}
return houses.amountOfVisitedHouses
}
fun countHousesWithRoboSanta(): Int {
val houses = HouseMap()
val normalSanta = Santa()
val roboSanta = Santa()
var moveRoboSanta = false
input.forEach { direction ->
val santa = if (moveRoboSanta) roboSanta else normalSanta
moveRoboSanta = !moveRoboSanta
santa.move(direction)
houses.visitHouse(santa.position)
}
return houses.amountOfVisitedHouses
}
private class HouseMap {
private val houses = mutableMapOf<Position, Int>()
val amountOfVisitedHouses
get() = houses.size
init {
houses[Position(0, 0)] = 1
}
fun visitHouse(position: Position) {
val visits = houses[position] ?: 0
houses[position] = visits + 1
}
}
private class Santa {
var position = Position(0, 0)
private set
fun move(direction: Char) {
position = when (direction) {
'^' -> position.goNorth()
'>' -> position.goEast()
'v' -> position.goSouth()
'<' -> position.goWest()
else -> error("direction must be one of ^, >, v, <.")
}
}
}
private data class Position(
val x: Int,
val y: Int
) {
fun goNorth() = Position(x, y + 1)
fun goSouth() = Position(x, y - 1)
fun goWest() = Position(x - 1, y)
fun goEast() = Position(x + 1, y)
}
} | 0 | Kotlin | 0 | 0 | 6d10f4a52b8c7757c40af38d7d814509cf0b9bbb | 1,896 | aoc2015 | Apache License 2.0 |
src/main/kotlin/de/niemeyer/aoc2022/Day25.kt | stefanniemeyer | 572,897,543 | false | {"Kotlin": 175820, "Shell": 133} | /**
* Advent of Code 2022, Day 25: Full of Hot Air
* Problem Description: https://adventofcode.com/2022/day/26
*/
package de.niemeyer.aoc2022
import de.niemeyer.aoc.utils.Resources.resourceAsList
import de.niemeyer.aoc.utils.getClassName
fun main() {
fun Char.toSnafuDigit(): Int =
when {
this == '-' -> -1
this == '=' -> -2
else -> digitToInt()
}
fun String.toSnafu(): Long =
fold(0) { acc, c ->
(acc * 5) + c.toSnafuDigit()
}
fun Long.toSnafu(): String =
generateSequence(this) { (it + 2) / 5 }
.takeWhile { it != 0L }
.map { "012=-"[(it % 5).toInt()] }
.joinToString("")
.reversed()
fun part1(input: List<String>): String =
input.sumOf { it.toSnafu() }.toSnafu()
val name = getClassName()
val testInput = resourceAsList(fileName = "${name}_test.txt")
val puzzleInput = resourceAsList(fileName = "${name}.txt")
check(part1(testInput) == "2=-1=0")
val puzzleResultPart1 = part1(puzzleInput)
println(puzzleResultPart1)
check(puzzleResultPart1 == "2011-=2=-1020-1===-1")
}
| 0 | Kotlin | 0 | 0 | ed762a391d63d345df5d142aa623bff34b794511 | 1,171 | AoC-2022 | Apache License 2.0 |
src/main/java/dev/haenara/mailprogramming/solution/y2019/m12/d08/UseCase191208.kt | HaenaraShin | 226,032,186 | false | null | package dev.haenara.mailprogramming.solution.y2019.m12.d08
import Solution191208
import dev.haenara.mailprogramming.solution.UseCase
class UseCase191208(args: Array<String>) : UseCase<Long, Long>(args) {
override val solution = Solution191208()
override val sampleInput = 12L
override val description = " * 매일프로그래밍 2019. 12. 08\n" +
" * 피보나치 배열은 0과 1로 시작하며, 다음 피보나치 수는 바로 앞의 두 피보나치 수의 합이 된다.\n" +
" * 정수 N이 주어지면, N보다 작은 모든 짝수 피보나치 수의 합을 구하여라.\n" +
" * Fibonacci sequence starts with 0 and 1 where each fibonacci number is a sum of two previous fibonacci numbers.\n" +
" * Given an integer N, find the sum of all even fibonacci numbers.\n" +
" *\n" +
" * Input: N = 12\n" +
" * Output: 10 // 0, 1, 2, 3, 5, 8 중 짝수인 2 + 8 = 10.\n" +
" *\n" +
" * 풀이 :\n" +
" * 재귀로 풀수도 있으나, 성능을 고려하여 반복문을 이용하여 풀었다.\n" +
" * 피보나치 수열의 합이 주어진 수보다 작은지 확인하여 짝수면 누적한다."
override fun parseInput(args: Array<String>) = args[0].toLong()
override fun outputToString(output: Long) = "$output"
override fun inputToString(input: Long) = "$input"
}
| 0 | Kotlin | 0 | 7 | b5e50907b8a7af5db2055a99461bff9cc0268293 | 1,438 | MailProgramming | MIT License |
src/main/kotlin/days/aoc2021/Day19.kt | bjdupuis | 435,570,912 | false | {"Kotlin": 537037} | package days.aoc2021
import days.Day
import org.jetbrains.kotlinx.multik.api.mk
import org.jetbrains.kotlinx.multik.api.ndarray
import org.jetbrains.kotlinx.multik.ndarray.data.*
import org.jetbrains.kotlinx.multik.ndarray.operations.map
import org.jetbrains.kotlinx.multik.ndarray.operations.minus
import org.jetbrains.kotlinx.multik.ndarray.operations.sum
import kotlin.math.absoluteValue
class Day19 : Day(2021, 19) {
override fun partOne(): Any {
return countDistinctBeacons(orientScanners(inputList))
}
override fun partTwo(): Any {
return calculateMaximumDistanceBetweenScanners(orientScanners(inputList))
}
fun calculateMaximumDistanceBetweenScanners(scanners: List<Scanner>): Int {
var max = 0
for (i in 0 until scanners.lastIndex) {
for (j in i+1..scanners.lastIndex) {
max = maxOf(max, (scanners[i].offset!! - scanners[j].offset!!).map { it.absoluteValue }.sum())
}
}
return max
}
fun countDistinctBeacons(scanners: List<Scanner>): Int {
return scanners.flatMap { it.rotatedAndOffset()!! }.distinct().count()
}
fun orientScanners(inputLines: List<String>): List<Scanner> {
var scanners = mutableListOf<Scanner>()
inputLines.filter { !it.startsWith("---") }
.fold(mutableListOf<D1Array<Int>>()) { list, line ->
if (line.isBlank() ) {
scanners.add(Scanner(list))
mutableListOf()
} else {
Regex("(-?)(\\d+),(-?)(\\d+),(-?)(\\d+)").matchEntire(line.trim())?.destructured?.let { (xsign, x, ysign, y, zsign, z) ->
list.add(mk.ndarray(mk[
if (xsign == "-") x.toInt().unaryMinus() else x.toInt(),
if (ysign == "-") y.toInt().unaryMinus() else y.toInt(),
if (zsign == "-") z.toInt().unaryMinus() else z.toInt()
]))
}
list
}
}
scanners[0].naturalRotation = rotationList[0]
scanners[0].offset = mk.ndarray(mk[0,0,0])
do {
// loop through the scanners whose orientation and offset we know
scanners.filter { it.naturalRotation != null }.forEach { scanner1 ->
// ... and loop through those we have yet to figure out
scanners.filter { it.naturalRotation == null }.forEach { scanner2 ->
run rotations@{
// now see if we can find an orientation that matches
rotations().forEach { rotation ->
val rotatedBeacons = scanner2.rotatedBy(rotation)
val scanner1Beacons = scanner1.rotatedAndOffset()!!
scanner1Beacons.forEach { beaconFromScanner1 ->
rotatedBeacons.forEach { rotatedBeacon ->
// assume these are the same beacon. Calculate the delta between
// them and then apply that delta to all of scanner2's beacons.
// Then check for enough matches... if we have matches, we found
// the same beacon in each scanner's relative coordinate system
val delta = rotatedBeacon - beaconFromScanner1
val offsetBeacons = rotatedBeacons.map { rotated ->
rotated - delta
}
if (offsetBeacons.count { scanner1Beacons.contains(it) } >= 12) {
scanner2.naturalRotation = rotation
scanner2.offset = delta
return@rotations
}
}
}
}
}
}
}
// keep going until all of the scanners are oriented
} while (scanners.count { it.naturalRotation == null } != 0)
return scanners
}
class Scanner(val beaconsDetected: List<D1Array<Int>>) {
var naturalRotation: D2Array<Int>? = null
var offset: NDArray<Int,D1>? = null
fun rotatedAndOffset() = if (naturalRotation == null || offset == null) null else rotatedBy(naturalRotation!!).map { it - offset!! }
fun rotatedBy(rotation: D2Array<Int>): List<D1Array<Int>> = beaconsDetected.map { beacon ->
mk.ndarray(mk[
rotation[0][0] * beacon[0] + rotation[0][1] * beacon[1] + rotation[0][2] * beacon[2],
rotation[1][0] * beacon[0] + rotation[1][1] * beacon[1] + rotation[1][2] * beacon[2],
rotation[2][0] * beacon[0] + rotation[2][1] * beacon[1] + rotation[2][2] * beacon[2]
])
}
}
private fun rotations() = sequence {
rotationList.forEach { yield(it) }
}
private val identityX = mk[1,0,0]
private val identityY = mk[0,1,0]
private val identityZ = mk[0,0,1]
private val rotationX = mk[-1,0,0]
private val rotationY = mk[0,-1,0]
private val rotationZ = mk[0,0,-1]
private val rotationList = listOf(
mk.ndarray(mk[identityX, identityY, identityZ]),
mk.ndarray(mk[identityX, rotationZ, identityY]),
mk.ndarray(mk[identityX, rotationY, rotationZ]),
mk.ndarray(mk[identityX, identityZ, rotationY]),
mk.ndarray(mk[rotationX, rotationY, identityZ]),
mk.ndarray(mk[rotationX, rotationZ, rotationY]),
mk.ndarray(mk[rotationX, identityY, rotationZ]),
mk.ndarray(mk[rotationX, identityZ, identityY]),
mk.ndarray(mk[identityZ, rotationX, rotationY]),
mk.ndarray(mk[identityY, rotationX, identityZ]),
mk.ndarray(mk[rotationZ, rotationX, identityY]),
mk.ndarray(mk[rotationY, rotationX, rotationZ]),
mk.ndarray(mk[rotationZ, identityX, rotationY]),
mk.ndarray(mk[identityY, identityX, rotationZ]),
mk.ndarray(mk[identityZ, identityX, identityY]),
mk.ndarray(mk[rotationY, identityX, identityZ]),
mk.ndarray(mk[rotationY, rotationZ, identityX]),
mk.ndarray(mk[identityZ, rotationY, identityX]),
mk.ndarray(mk[identityY, identityZ, identityX]),
mk.ndarray(mk[rotationZ, identityY, identityX]),
mk.ndarray(mk[identityZ, identityY, rotationX]),
mk.ndarray(mk[rotationY, identityZ, rotationX]),
mk.ndarray(mk[rotationZ, rotationY, rotationX]),
mk.ndarray(mk[identityY, rotationZ, rotationX])
)
}
| 0 | Kotlin | 0 | 1 | c692fb71811055c79d53f9b510fe58a6153a1397 | 6,823 | Advent-Of-Code | Creative Commons Zero v1.0 Universal |
src/Day08.kt | ka1eka | 574,248,838 | false | {"Kotlin": 36739} | fun main() {
class Calculator1(private val input: List<String>) {
private val rows = input.size
private val cols = input[0].length
private val lefts: MutableList<Char?> = MutableList(rows) { null }
private val rights: MutableList<Char?> = MutableList(rows) { null }
private val tops: MutableList<Char?> = MutableList(cols) { null }
private val bottoms: MutableList<Char?> = MutableList(cols) { null }
private val visibility: List<MutableList<Boolean>> = List(rows) {
MutableList(cols) { false }
}
fun toVisibleSequence(): Sequence<Int> = sequence {
for (y in 0 until rows) {
for (x in 0 until cols) {
if(isVisible(lefts, tops, x, y)) {
yield(1)
}
if(isVisible(rights, bottoms, cols - x - 1, rows - y - 1)) {
yield(1)
}
}
}
}
private fun isVisible(vLine: MutableList<Char?>, hLine: MutableList<Char?>, x: Int, y: Int): Boolean {
val current = input[y][x]
var visible = false
if (isVisible(vLine, current, y)) {
visible = true
}
if (isVisible(hLine, current, x)) {
visible = true
}
if (!visibility[y][x] && visible) {
visibility[y][x] = true
return true
}
return false
}
private fun isVisible(line: MutableList<Char?>, current: Char, index: Int): Boolean {
if (line[index] == null || current > line[index]!!) {
line[index] = current
return true
}
return false
}
}
class Calculator2(private val input: List<String>) {
private val rows = input.size
private val cols = input[0].length
private val lefts: List<MutableList<Int?>> = List(rows) { MutableList(cols) { null } }
private val rights: List<MutableList<Int?>> = List(rows) { MutableList(cols) { null } }
private val tops: List<MutableList<Int?>> = List(rows) { MutableList(cols) { null } }
private val bottoms: List<MutableList<Int?>> = List(rows) { MutableList(cols) { null } }
fun toScenicScoreSequence(): Sequence<Int> = sequence {
for (y in 0 until rows) {
for (x in 0 until cols) {
countVisibleTrees(lefts, tops, x, y, -1, -1)
countVisibleTrees(rights, bottoms, cols - x - 1, rows - y - 1, 1, 1)
if (lefts[y][x] != null && rights[y][x] != null && tops[y][x] != null && bottoms[y][x] != null) {
yield(lefts[y][x]!! * rights[y][x]!! * tops[y][x]!! * bottoms[y][x]!!)
}
}
}
}
private fun countVisibleTrees(
vLine: List<MutableList<Int?>>,
hLine: List<MutableList<Int?>>,
x: Int,
y: Int,
dx: Int,
dy: Int
) {
val current = input[y][x]
vLine[y][x] = countVisibleTrees(vLine, current, x + dx, y, dx, 0)
hLine[y][x] = countVisibleTrees(hLine, current, x, y + dy, 0, dy)
}
private fun countVisibleTrees(
line: List<MutableList<Int?>>,
target: Char,
x: Int,
y: Int,
dx: Int,
dy: Int
): Int {
val current = input.getOrNull(y)?.getOrNull(x) ?: return 0
if (current >= target) {
return 1
}
val currentCount = line[y][x]!!
if (currentCount == 0) {
return 1
}
return currentCount + countVisibleTrees(line, target, x + dx * currentCount, y + dy * currentCount, dx, dy)
}
}
fun part1(input: List<String>): Int = with(Calculator1(input)) { this.toVisibleSequence().sum() }
fun part2(input: List<String>): Int = with(Calculator2(input)) { this.toScenicScoreSequence().max() }
val testInput = readInput("Day08_test")
check(part1(testInput) == 21)
check(part2(testInput) == 8)
val input = readInput("Day08")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 4f7893448db92a313c48693b64b3b2998c744f3b | 4,370 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/Day25.kt | dlew | 75,886,947 | false | null | import java.util.*
class Day25 {
sealed class Instruction {
class CopyNum(val num: Int, val to: Char) : Instruction()
class CopyRegister(val from: Char, val to: Char) : Instruction()
class CopyInvalid(val num: Int, val invalid: Int) : Instruction()
class CopyInvalid2(val invalid1: Char, val invalid2: Int) : Instruction()
class Increment(val register: Char) : Instruction()
class Decrement(val register: Char) : Instruction()
class Jump1(val num: Int, val distance: Int) : Instruction()
class Jump2(val num: Int, val distanceRegister: Char) : Instruction()
class Jump3(val numRegister: Char, val distance: Int) : Instruction()
class Jump4(val numRegister: Char, val distanceRegister: Char) : Instruction()
class Toggle(val register: Char) : Instruction()
class Transmit(val register: Char) : Instruction()
}
data class State(val instructions: List<Instruction>, val pointer: Int)
companion object {
private fun isRegister(char: Char) = char >= 'a' && char <= 'd'
fun parseInstruction(input: String): Instruction {
val split = input.split(' ')
return when (input.take(3)) {
"cpy" -> {
if (isRegister(split[1][0])) {
Instruction.CopyRegister(split[1][0], split[2][0])
} else {
Instruction.CopyNum(split[1].toInt(), split[2][0])
}
}
"inc" -> Instruction.Increment(split[1][0])
"dec" -> Instruction.Decrement(split[1][0])
"jnz" -> {
val firstRegister = isRegister(split[1][0])
val secondRegister = isRegister(split[2][0])
if (!firstRegister && !secondRegister) {
Instruction.Jump1(split[1].toInt(), split[2].toInt())
} else if (firstRegister) {
Instruction.Jump3(split[1][0], split[2].toInt())
} else if (secondRegister) {
Instruction.Jump2(split[1].toInt(), split[2][0])
} else {
Instruction.Jump4(split[1][0], split[2][0])
}
}
"tgl" -> Instruction.Toggle(split[1][0])
"out" -> Instruction.Transmit(split[1][0])
else -> throw IllegalArgumentException("Cannot parse $input")
}
}
fun lowestForClock(input: String): Int {
val instructions = input.split("\n").map { parseInstruction(it) }
return generateSequence(1) { it + 1 }
.first { solve(instructions, hashMapOf('a' to it, 'b' to 0, 'c' to 0, 'd' to 0)) }
}
fun solve(input: List<Instruction>, start: Map<Char, Int>): Boolean {
val registers = HashMap<Char, Int>(start)
var instructions = input
var pointer = 0
var lastOut = 1
var transmissions = 0
while (pointer < instructions.size) {
val instruction = instructions[pointer]
when (instruction) {
is Instruction.CopyNum -> {
registers[instruction.to] = instruction.num
pointer++
}
is Instruction.CopyRegister -> {
registers[instruction.to] = registers[instruction.from]
?: throw IllegalArgumentException("invalid numRegister: ${instruction.from}")
pointer++
}
is Instruction.Increment -> {
val num = registers[instruction.register]
?: throw IllegalArgumentException("invalid numRegister: ${instruction.register}")
registers[instruction.register] = num + 1
pointer++
}
is Instruction.Decrement -> {
registers[instruction.register] = registers[instruction.register]?.minus(1)
?: throw IllegalArgumentException("invalid numRegister: ${instruction.register}")
pointer++
}
is Instruction.Jump1 -> {
pointer += jump(instruction.num, instruction.distance)
}
is Instruction.Jump2 -> {
val distance = registers[instruction.distanceRegister]
?: throw IllegalArgumentException("invalid numRegister: ${instruction.distanceRegister}")
pointer += jump(instruction.num, distance)
}
is Instruction.Jump3 -> {
val num = registers[instruction.numRegister]
?: throw IllegalArgumentException("invalid numRegister: " + "${instruction.numRegister}")
pointer += jump(num, instruction.distance)
}
is Instruction.Jump4 -> {
val distance = registers[instruction.distanceRegister]
?: throw IllegalArgumentException("invalid numRegister: ${instruction.distanceRegister}")
val num = registers[instruction.numRegister]
?: throw IllegalArgumentException("invalid numRegister: " + "${instruction.numRegister}")
pointer += jump(num, distance)
}
is Instruction.Toggle -> {
val distance = registers[instruction.register]
?: throw IllegalArgumentException("invalid numRegister: " + "${instruction.register}")
instructions = toggle(instructions, pointer + distance)
pointer++
}
is Instruction.Transmit -> {
val num = registers[instruction.register]
?: throw IllegalArgumentException("invalid numRegister: " + "${instruction.register}")
val expectedOut = if (lastOut == 1) 0 else 1
if (num != expectedOut) {
return false
}
transmissions++
lastOut = expectedOut
// Instead of actually doing cycle detection, this is good enough!
if (transmissions == 10000) {
return true
}
pointer++
}
else -> pointer++
}
}
return false
}
fun jump(num: Int, distance: Int) = if (num == 0) 1 else distance
fun toggle(instructions: List<Instruction>, index: Int): List<Instruction> {
if (index >= instructions.size) {
return instructions
}
val mutableInstructions = instructions.toMutableList()
val originalInstruction = mutableInstructions.removeAt(index)
val toggledInstruction = toggle(originalInstruction)
mutableInstructions.add(index, toggledInstruction)
return mutableInstructions
}
fun toggle(instruction: Instruction) =
when (instruction) {
is Instruction.CopyNum -> Instruction.Jump2(instruction.num, instruction.to)
is Instruction.CopyRegister -> Instruction.Jump4(instruction.from, instruction.to)
is Instruction.CopyInvalid -> Instruction.Jump1(instruction.num, instruction.invalid)
is Instruction.CopyInvalid2 -> Instruction.Jump3(instruction.invalid1, instruction.invalid2)
is Instruction.Increment -> Instruction.Decrement(instruction.register)
is Instruction.Decrement -> Instruction.Increment(instruction.register)
is Instruction.Jump1 -> Instruction.CopyInvalid(instruction.num, instruction.distance)
is Instruction.Jump2 -> Instruction.CopyNum(instruction.num, instruction.distanceRegister)
is Instruction.Jump3 -> Instruction.CopyInvalid2(instruction.numRegister, instruction.distance)
is Instruction.Jump4 -> Instruction.CopyRegister(instruction.numRegister, instruction.distanceRegister)
is Instruction.Toggle -> Instruction.Increment(instruction.register)
is Instruction.Transmit -> Instruction.Increment(instruction.register)
}
}
} | 0 | Kotlin | 2 | 12 | 527e6f509e677520d7a8b8ee99f2ae74fc2e3ecd | 7,518 | aoc-2016 | MIT License |
kotlin/aoc2018/src/main/kotlin/Day12.kt | aochsner | 160,386,044 | false | null | import java.io.File
class Day12 {
fun part1(lines: List<String>): Int {
val puzzle = Puzzle(lines)
val pots = puzzle.generate(20)
return pots.asSequence().mapIndexed { index, char ->
if (char == '#')
index-(4*20)
else
0
}.sum()
}
fun part2(lines: List<String>): Int {
val puzzle = Puzzle(lines)
val pots = puzzle.generate(10000)
return pots.asSequence().mapIndexed { index, char ->
if (char == '#')
index-(4*10000)
else
0
}.sum()
}
}
class Puzzle(lines: List<String>) {
val initialState = """^initial state: (.+)$""".toRegex().find(lines[0])!!.destructured.component1()
val rules = (2 until lines.size).associate {
val (pattern, plant) = """^(.+) => (.)$""".toRegex().find(lines[it])!!.destructured
pattern to plant[0]
}
fun generate(iterations: Int): String {
var state = initialState
repeat(iterations) {
state = "....$state...."
val nextGeneration = ".".repeat(state.length).toCharArray()
(2 until state.length-2).forEach {index ->
nextGeneration[index] = rules.getOrDefault(state.slice(index-2..index+2), '.')
}
state = String(nextGeneration)
println(state)
}
return state
}
} | 0 | Kotlin | 0 | 1 | 7c42ec9c20147c4be056d03e5a1492c137e63615 | 1,444 | adventofcode2018 | MIT License |
leetcode2/src/leetcode/SearchInsertPosition.kt | hewking | 68,515,222 | false | null | package leetcode
/**35.搜索插入位置
* https://leetcode-cn.com/problems/search-insert-position/
* Created by test
* Date 2019/5/20 23:41
* Description
* 给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
你可以假设数组中无重复元素。
示例 1:
输入: [1,3,5,6], 5
输出: 2
示例 2:
输入: [1,3,5,6], 2
输出: 1
示例 3:
输入: [1,3,5,6], 7
输出: 4
示例 4:
输入: [1,3,5,6], 0
输出: 0
*/
object SearchInsertPosition{
class Solution {
/**
* 思路:
* 1.已排序数组,说明是利用二分查找的条件
* 2.这不就是二分查找吗,然后多加了个条件返回插入位置
* 也是符合二分查找的啊
*/
fun searchInsert(nums: IntArray, target: Int): Int {
if (nums.isEmpty()) return 0
if (target > nums.last() ) {
return nums.size
} else if (target < nums.first()) {
return 0
}
var low = 0
var high = nums.size - 1
while (low <= high) {
var m = (low + high).div(2)
if (nums[m] > target) {
high = m - 1
} else if (nums[m] < target) {
low = m + 1
} else {
return m
}
}
return low
}
}
} | 0 | Kotlin | 0 | 0 | a00a7aeff74e6beb67483d9a8ece9c1deae0267d | 1,535 | leetcode | MIT License |
src/main/kotlin/org/kalasim/misc/Histogram.kt | holgerbrandl | 299,282,108 | false | {"Kotlin": 3670626, "HTML": 818831, "Java": 56143, "R": 12761} | package org.kalasim.misc
import org.apache.commons.math3.random.EmpiricalDistribution
import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics
import kotlin.math.roundToInt
// Extensions to build histograms
data class HistogramBin(val lowerBound: Double, val upperBound: Double, val value: Long)
class Histogram(val bins: List<HistogramBin>) {
val n = bins.sumOf { it.value }
// val legacyFormat = bins.map { (it.lowerBound to it.upperBound) to it.value }
}
// https://stackoverflow.com/questions/10786465/how-to-generate-bins-for-histogram-using-apache-math-3-0-in-java
internal fun DescriptiveStatistics.buildHistogram(
binCount: Int = 30,
lowerBound: Double? = null,
upperBound: Double? = null,
): Histogram {
require(lowerBound == null && upperBound == null) { ImplementMe() }
val histogram = LongArray(binCount)
val distribution = EmpiricalDistribution(binCount)
distribution.load(values)
var k = 0
for(ss in distribution.binStats) {
histogram[k++] = ss.n
}
val intervals = (listOf(distribution.binStats[0].min) + distribution.upperBounds.toList()).zipWithNext()
return intervals.zip(distribution.binStats.map { it.n }).map {
HistogramBin(it.first.first, it.first.second, it.second)
}.let { Histogram(it) }
}
// Console backend
internal fun Histogram.printHistogram(colWidth: Double = 40.0) {
listOf("bin", "entries", "pct", "").zip(listOf(17, 7, 4, colWidth.toInt()))
.joinToString(" | ") { it.first.padStart(it.second) }
.printThis()
bins.forEach { (lower, upper, value) ->
val scaledValue: Double = value.toDouble() / n
val range = "[${JSON_DF.format(lower)}, ${JSON_DF.format(upper)}]"
val pct = JSON_DF.format(scaledValue)
val stars = "*".repeat((scaledValue * colWidth).roundToInt()).padEnd(colWidth.roundToInt(), ' ')
listOf(range.padEnd(17), value.toString().padStart(7), pct.padStart(4), stars)
.joinToString(" | ")
.printThis()
}
println()
} | 6 | Kotlin | 10 | 65 | 692f30b5154370702e621cfb9e7b5caa2c84b14a | 2,058 | kalasim | MIT License |
src/main/kotlin/com/ginsberg/advent2023/Day18.kt | tginsberg | 723,688,654 | false | {"Kotlin": 112398} | /*
* Copyright (c) 2023 by <NAME>
*/
/**
* Advent of Code 2023, Day 18 - Lavaduct Lagoon
* Problem Description: http://adventofcode.com/2023/day/18
* Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2023/day18/
*/
package com.ginsberg.advent2023
import com.ginsberg.advent2023.Point2D.Companion.EAST
import com.ginsberg.advent2023.Point2D.Companion.NORTH
import com.ginsberg.advent2023.Point2D.Companion.ORIGIN
import com.ginsberg.advent2023.Point2D.Companion.SOUTH
import com.ginsberg.advent2023.Point2D.Companion.WEST
class Day18(private val input: List<String>) {
fun solvePart1(): Long =
calculateLava(input.map { parseRowPart1(it) })
fun solvePart2(): Long =
calculateLava(input.map { parseRowPart2(it) })
private fun calculateLava(instructions: List<Pair<Point2D, Int>>): Long {
val area = instructions
.runningFold(ORIGIN) { acc, (direction, distance) ->
acc + (direction * distance)
}
.zipWithNext()
.sumOf { (a, b) ->
(a.x.toLong() * b.y.toLong()) - (a.y.toLong() * b.x.toLong())
} / 2
val perimeter = instructions.sumOf { it.second }
return area + (perimeter / 2) + 1
}
private fun parseRowPart1(input: String): Pair<Point2D, Int> =
when (input[0]) {
'U' -> NORTH
'D' -> SOUTH
'L' -> WEST
'R' -> EAST
else -> throw IllegalStateException("Bad direction $input")
} to input.substringAfter(" ").substringBefore(" ").toInt()
private fun parseRowPart2(input: String): Pair<Point2D, Int> =
with(input.substringAfter("#").substringBefore(")")) {
when (last()) {
'0' -> EAST
'1' -> SOUTH
'2' -> WEST
'3' -> NORTH
else -> throw IllegalStateException("Bad direction $input")
} to dropLast(1).toInt(16)
}
} | 0 | Kotlin | 0 | 12 | 0d5732508025a7e340366594c879b99fe6e7cbf0 | 1,998 | advent-2023-kotlin | Apache License 2.0 |
2021/src/main/kotlin/de/skyrising/aoc2021/day25/solution.kt | skyrising | 317,830,992 | false | {"Kotlin": 411565} | package de.skyrising.aoc2021.day25
import de.skyrising.aoc.*
import it.unimi.dsi.fastutil.objects.Object2CharMap
import it.unimi.dsi.fastutil.objects.Object2CharOpenHashMap
val test = TestInput("""
v...>>.vv>
.vv>>.vv..
>>.>v>...v
>>v>>.>.v.
v>v.vv.v..
>.>>..v...
.vv..>.>v.
v.v..>>v.v
....v..v.>
""")
@PuzzleName("Sea Cucumber")
fun PuzzleInput.part1(): Any {
val (map, size) = parseInput(this)
var state = map
var steps = 0
while (true) {
steps++
val newState = step(state, size)
if (state == newState) break
state = newState
}
return steps
}
private fun step(map: Object2CharMap<Vec2i>, size: Vec2i): Object2CharMap<Vec2i> {
val newMap = Object2CharOpenHashMap<Vec2i>()
for (e in map.object2CharEntrySet()) {
if (e.charValue != '>') continue
val (x, y) = e.key
val destPos = Vec2i((x + 1) % size.x, y)
if (!map.containsKey(destPos)) {
newMap[destPos] = '>'
} else {
newMap[e.key] = '>'
}
}
for (e in map.object2CharEntrySet()) {
if (e.charValue != 'v') continue
val (x, y) = e.key
val destPos = Vec2i(x, (y + 1) % size.y)
if (!newMap.containsKey(destPos) && map.getChar(destPos) != 'v') {
newMap[destPos] = 'v'
} else {
newMap[e.key] = 'v'
}
}
return newMap
}
private fun show(map: Object2CharMap<Vec2i>, size: Vec2i): String {
val sb = StringBuilder()
for (y in 0 until size.y) {
if (y > 0) sb.append('\n')
for (x in 0 until size.x) {
sb.append(map.getOrDefault(Vec2i(x, y) as Any, '.'))
}
}
return sb.toString()
}
private fun parseInput(input: PuzzleInput): Pair<Object2CharMap<Vec2i>, Vec2i> {
val map = Object2CharOpenHashMap<Vec2i>()
for ((y, line) in input.lines.withIndex()) {
for ((x, c) in line.withIndex()) {
if (c == '.') continue
map[Vec2i(x, y)] = c
}
}
return map to Vec2i(input.lines[0].length, input.lines.size)
} | 0 | Kotlin | 0 | 0 | 19599c1204f6994226d31bce27d8f01440322f39 | 2,106 | aoc | MIT License |
day6/src/test/kotlin/be/swsb/aoc2020/Day6Test.kt | Sch3lp | 318,098,967 | false | null | package be.swsb.aoc2020
import be.swsb.aoc.common.*
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.TestInstance
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class Day6Test {
@Nested
inner class Exercise1 {
@Test
fun `solve exercise 1 - test input`() {
val stuff = Files.readLinesIncludingBlanks("input.txt")
assertThat(solve1(stuff)).isEqualTo(3 + 3 + 3 + 1 + 1).isEqualTo(11)
}
@Test
fun `solve exercise 1`() {
val stuff = Files.readLinesIncludingBlanks("actualInput.txt")
assertThat(solve1(stuff)).isEqualTo(7110)
}
@Test
fun `solve exercise 2 - test input`() {
val stuff = Files.readLinesIncludingBlanks("input.txt")
assertThat(solve2(stuff)).isEqualTo(3 + 0 + 1 + 1 + 1).isEqualTo(6)
}
@Test
fun `solve exercise 2`() {
val stuff = Files.readLinesIncludingBlanks("actualInput.txt")
assertThat(solve2(stuff)).isLessThan(3963).isEqualTo(3628)
}
}
@Nested
inner class OneGroupAnswers {
@Test
internal fun findSameAnswers() {
assertThat(findAmountOfSameAnswers(listOf("abc"))).isEqualTo(3)
assertThat(findAmountOfSameAnswers(listOf("a","b","c"))).isEqualTo(0)
assertThat(findAmountOfSameAnswers(listOf("ab","ac"))).isEqualTo(1)
assertThat(findAmountOfSameAnswers(listOf("a","a","a","a"))).isEqualTo(1)
assertThat(findAmountOfSameAnswers(listOf("b"))).isEqualTo(1)
assertThat(findAmountOfSameAnswers(listOf("ab","ac","bd"))).isEqualTo(0) // last persons answer did not answer yes to a
assertThat(findAmountOfSameAnswers(listOf("ab","bac","adb"))).isEqualTo(2) // both a and b were questions that people in this group answered yes to
}
}
}
fun solve1(answers: List<String>): Int {
return answers
.toStringGroups()
.debugln { "groups: $it" }
.map { group -> group.removeBlanks().debugln { "blanksRemoved $it" }.toSet().size }
.debugln { it }
.sum()
}
fun solve2(answers: List<String>): Int {
val answersPerGroup: List<Pair<Int, List<String>>> = answers
.toStringGroups()
.debugln { "groups: $it" }
.mapIndexed { idx, group ->
val personalAnswers = group.split(" ")
idx to personalAnswers
}
.debugln { "PersonalAnswers per group $it" }
return answersPerGroup
.map { (idx, oneGroupsAnswers) ->
findAmountOfSameAnswers(oneGroupsAnswers)
.debugln { "same answers per person in the group $idx: $it" }
}
.sum()
}
private fun findAmountOfSameAnswers(oneGroupsAnswers: List<String>) : Int {
return if (oneGroupsAnswers.size == 1) {
oneGroupsAnswers.flatMap { it.split("") }.filterNotEmpty().size
} else {
val answersPerPerson = oneGroupsAnswers
.flatMap { it.split("") }
.filterNotEmpty()
return answersPerPerson.groupBy { it }
.debugln { "answersPerPerson grouped: $it" }
.map { (_, values) -> values}
.sumBy { values -> if (values.size == oneGroupsAnswers.size) 1 else 0 }
}
}
| 0 | Kotlin | 0 | 0 | 32630a7efa7893b4540fd91d52c2ff3588174c96 | 3,371 | Advent-of-Code-2020 | MIT License |
src/main/kotlin/no/mortenaa/exercises/part1/01_Functions.kt | elisabethmarie | 188,365,697 | false | null | package no.mortenaa.exercises.part1
/**
*
* Kotlin Workshop Exercises Part 1
*
*/
/**
* 1. Hello World.
*
* Make the function [helloWorld] return the [String] "Hello World!"
*/
fun helloWorld(): String {
return "Hello World!"
}
/**
* 2. Assignment.
*
* Assign a value to [a] such that the function returns 25"
*
*/
fun assignment(): Int {
val a: Int = 5
val b = 5
return a * b
}
/**
* 3. Var and Val
*
* Rewrite the function to use [val] instead of [var]
* (this exercise cannot be verified by the test code, so simply
* remove the call to fail("...") when you're done)
*
*/
fun varAndVal(a: String, b: String): String {
return a.capitalize() + " and " + b.capitalize()
}
/**
* 4. Square
*
* Return the square of the input [n]
*/
fun square(n: Int): Int {
return n*n
}
/**
* 5. Max.
*
* Make this function return the highest number of [n] or [m]
*/
fun max(n: Int, m: Int): Int {
when (n > m) {
true -> return n
false -> return m
}
}
/**
* 6. Max of 3.
*
* Make this function return the highest number of [n], [m] and [i]
*/
fun maxOf3(n: Int, m: Int, i: Int): Int {
return max(max(n, m), i)
}
/**
* 7. Absolute value
*
* Implement a function to return the absolute value of the input
* (without using the built in [Double.absoluteValue])
*/
fun abs(value: Double): Double {
when (value>0) {
true -> return value
false -> return value*(-1)
}
}
// EXTRA if you've got time in the end, come back and solve these
/**
* 8. Leap Year
*
* Decide if the given year is a leap year.
*
* Every year that is exactly divisible by four is a leap year,
* except for years that are exactly divisible by 100,
* but these centurial years *are* leap years if they are exactly divisible by 400.
*
* The function [Int.rem] will be usefull
*
*/
fun isLeapYear(year: Int): Boolean {
return (year%4 == 0 && (year%100!=0 || year%400==0))
}
/**
* 9. Pace caclculator
*
* Given a distance in meters, and the time it took to run it in minutes and seconds,
* calculate the pace (as minutes and seconds per km)
*
* use `Pair(minutes, seconds)` to return two values
*
*
*/
fun pace(distance: Int, minutes: Int, seconds: Int): Pair<Int, Int> {
TODO()
}
| 1 | Kotlin | 0 | 0 | 67b1e6c8fc8e22cf5789165ae0007f4976fcc2eb | 2,388 | kotlin-workshop | MIT License |
src/main/kotlin/tr/emreone/adventofcode/days/Day10.kt | EmRe-One | 433,772,813 | false | {"Kotlin": 118159} | package tr.emreone.adventofcode.days
import tr.emreone.kotlin_utils.automation.Day
import java.util.*
class Day10 : Day(10, 2021, "Syntax Scoring") {
private fun isStringCorrupted(input: String): Boolean {
val stack = Stack<Char>()
for (currentChar in input) {
if (currentChar in arrayOf('(', '[', '{', '<')) {
stack.push(currentChar)
} else {
if (stack.isEmpty()) {
return true
}
when (stack.pop()) {
'(' -> if (currentChar != ')') {
return true
}
'[' -> if (currentChar != ']') {
return true
}
'{' -> if (currentChar != '}') {
return true
}
'<' -> if (currentChar != '>') {
return true
}
}
}
}
return false
}
override fun part1(): Long {
val scores = mapOf(
')' to 3L,
']' to 57L,
'}' to 1197L,
'>' to 25137L
)
return inputAsList
.filter {
isStringCorrupted(it)
}
.sumOf { line ->
var firstCorruptedChar = '!'
val stack = Stack<Char>()
for (c in line) {
if (c in arrayOf('(', '[', '{', '<')) {
stack.push(c)
} else {
if (stack.isEmpty()) {
firstCorruptedChar = c
break
}
when (stack.pop()) {
'(' -> if (c != ')') {
firstCorruptedChar = c
break
}
'[' -> if (c != ']') {
firstCorruptedChar = c
break
}
'{' -> if (c != '}') {
firstCorruptedChar = c
break
}
'<' -> if (c != '>') {
firstCorruptedChar = c
break
}
}
}
}
scores[firstCorruptedChar]!!
}
}
override fun part2(): Long {
val sortedScoreList = inputAsList
.filter {
!isStringCorrupted(it)
}
.map { line ->
val stack = Stack<Char>()
for (c in line) {
if (c in arrayOf('(', '[', '{', '<')) {
stack.push(c)
} else {
stack.pop()
}
}
var score = 0L
for (c in stack.reversed()) {
score = score * 5 + when (c) {
'(' -> 1
'[' -> 2
'{' -> 3
'<' -> 4
else -> 0
}
}
score
}
.sortedBy { it }
return sortedScoreList[sortedScoreList.size / 2]
}
}
| 0 | Kotlin | 0 | 0 | 516718bd31fbf00693752c1eabdfcf3fe2ce903c | 3,562 | advent-of-code-2021 | Apache License 2.0 |
app/src/main/java/com/tripletres/platformscience/domain/algorithm/AntColonyOptimizationAlgorithm.kt | daniel553 | 540,959,283 | false | {"Kotlin": 95616} | package com.tripletres.platformscience.domain.algorithm
import com.tripletres.platformscience.domain.ShipmentDriverAssignation.SuitabilityScore
import com.tripletres.platformscience.domain.model.Driver
/**
* Ant colony optimization algorithm: AI meta heuristic for assignation problem:
*
* Algorithm:
* 1. Repeat until stop criterion satisfied, do:
* 1.1 Generate ant set
* 1.2 Position ants in initial position
* 1.3 For each ant, do:
* 1.3.1 Generate ant path (solution)
* 1.3.2 Evaluate fitness
* 1.4. Apply pheromone
* 1.5. Update best solution
* 2. Return best solution
*
*/
class AntColonyOptimizationAlgorithm : IAssignationAlgorithm {
private val MAX_ITERS = 20
private val MAX_ANTS = 20
private val EXPLORE_RATIO = 2
private val PHEROMONE_INC = 1f
private lateinit var initialInput: List<SuitabilityScore>
private var driverCount: Int = 0
private var shipmentCount: Int = 0
private val pheromonePath = mutableMapOf<SuitabilityScore, Float>()
override fun getBestMatching(input: MutableList<MutableList<SuitabilityScore>>): List<Driver> {
initialInput = prepareInitialInput(input)
return execute()
}
/**
* Prepare initial input, creates a pheromone path with initial values and size of drivers and
* shipment with given input
* @param input a non empty input matrix nxm with [SuitabilityScore] values
*/
private fun prepareInitialInput(input: MutableList<MutableList<SuitabilityScore>>): List<SuitabilityScore> {
val res = mutableListOf<SuitabilityScore>()
for (i in 0 until input.size) {
for (j in 0 until input[i].size) {
res.add(input[i][j])
pheromonePath[input[i][j]] = 0f
}
}
shipmentCount = input.size
driverCount = input[0].size
return res.toList()
}
/**
* Main execution program
*
* @return best driver list solution
*/
private fun execute(): List<Driver> {
var iteration = 0
val bestSolution = mutableListOf<Ant>()
//Repeat until solution or max iteration is acceptable
while (stopCondition(iteration++)) {
val ants = MutableList(MAX_ANTS) { Ant() }
var bestAnt = ants[0]
ants.forEach { ant ->
//Generate a path with assignation
applyAntAssignationPath(ant)
//Update best ant path
if (ant.ss < bestAnt.ss) {
bestAnt = ant
}
}
//Update pheromone path (globally) where ant traveled
updatePheromonePhat(bestAnt)
//Save the best ant for iteration
bestSolution.add(bestAnt)
}
//Sort by ss for best solution
bestSolution.sortBy { it.ss }
return buildDriverList(bestSolution.first())
}
/**
* Defines a stop condition strategy
*/
private fun stopCondition(iteration: Int = 0): Boolean {
return iteration < MAX_ITERS
}
/**
* Given an ant builds a path with a valid assignation
* @param ant
*/
private fun applyAntAssignationPath(ant: Ant) {
var allPaths: List<SuitabilityScore> = initialInput
var firstRun = true
//Assign drivers to ant path
do {
//And move ant to next position
val lastPosition = if (firstRun) {
firstRun = !firstRun
//Initial ant position could be random
initialInput.random().also { //Eg: Driver 3
ant.ss += it.ss
}
} else {
//Use pheromone path to update new ant position
moveAntToNextPosition(ant, allPaths)
}
//Add record of last position to ant path
ant.path.add(lastPosition)
//Remove driver from all paths assignation
allPaths = allPaths.filter {
it.driver.id != lastPosition.driver.id &&
it.shipment.id != lastPosition.shipment.id
}
} while (allPaths.isNotEmpty())
}
/**
* Strategy to move an ant to next promising position, assuming any ant can be an scout
* according to [EXPLORE_RATIO] value
*/
private fun moveAntToNextPosition(
ant: Ant,
allPaths: List<SuitabilityScore>,
): SuitabilityScore {
//Initialize the first promising path to follow
var promising: SuitabilityScore = allPaths[0]
//For each path look for
allPaths.forEach {
if (it.ss < promising.ss) {
//Check phat of pheromone
if (pheromonePath.containsKey(it) && pheromonePath.containsKey(promising) &&
pheromonePath[it]!! > pheromonePath[promising]!!
) {
promising = it
}
}
}
//Ant strategy: Explore or follow pheromone
if ((0 until 100).random() < EXPLORE_RATIO) { // ie: only 1%, 2% etc will explore another path
// Explore another path
promising = allPaths.random()
}
//update ss
ant.ss += promising.ss
return promising
}
/**
* Increases pheromone path by [PHEROMONE_INC] value
*/
private fun updatePheromonePhat(ant: Ant) {
ant.path.forEach {
pheromonePath[it] = pheromonePath[it]?.plus(PHEROMONE_INC) ?: PHEROMONE_INC
}
}
/**
* Get solution
*/
private fun buildDriverList(ant: Ant): List<Driver> {
val list = ant.path.map {
it.driver.copy(shipment = it.shipment, ss = it.ss)
}
return list
}
/**
* Ant with properties
*/
internal data class Ant(
val path: MutableList<SuitabilityScore> = mutableListOf(),
var ss: Float = 0f,
)
} | 0 | Kotlin | 0 | 0 | 2ea5962dc0ad349ae97b277ab4ecf9e9a0aee1e6 | 5,957 | PlatformScience | FSF All Permissive License |
src/main/kotlin/Day01.kt | alex859 | 573,174,372 | false | {"Kotlin": 80552} | fun main() {
val testInput = readInput("Day01_test.txt")
check(testInput.maxTotalCalories() == 24000)
check(testInput.topThreeTotalCalories() == 45000)
val input = readInput("Day01.txt")
println(input.maxTotalCalories())
println(input.topThreeTotalCalories())
}
fun String.maxTotalCalories(): Int = elves().maxOf { it.food().totalCalories() }
fun String.topThreeTotalCalories(): Int = elves().map { it.food().totalCalories() }.sortedDescending().take(3).sum()
private fun String.food() = split("\n")
private fun String.elves() = split("\n\n")
private fun List<String>.totalCalories(): Int = sumOf { it.toInt() }
| 0 | Kotlin | 0 | 0 | fbbd1543b5c5d57885e620ede296b9103477f61d | 642 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/8ExponentialTimeAlgorithms/MapColouring.kt | bejohi | 136,087,641 | false | {"Java": 63408, "Kotlin": 5933, "C++": 5711, "Python": 3670} | import java.util.*
val resultList = mutableListOf<String>()
var done = false
// Solution for https://open.kattis.com/problems/mapcolouring
// With help from https://github.com/amartop
fun main(args: Array<String>){
val input = Scanner(System.`in`)
val numberOfTestCases = input.nextInt()
for(testCase in 1..numberOfTestCases){
val countries = input.nextInt()
val borders = input.nextInt()
val adjMatrix = Array(countries+1,{IntArray(countries+1)})
var coloredArr = IntArray(countries+1, { _ -> 1})
for(border in 0 until borders){
val c1 = input.nextInt()
val c2 = input.nextInt()
adjMatrix[c1][c2] = 1
adjMatrix[c2][c1] = 1
}
if(borders == 0){
resultList.add("1")
continue
}
done = false
for(i in 1..countries+1){
solve(i,adjMatrix,0,coloredArr)
}
}
resultList.forEach {println(it)}
}
fun solve(numberOfColors: Int, adjMatrix: Array<IntArray>, currentVertex: Int, vertColored: IntArray){
if(done){
return
}
val colorOk = checkColor(adjMatrix,currentVertex,vertColored)
if(!colorOk){
return
}
if(numberOfColors+1 > 4){
resultList.add("many")
done = true
return
}
if(currentVertex == adjMatrix.size-1){
resultList.add((numberOfColors+1).toString())
done = true
return
}
for(i in 1..numberOfColors+1) {
vertColored[currentVertex+1] = i
solve(numberOfColors,adjMatrix,currentVertex+1,vertColored)
}
return
}
fun checkColor(adjMatrix: Array<IntArray>, currentVertex: Int, vertColored: IntArray): Boolean {
for(i in 0 until currentVertex){
if(adjMatrix[i][currentVertex] != 0 && vertColored[i] == vertColored[currentVertex]){
return false;
}
}
return true
} | 0 | Java | 0 | 0 | 7e346636786215dee4c681b80bc694c8e016e762 | 1,930 | UiB_INF237 | MIT License |
src/main/kotlin/org/domnikl/algorithms/sorting/RadixSort.kt | domnikl | 231,452,742 | false | null | package org.domnikl.algorithms.sorting
import kotlin.math.ceil
import kotlin.math.log10
import kotlin.math.pow
fun IntArray.radixSort(): IntArray {
if (this.isEmpty()) return this
require(this.min()!! >= 0) { "number smaller zero not allowed" }
val base = ceil(log10(this.max()!!.toDouble())).toInt()
repeat(base + 1) {
countingSort(10.0.pow(it).toInt())
}
return this
}
private fun IntArray.countingSort(exp: Int) {
val counts = IntArray(10)
val output = IntArray(this.size)
this.forEach { counts[(it / exp) % 10]++ }
(1 until counts.size).forEach {
counts[it] += counts[it - 1]
}
this.indices.reversed().forEach {
val index = this[it] / exp
output[counts[index % 10] - 1] = this[it]
counts[index % 10]--
}
output.forEachIndexed { index, i ->
this[index] = i
}
}
| 5 | Kotlin | 3 | 13 | 3b2c191876e58415d8221e511e6151a8747d15dc | 883 | algorithms-and-data-structures | Apache License 2.0 |
2021/src/main/kotlin/Day02.kt | eduellery | 433,983,584 | false | {"Kotlin": 97092} | class Day02(input: List<String>) {
private val commands = input.map { Command.of(it) }
fun solve1(): Int {
var (depth1, horizontal) = arrayOf(0, 0)
commands.forEach {
when (it.name) {
"forward" -> horizontal += it.amount
"down" -> depth1 += it.amount
"up" -> depth1 -= it.amount
}
}
return depth1 * horizontal
}
fun solve2(): Int {
var (depth2, horizontal, aim) = arrayOf(0, 0, 0)
commands.forEach {
when (it.name) {
"forward" -> {
depth2 += aim * it.amount
horizontal += it.amount
}
"down" -> aim += it.amount
"up" -> aim -= it.amount
}
}
return depth2 * horizontal
}
private class Command(val name: String, val amount: Int) {
companion object {
fun of(input: String) = run { Command(input.substringBefore(" "), input.substringAfter(" ").toInt()) }
}
}
}
| 0 | Kotlin | 0 | 1 | 3e279dd04bbcaa9fd4b3c226d39700ef70b031fc | 1,080 | adventofcode-2021-2025 | MIT License |
src/Day08.kt | ambrosil | 572,667,754 | false | {"Kotlin": 70967} | fun main() {
fun part1(input: List<String>): Int {
val matrix = input.map { it.toList() }
return matrix.count { row, col -> matrix.visible(row, col) }
}
fun part2(input: List<String>): Int {
val matrix = input.map { it.toList() }
return matrix.maxOf { row, col -> matrix.score(row, col) }
}
val input = readInput("inputs/Day08")
println(part1(input))
println(part2(input))
}
fun List<List<Char>>.score(row: Int, col: Int) = scoreUp(row, col) * scoreDown(row, col) * scoreLeft(row, col) * scoreRight(row, col)
fun List<List<Char>>.scoreUp(row: Int, col: Int): Int {
var count = 0
for (i in row-1 downTo 0) {
count++
if (this[i][col] >= this[row][col]) {
break
}
}
return count
}
fun List<List<Char>>.scoreDown(row: Int, col: Int): Int {
var count = 0
for (i in row+1 until size) {
count++
if (this[i][col] >= this[row][col]) {
break
}
}
return count
}
fun List<List<Char>>.scoreLeft(row: Int, col: Int): Int {
var count = 0
for (i in col-1 downTo 0) {
count++
if (this[row][i] >= this[row][col]) {
break
}
}
return count
}
fun List<List<Char>>.scoreRight(row: Int, col: Int): Int {
var count = 0
for (i in col+1 until first().size) {
count++
if (this[row][i] >= this[row][col]) {
break
}
}
return count
}
fun List<List<Char>>.visibleUp(row: Int, col: Int): Boolean {
for (i in 0 until row) {
if (this[i][col] >= this[row][col]) {
return false
}
}
return true
}
fun List<List<Char>>.visibleDown(row: Int, col: Int): Boolean {
for (i in row+1 until size) {
if (this[i][col] >= this[row][col]) {
return false
}
}
return true
}
fun List<List<Char>>.visibleLeft(row: Int, col: Int): Boolean {
for (i in 0 until col) {
if (this[row][i] >= this[row][col]) {
return false
}
}
return true
}
fun List<List<Char>>.visibleRight(row: Int, col: Int): Boolean {
for (i in col+1 until first().size) {
if (this[row][i] >= this[row][col]) {
return false
}
}
return true
}
fun List<List<Char>>.visible(row: Int, col: Int): Boolean {
if (row == 0 || col == 0) {
return true
} else if (row == size-1 || col == first().size-1) {
return true
}
return visibleUp(row, col) || visibleDown(row, col) || visibleRight(row, col) || visibleLeft(row, col)
}
| 0 | Kotlin | 0 | 0 | ebaacfc65877bb5387ba6b43e748898c15b1b80a | 2,615 | aoc-2022 | Apache License 2.0 |
src/challenges/Day01.kt | paralleldynamic | 572,256,326 | false | {"Kotlin": 15982} | package challenges
import utils.splitInput
fun main() {
fun countElfInventory(input: List<String>): List<Int> = input
.map{ elf -> elf.trim().split("\n") }
.map{ bundle -> bundle.map{ s -> s.toInt() } }
.map{ bundle -> bundle.sum() }
fun part1(elves: List<Int>): Int = elves.max()
fun part2(elves: List<Int>): Int = elves
.sortedDescending()
.subList(0, 3)
.sum()
// Part 1
val testInput = splitInput("Day01_test")
val testElves = countElfInventory(testInput)
check(part1(testElves) == 24000)
val input = splitInput("Day01")
val elves = countElfInventory(input)
println(part1(elves))
// Part 2
check(part2(testElves) == 45000)
println(part2(elves))
}
| 0 | Kotlin | 0 | 0 | ad32a9609b5ce51ac28225507f77618482710424 | 770 | advent-of-code-kotlin-2022 | Apache License 2.0 |
aoc-day6/src/Day6.kt | rnicoll | 438,043,402 | false | {"Kotlin": 90620, "Rust": 1313} | import java.nio.file.Files
import java.nio.file.Path
object Day6 {
const val PART_1_MAX = 8
const val PART_1_RESET = 6
const val PART_1_DAYS = 80
const val PART_2_DAYS = 256
}
fun main() {
val path = Path.of("input")
val ages = Files.readAllLines(path)
.first()
.split(",")
.map { age -> age.toInt() }
.toList()
part1(ages)
part2(ages)
}
fun part1(input: Iterable<Int>) {
val ages = Array(Day6.PART_1_MAX + 1) { 0 }
input.forEach {
ages[it + 1]++
}
for (day in 0 .. Day6.PART_1_DAYS) {
val zeroFish = ages[0]
for (i in 1 until ages.size) {
ages[i - 1] = ages[i]
}
ages[Day6.PART_1_RESET] += zeroFish
ages[Day6.PART_1_MAX] = zeroFish
}
println(ages.sum())
}
fun part2(input: Iterable<Int>) {
val ages = Array<Long>(Day6.PART_1_MAX + 1) { 0 }
input.forEach {
ages[it + 1]++
}
for (day in 0 .. Day6.PART_2_DAYS) {
val zeroFish = ages[0]
for (i in 1 until ages.size) {
ages[i - 1] = ages[i]
}
ages[Day6.PART_1_RESET] += zeroFish
ages[Day6.PART_1_MAX] = zeroFish
}
println(ages.sum())
} | 0 | Kotlin | 0 | 0 | 8c3aa2a97cb7b71d76542f5aa7f81eedd4015661 | 1,217 | adventofcode2021 | MIT License |
src/Day11.kt | TinusHeystek | 574,474,118 | false | {"Kotlin": 53071} | class Day11 : Day(11) {
class Monkey(input: String) {
var items = mutableListOf<Long>()
var divisibleBy = 0
var divisibleTrueToMonkey = 0
var divisibleFalseToMonkey = 0
var numberOfItemsThrown : Int = 0
init {
val lines = input.lines()
items = lines[1].substringAfter("Starting items: ").split(", ").map { it.toLong() }.toMutableList()
divisibleBy = lines[3].substringAfter("Test: divisible by ").toInt()
divisibleTrueToMonkey = lines[4].substringAfter("If true: throw to monkey ").toInt()
divisibleFalseToMonkey = lines[5].substringAfter("If false: throw to monkey ").toInt()
}
}
// private fun doOperationAction(index: Int, old: Long) : Long {
// var result: Long = 0
// when (index) {
// 0 -> result = old * 7
// 1 -> result = old + 7
// 2 -> result = old * 3
// 3 -> result = old + 3
// 4 -> result = old * old
// 5 -> result = old + 8
// 6 -> result = old + 2
// 7 -> result = old + 4
// }
// return result
// }
// Test
private fun doOperationAction(index: Int, old: Long) : Long {
var result: Long = 0
when (index) {
0 -> result = old * 19
1 -> result = old + 6
2 -> result = old * old
3 -> result = old + 3
}
return result
}
private fun parseInput(input: String) : List<Monkey> {
val newLine = System.lineSeparator()
val monkeyInput = input.split("$newLine$newLine")
val monkeys = mutableListOf<Monkey>()
monkeyInput.forEach{ m -> monkeys.add(Monkey(m)) }
return monkeys
}
private fun playMonkeyInTheMiddle(input: String, rounds: Int, reliefDivisibleBy: Int) : Long {
val monkeys = parseInput(input)
// Part 2
val monkeyDivisor = monkeys.map{ monkey -> monkey.divisibleBy }.reduce { a, b -> a * b }
repeat(rounds) {
monkeys.forEachIndexed { index, monkey ->
while (monkey.items.any()) {
var worryLevel = doOperationAction(index, monkey.items.first())
if (reliefDivisibleBy > 0)
worryLevel = worryLevel.floorDiv(reliefDivisibleBy)
else
worryLevel %= monkeyDivisor
if (worryLevel.mod(monkey.divisibleBy) == 0)
monkeys[monkey.divisibleTrueToMonkey].items.add(worryLevel)
else
monkeys[monkey.divisibleFalseToMonkey].items.add(worryLevel)
monkey.numberOfItemsThrown++
monkey.items.removeAt(0)
}
}
// if ((it + 1).mod(1000) == 0 || it == 19 || it == 0) {
// println("== After round ${(it + 1)} ==")
// monkeys.forEachIndexed { index, monkey ->
// println("Monkey $index inspected items ${monkey.numberOfItemsThrown} times - ${monkey.items.joinToString(" - ")}" )
//
// }
// println("")
// }
}
val max2 = monkeys.sortedByDescending { it.numberOfItemsThrown }.take(2)
println(max2[0].numberOfItemsThrown.toString() + " * " + max2[1].numberOfItemsThrown.toString())
return max2[0].numberOfItemsThrown.toLong() * max2[1].numberOfItemsThrown.toLong()
}
// --- Part 1 ---
override fun part1ToString(input: String): String {
return playMonkeyInTheMiddle(input, 20 , 3).toString()
}
// --- Part 2 ---
override fun part2ToString(input: String): String {
return playMonkeyInTheMiddle(input, 10000, 0).toString()
}
}
fun main() {
Day11().printToStringResults("10605", "2713310158")
}
| 0 | Kotlin | 0 | 0 | 80b9ea6b25869a8267432c3a6f794fcaed2cf28b | 3,889 | aoc-2022-in-kotlin | Apache License 2.0 |
solutions/aockt/y2023/Y2023D14.kt | Jadarma | 624,153,848 | false | {"Kotlin": 435090} | package aockt.y2023
import aockt.util.parse
import aockt.util.spacial.Direction
import aockt.util.spacial.Point
import io.github.jadarma.aockt.core.Solution
// TODO: Could use some more code cleanup.
object Y2023D14 : Solution {
/** The type of rock you can encounter on the dish. */
private enum class Rock { None, Rounded, Cubic }
/**
* Simulates rolling rocks on top of a parabolic reflector dish.
* @param initial The initial state of the dish surface.
*/
private class ParabolicDish(initial: List<List<Rock>>) {
private val state: List<Array<Rock>> = run {
require(initial.isNotEmpty()) { "No state." }
val rows = initial.size
val columns = initial.first().size
val map = List(rows) { Array(columns) { Rock.None } }
require(initial.all { it.size == columns }) { "Initial state not a perfect grid." }
for (y in initial.indices) {
for (x in initial.first().indices) {
map[y][x] = initial[y][x]
}
}
map
}
private val height = state.size
private val width = state.first().size
/** Rolls a rounded rock from the given point in a [direction], returning the point where it rests. */
private fun Point.lastFreeSpaceIn(direction: Direction): Point {
val nx = when (direction) {
Direction.Left -> run {
for (dx in x.toInt() downTo 1) if (state[y.toInt()][dx - 1] != Rock.None) return@run dx
0
}
Direction.Right -> run {
for (dx in x.toInt()..<width.dec()) if (state[y.toInt()][dx + 1] != Rock.None) return@run dx
width.dec()
}
else -> x.toInt()
}
val ny = when (direction) {
Direction.Up -> run {
for (dy in y.toInt()..<height.dec()) if (state[dy + 1][x.toInt()] != Rock.None) return@run dy
height.dec()
}
Direction.Down -> run {
for (dy in y.toInt() downTo 1) if (state[dy - 1][x.toInt()] != Rock.None) return@run dy
0
}
else -> y.toInt()
}
return Point(nx, ny)
}
/** Tilt the dish in a [direction], updating the coordinates of the rounded stones. */
fun tilt(direction: Direction): ParabolicDish = apply {
val xRange = if (direction == Direction.Right) width.dec() downTo 0 else 0..<width
val yRange = if (direction == Direction.Up) height.dec() downTo 0 else 0..<height
for (x in xRange) {
for (y in yRange) {
if (state[y][x] != Rock.Rounded) continue
val rollStart = Point(x, y)
val rollEnd = rollStart.lastFreeSpaceIn(direction)
state[rollStart.y.toInt()][rollStart.x.toInt()] = Rock.None
state[rollEnd.y.toInt()][rollEnd.x.toInt()] = Rock.Rounded
}
}
}
/** Spins the dish once, tilting in all directions in counterclockwise order. */
fun spin(): ParabolicDish = apply {
tilt(Direction.Up)
tilt(Direction.Left)
tilt(Direction.Down)
tilt(Direction.Right)
}
/** Returns the positions of all rounded rocks on the dish. */
fun roundedRocks(): Sequence<Point> = sequence {
for (x in 0..<width) {
for (y in 0..<height) {
if (state[y][x] == Rock.Rounded) yield(Point(x, y))
}
}
}
/** Serializes the current state in a string. It can be either used to display, or as a cache key. */
fun render() = buildString {
for (y in height.dec() downTo 0) {
state[y].joinToString(" ") {
when (it) {
Rock.None -> "."
Rock.Cubic -> "#"
Rock.Rounded -> "O"
}
}.let(::appendLine)
}
}
}
/** Parse the [input] and return the initial state of the [ParabolicDish]. */
private fun parseInput(input: String): ParabolicDish = parse {
fun parseRock(symbol: Char) = when (symbol) {
'.' -> Rock.None
'#' -> Rock.Cubic
'O' -> Rock.Rounded
else -> error("Unknown symbol '$symbol'.")
}
input
.lines()
.asReversed()
.map { line -> line.map(::parseRock) }
.let(::ParabolicDish)
}
override fun partOne(input: String) =
parseInput(input)
.tilt(Direction.Up)
.roundedRocks()
.sumOf { it.y + 1 }
override fun partTwo(input: String) = parseInput(input).run {
val seen = mutableMapOf<String, Long>()
val targetSpins = 1_000_000_000L
var spins = 0L
while (spins < targetSpins) {
val key = render()
if (key in seen) {
val detectedCycleLength = spins - seen.getValue(key)
val remainingCycles = (targetSpins - spins) % detectedCycleLength
for (i in 0..<remainingCycles) spin()
break
}
seen[key] = spins
spins += 1
spin()
}
roundedRocks().sumOf { it.y + 1 }
}
}
| 0 | Kotlin | 0 | 3 | 19773317d665dcb29c84e44fa1b35a6f6122a5fa | 5,598 | advent-of-code-kotlin-solutions | The Unlicense |
src/main/kotlin/days/Day12.kt | TheMrMilchmann | 571,779,671 | false | {"Kotlin": 56525} | /*
* Copyright (c) 2022 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package days
import utils.*
import java.util.*
fun main() {
val grid = readInput().map(String::toList).toGrid()
fun Char.toElevation() = when (this) {
'E' -> 'z'
'S' -> 'a'
else -> this
}
fun Grid<Char>.solve(
startingPos: GridPos,
isDestination: (GridPos) -> Boolean,
canMoveTo: GridPos.(GridPos) -> Boolean
): Int {
fun flatIndexOf(pos: GridPos) =
(pos.y.intValue * width) + pos.x.intValue
val steps = IntArray(grid.positions.size) { Int.MAX_VALUE }
steps[flatIndexOf(startingPos)] = 0
val queue = PriorityQueue<Pair<GridPos, Int>>(compareBy { (_, priority) -> priority })
queue.add(startingPos to 0)
while (queue.isNotEmpty()) {
val (pos, _) = queue.remove()
val index = flatIndexOf(pos)
if (isDestination(pos)) return steps[index]
for (vPos in getAdjacentPositions(pos)) {
val vIndex = flatIndexOf(vPos)
val alt = steps[index] + 1
if (alt < steps[vIndex] && pos.canMoveTo(vPos)) {
steps[vIndex] = alt
queue.add(vPos to alt)
}
}
}
error("Step calculation aborted unexpectedly")
}
fun part1(): Int {
val (startingPos) = grid.positions.zip(grid).single { (_, v) -> v == 'S' }
val (targetPos) = grid.positions.zip(grid).single { (_, v) -> v == 'E' }
return grid.solve(startingPos, { it == targetPos }, { grid[this].toElevation() + 1 >= grid[it].toElevation() })
}
fun part2(): Int {
val (startingPos) = grid.positions.zip(grid).single { (_, v) -> v == 'E' }
return grid.solve(startingPos, { grid[it].toElevation() == 'a' }, { grid[it].toElevation() + 1 >= grid[this].toElevation() })
}
println("Part 1: ${part1()}")
println("Part 2: ${part2()}")
} | 0 | Kotlin | 0 | 1 | 2e01ab62e44d965a626198127699720563ed934b | 3,054 | AdventOfCode2022 | MIT License |
src/Day09_part1.kt | arisaksen | 573,116,584 | false | {"Kotlin": 42887} | import org.assertj.core.api.Assertions.assertThat
fun main() {
val startPos = 400
// val startPos = 1
open class Head(
val signature: Char = 'H',
var positionX: Int = startPos,
var positionY: Int = startPos,
var prevPositionX: Int = startPos,
var prevPositionY: Int = startPos
)
class Tail(signature: Char, positionX: Int, positionY: Int, prevPositionX: Int, prevPositionY: Int) :
Head(signature, positionX, positionY, prevPositionX, prevPositionY)
data class Grid(
private val input: List<String>,
) {
val head = Head()
val tail = Tail('T', head.positionX, head.positionY, head.prevPositionX, head.prevPositionY)
val grid = mutableListOf<MutableList<Char>>()
val tailTrail = mutableSetOf<String>()
init {
repeat(startPos * 2) { grid.add(".".repeat(startPos * 2).toMutableList()) }
}
fun moveHead() {
input.forEach { line ->
println("== $line ==")
val direction = line.split(" ").first()
val times = line.split(" ").last().toInt()
repeat(times) { time ->
head.prevPositionX = head.positionX
head.prevPositionY = head.positionY
when (direction) {
"R" -> head.positionX++
"L" -> head.positionX--
"U" -> head.positionY++
"D" -> head.positionY--
else -> error("Check inputs: $line")
}
moveTail()
updateGrid()
}
}
}
fun tailMoves() = tailTrail.size
private fun moveTail() {
when {
head.positionX > tail.positionX + 1 || head.positionY > tail.positionY + 1 -> {
tail.prevPositionX = tail.positionX
tail.prevPositionY = tail.positionY
tail.positionX = head.prevPositionX
tail.positionY = head.prevPositionY
tailTrail.add("${tail.positionX}-${tail.positionY}")
}
head.positionX < tail.positionX - 1 || head.positionY < tail.positionY - 1 -> {
tail.prevPositionX = tail.positionX
tail.prevPositionY = tail.positionY
tail.positionX = head.prevPositionX
tail.positionY = head.prevPositionY
tailTrail.add("${tail.positionX}-${tail.positionY}")
}
else -> return
}
}
private fun updateGrid() {
if (grid[tail.prevPositionY][tail.prevPositionX] == tail.signature) {
grid[tail.prevPositionY][tail.prevPositionX] = '.'
}
if (grid[head.prevPositionY][head.prevPositionX] != tail.signature) {
grid[head.prevPositionY][head.prevPositionX] = '.'
}
if (grid.size <= head.positionY) grid.add(mutableListOf('.'))
while (grid[head.positionY].size <= head.positionX) grid[head.positionY].add('.')
grid[tail.positionY][tail.positionX] = tail.signature
grid[head.positionY][head.positionX] = head.signature
if (grid[startPos][startPos] == '.') grid[startPos][startPos] = 's'
// drawGrid()
}
private fun drawGrid() {
grid.reversed().forEach {
print(it.joinToString(""))
println()
}
println()
}
}
fun part1(input: List<String>): Int =
Grid(input)
.apply { moveHead() }
.run { tailMoves() }
fun part2(input: List<String>): Int =
input
.map { it }.size
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day09_test")
assertThat(part1(testInput)).isEqualTo(12)
// assertThat(part2(testInput)).isEqualTo(24933642)
// print the puzzle answer
val input = readInput("Day09")
println(part1(input))
// println(part2(input))
} | 0 | Kotlin | 0 | 0 | 85da7e06b3355f2aa92847280c6cb334578c2463 | 4,224 | aoc-2022-kotlin | Apache License 2.0 |
src/main/kotlin/com/headlessideas/adventofcode/december13/PacketScanner.kt | Nandi | 113,094,752 | false | null | package com.headlessideas.adventofcode.december13
import com.headlessideas.adventofcode.utils.readFile
fun crossFirewall(firewalls: Array<Firewall?>, delay: Int = 0): Pair<Int, Boolean> {
var pos = -1 - delay
var severity = 0
var detected = false
while (pos < firewalls.lastIndex) {
pos++
if (pos >= 0) {
firewalls[pos]?.let {
if (it.detected()) {
severity += it.severity()
detected = true
}
}
}
firewalls.forEach { it?.move() }
}
return severity to detected
}
fun main(args: Array<String>) {
val map = readFile("13.dec.txt").map {
val parts = it.split(": ")
parts[0].toInt() to Firewall(parts[0].toInt(), parts[1].toInt())
}.toMap()
val firewalls = Array(map.keys.last() + 1) {
map[it]
}
println(crossFirewall(firewalls.copyOf()).first)
var delay = 0
while (true) {
firewalls.forEach { it?.reset() }
if (!firewalls.any { it?.detected(delay) == true }) break
delay++
}
println(delay)
}
class Firewall(private val id: Int, private val depth: Int) {
var direction: Direction = Direction.DOWN
var pos: Int = TOP
fun move() {
pos += when (direction) {
Direction.UP -> -1
Direction.DOWN -> 1
}
if (pos == depth) {
direction = Direction.UP
} else if (pos == TOP) {
direction = Direction.DOWN
}
}
fun reset() {
pos = TOP
direction = Direction.DOWN
}
fun detected() = pos == 1
fun detected(time: Int) = (time + id) % ((depth - 1) * 2) == 0
fun severity() = id * depth
companion object {
private val TOP = 1
}
}
enum class Direction {
UP, DOWN
} | 0 | Kotlin | 0 | 0 | 2d8f72b785cf53ff374e9322a84c001e525b9ee6 | 1,851 | adventofcode-2017 | MIT License |
src/main/kotlin/Day13.kt | chjaeggi | 728,738,815 | false | {"Kotlin": 87254} | import utils.Stack
import utils.execFileByLineIndexed
import utils.numberOfLinesPerFile
import utils.stackOf
class Day13 {
fun solveFirst(): Int {
// could have used kotlin.collections.ArrayDeque instead of my own Stack implementation :/
// with:
// Stack.push = addLast()
// Stack.pop = removeLast()
val (patternRows, patternCols) = createInput()
var rowSolution = 0
var colSolution = 0
patternRows.forEach { rowPattern ->
var stackRow = Stack<String>()
var searchIndexRow = -1
var possibleFindRow: Int? = null
var isPushingRow = true
for (p in rowPattern) {
searchIndexRow++
if (stackRow.peek() == p) {
stackRow.pop()
if (possibleFindRow == null) {
possibleFindRow = searchIndexRow
}
isPushingRow = false
if (stackRow.isEmpty) {
searchIndexRow = possibleFindRow
break
}
} else {
if (!isPushingRow) {
stackRow = stackOf()
possibleFindRow = null
}
stackRow.push(p)
isPushingRow = true
}
}
if (!isPushingRow) {
rowSolution += (possibleFindRow ?: searchIndexRow) * 100
}
}
patternCols.forEach { patternCol ->
var stackCol = Stack<String>()
var searchIndexCol = -1
var possibleFindCol: Int? = null
var isPushingCol = true
for (p in patternCol) {
searchIndexCol++
if (stackCol.peek() == p) {
stackCol.pop()
if (possibleFindCol == null) {
possibleFindCol = searchIndexCol
}
isPushingCol = false
if (stackCol.isEmpty) {
searchIndexCol = possibleFindCol
break
}
} else {
if (!isPushingCol) {
stackCol = stackOf()
possibleFindCol = null
}
stackCol.push(p)
isPushingCol = true
}
}
if (!isPushingCol) {
colSolution += possibleFindCol ?: searchIndexCol
}
}
return rowSolution + colSolution
}
fun solveSecond(): Int {
val (patternRows, patternCols) = createInput()
var rowSolution = 0
var colSolution = 0
patternRows.forEach { rowPattern ->
rowSolution += findMirror(rowPattern) * 100
}
patternCols.forEach { colPattern ->
colSolution += findMirror(colPattern)
}
return rowSolution + colSolution
}
private fun findMirror(pattern: List<String>): Int {
val maxNumber = pattern.size / 2 + 1
// from top to bottom
for (i in 1..maxNumber) {
val arr1 = pattern.take(i)
val endIndex = if (2 * i >= pattern.size - 1) {
pattern.size - 1
} else {
2 * i
}
val arr2 = pattern.subList(i, endIndex).reversed()
if (diffBy(arr1, arr2) == 1) {
return i
}
}
for (i in 1..maxNumber) {
val arr1 = pattern.reversed().take(i)
val endIndex = if (2 * i >= pattern.size - 1) {
pattern.size - 1
} else {
2 * i
}
val arr2 = pattern.reversed().subList(i, endIndex).reversed()
if (diffBy(arr1, arr2) == 1) {
return (pattern.size - i)
}
}
return 0
}
private fun diffBy(arr1: List<String>, arr2: List<String>): Int {
var res = 0
for (i in 0..arr2.lastIndex) {
res += unCommonChars(arr1[i], arr2[i])
}
return res
}
private fun unCommonChars(s1: String, s2: String): Int {
var count = 0
for (i in s1.indices) {
count += if (s1[i] == s2[i]) 1 else 0
}
return s1.length - count
}
}
private fun createInput(): Pair<List<List<String>>, List<List<String>>> {
val patternRows = mutableListOf<List<String>>()
val patternCols = mutableListOf<List<String>>()
val pattern = mutableListOf<String>()
execFileByLineIndexed(13) { it, index ->
if (it == "") {
patternRows.add(pattern.toList())
pattern.clear()
} else {
pattern.add(it)
}
if (index >= (numberOfLinesPerFile(13) - 1)) {
patternRows.add(pattern.toList())
pattern.clear()
}
}
for (p in patternRows) {
val tempList = mutableListOf<String>()
for (letterIndex in 0..p[0].lastIndex) {
val temp = mutableListOf<Char>()
for (word in p) {
temp.add(word[letterIndex])
}
tempList.add(String(temp.toCharArray()))
}
patternCols.add(tempList)
}
return Pair(patternRows, patternCols)
} | 0 | Kotlin | 1 | 1 | a6522b7b8dc55bfc03d8105086facde1e338086a | 5,441 | aoc2023 | Apache License 2.0 |
2020/Day8/src/main/kotlin/main.kt | airstandley | 225,475,112 | false | {"Python": 104962, "Kotlin": 59337} | import java.io.File
fun getInput(): List<String> {
return File("Input").readLines()
}
data class Command(val name: String, val function: (Int) -> Unit, val value: Int)
fun parseCommand(input:String): Command {
val parts = input.split(" ")
val command = parts[0]
val sign = parts[1].drop(1)
val value = if (sign == "-") { parts[1].toInt() * -1 } else { parts[1].toInt() }
val function: (Int) -> Unit = when (command) {
"acc" -> {
{ v -> accumulate(v) }
}
"jmp" -> {
{ v -> jump(v) }
}
"nop" -> {
{ v -> noop(v) }
}
else -> {
{ v -> invalid(v, command) }
}
}
return Command(command, function, value)
}
fun parseProgram(code: List<String>): List<Command> {
val program: MutableList<Command> = mutableListOf()
for (line in code) {
program.add(parseCommand(line))
}
return program
}
var accumulator: Long = 0
var programCounter: Int = 0
fun accumulate(value: Int) {
// Increment or De-increment the global accumulator
accumulator += value
programCounter++
}
fun jump(offset: Int) {
// Jump by offset
programCounter += offset
}
fun noop(value: Int) {
// Do Nothing
programCounter++
}
fun invalid(value: Int, command:String) {
throw Exception("Invalid Command $command $value")
}
fun run(program: List<Command>): Pair<Long, Boolean> {
accumulator = 0
programCounter = 0
var infinite = false
val infiniteLoopDetection: MutableMap<Int, List<Long>> = mutableMapOf()
while (programCounter < program.size) {
val command = program[programCounter]
if (programCounter in infiniteLoopDetection) {
// Since we don't jump based on accumulator yet, if we hit a command twice then we're infinite
//println("Infinite Loop Detected at $programCounter")
infinite = true
break
} else {
infiniteLoopDetection[programCounter] = listOf(accumulator)
}
//println("$programCounter ${command.name} ${command.value} $accumulator")
command.function(command.value)
}
return Pair(accumulator, infinite)
}
fun fixProgram(program: List<Command>): Pair<List<Command>, Long> {
val fixedProgram: MutableList<Command> = mutableListOf(*program.toTypedArray())
for(i in program.indices) {
val command = program[i]
when (command.name) {
"acc" -> continue
"nop" -> { fixedProgram[i] = Command("jmp", { v -> jump(v) }, command.value)}
"jmp" -> { fixedProgram[i] = Command("nop", { v -> noop(v) }, command.value)}
}
val result = run(fixedProgram)
if (!result.second) {
//println("Fixed an infinite loop by changing $command to ${fixedProgram[i]}")
return Pair(fixedProgram, result.first)
} else {
fixedProgram[i] = command
}
}
throw Exception("Unable to Fix the Program!")
}
fun main(args: Array<String>) {
val program = parseProgram(getInput())
println("First Solution: ${run(program).first}")
println("Second Solution: ${fixProgram(program).second}")
} | 0 | Python | 0 | 0 | 86b7e289d67ba3ea31a78f4a4005253098f47254 | 3,214 | AdventofCode | MIT License |
src/main/kotlin/com/ginsberg/advent2023/Day25.kt | tginsberg | 723,688,654 | false | {"Kotlin": 112398} | /*
* Copyright (c) 2023 by <NAME>
*/
/**
* Advent of Code 2023, Day 25 - Snowverload
* Problem Description: http://adventofcode.com/2023/day/25
* Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2023/day25/
*/
package com.ginsberg.advent2023
class Day25(private val input: List<String>) {
fun solvePart1(): Int {
while (true) {
val graph = parseInput(input)
val counts = graph.keys.associateWith { 1 }.toMutableMap()
while (graph.size > 2) {
val a = graph.keys.random()
val b = graph.getValue(a).random()
val newNode = "$a-$b"
counts[newNode] = (counts.remove(a) ?: 0) + (counts.remove(b) ?: 0)
graph.combineValues(a, b, newNode)
graph.mergeNodes(a, newNode)
graph.mergeNodes(b, newNode)
}
val (nodeA, nodeB) = graph.keys.toList()
if (graph.getValue(nodeA).size == 3) {
return counts.getValue(nodeA) * counts.getValue(nodeB)
}
}
}
private fun MutableMap<String, MutableList<String>>.combineValues(a: String, b: String, newNode: String) {
this[newNode] = (this.getValue(a).filter { it != b } + this.getValue(b).filter { it != a }).toMutableList()
}
private fun MutableMap<String, MutableList<String>>.mergeNodes(oldNode: String, newNode: String) {
remove(oldNode)?.forEach { target ->
getValue(target).replaceAll { if (it == oldNode) newNode else it }
}
}
private fun parseInput(input: List<String>): MutableMap<String, MutableList<String>> {
val map = mutableMapOf<String, MutableList<String>>()
input.forEach { row ->
val sourceName = row.substringBefore(":")
val source = map.getOrPut(sourceName) { mutableListOf() }
row.substringAfter(":").trim().split(" ").forEach { connection ->
source += connection
map.getOrPut(connection) { mutableListOf() }.add(sourceName)
}
}
return map
}
} | 0 | Kotlin | 0 | 12 | 0d5732508025a7e340366594c879b99fe6e7cbf0 | 2,134 | advent-2023-kotlin | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.