path stringlengths 5 169 | owner stringlengths 2 34 | repo_id int64 1.49M 755M | is_fork bool 2
classes | languages_distribution stringlengths 16 1.68k ⌀ | content stringlengths 446 72k | issues float64 0 1.84k | main_language stringclasses 37
values | forks int64 0 5.77k | stars int64 0 46.8k | commit_sha stringlengths 40 40 | size int64 446 72.6k | name stringlengths 2 64 | license stringclasses 15
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/ca/josue/solution/src/TaxiParkTask.kt | josue-lubaki | 428,923,506 | false | {"Kotlin": 171443} | package ca.josue.solution.src
import ca.josue.solution.test.passenger
/*
* Task #1. Find all the drivers who performed no trips.
*/
fun TaxiPark.findFakeDrivers(): Set<Driver> =
allDrivers - trips.map{ it.driver}.toSet()
// this.allDrivers.filter { d -> trips.none{ it.driver == d }}.toSet()
/*
* Task #2. Find all the clients who completed at least the given number of trips.
*/
fun TaxiPark.findFaithfulPassengers(minTrips: Int): Set<Passenger> =
allPassengers.filter { p ->
trips.count { p in it.passengers } >= minTrips
}.toSet()
// trips.flatMap (Trip::passengers)
// .groupBy { passenger -> passenger }
// .filterValues { group -> group.size >= minTrips }
// .keys
/*
* Task #3. Find all the passengers, who were taken by a given driver more than once.
*/
fun TaxiPark.findFrequentPassengers(driver: Driver): Set<Passenger> =
trips
.filter { trip -> trip.driver == driver }
.flatMap(Trip::passengers)
.groupBy { passenger -> passenger }
.filterValues{ group -> group.size > 1}
.keys
// this.allPassengers.filter {
// this.trips.count { trip ->
// it in trip.passengers && trip.driver == driver
// } > 1
// }.toSet()
/*
* Task #4. Find the passengers who had a discount for majority of their trips.
*/
fun TaxiPark.findSmartPassengers(): Set<Passenger>
//{
// val (tripsWithDiscount, tripsWithoutDiscount) = trips.partition { it.discount != null }
// return allPassengers
// .filter { passenger ->
// tripsWithDiscount.count { passenger in it.passengers } >
// tripsWithoutDiscount.count { passenger in it.passengers }
// }
// .toSet()
//}
//= allPassengers.associateWith { p -> trips.filter { t -> p in t.passengers } }
// .filterValues { group ->
// val (withDiscount, withoutDiscount) = group
// .partition { it.discount != null }
// withDiscount.size > withoutDiscount.size
// }
// .keys
= allPassengers.filter { p ->
val withDiscount = trips.count { t -> p in t.passengers && t.discount != null }
val withoutDiscount = trips.count { t-> p in t.passengers && t.discount == null }
withDiscount > withoutDiscount
}.toSet()
/*
* Task #5. Find the most frequent trip duration among minute periods 0..9, 10..19, 20..29, and so on.
* Return any period if many are the most frequent, return `null` if there're no trips.
*/
fun TaxiPark.findTheMostFrequentTripDurationPeriod(): IntRange? {
return trips
.groupBy {
val start = it.duration / 10 * 10
val end = start + 9
start..end
}
.maxByOrNull { (_, group) -> group.size }
?.key
}
/*
* Task #6.
* Check whether 20% of the drivers contribute 80% of the income.
*/
fun TaxiPark.checkParetoPrinciple(): Boolean {
return if (this.trips.isNotEmpty())
this.trips
.map{it.driver to it.cost}
.groupBy{it.first}
.mapValues { it.value.sumOf { pair -> pair.second } }
.values
.sortedDescending()
.take((this.allDrivers.size * 0.2).toInt())
.sum() >= this.trips.map { it.cost }.sum() * 0.8
else false
}
| 0 | Kotlin | 0 | 1 | 847f7af8ba9b5712241c36ca3979e4195766b9ab | 3,248 | TaxiPark | Apache License 2.0 |
src/main/kotlin/me/peckb/aoc/_2020/calendar/day21/Day21.kt | peckb1 | 433,943,215 | false | {"Kotlin": 956135} | package me.peckb.aoc._2020.calendar.day21
import javax.inject.Inject
import me.peckb.aoc.generators.InputGenerator.InputGeneratorFactory
class Day21 @Inject constructor(
private val generatorFactory: InputGeneratorFactory,
) {
fun partOne(filename: String) = generatorFactory.forFile(filename).readAs(::food) { input ->
val (allergenToPossibilities, nonAllergenIngredientCounts) = generatePossibilitiesAndCounts(input)
allergenToPossibilities.forEach { (_, ingredientPossibilityCounts) ->
val sortedByCounts = ingredientPossibilityCounts.entries.sortedByDescending { it.value }
val topCountValue = sortedByCounts.first().value
val mightBe = sortedByCounts.filter { it.value == topCountValue }
mightBe.forEach {
nonAllergenIngredientCounts.remove(it.key)
}
}
nonAllergenIngredientCounts.entries.sumOf { it.value }
}
fun partTwo(filename: String) = generatorFactory.forFile(filename).readAs(::food) { input ->
val (allergenToPossibilities, _) = generatePossibilitiesAndCounts(input)
val probableAllergenIngredients = mutableMapOf<String, MutableMap<String, Int>>()
allergenToPossibilities.forEach { (allergen, ingredientPossibilityCounts) ->
val sortedByCounts = ingredientPossibilityCounts.entries.sortedByDescending { it.value }
val topCountValue = sortedByCounts.first().value
val mightBe= sortedByCounts.filter { it.value == topCountValue }
probableAllergenIngredients[allergen] = mightBe.associateBy({it.key}, {it.value}).toMutableMap()
}
val ingredientWithAllergen = mutableMapOf<String, String>()
while (probableAllergenIngredients.isNotEmpty()) {
val (guaranteedValues, valuesStillUnknown) = probableAllergenIngredients.entries.partition { it.value.count() == 1 }
guaranteedValues.forEach { (allergen, ingredientMap) ->
val ingredient = ingredientMap.entries.first().key
ingredientWithAllergen[allergen] = ingredient
valuesStillUnknown.forEach { (_, ingredientPossibilities) ->
ingredientPossibilities.remove(ingredient)
}
}
guaranteedValues.forEach {
probableAllergenIngredients.remove(it.key)
}
}
ingredientWithAllergen.toSortedMap().values.joinToString(",")
}
private fun food(line: String): Food {
val (ingredientsString, allergensString) = line.split(" (contains ")
val ingredients = ingredientsString.split(" ")
val allergens = allergensString.dropLast(1).split(", ")
return Food(ingredients, allergens)
}
private fun generatePossibilitiesAndCounts(input: Sequence<Food>): FoodContents {
val allergenToPossibilities = mutableMapOf<String, MutableMap<String, Int>>()
val nonAllergenIngredientCounts = mutableMapOf<String, Int>()
input.forEach { (ingredients, allergens) ->
ingredients.forEach { i -> nonAllergenIngredientCounts.merge(i, 1, Int::plus) }
allergens.forEach { allergen ->
allergenToPossibilities.merge(
allergen,
ingredients.associateWith { 1 }.toMutableMap()
) { originalMap, newMap ->
originalMap.apply {
newMap.forEach { (ingredient, count) ->
this.merge(ingredient, count, Int::plus)
}
}
}
}
}
return FoodContents(allergenToPossibilities, nonAllergenIngredientCounts)
}
data class FoodContents(
val allergenToPossibilities: MutableMap<String, MutableMap<String, Int>>,
val nonAllergenIngredientCounts: MutableMap<String, Int>
)
data class Food(
val ingredients: List<String>,
val allergens: List<String>
)
}
| 0 | Kotlin | 1 | 3 | 2625719b657eb22c83af95abfb25eb275dbfee6a | 3,650 | advent-of-code | MIT License |
2020/src/main/java/D02.kt | ununhexium | 113,359,669 | false | null | // counts valid passwords
fun day2a(input: List<String>): Int {
return input.count { l ->
val (policy, password) = l.split(':')
val (low, tail) = policy.split('-')
val (high, char) = tail.split(' ')
val freq = password.groupingBy { it }.eachCount()
val charFreq = (freq[char.first()] ?: 0)
(low.toInt() <= charFreq) && (charFreq <= high.toInt())
}
}
fun day2b(input: List<String>): Int {
return input.count { l ->
val (policy, password) = l.split(':')
val (low, tail) = policy.split('-')
val (high, char) = tail.split(' ')
val indexLow = low.toInt()
val indexHigh = high.toInt()
val pos1 = password.lastIndex >= indexLow && password[indexLow] == char.first()
val pos2 = password.lastIndex >= indexHigh && password[indexHigh] == char.first()
pos1 xor pos2
}
}
| 6 | Kotlin | 0 | 0 | d5c38e55b9574137ed6b351a64f80d764e7e61a9 | 828 | adventofcode | The Unlicense |
ceria/08/src/main/kotlin/Solution.kt | VisionistInc | 433,099,870 | false | {"Kotlin": 91599, "Go": 87605, "Ruby": 65600, "Python": 21104} | import java.io.File;
val knownDigits = mapOf<Int, Int>(2 to 1, 3 to 7, 4 to 4, 7 to 8)
fun main(args : Array<String>) {
var inputMap = mutableMapOf<String, String>()
File(args.first()).readLines().map {
val input = it.split(" | ")
inputMap.put(input[0], input[1])
}
println("Solution 1: ${solution1(inputMap)}")
println("Solution 2: ${solution2(inputMap)}")
}
private fun solution1(inputMap: Map<String,String>) :Int {
val knownDigitLengths = knownDigits.keys
var count = 0
for (output in inputMap.values) {
count += output.split(" ").filter{ it.length in knownDigitLengths }.size
}
return count
}
/**
* I realized half way through that I could've created a structure to represent the 7 segments, and then determined
* what numbers map to each setgment, and then mapped the segments, but I did the dumb brute force solution.
* Perhaps I'll come back and do the better solution as time allows
*/
private fun solution2(inputMap: Map<String,String>) :Int {
var translated = mutableListOf<Int>()
for ((signalVal, outputVal) in inputMap) {
var digitsTranslator = mutableMapOf<String, String>()
val sig = signalVal.split(" ")
val out = outputVal.split(" ")
// Determine the letters of the known unique numbers (2 letters = 1, 3 letters = 7, 4 letters = 4 7 letters = 8)
for ((digitLength, digit) in knownDigits) {
digitsTranslator.put(digit.toString(), sig.filter{ it.length == digitLength }.first())
}
// 5 letters could be either 2, 3, or 5.
var fiveLetters = sig.filter{ it.length == 5 }.toMutableList()
// 6 letters could be either 0, 6, or 9.
var sixLetters = sig.filter{ it.length == 6 }.toMutableList()
// 3 letters will be in common among all of them, so filter those out
var common = mutableListOf<String>()
for (c in fiveLetters.first()) {
if (fiveLetters[0].contains(c) && fiveLetters[1].contains(c) && fiveLetters[2].contains(c)) {
common.add(c.toString())
}
}
var leftOversToOrig = mutableMapOf<String, String>()
for (code in fiveLetters) {
var removed = code
for (letter in common) {
removed.replace(letter, "")
}
leftOversToOrig.put(removed, code)
}
// the cdoe for 3 will be left with the same two letters as is the code for the 1 - order won't be guaranteed though
val codeForOne = digitsTranslator.get("1")!!.toList()
for (leftover in leftOversToOrig.keys) {
if (leftover.toList().containsAll(codeForOne)) {
// this is the case for the 3 code
digitsTranslator.put("3", leftOversToOrig.get(leftover)!!)
fiveLetters.remove(leftOversToOrig.get(leftover)!!)
break
}
}
// the code for 9 will contain all of the code for 3, plus 1 extra
val codeForThree = digitsTranslator.get("3")!!.toList()
for (code in sixLetters) {
if (code.toList().containsAll(codeForThree)) {
digitsTranslator.put("9", code)
sixLetters.remove(code)
break
}
}
// the code for 9 will contain all of the code for 5, but not all of the code for 2,
// which we will know the code for 2 because it'll the the only code left in fiveLetters
val codeForNine = digitsTranslator.get("9")!!.toList()
for (code in fiveLetters) {
if (codeForNine.containsAll(code.toList())) {
digitsTranslator.put("5", code)
} else {
digitsTranslator.put("2", code)
}
}
// the code for 0 will contain both characters from the code for 1. The code for 6 will not.
for (code in sixLetters) {
if (code.toList().containsAll(codeForOne.toList())) {
digitsTranslator.put("0", code)
} else {
digitsTranslator.put("6", code)
}
}
var output = ""
for (o in out) {
for ((digit, code) in digitsTranslator) {
if (code.length == o.length && o.toList().containsAll(code.toList())) {
output = output + digit
break
}
}
}
translated.add(output.toInt())
}
return translated.sum()
}
| 0 | Kotlin | 4 | 1 | e22a1d45c38417868f05e0501bacd1cad717a016 | 4,544 | advent-of-code-2021 | MIT License |
2022/main/day_07/Main.kt | Bluesy1 | 572,214,020 | false | {"Rust": 280861, "Kotlin": 94178, "Shell": 996} | package day_07_2022
import java.io.File
@Suppress("UNCHECKED_CAST")
fun castMapTypes(toCast: Any?): MutableMap<String, Any> = toCast as MutableMap<String, Any>
fun calculateDirSize(dirName: String, dir: Map<String, Any>, dirSizes: MutableMap<String, Int>): Int{
if (dir.values.any { it is MutableMap<*,*> }){
for (subdir in dir.entries.filter { it.value is MutableMap<*, *> }) {
val newDirName = dirName + "/" + subdir.key
dirSizes[newDirName] = calculateDirSize(newDirName, castMapTypes(subdir.value), dirSizes)
}
}
var size = 0
for (file in dir.entries.filter { it.value is Int }) {
size += file.value as Int
}
for (subdir in dir.entries.filter { it.value is MutableMap<*, *> }) {
size += dirSizes[dirName + "/" + subdir.key]!!
}
return size
}
fun parseInputToFileStructure(input: List<String>): Map<String, Any> {
val dir: MutableMap<String, Any> = mutableMapOf()
var currentDir = dir
val dirTree = mutableListOf<MutableMap<String, Any>>()
for (row in input.subList(1, input.size)){
if (row.startsWith("$")){
val command = row.split(" ")[1]
if (command == "cd") {
val subCommand = row.split(" ")[2]
currentDir = if (subCommand == "..") {
dirTree.removeLast()
} else {
dirTree.add(currentDir)
castMapTypes(currentDir[subCommand])
}
}
} else if (row.startsWith("dir")){
currentDir[row.split(' ')[1]] = mutableMapOf<String, Any>()
} else {
val size = row.split(' ')[0].toInt()
var fileName = row.split(' ')[1]
fileName = if (fileName.contains('.')) fileName else "${fileName}.noext"
currentDir[fileName] = size
}
}
return dir
}
fun part1(input: List<String>) {
val dir = parseInputToFileStructure(input)
val dirSizes = mutableMapOf<String, Int>()
dirSizes[""] = calculateDirSize("", dir, dirSizes)
print("The total size of all dirs under 100000 is ${dirSizes.values.filter { it < 100000 }.sum()}")
}
fun part2(input: List<String>) {
val dir = parseInputToFileStructure(input)
val dirSizes = mutableMapOf<String, Int>()
dirSizes[""] = calculateDirSize("", dir, dirSizes)
val spaceNeeded = 30000000 - (70000000 - dirSizes[""]!!)
print("The space of the smallest directory that satisfies the space requirements is ${dirSizes.values.filter { it >= spaceNeeded }.min()}")
}
fun main(){
val inputFile = File("src/inputs/Day_07.txt")
print("\n----- Part 1 -----\n")
part1(inputFile.readLines())
print("\n----- Part 2 -----\n")
part2(inputFile.readLines())
} | 0 | Rust | 0 | 0 | 537497bdb2fc0c75f7281186abe52985b600cbfb | 2,777 | AdventofCode | MIT License |
src/main/kotlin/adventofcode2017/potasz/P08Registers.kt | potasz | 113,064,245 | false | null | package adventofcode2017.potasz
import kotlin.math.max
sealed class Expr<out T>(val reg: String, val number: Int, val op: (Int) -> T) {
fun eval(context: MutableMap<String, Int>): T {
return op(context.getOrDefault(reg, 0))
}
override fun toString(): String {
return "${this.javaClass.simpleName}($reg, $number)"
}
companion object {
fun operation(reg: String, token: String, number: Int): Expr<Int> = when (token) {
"inc" -> Inc(reg, number)
"dec" -> Dec(reg, number)
else -> throw RuntimeException("Unknown operation: $token")
}
fun condition(reg: String, token: String, number: Int): Expr<Boolean> = when (token) {
"==" -> Eq(reg, number)
"!=" -> Neq(reg, number)
"<" -> Lt(reg, number)
"<=" -> Lte(reg, number)
">" -> Gt(reg, number)
">=" -> Gte(reg, number)
else -> throw RuntimeException("Unknown condition: $token")
}
}
}
class Inc(reg: String, number: Int): Expr<Int>(reg, number, { it + number })
class Dec(reg: String, number: Int): Expr<Int>(reg, number, { it - number })
class Eq(reg: String, number: Int): Expr<Boolean>(reg, number, { it == number })
class Neq(reg: String, number: Int): Expr<Boolean>(reg, number, { it != number})
class Lt(reg: String, number: Int): Expr<Boolean>(reg, number, { it < number})
class Lte(reg: String, number: Int): Expr<Boolean>(reg, number, { it <= number })
class Gt(reg: String, number: Int): Expr<Boolean>(reg, number, { it > number})
class Gte(reg: String, number: Int): Expr<Boolean>(reg, number, { it >= number})
object P08Registers {
// c inc -20 if c == 10
val PATTERN = """(\w+)\s(inc|dec)\s([-0-9]+)\sif\s(\w+)\s([!=<>]+)\s([-0-9]+)""".toRegex()
data class Instruction(val op: Expr<Int>, val cond: Expr<Boolean>)
fun parseLine(line: String): Instruction {
val tokens = PATTERN.matchEntire(line)?.groupValues ?: throw RuntimeException("Cannot parse line: $line")
return Instruction(Expr.operation(tokens[1], tokens[2], tokens[3].toInt()),
Expr.condition(tokens[4], tokens[5], tokens[6].toInt()))
}
fun solve(lines: List<String>): Pair<Int, Int> {
val context = mutableMapOf<String, Int>()
var max = Int.MIN_VALUE
lines.map { parseLine(it) }.forEach {
if (it.cond.eval(context)) {
val result = it.op.eval(context)
context[it.op.reg] = result
max = max(max, result)
}
}
return (context.values.max() ?: 0) to max
}
@JvmStatic
fun main(args: Array<String>) {
val sample = readLines("sample08.txt")
val sampleSolution = solve(sample)
println("Sample -> max register value: ${sampleSolution.first}, highest value: ${sampleSolution.second}")
val input = readLines("input08.txt")
val solution = solve(input)
println("Input -> max register value: ${solution.first}, highest value: ${solution.second}")
}
}
| 0 | Kotlin | 0 | 1 | f787d9deb1f313febff158a38466ee7ddcea10ab | 3,092 | adventofcode2017 | Apache License 2.0 |
src/Day02.kt | daividssilverio | 572,944,347 | false | {"Kotlin": 10575} | import java.lang.Exception
fun main() {
/*
scoring
win = 6
lose = 0
draw = 3
initial strategy (wrong)
A, X = Rock (1)
B, Y = Paper (2)
C, Z = Scissors (3)
actual strategy
X = lose
Y = draw
Z = win
*/
val entries = readInput("Day02_test")
val wronglyCalculatedResult = entries.fold(0) { acc, game ->
acc + judgeMatch(game) { _, player2 -> player2.minus(23) }
}
val actualIdealResult = entries.fold(0) { acc, game ->
acc + judgeMatch(game) { player1, player2 ->
when (player2) {
'X' -> loseTo(player1)
'Z' -> winAgainst(player1)
'Y' -> player1
else -> throw Exception("Invalid game $game $player1, $player2")
}
}
}
println(wronglyCalculatedResult)
println(actualIdealResult)
}
private fun Char.scoreValue() = code - 64
private fun winAgainst(game: Char) = when (game) {
'A' -> 'B'
'B' -> 'C'
'C' -> 'A'
else -> throw Exception("Invalid hand $game")
}
private fun loseTo(game: Char) = winAgainst(winAgainst(game))
private val resultMap = mapOf(
0 to 3, // draw
-1 to 0, // lose
-2 to 6, // win
1 to 6, // win
2 to 0 // lose
)
private fun judgeMatch(game: String, strategy: (Char, Char) -> Char): Int {
val player1game = game[0]
val player2Strategy = game[2]
val player2game = strategy(player1game, player2Strategy)
return (resultMap[player2game - player1game] ?: throw Exception("unexpected result $player2game - $player1game")) +
player2game.scoreValue()
} | 0 | Kotlin | 0 | 0 | 141236c67fe03692785e0f3ab90248064a1693da | 1,624 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/com/jacobhyphenated/advent2022/day15/Day15.kt | jacobhyphenated | 573,603,184 | false | {"Kotlin": 144303} | package com.jacobhyphenated.advent2022.day15
import com.jacobhyphenated.advent2022.Day
import kotlin.math.absoluteValue
/**
* Day 15: Beacon Exclusion Zone
*
* There are a number of beacons. You have sensors that can show the beacon locations.
* Each sensor knows its own location as well as the closest beacon to itself.
* Distances are measured using Manhattan (taxicab) distance.
*
* There may exist beacons that are not picked up by the sensors as each sensor only shows the closest beacon.
*/
class Day15: Day<List<Sensor>> {
override fun getInput(): List<Sensor> {
return parseInput(readInputFile("day15"))
}
/**
* In the 2d grid, look at only the y-axis where y == 2,000,000
* How many positions on this axis CANNOT contain a beacon?
*
* Do not count places that have beacons already.
*/
override fun part1(input: List<Sensor>): Int {
return countPositionsWithoutBeacon(input,2000000)
}
/**
* There is a missing distress beacon in between 0 and 4,000,000 (both x and y).
* Find the one location in that search space that is not excluded by the other sensor,
* and therefore must contain the missing beacon.
* Return the x coordinate * 4,000,000 + y coordinate
*/
override fun part2(input: List<Sensor>): Long {
return findBeaconFrequencyInRange(4000000, input)
}
/**
* This is a brute force approach. Use a reasonable x range that might be in
* the coverage exclusion area for each sensor. Evaluate every coordinate along that x range.
* If it's in the coverage exclusion are for any sensor, a beacon cannot exist at that coordinate.
*
* Note: I might be able to get the runtime down by using a skip ahead approach like in part 2.
*/
fun countPositionsWithoutBeacon(sensors: List<Sensor>, y: Int): Int {
val maxDistance = sensors.maxOf { it.beaconDistance }
val allXPositions = sensors.flatMap { listOf(it.x, it.closestBeacon.first) }
val minX = allXPositions.min() - maxDistance
val maxX = allXPositions.max() + maxDistance
return (minX .. maxX).map { Pair(it, y) }.count { coordinate ->
sensors.any { it.isInCoverageArea(coordinate) }
}
}
/**
* It's not possible to brute force a search space of 4,000,000 x 4,000,000
*
* We do need to search every y coordinate.
* But we can skip ahead through chunks of each x coordinate.
*
* Use the manhattan distance from the search location to a nearby sensor.
* Calculate the sensor's exclusion coverage area along the given x-axis and
* skip the areas we know must be excluded by that sensor
*/
fun findBeaconFrequencyInRange(maxRange: Int, sensors: List<Sensor>): Long {
var x = 0
var y = 0
while (true) {
if (y > maxRange) { break }
if (x > maxRange) {
y++
x = 0
continue
}
val current = Pair(x,y)
// find the first sensor that this point is covered by
// if we can't find a sensor that covers this point, this point must be the missing beacon
val inRangeOf = sensors.firstOrNull { it.closestBeacon == current || it.isInCoverageArea(current) }
?: return current.first.toLong() * 4000000L + current.second
// manhattan distance can be used to determine where we are within the exclusion coverage area
val diff = inRangeOf.beaconDistance - calcManhattanDistance(Pair(inRangeOf.x, inRangeOf.y), current)
val xDiff = if (current.first < inRangeOf.x) { (inRangeOf.x - current.first) * 2 + diff } else { diff }
// if we're on the edge of the coverage area, xDiff will be 0, so always advance x by at least 1
x += xDiff.coerceAtLeast(1)
}
return -1
}
fun parseInput(input: String): List<Sensor> {
return input.lines().map { line ->
val (sensorPart, beaconPart) = line.split(": closest beacon is at ")
val (x,y) = sensorPart.split(",")
.map { it.split("=")[1].trim().toInt() }
val (beaconX, beaconY) = beaconPart.split(",")
.map { it.split("=")[1].trim().toInt() }
Sensor(x,y,Pair(beaconX, beaconY))
}
}
}
class Sensor(
val x: Int,
val y: Int,
val closestBeacon: Pair<Int,Int>
) {
val beaconDistance = calcManhattanDistance(Pair(x,y), closestBeacon)
fun isInCoverageArea(point: Pair<Int,Int>): Boolean {
if (point == closestBeacon) { return false }
return calcManhattanDistance(Pair(x,y), point) <= beaconDistance
}
}
private fun calcManhattanDistance(p1: Pair<Int,Int>, p2: Pair<Int,Int>): Int {
val (x1,y1) = p1
val (x2, y2) = p2
return (x1 - x2).absoluteValue + (y1 - y2).absoluteValue
} | 0 | Kotlin | 0 | 0 | 9f4527ee2655fedf159d91c3d7ff1fac7e9830f7 | 4,923 | advent2022 | The Unlicense |
src/main/kotlin/days/day7/Day7.kt | Stenz123 | 725,707,248 | false | {"Kotlin": 123279, "Shell": 862} | package days.day7
import days.Day
class Day7 : Day(false) {
override fun partOne(): Any {
val hands: MutableMap<Hand, Int> = readInput().map { line ->
val cards = line.split(" ")[0].map { Card(it) }
val hand = Hand(cards)
hand to line.split(" ")[1].toInt()
}.toMap().toMutableMap()
val linkedHands = hands.keys.sorted()
for (i in linkedHands.indices) {
hands[linkedHands[i]] = hands[linkedHands[i]]!! * (i + 1)
}
return hands.keys.sumBy { hands[it]!! }
}
override fun partTwo(): Any {
return "Part one is part two"
}
companion object {
var jokerCache: MutableMap<Hand, Hand> = mutableMapOf()
}
}
class Hand(val cards: List<Card>) : Comparable<Hand> {
override fun compareTo(other: Hand): Int {
val thisJokerTransformedCard = transformCardToHighestPossibleWithJoker(this)
val otherJokerTransformedCard = transformCardToHighestPossibleWithJoker(other)
if (cards.size != other.cards.size) {
throw Exception("Hands are not the same size")
}
// Five of a kind
if (thisJokerTransformedCard.cards.distinct().size == 1 && otherJokerTransformedCard.cards.distinct().size == 1) {
return compareEqualValuedHands(this, other)
} else if (thisJokerTransformedCard.cards.distinct().size == 1) {
return 1
} else if (otherJokerTransformedCard.cards.distinct().size == 1) {
return -1
}
// Four of a kind
if (thisJokerTransformedCard.cards.groupBy { it.value }.filter { it.value.size == 4 }
.isNotEmpty() && otherJokerTransformedCard.cards.groupBy { it.value }.filter { it.value.size == 4 }
.isNotEmpty()) {
return compareEqualValuedHands(this, other)
} else if (thisJokerTransformedCard.cards.groupBy { it.value }.filter { it.value.size == 4 }.isNotEmpty()) {
return 1
} else if (otherJokerTransformedCard.cards.groupBy { it.value }.filter { it.value.size == 4 }.isNotEmpty()) {
return -1
}
// Full house
if (thisJokerTransformedCard.cards.groupBy { it.value }.filter { it.value.size == 3 }
.isNotEmpty() && thisJokerTransformedCard.cards.groupBy { it.value }.filter { it.value.size == 2 }
.isNotEmpty() && otherJokerTransformedCard.cards.groupBy { it.value }.filter { it.value.size == 3 }
.isNotEmpty() && otherJokerTransformedCard.cards.groupBy { it.value }.filter { it.value.size == 2 }
.isNotEmpty()) {
return compareEqualValuedHands(this, other)
} else if (thisJokerTransformedCard.cards.groupBy { it.value }.filter { it.value.size == 3 }.isNotEmpty() && thisJokerTransformedCard.cards.groupBy { it.value }
.filter { it.value.size == 2 }.isNotEmpty()) {
return 1
} else if (otherJokerTransformedCard.cards.groupBy { it.value }.filter { it.value.size == 3 }
.isNotEmpty() && otherJokerTransformedCard.cards.groupBy { it.value }.filter { it.value.size == 2 }
.isNotEmpty()) {
return -1
}
// Three of a kind
if (thisJokerTransformedCard.cards.groupBy { it.value }.filter { it.value.size == 3 }
.isNotEmpty() && otherJokerTransformedCard.cards.groupBy { it.value }.filter { it.value.size == 3 }
.isNotEmpty()) {
return compareEqualValuedHands(this, other)
} else if (thisJokerTransformedCard.cards.groupBy { it.value }.filter { it.value.size == 3 }.isNotEmpty()) {
return 1
} else if (otherJokerTransformedCard.cards.groupBy { it.value }.filter { it.value.size == 3 }.isNotEmpty()) {
return -1
}
// Two pair
if (thisJokerTransformedCard.cards.groupBy { it.value }
.filter { it.value.size == 2 }.size == 2 && otherJokerTransformedCard.cards.groupBy { it.value }
.filter { it.value.size == 2 }.size == 2) {
return compareEqualValuedHands(this, other)
} else if (thisJokerTransformedCard.cards.groupBy { it.value }.filter { it.value.size == 2 }.size == 2) {
return 1
} else if (otherJokerTransformedCard.cards.groupBy { it.value }.filter { it.value.size == 2 }.size == 2) {
return -1
}
// Pair
if (thisJokerTransformedCard.cards.groupBy { it.value }.filter { it.value.size == 2 }
.isNotEmpty() && otherJokerTransformedCard.cards.groupBy { it.value }.filter { it.value.size == 2 }
.isNotEmpty()) {
return compareEqualValuedHands(this, other)
} else if (thisJokerTransformedCard.cards.groupBy { it.value }.filter { it.value.size == 2 }.isNotEmpty()) {
return 1
} else if (otherJokerTransformedCard.cards.groupBy { it.value }.filter { it.value.size == 2 }.isNotEmpty()) {
return -1
}
// High card
return compareEqualValuedHands(this, other)
}
fun compareWithoutJoker(first: Hand, other: Hand): Int {
val thisJokerTransformedCard = (first)
val otherJokerTransformedCard = (other)
if (cards.size != other.cards.size) {
throw Exception("Hands are not the same size")
}
// Five of a kind
if (thisJokerTransformedCard.cards.distinct().size == 1 && otherJokerTransformedCard.cards.distinct().size == 1) {
return compareEqualValuedHands(this, other)
} else if (cards.distinct().size == 1) {
return 1
} else if (otherJokerTransformedCard.cards.distinct().size == 1) {
return -1
}
// Four of a kind
if (thisJokerTransformedCard.cards.groupBy { it.value }.filter { it.value.size == 4 }
.isNotEmpty() && otherJokerTransformedCard.cards.groupBy { it.value }.filter { it.value.size == 4 }
.isNotEmpty()) {
return compareEqualValuedHands(this, other)
} else if (thisJokerTransformedCard.cards.groupBy { it.value }.filter { it.value.size == 4 }.isNotEmpty()) {
return 1
} else if (otherJokerTransformedCard.cards.groupBy { it.value }.filter { it.value.size == 4 }.isNotEmpty()) {
return -1
}
// Full house
if (thisJokerTransformedCard.cards.groupBy { it.value }.filter { it.value.size == 3 }
.isNotEmpty() && thisJokerTransformedCard.cards.groupBy { it.value }.filter { it.value.size == 2 }
.isNotEmpty() && otherJokerTransformedCard.cards.groupBy { it.value }.filter { it.value.size == 3 }
.isNotEmpty() && otherJokerTransformedCard.cards.groupBy { it.value }.filter { it.value.size == 2 }
.isNotEmpty()) {
return compareEqualValuedHands(this, other)
} else if (thisJokerTransformedCard.cards.groupBy { it.value }.filter { it.value.size == 3 }.isNotEmpty() && thisJokerTransformedCard.cards.groupBy { it.value }
.filter { it.value.size == 2 }.isNotEmpty()) {
return 1
} else if (otherJokerTransformedCard.cards.groupBy { it.value }.filter { it.value.size == 3 }
.isNotEmpty() && otherJokerTransformedCard.cards.groupBy { it.value }.filter { it.value.size == 2 }
.isNotEmpty()) {
return -1
}
// Three of a kind
if (thisJokerTransformedCard.cards.groupBy { it.value }.filter { it.value.size == 3 }
.isNotEmpty() && otherJokerTransformedCard.cards.groupBy { it.value }.filter { it.value.size == 3 }
.isNotEmpty()) {
return compareEqualValuedHands(this, other)
} else if (thisJokerTransformedCard.cards.groupBy { it.value }.filter { it.value.size == 3 }.isNotEmpty()) {
return 1
} else if (otherJokerTransformedCard.cards.groupBy { it.value }.filter { it.value.size == 3 }.isNotEmpty()) {
return -1
}
// Two pair
if (thisJokerTransformedCard.cards.groupBy { it.value }
.filter { it.value.size == 2 }.size == 2 && otherJokerTransformedCard.cards.groupBy { it.value }
.filter { it.value.size == 2 }.size == 2) {
return compareEqualValuedHands(this, other)
} else if (thisJokerTransformedCard.cards.groupBy { it.value }.filter { it.value.size == 2 }.size == 2) {
return 1
} else if (otherJokerTransformedCard.cards.groupBy { it.value }.filter { it.value.size == 2 }.size == 2) {
return -1
}
// Pair
if (thisJokerTransformedCard.cards.groupBy { it.value }.filter { it.value.size == 2 }
.isNotEmpty() && otherJokerTransformedCard.cards.groupBy { it.value }.filter { it.value.size == 2 }
.isNotEmpty()) {
return compareEqualValuedHands(this, other)
} else if (thisJokerTransformedCard.cards.groupBy { it.value }.filter { it.value.size == 2 }.isNotEmpty()) {
return 1
} else if (otherJokerTransformedCard.cards.groupBy { it.value }.filter { it.value.size == 2 }.isNotEmpty()) {
return -1
}
// High card
return compareEqualValuedHands(this, other)
}
override fun toString(): String {
return "Hand($cards)"
}
private fun transformCardToHighestPossibleWithJoker(hand: Hand): Hand {
if (hand.cards == listOf(Card('J'), Card('J'), Card('J'), Card('J'), Card('J'))) {
return Hand(listOf(Card('A'), Card('A'), Card('A'), Card('A'), Card('A')))
}
if (hand in Day7.jokerCache) {
return Day7.jokerCache[hand]!!
}
if (hand.cards.none { it.value == 'J' }) {
return hand
}
val jIndexes = mutableListOf<Int>()
for (i in hand.cards.indices) {
if (hand.cards[i].value == 'J') {
jIndexes.add(i)
}
}
val allCombinations = linkedSetOf<Hand>()
val combinationArray = generateCombinations(jIndexes.size)
for (combination in combinationArray) {
val newHand = hand.cards.toMutableList()
for (index in jIndexes) {
newHand[index]=Card(combination[jIndexes.indexOf(index)])
}
allCombinations.add(Hand(newHand))
}
val result = allCombinations.sortedWith(withoutJokerComperator()).last()
Day7.jokerCache[hand] = result
return result
}
}
fun generateCombinations(length: Int): List<List<Char>> {
val values = listOf('2', '3', '4', '5', '6', '7', '8', '9', 'T', 'Q', 'K', 'A')
// Base case: If the length is 0, return a list containing an empty list
if (length == 0) {
return listOf(emptyList())
}
// Recursive case: Generate combinations for the previous length
val prevCombinations = generateCombinations(length - 1)
// Build new combinations by appending each value to the existing combinations
return values.flatMap { value ->
prevCombinations.map { combination -> listOf(value) + combination }
}
}
private fun compareEqualValuedHands(hand: Hand, other: Hand): Int {
for (i in 0 until hand.cards.size) {
if (hand.cards[i].compareTo(other.cards[i]) != 0) {
val result = hand.cards[i].compareTo(other.cards[i])
return result
}
}
return 0
}
class withoutJokerComperator : Comparator<Hand> {
override fun compare(o1: Hand, o2: Hand): Int {
return o1.compareWithoutJoker(o1, o2)
}
}
class Card(val value: Char) : Comparable<Card> {
override fun compareTo(other: Card): Int {
val values = listOf( 'J','2', '3', '4', '5', '6', '7', '8', '9', 'T', 'Q', 'K', 'A')
return (values.indexOf(value) - values.indexOf(other.value))
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Card
return value == other.value
}
override fun hashCode(): Int {
return value.hashCode()
}
override fun toString(): String {
return "Card($value)"
}
}
| 0 | Kotlin | 1 | 0 | 3de47ec31c5241947d38400d0a4d40c681c197be | 12,356 | advent-of-code_2023 | The Unlicense |
src/twentytwo/Day01.kt | mihainov | 573,105,304 | false | {"Kotlin": 42574} | package twentytwo
import readInputTwentyTwo
import kotlin.math.max
fun main() {
fun part1(input: List<String>): Int {
var maxSum: Int = -1
var tempSum = 0
input.forEach { inputString ->
if (inputString.isBlank()) {
maxSum = max(tempSum, maxSum)
tempSum = 0
return@forEach
}
tempSum += inputString.toInt()
}
return maxSum
}
fun part2(input: List<String>): Int {
val elvesSum = mutableListOf<Int>()
var tempSum = 0
input.forEach { inputString ->
if (inputString.isBlank()) {
elvesSum.add(tempSum)
tempSum = 0
return@forEach
}
tempSum += inputString.toInt()
}
// handle last elf's calories
elvesSum.add(tempSum)
elvesSum.sortDescending()
return elvesSum.subList(0, 3).sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInputTwentyTwo("Day01_test")
check(part1(testInput) == 24_000)
check(part2(testInput) == 45_000)
val input = readInputTwentyTwo("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | a9aae753cf97a8909656b6137918ed176a84765e | 1,269 | kotlin-aoc-1 | Apache License 2.0 |
day04/src/main/kotlin/Main.kt | rstockbridge | 225,212,001 | false | null | fun main() {
println("Part I: the solution is ${solvePartI()}.")
println("Part II: the solution is ${solvePartII()}.")
}
fun solvePartI(): Int {
var result = 0
for (password in Range.lowerBound..Range.upperBound) {
if (isValidPartI(password)) {
result++
}
}
return result
}
fun solvePartII(): Int {
var result = 0
for (password in Range.lowerBound..Range.upperBound) {
if (isValidPartII(password)) {
result++
}
}
return result
}
fun isValidPartI(password: Int): Boolean {
return hasDouble(password.toString()) && neverDecreases(password.toString())
}
fun isValidPartII(password: Int): Boolean {
return hasDoubleOnly(password.toString()) && neverDecreases(password.toString())
}
private fun hasDouble(password: String): Boolean {
for (i in 0 until password.length - 1) {
if (password[i].toInt() == password[i + 1].toInt()) {
return true
}
}
return false;
}
private fun hasDoubleOnly(password: String): Boolean {
// double is at beginning of password
if (password[0].toInt() == password[1].toInt() && password[1].toInt() != password[2].toInt()) {
return true
}
// double is at end of password
if (password[password.length - 3].toInt() != password[password.length - 2].toInt() && password[password.length - 2].toInt() == password[password.length - 1].toInt()) {
return true
}
// double is in middle of password
for (i in 0 until password.length - 3) {
if (password[i].toInt() != password[i + 1].toInt() && password[i + 1].toInt() == password[i + 2].toInt() && password[i + 2].toInt() != password[i + 3].toInt()
) {
return true
}
}
return false
}
private fun neverDecreases(password: String): Boolean {
for (i in 1 until password.length) {
if (password[i - 1].toInt() > password[i].toInt()) {
return false
}
}
return true;
}
object Range {
const val lowerBound = 130254
const val upperBound = 678275
}
| 0 | Kotlin | 0 | 0 | bcd6daf81787ed9a1d90afaa9646b1c513505d75 | 2,100 | AdventOfCode2019 | MIT License |
src/main/kotlin/aoc2015/day05_intern_elves/InternElves.kt | barneyb | 425,532,798 | false | {"Kotlin": 238776, "Shell": 3825, "Java": 567} | package aoc2015.day05_intern_elves
fun main() {
util.solve(236, ::partOne)
util.solve(51, ::partTwo)
}
private fun String.isNice(): Boolean {
var vowelCount = 0
var prev = '\u0000'
var double = false
forEach { c ->
when (c) {
'a', 'e', 'i', 'o', 'u' -> ++vowelCount
'b' -> if (prev == 'a') return false
'd' -> if (prev == 'c') return false
'q' -> if (prev == 'p') return false
'y' -> if (prev == 'x') return false
}
if (c == prev) {
double = true
}
prev = c
}
return vowelCount >= 3 && double
}
fun partOne(input: String) = input
.lines()
.count { it.isNice() }
private var RE_REPEATED_PAIR = Regex(".*(..).*\\1.*")
private var RE_SEPARATED_REPEAT = Regex(".*(.).\\1.*")
fun partTwo(input: String) = input
.lines()
.count {
RE_REPEATED_PAIR.matches(it) && RE_SEPARATED_REPEAT.matches(it)
}
| 0 | Kotlin | 0 | 0 | a8d52412772750c5e7d2e2e018f3a82354e8b1c3 | 967 | aoc-2021 | MIT License |
kotlin/structures/RTree.kt | polydisc | 281,633,906 | true | {"Java": 540473, "Kotlin": 515759, "C++": 265630, "CMake": 571} | package structures
// https://en.wikipedia.org/wiki/R-tree
class RTree(segments: Array<Segment?>) {
class Segment(val x1: Int, val y1: Int, val x2: Int, val y2: Int)
val x1: IntArray
val y1: IntArray
val x2: IntArray
val y2: IntArray
val minx: IntArray
val maxx: IntArray
val miny: IntArray
val maxy: IntArray
fun build(low: Int, high: Int, divX: Boolean, segments: Array<Segment?>) {
if (low >= high) return
val mid = low + high ushr 1
nth_element(segments, low, high, mid, divX)
x1[mid] = segments[mid]!!.x1
y1[mid] = segments[mid]!!.y1
x2[mid] = segments[mid]!!.x2
y2[mid] = segments[mid]!!.y2
for (i in low until high) {
minx[mid] = Math.min(minx[mid], Math.min(segments[i]!!.x1, segments[i]!!.x2))
miny[mid] = Math.min(miny[mid], Math.min(segments[i]!!.y1, segments[i]!!.y2))
maxx[mid] = Math.max(maxx[mid], Math.max(segments[i]!!.x1, segments[i]!!.x2))
maxy[mid] = Math.max(maxy[mid], Math.max(segments[i]!!.y1, segments[i]!!.y2))
}
build(low, mid, !divX, segments)
build(mid + 1, high, !divX, segments)
}
var bestDist = 0.0
var bestNode = 0
fun findNearestNeighbour(x: Int, y: Int): Int {
bestDist = Double.POSITIVE_INFINITY
findNearestNeighbour(0, x1.size, x, y, true)
return bestNode
}
fun findNearestNeighbour(low: Int, high: Int, x: Int, y: Int, divX: Boolean) {
if (low >= high) return
val mid = low + high ushr 1
val distance = pointToSegmentSquaredDistance(x, y, x1[mid], y1[mid], x2[mid], y2[mid])
if (bestDist > distance) {
bestDist = distance
bestNode = mid
}
val delta = if (divX) (2 * x - x1[mid] - x2[mid]).toLong() else 2 * y - y1[mid] - y2[mid].toLong()
if (delta <= 0) {
findNearestNeighbour(low, mid, x, y, !divX)
if (mid + 1 < high) {
val mid1 = mid + 1 + high ushr 1
val dist = if (divX) getDist(x, minx[mid1], maxx[mid1])
.toLong() else getDist(y, miny[mid1], maxy[mid1]).toLong()
if (dist * dist < bestDist) findNearestNeighbour(mid + 1, high, x, y, !divX)
}
} else {
findNearestNeighbour(mid + 1, high, x, y, !divX)
if (low < mid) {
val mid1 = low + mid ushr 1
val dist = if (divX) getDist(x, minx[mid1], maxx[mid1])
.toLong() else getDist(y, miny[mid1], maxy[mid1]).toLong()
if (dist * dist < bestDist) findNearestNeighbour(low, mid, x, y, !divX)
}
}
}
companion object {
val rnd: Random = Random(1)
// See: http://www.cplusplus.com/reference/algorithm/nth_element
fun nth_element(a: Array<Segment?>, low: Int, high: Int, n: Int, divX: Boolean) {
var low = low
var high = high
while (true) {
val k = partition(a, low, high, low + rnd.nextInt(high - low), divX)
if (n < k) high = k else if (n > k) low = k + 1 else return
}
}
fun partition(
a: Array<Segment?>,
fromInclusive: Int,
toExclusive: Int,
separatorIndex: Int,
divX: Boolean
): Int {
var i = fromInclusive
var j = toExclusive - 1
if (i >= j) return j
val separator =
if (divX) a[separatorIndex]!!.x1 + a[separatorIndex]!!.x2 else a[separatorIndex]!!.y1 + a[separatorIndex]!!.y2
swap(a, i++, separatorIndex)
while (i <= j) {
while (i <= j && (if (divX) a[i]!!.x1 + a[i]!!.x2 else a[i]!!.y1 + a[i]!!.y2) < separator) ++i
while (i <= j && (if (divX) a[j]!!.x1 + a[j]!!.x2 else a[j]!!.y1 + a[j]!!.y2) > separator) --j
if (i >= j) break
swap(a, i++, j--)
}
swap(a, j, fromInclusive)
return j
}
fun swap(a: Array<Segment?>, i: Int, j: Int) {
val t = a[i]
a[i] = a[j]
a[j] = t
}
fun getDist(v: Int, min: Int, max: Int): Int {
if (v <= min) return min - v
return if (v >= max) v - max else 0
}
fun pointToSegmentSquaredDistance(x: Int, y: Int, x1: Int, y1: Int, x2: Int, y2: Int): Double {
val dx = (x2 - x1).toLong()
val dy = (y2 - y1).toLong()
val px = (x - x1).toLong()
val py = (y - y1).toLong()
val squaredLength = dx * dx + dy * dy
val dotProduct = dx * px + dy * py
if (dotProduct <= 0 || squaredLength == 0L) return (px * px + py * py).toDouble()
if (dotProduct >= squaredLength) return ((px - dx) * (px - dx) + (py - dy) * (py - dy)).toDouble()
val q = dotProduct.toDouble() / squaredLength
return (px - q * dx) * (px - q * dx) + (py - q * dy) * (py - q * dy)
}
// random test
fun main(args: Array<String?>?) {
for (step in 0..99999) {
val qx: Int = rnd.nextInt(1000) - 500
val qy: Int = rnd.nextInt(1000) - 500
val n: Int = rnd.nextInt(100) + 1
val segments = arrayOfNulls<Segment>(n)
var minDist = Double.POSITIVE_INFINITY
for (i in 0 until n) {
val x1: Int = rnd.nextInt(1000) - 500
val y1: Int = rnd.nextInt(1000) - 500
val x2: Int = x1 + rnd.nextInt(10)
val y2: Int = y1 + rnd.nextInt(10)
segments[i] = Segment(x1, y1, x2, y2)
minDist = Math.min(minDist, pointToSegmentSquaredDistance(qx, qy, x1, y1, x2, y2))
}
val rTree = RTree(segments)
val index = rTree.findNearestNeighbour(qx, qy)
val s = segments[index]
if (minDist != rTree.bestDist
|| Math.abs(pointToSegmentSquaredDistance(qx, qy, s!!.x1, s.y1, s.x2, s.y2) - minDist) >= 1e-9
) throw RuntimeException()
}
}
}
init {
val n = segments.size
x1 = IntArray(n)
y1 = IntArray(n)
x2 = IntArray(n)
y2 = IntArray(n)
minx = IntArray(n)
maxx = IntArray(n)
miny = IntArray(n)
maxy = IntArray(n)
Arrays.fill(minx, Integer.MAX_VALUE)
Arrays.fill(maxx, Integer.MIN_VALUE)
Arrays.fill(miny, Integer.MAX_VALUE)
Arrays.fill(maxy, Integer.MIN_VALUE)
build(0, n, true, segments)
}
}
| 1 | Java | 0 | 0 | 4566f3145be72827d72cb93abca8bfd93f1c58df | 6,780 | codelibrary | The Unlicense |
kotlin/src/com/s13g/aoc/aoc2023/Day4.kt | shaeberling | 50,704,971 | false | {"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245} | package com.s13g.aoc.aoc2023
import com.s13g.aoc.Result
import com.s13g.aoc.Solver
import com.s13g.aoc.resultFrom
import com.s13g.aoc.`**`
/**
* --- Day 4: Scratchcards ---
* https://adventofcode.com/2023/day/4
*/
class Day4 : Solver {
override fun solve(lines: List<String>): Result {
val cards = lines.map { parseCard(it) }
val partA = cards.map { it.numMatching() }.map { 2 `**` (it - 1) }.sum()
return resultFrom(partA, solvePartB(cards))
}
private fun solvePartB(cards: List<Card>): Int {
val cardCounts = cards.indices.groupBy { it }.mapValues { 1 }.toMutableMap()
for ((idx, card) in cards.withIndex()) {
for (i in 0 until card.numMatching()) {
// Add the number that the idx's card exist to all the following n cards.
cardCounts[idx + i + 1] = cardCounts[idx + i + 1]!! + cardCounts[idx]!!
}
}
return cardCounts.values.sum()
}
private fun parseCard(line: String): Card {
val numsStr = line.split(": ")[1]
val (lhs, rhs) = numsStr.split(" | ")
return Card(lhs.getListOfNums(), rhs.getListOfNums())
}
private data class Card(val winning: Set<Int>, val have: Set<Int>)
private fun Card.numMatching() = have.intersect(winning).count()
private fun String.getListOfNums() =
trim().split(" ").filter { it.isNotBlank() }
.map { it.trim().toInt() }.toSet()
} | 0 | Kotlin | 1 | 2 | 7e5806f288e87d26cd22eca44e5c695faf62a0d7 | 1,363 | euler | Apache License 2.0 |
src/main/kotlin/cloud/dqn/leetcode/Permutations2Kt.kt | aviuswen | 112,305,062 | false | null | package cloud.dqn.leetcode
/**
* https://leetcode.com/problems/permutations-ii/description/
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
For example,
[1,1,2] have the following unique permutations:
[
[1,1,2],
[1,2,1],
[2,1,1]
]
*/
class Permutations2Kt {
class Solution {
fun permuteUnique(nums: IntArray): List<List<Int>> {
val result = ArrayList<List<Int>>()
val remainder = ArrayList<Int>(nums.size)
nums.forEach { remainder.add(it) }
backtrack(result, ArrayList(), nums.size, remainder)
return result
}
private fun backtrack(res: ArrayList<List<Int>>, tempList: ArrayList<Int>, doneSize: Int, remainder: ArrayList<Int>) {
if (tempList.size == doneSize) {
var addIt = true
var index = 0
while (index < res.size) {
val current = res[index]
if (equalLists(current, tempList)) {
addIt = false
break
}
index++
}
if (addIt) {
res.add(ArrayList(tempList))
}
} else {
remainder.forEachIndexed { index, value ->
val newTempList = ArrayList(tempList)
newTempList.add(value)
val newRemainder = ArrayList<Int>(remainder.size - 1)
remainder.forEachIndexed { i, v ->
if (i != index) {
newRemainder.add(v)
}
}
backtrack(res, newTempList, doneSize, newRemainder)
}
}
}
private fun equalLists(l0: List<Int>, l1: List<Int>): Boolean {
if (l0.size != l1.size) {
return false
}
var index = 0
while (index < l0.size) {
if (l0[index] != l1[index]) {
return false
}
index++
}
return true
}
}
} | 0 | Kotlin | 0 | 0 | 23458b98104fa5d32efe811c3d2d4c1578b67f4b | 2,259 | cloud-dqn-leetcode | No Limit Public License |
solutions/aockt/y2021/Y2021D19.kt | Jadarma | 624,153,848 | false | {"Kotlin": 435090} | package aockt.y2021
import io.github.jadarma.aockt.core.Solution
import kotlin.math.absoluteValue
object Y2021D19 : Solution {
/** Represents a discrete point in 3D space. */
private data class Point(val x: Int, val y: Int, val z: Int)
private operator fun Point.minus(other: Point): Point = Point(x - other.x, y - other.y, z - other.z)
private operator fun Point.plus(other: Point): Point = Point(x + other.x, y + other.y, z + other.z)
private infix fun Point.manhattanDistanceTo(other: Point): Int =
(other - this).run { listOf(x.absoluteValue, y.absoluteValue, z.absoluteValue).sum() }
/** Represents a rotation relative to the local origin in 90 degree increments. */
private class Orientation private constructor(val upVector: Point, val rotation: Int) {
fun remap(point: Point): Point {
val reoriented = reorient.getValue(upVector).invoke(point)
return rotate.getValue(rotation).invoke(reoriented)
}
companion object {
private val reorient: Map<Point, Point.() -> Point> = mapOf(
Point(0, 1, 0) to { this },
Point(0, -1, 0) to { Point(x, -y, -z) },
Point(1, 0, 0) to { Point(y, x, -z) },
Point(-1, 0, 0) to { Point(y, -x, z) },
Point(0, 0, 1) to { Point(y, z, x) },
Point(0, 0, -1) to { Point(y, -z, -x) },
)
private val rotate: Map<Int, Point.() -> Point> = mapOf(
0 to { this },
1 to { Point(z, y, -x) },
2 to { Point(-x, y, -z) },
3 to { Point(-z, y, x) },
)
/** Precompiled list of all the valid orientations. */
val all: List<Orientation> = buildList {
for (upVector in reorient.keys) {
for (rotation in rotate.keys) {
add(Orientation(upVector, rotation))
}
}
}
}
}
/** Holds readings of a beacon scanner. */
private data class Scanner(val id: Int, val beaconDeltas: List<Point>) : List<Point> by beaconDeltas {
fun withOrientation(orientation: Orientation): Scanner =
copy(beaconDeltas = beaconDeltas.map { orientation.remap(it) })
}
/**
* Tries to match a [target] scanner with a [reference] one. If successful, returns the transformed [target] such
* that the two scanners have the same orientation, and the delta between them.
*/
private fun calibrateScannersOrNull(reference: Scanner, target: Scanner): Pair<Scanner, Point>? {
if (reference.size < 12 || target.size < 12) return null
Orientation.all.forEach { orientation ->
val reorientedScanner = target.withOrientation(orientation)
reference.forEach { p1 ->
reorientedScanner.forEach { p2 ->
val delta = p2 - p1
val transformed = reorientedScanner.map { it - delta }.toSet()
if (reference.intersect(transformed).size >= 12) return reorientedScanner to delta
}
}
}
return null
}
/**
* Given a set of [scanners], tries to calibrate them, remapping them to the same [Orientation] and returning a map
* of their positions relative to the first. Any scanners that do not share at least 12 beacons with the rest are
* ignored.
*/
private fun calibrateScanners(scanners: Set<Scanner>): Map<Scanner, Point> {
if (scanners.isEmpty()) return emptyMap()
return buildMap {
val pendingScanners = scanners.toMutableList()
put(pendingScanners.removeFirst(), Point(0, 0, 0))
while (pendingScanners.isNotEmpty()) {
var adjustedScannerId = -1
for (scanner in pendingScanners.shuffled()) {
for (reference in keys.shuffled()) {
val (adjustedScanner, deltaToRef) = calibrateScannersOrNull(reference, scanner) ?: continue
put(adjustedScanner, getValue(reference) - deltaToRef)
adjustedScannerId = scanner.id
break
}
if (adjustedScannerId >= 0) break
}
if (adjustedScannerId == -1) return@buildMap
pendingScanners.removeIf { it.id == adjustedScannerId }
}
}
}
/** Parse the [input] and return the [Scanner] readings. */
private fun parseInput(input: String): Set<Scanner> = buildSet {
val points = mutableListOf<Point>()
var id = -1
input
.lineSequence()
.map { it.removeSurrounding("--- ", " ---") }
.forEach { line ->
when {
line.startsWith("scanner") -> id = line.substringAfter(' ').toInt()
line.isEmpty() -> add(Scanner(id, points.toList())).also { points.clear() }
else -> line.split(",").map { it.toInt() }.let { (x, y, z) -> points.add(Point(x, y, z)) }
}
}
add(Scanner(id, points.toList()))
}
override fun partOne(input: String) =
parseInput(input)
.let(this::calibrateScanners)
.flatMap { (scanner, delta) -> scanner.map { it + delta } }
.toSet()
.count()
override fun partTwo(input: String) =
parseInput(input)
.let(this::calibrateScanners)
.run {
keys
.flatMap { s1 -> (keys - s1).map { s2 -> getValue(s1) to getValue(s2 as Scanner) } }
.distinct()
.maxOf { (p1, p2) -> p1 manhattanDistanceTo p2 }
}
}
| 0 | Kotlin | 0 | 3 | 19773317d665dcb29c84e44fa1b35a6f6122a5fa | 5,837 | advent-of-code-kotlin-solutions | The Unlicense |
src/com/freaklius/kotlin/algorithms/sort/RadixSort.kt | vania-pooh | 8,736,623 | false | null | package com.freaklius.kotlin.algorithms.sort
import java.util.LinkedList
/**
* Radix sort algorithm
* Assumption: all sorted values has the same number of digits.
* Average performance = O(n + k), where k is a number of digits
*/
class RadixSort : SortAlgorithm {
override fun sort(arr: Array<Long>): Array<Long> {
//The main idea is to sort input array by each digit using any sort algorithm
var outputArray = arr
for (digitNumber in 0..getMaximumDigitsCount(arr) - 1){
outputArray = sortArrayBySingleDigit(outputArray, digitNumber)
}
return outputArray
}
/**
* Sorts input array by specified digit using counting sort algorithm. In fact this is a bucket sort
* where each of 10 buckets correspond to one of 10 possible decimal system digit values (from 0 to 9).
* @param arr
* @param digitNumber
*/
private fun sortArrayBySingleDigit(arr: Array<Long>, digitNumber: Int) : Array<Long>{
val outputArray = arr
val mappingArray = Array<LinkedList<Long>>(10, { i -> LinkedList()}) //We need to store digits in range 0..9
for (i in 0..arr.size - 1){
val number = arr[i]
val digit = digitAt(number, digitNumber) // It's a number in range 0..9
mappingArray[digit].add(number)
}
var outputArrayIndex = 0
for (list in mappingArray){
if (list.size > 0){
for (value in list){
outputArray[outputArrayIndex] = value
outputArrayIndex++
}
}
}
return outputArray
}
/**
* Returns digit positioned at specified position number starting from the right end.
* I.e. digitAt(123, 1) = 3; digitAt(123, 2) = 2 and so on.
* @param number
* @param digitNumber zero-based digit number
*/
private fun digitAt(number: Long, digitNumber: Int) : Int{
val numberString = number.toString()
return if (digitNumber <= numberString.length - 1)
numberString.get(numberString.length - digitNumber - 1).toString().toInt() //Char.toInt() is a char code
else 0
}
/**
* Returns maximum digits count assuming that input array is in decimal
*/
private fun getMaximumDigitsCount(arr: Array<Long>) : Int{
return maximum(arr).toString().length
}
override fun getName(): String {
return "RadixSort"
}
} | 1 | Kotlin | 14 | 51 | 8c5e7b52d2831322d578af895cd4e80fbe471950 | 2,482 | kotlin-algorithms | MIT License |
src/main/kotlin/week1/Rucksack.kt | waikontse | 572,850,856 | false | {"Kotlin": 63258} | package week1
import shared.Puzzle
class Rucksack : Puzzle(3) {
override fun solveFirstPart(): Any {
return puzzleInput
.map { splitRucksack(it) }
.map { it.map { charArray -> charArray.toSet() } }
.map { getMisplacedSnackType(it, 2) }
.sumOf { snackToPoint(it) }
}
override fun solveSecondPart(): Any {
return puzzleInput.chunked(3)
.map { it.map { bag -> bag.toSet() } }
.map { getMisplacedSnackType(it, 3) }
.sumOf { snackToPoint(it) }
}
private fun splitRucksack(rucksacks: String) =
listOf(
rucksacks.substring(0, rucksacks.length / 2).toCharArray(),
rucksacks.substring(rucksacks.length / 2).toCharArray()
)
private fun getMisplacedSnackType(rucksacks: List<Set<Char>>, snackCount: Int): Char =
rucksacks.map { it.toCharArray() }
.reduce { acc, arr -> acc + arr }
.groupBy { it }
.filterValues { it.size == snackCount }
.keys
.first()
private fun snackToPoint(snack: Char) =
if (snack.isUpperCase()) snack.code - 38 else snack.code - 96
}
| 0 | Kotlin | 0 | 0 | 860792f79b59aedda19fb0360f9ce05a076b61fe | 1,195 | aoc-2022-in-kotllin | Creative Commons Zero v1.0 Universal |
src/Day06.kt | jaldhar | 573,188,501 | false | {"Kotlin": 14191} | fun List<Char>.isUnique(): Boolean {
return this.distinct().size == this.size
}
fun List<Char>.search(length: Int): Int {
for (chunk in this.windowed(length).withIndex()) {
if (chunk.value.isUnique()) {
return chunk.index + length
}
}
return 0
}
fun main() {
fun part1(input: List<String>): Int {
return input[0].toList().search(4)
}
fun part2(input: List<String>): Int {
return input[0].toList().search(14)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day06_test")
check(part1(testInput) == 7)
check(part2(testInput) == 19)
val input = readInput("Day06")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | b193df75071022cfb5e7172cc044dd6cff0f6fdf | 766 | aoc2022-kotlin | Apache License 2.0 |
src/array/LeetCode384.kt | Alex-Linrk | 180,918,573 | false | null | package array
import java.util.concurrent.ThreadLocalRandom
import kotlin.random.Random
/**
* 打乱一个没有重复元素的数组。
示例:
// 以数字集合 1, 2 和 3 初始化数组。
int[] nums = {1,2,3};
Solution solution = new Solution(nums);
// 打乱数组 [1,2,3] 并返回结果。任何 [1,2,3]的排列返回的概率应该相同。
solution.shuffle();
// 重设数组到它的初始状态[1,2,3]。
solution.reset();
// 随机返回数组[1,2,3]打乱后的结果。
solution.shuffle();
在真实的面试中遇到过这道题?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shuffle-an-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
class Solution(nums: IntArray) {
val original = nums.clone()
var nums = nums
/** Resets the array to its original configuration and return it. */
fun reset(): IntArray {
nums = original.clone()
return nums
}
/** Returns a random shuffling of the array. */
fun shuffle(): IntArray {
for (index in 0 .. nums.lastIndex) {
val other = java.util.concurrent.ThreadLocalRandom.current().nextInt(index, nums.lastIndex+1)
println(other)
swip(nums, other, index)
}
return nums
}
fun swip(nums: IntArray, x: Int, y: Int) {
val temp = nums[x]
nums[x] = nums[y]
nums[y] = temp
}
}
fun main() {
val solution = Solution(intArrayOf(1,2,3))
println(solution.shuffle().toList())
println(solution.reset().toList())
println(solution.shuffle().toList())
} | 0 | Kotlin | 0 | 0 | 59f4ab02819b7782a6af19bc73307b93fdc5bf37 | 1,650 | LeetCode | Apache License 2.0 |
2021/src/day02/day2.kt | scrubskip | 160,313,272 | false | {"Kotlin": 198319, "Python": 114888, "Dart": 86314} | package day02
import java.io.File
fun main() {
// println(testSample())
println(readFile("day2.txt"))
}
fun testSample(): Int {
val (depth, distance) =
moveSubWithAim(
listOf("forward 5", "down 5", "forward 8", "up 3", "down 8", "forward 2")
)
return depth * distance
}
fun readFile(arg: String): Int {
val lineList = mutableListOf<String>()
File("src/day02", arg).useLines { lines -> lines.forEach { lineList.add(it.toString()) } }
val (depth, distance) = moveSubWithAim(lineList)
return depth * distance
}
fun moveSub(input: List<String>): Pair<Int, Int> {
var depth: Int = 0
var distance: Int = 0
input.forEach {
// println(it)
val command = it.split(" ")
val direction = command[0]
val unit: Int = command[1].toInt()
when (direction) {
"forward" -> distance += unit
"down" -> depth += unit
"up" -> depth -= unit
}
}
return Pair(depth, distance)
}
fun moveSubWithAim(input: List<String>): Pair<Int, Int> {
var depth: Int = 0
var distance: Int = 0
var aim: Int = 0
input.forEach {
// println(it)
val command = it.split(" ")
val direction = command[0]
val unit: Int = command[1].toInt()
when (direction) {
"forward" -> {
distance += unit
depth += (aim * unit)
}
"down" -> aim += unit
"up" -> aim -= unit
}
}
return Pair(depth, distance)
}
| 0 | Kotlin | 0 | 0 | a5b7f69b43ad02b9356d19c15ce478866e6c38a1 | 1,583 | adventofcode | Apache License 2.0 |
logicsolver/src/test/kotlin/nl/hiddewieringa/logicsolver/SudokuIntegrationTest.kt | hiddewie | 147,922,971 | false | null | package nl.hiddewieringa.logicsolver
import org.junit.Assert.assertEquals
import org.junit.Test
class SudokuIntegrationTest {
@Test
fun solveAlreadySolvedSudoku() {
val coordinates = (1..9).flatMap { i ->
(1..9).map { j ->
Coordinate(i, j)
}
}
val valueMap = coordinates.map { coordinate ->
coordinate to (1 + ((coordinate.a - 1) + (coordinate.b - 1)) % 9)
}.toMap()
val input = Sudoku(valueMap)
val solver = SudokuSolver()
val output = solver.solve(input)
val expected = SudokuOutput(coordinates, valueMap)
assertEquals(true, output.isLeft())
assertEquals(expected, output.left())
}
@Test
fun solveSudoku() {
val input = Sudoku.readFromString("""
. . . . 4 5 . . 9
9 5 . . . 7 3 2 .
. 8 2 . 6 . 1 . .
6 7 . 4 . 8 9 . 2
. 1 5 6 . 9 4 . .
. . . . . . . . 8
. 3 . . 7 . . . 1
. . 7 8 . . . 4 .
. 4 6 3 . 2 7 . 5
""")
val solver = SudokuSolver()
val output = solver.solve(input)
val expected = """
3 6 1 2 4 5 8 7 9
9 5 4 1 8 7 3 2 6
7 8 2 9 6 3 1 5 4
6 7 3 4 5 8 9 1 2
8 1 5 6 2 9 4 3 7
4 2 9 7 3 1 5 6 8
2 3 8 5 7 4 6 9 1
5 9 7 8 1 6 2 4 3
1 4 6 3 9 2 7 8 5
"""
assertEquals(true, output.isLeft())
assertEquals(expected.trim(), output.left().toString().trim())
}
@Test
fun solveSudokuX() {
val input = SudokuX.readFromString("""
. 3 . . 8 . . . .
9 . 6 5 3 7 . . .
2 . . . 9 . . . 5
. . 3 . . . 1 . 8
. . 9 8 . 6 3 . .
8 . 5 . . . 6 . .
1 . . . 6 . . . 4
. . . 1 5 8 7 . 2
. . . . 2 . . 1 .
""")
val solver = SudokuSolver()
val output = solver.solve(input)
val expected = """
5 3 1 2 8 4 9 7 6
9 4 6 5 3 7 2 8 1
2 8 7 6 9 1 4 3 5
6 7 3 9 4 5 1 2 8
4 2 9 8 1 6 3 5 7
8 1 5 3 7 2 6 4 9
1 5 2 7 6 3 8 9 4
3 9 4 1 5 8 7 6 2
7 6 8 4 2 9 5 1 3
"""
assertEquals(true, output.isLeft())
assertEquals(expected.trim(), output.left().toString().trim())
}
@Test
fun solveSudokuHyper() {
val input = SudokuHyper.readFromString("""
7 . 3 . . 8 5 . .
. . . . . 5 1 . 9
5 . . . . . . 7 .
. . 4 . . . . 3 8
. . 6 . 5 . 7 . .
8 3 . . . . 2 . .
. 1 . . . . . . 4
6 . 9 2 . . . . .
. . 5 4 . . 9 . 2
""")
val solver = SudokuSolver()
val output = solver.solve(input)
val expected = """
7 9 3 1 4 8 5 2 6
4 6 2 3 7 5 1 8 9
5 8 1 9 6 2 4 7 3
1 5 4 7 2 9 6 3 8
9 2 6 8 5 3 7 4 1
8 3 7 6 1 4 2 9 5
2 1 8 5 9 7 3 6 4
6 4 9 2 3 1 8 5 7
3 7 5 4 8 6 9 1 2
"""
assertEquals(true, output.isLeft())
assertEquals(expected.trim(), output.left().toString().trim())
}
@Test
fun solveSudokuDouble() {
val input = SudokuDouble.readFromString("""
. 8 1 . 4 . 7 3 .
. 4 9 . . . 8 1 .
. . . . 5 . . . .
6 . 4 . . . 9 . 7
. . . . . . . . .
7 . . 5 9 4 . . 3
. . . 6 . 5 . . .
. . . . 1 . . . .
. . . 4 . 8 . . .
6 . . 3 7 2 . . 5
. . . . . . . . .
8 . 3 . . . 6 . 1
. . . . 6 . . . .
. 4 6 . . . 8 3 .
. 8 1 . 5 . 2 9 .
""")
val solver = SudokuSolver()
val output = solver.solve(input)
val expected = """
5 8 1 2 4 9 7 3 6
2 4 9 3 7 6 8 1 5
3 7 6 8 5 1 2 9 4
6 5 4 1 8 3 9 2 7
8 9 3 7 6 2 5 4 1
7 1 2 5 9 4 6 8 3
1 3 8 6 2 5 4 7 9
4 2 5 9 1 7 3 6 8
9 6 7 4 3 8 1 5 2
6 1 4 3 7 2 9 8 5
2 5 9 1 8 6 7 4 3
8 7 3 5 4 9 6 2 1
7 9 2 8 6 3 5 1 4
5 4 6 2 9 1 8 3 7
3 8 1 7 5 4 2 9 6
"""
assertEquals(true, output.isLeft())
assertEquals(expected.trim(), output.left().toString().trim())
}
@Test
fun solveSudokuSamurai() {
val input = SudokuSamurai.readFromString("""
. 4 9 . . . . 7 3 3 9 . . . . 8 2 .
2 . 8 . . . 1 . 5 2 . 8 . . . 6 . 9
5 6 . . . . 4 8 . . 6 7 . . . . 1 3
. . . . 9 5 . . . . . . 3 6 . . . .
. . . 8 . 1 . . . . . . 5 . 2 . . .
. . . 7 6 . . . . . . . . 7 9 . . .
. 2 5 . . . . 6 7 . . . 8 4 . . . . 7 3 .
8 . 6 . . . 3 . 4 . 7 . 9 . 6 . . . 2 . 4
7 3 . . . . 5 2 . . . . . 3 1 . . . . 5 6
. . . 1 . 4 . . .
. 8 . . . . . 1 .
. . . 5 . 7 . . .
5 1 . . . . 6 9 . . . . . 2 7 . . . . 9 8
3 . 8 . . . 4 . 1 . 6 . 3 . 5 . . . 4 . 2
. 4 7 . . . . 5 2 . . . 4 6 . . . . 7 1 .
. . . 1 5 . . . . . . . . 4 1 . . .
. . . 6 . 8 . . . . . . 3 . 5 . . .
. . . . 9 4 . . . . . . 6 9 . . . .
1 6 . . . . 2 8 . . 9 1 . . . . 4 3
2 . 9 . . . 1 . 4 2 . 4 . . . 6 . 1
. 5 4 . . . . 3 7 5 7 . . . . 8 2 .
""")
val solver = SudokuSolver()
val output = solver.solve(input)
val expected = """
1 4 9 2 5 8 6 7 3 3 9 5 4 1 6 8 2 7
2 7 8 4 3 6 1 9 5 2 1 8 7 5 3 6 4 9
5 6 3 9 1 7 4 8 2 4 6 7 9 2 8 5 1 3
6 8 7 3 9 5 2 4 1 5 8 9 3 6 1 4 7 2
9 5 4 8 2 1 7 3 6 6 7 3 5 4 2 1 9 8
3 1 2 7 6 4 8 5 9 1 2 4 8 7 9 3 6 5
4 2 5 1 8 3 9 6 7 3 1 5 8 4 2 6 9 5 7 3 1
8 9 6 5 7 2 3 1 4 8 7 2 9 5 6 1 3 7 2 8 4
7 3 1 6 4 9 5 2 8 9 4 6 7 3 1 2 8 4 9 5 6
2 3 5 1 9 4 6 7 8 .
7 8 9 6 2 3 5 1 4 .
1 4 6 5 8 7 2 9 3 .
5 1 2 4 8 7 6 9 3 4 5 8 1 2 7 4 5 6 3 9 8
3 9 8 5 2 6 4 7 1 2 6 9 3 8 5 9 1 7 4 6 2
6 4 7 9 1 3 8 5 2 7 3 1 4 6 9 8 2 3 7 1 5
9 3 6 1 5 2 7 4 8 6 5 8 2 4 1 9 3 7
4 2 5 6 7 8 3 1 9 9 4 2 3 7 5 1 8 6
7 8 1 3 9 4 5 2 6 7 1 3 6 9 8 2 5 4
1 6 3 7 4 9 2 8 5 8 9 1 7 6 2 5 4 3
2 7 9 8 3 5 1 6 4 2 3 4 5 8 9 6 7 1
8 5 4 2 6 1 9 3 7 5 7 6 1 3 4 8 2 9
"""
assertEquals(true, output.isLeft())
assertEquals(expected.replace(".", "").trim(), output.left().toString().trim())
}
@Test
fun solveSudokuTiny() {
val input = SudokuTiny.readFromString("""
. . . 6 4 2
. . . . . .
. . . . . 6
. . . . 3 .
4 . 5 . . .
2 . 6 5 . .
""")
val solver = SudokuSolver()
val output = solver.solve(input)
val expected = """
3 5 1 6 4 2
6 2 4 3 5 1
5 4 3 1 2 6
1 6 2 4 3 5
4 1 5 2 6 3
2 3 6 5 1 4
"""
assertEquals(true, output.isLeft())
assertEquals(expected.trim(), output.left().toString().trim())
}
@Test
fun failToSolveUnsolvableSudoku() {
val valueMap = mapOf(
Coordinate(1, 1) to 1
)
val input = Sudoku(valueMap)
val solver = SudokuSolver()
val output = solver.solve(input)
val expected = listOf(
LogicSolveError("No more conclusions, cannot solve")
)
assertEquals(true, output.isRight())
assertEquals(expected, output.right())
}
}
| 0 | Kotlin | 0 | 0 | bcf12c102f4ab77c5aa380dbf7c98a1cc3e585c0 | 6,856 | LogicSolver | MIT License |
src/Day01.kt | StephenVinouze | 572,377,941 | false | {"Kotlin": 55719} | fun main() {
fun caloriesPerEfl(input: List<String>): List<Int> {
var caloriesPerElf = 0
val elfCalories = mutableListOf<Int>()
input.forEachIndexed { index, calories ->
when {
calories.isBlank() -> {
elfCalories.add(caloriesPerElf)
caloriesPerElf = 0
}
else -> {
caloriesPerElf += calories.toInt()
if (index == input.lastIndex && input[input.lastIndex - 1].isBlank()) {
elfCalories.add(caloriesPerElf)
}
}
}
}
return elfCalories
}
fun part1(input: List<String>): Int =
caloriesPerEfl(input).max()
fun part2(input: List<String>): Int =
caloriesPerEfl(input).sortedDescending()
.take(3)
.sum()
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 11b9c8816ded366aed1a5282a0eb30af20fff0c5 | 1,112 | AdventOfCode2022 | Apache License 2.0 |
src/Day01.kt | mpythonite | 572,671,910 | false | {"Kotlin": 29542} | fun main() {
fun part1(input: List<String>): Int {
var currentCalories = 0
var maxCalories = 0
for (i in input.indices)
{
if (input[i].isBlank())
{
if (currentCalories > maxCalories) {
maxCalories = currentCalories
}
currentCalories = 0
}
else currentCalories += input[i].toInt()
}
if (currentCalories > maxCalories) {
maxCalories = currentCalories
}
return maxCalories
}
fun part2(input: List<String>): Int {
var currentCalories = 0
var calorieList: MutableList<Int> = mutableListOf()
var totalCalories = 0
for (i in input.indices) {
if (input[i].isBlank()) {
calorieList.add(currentCalories)
currentCalories = 0
} else currentCalories += input[i].toInt()
}
calorieList.add(currentCalories)
calorieList.sortDescending()
for (i in 0 until 3) {
totalCalories += calorieList[i]
}
return totalCalories
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | cac94823f41f3db4b71deb1413239f6c8878c6e4 | 1,448 | advent-of-code-2022 | Apache License 2.0 |
16117/solution.kt | daily-boj | 253,815,781 | false | null | fun main(args: Array<out String>) {
val (height, width) = readLine()!!.split(" ").map { it.toInt() }
val realMap = List(height * 2) {
if (it % 2 == 0) {
List(width * 2) { 0L }
} else {
readLine()!!.split(" ").flatMap { listOf(0L, it.toLong()) }
}
}
fun getSafe(map: List<List<Long>>, x: Int, y: Int): Long =
if (y in 0 until 2 * height && x in 0 until 2 * width) map[y][x]
else 0
val intDP = List(height * 2) {
MutableList(width * 2) { 0L }
}
for (x in (0 until width * 2).reversed()) {
for (y in (0 until height * 2).reversed()) {
val here = realMap[y][x]
val best = maxOf(
getSafe(realMap, x + 1, y - 1) + getSafe(intDP, x + 2, y - 2),
getSafe(realMap, x + 2, y) + getSafe(intDP, x + 4, y),
getSafe(realMap, x + 1, y + 1) + getSafe(intDP, x + 2, y + 2)
)
intDP[y][x] = here + best
}
}
val max = (0 until height * 2).fold(0L) { acc, y -> maxOf(acc, getSafe(intDP, 0, y), getSafe(intDP, 1, y)) }
println(max)
}
| 0 | Rust | 0 | 12 | 74294a4628e96a64def885fdcdd9c1444224802c | 1,140 | RanolP | The Unlicense |
app/src/main/kotlin/day11/Day11.kt | W3D3 | 572,447,546 | false | {"Kotlin": 159335} | package day11
import com.github.keelar.exprk.Expressions
import common.InputRepo
import common.readSessionCookie
import common.solve
import util.split
import java.math.BigInteger
data class MonkeyTest(val divisor: Int, val positive: Int, val negative: Int)
data class Monkey(
val id: Int,
val items: MutableList<BigInteger>,
val operation: String,
val test: MonkeyTest
) {
var inspects = 0L
fun executeOperation(worryLevel: BigInteger): BigInteger {
inspects++
return Expressions()
.define("old", worryLevel.toBigDecimal())
.eval(operation)
.toBigInteger()
}
fun executeTest(worryLevel: BigInteger): Int {
return if (worryLevel % test.divisor.toBigInteger() == BigInteger.ZERO) {
test.positive
} else {
test.negative
}
}
}
fun main(args: Array<String>) {
val day = 11
val input = InputRepo(args.readSessionCookie()).get(day = day)
solve(day, input, ::solveDay11Part1, ::solveDay11Part2)
}
fun solveDay11Part1(input: List<String>): Long {
val monkeys = input.split({ it.isBlank() })
.map { convertToMonkey(it) }
println(monkeys)
repeat(20, action = {
for (monkey in monkeys) {
for (item in monkey.items) {
println("${monkey.id} inspects item with worry level ${item}")
val worry = monkey.executeOperation(item) / BigInteger.valueOf(3L)
val target = monkey.executeTest(worry)
println("throw to $target")
monkeys.first { it.id == target }.items.add(worry)
}
monkey.items.clear()
}
})
val mostActive = monkeys.sortedByDescending { it.inspects }
return mostActive[0].inspects * mostActive[1].inspects
}
fun convertToMonkey(monkeyDefinition: Collection<String>): Monkey {
val startingItemsPrefix = "Starting items:"
val opPrefix = "Operation:"
var id = 0
var list: MutableList<BigInteger> = emptyList<BigInteger>().toMutableList()
var operation = ""
var divisor = 0
var pos = 0
var neg = 0
// this is why I just should have used RegEx.
for (line in monkeyDefinition.map { it.trim() }) {
if (line.startsWith("Monkey")) {
id = line.removePrefix("Monkey")
.trim()
.removeSuffix(":")
.toInt()
}
if (line.startsWith(startingItemsPrefix)) {
list = line.removePrefix(startingItemsPrefix)
.trim()
.split(", ").map { BigInteger.valueOf(it.toLong()) }.toMutableList()
}
if (line.startsWith(opPrefix)) {
operation = line.removePrefix(opPrefix)
.trim()
.removePrefix("new =")
.trim()
}
if (line.startsWith("Test:")) {
divisor = line.removePrefix("Test: divisible by")
.trim()
.toInt()
}
if (line.startsWith("Test:")) {
divisor = line.removePrefix("Test: divisible by")
.trim()
.toInt()
}
if (line.startsWith("If true: throw to monkey ")) {
pos = line.removePrefix("If true: throw to monkey ")
.trim()
.toInt()
}
if (line.startsWith("If false: throw to monkey ")) {
neg = line.removePrefix("If false: throw to monkey ")
.trim()
.toInt()
}
}
return Monkey(id, list, operation, MonkeyTest(divisor, pos, neg))
}
fun solveDay11Part2(input: List<String>): Long {
val monkeys = input.split({ it.isBlank() })
.map { convertToMonkey(it) }
// gcd for all primes is just multiplication
val gcd = monkeys.map { it.test.divisor }.reduce { acc: Int, current: Int -> acc * current }
repeat(10000, action = {
for (monkey in monkeys) {
for (item in monkey.items) {
val worry = monkey.executeOperation(item) % gcd.toBigInteger()
val target = monkey.executeTest(worry)
monkeys.first { it.id == target }.items.add(worry)
}
monkey.items.clear()
}
})
val mostActive = monkeys.sortedByDescending { it.inspects }
mostActive.forEach { println("${it.id}: ${it.inspects}") }
return mostActive[0].inspects * mostActive[1].inspects
} | 0 | Kotlin | 0 | 0 | 34437876bf5c391aa064e42f5c984c7014a9f46d | 4,459 | AdventOfCode2022 | Apache License 2.0 |
src/Day08/Day08.kt | G-lalonde | 574,649,075 | false | {"Kotlin": 39626} | package Day08
import readInput
import kotlin.math.max
fun main() {
fun buildMatrix(treeMatrix: Matrix, input: List<String>) {
for ((i, line) in input.withIndex()) {
for ((j, v) in line.withIndex()) {
treeMatrix[i, j] = v.digitToInt()
}
}
}
fun part1(input: List<String>): Int {
val rowCount = input.size
val colCount = input.first().length
val outerCount = colCount * 2 + (rowCount - 2) * 2
val treeMatrix = Matrix(rowCount, colCount)
buildMatrix(treeMatrix, input)
val visibleMatrix = Matrix(rowCount, colCount) // check pas le outer
for (i in 1 until rowCount - 1) {
// looking from the left
var highestValueOnRowFromLeft = treeMatrix[i, 0]
treeMatrix.forEachInRow(i, startFromBeginning = true) { j, value ->
if (value > highestValueOnRowFromLeft) {
visibleMatrix[i, j] = 1
}
if (value > highestValueOnRowFromLeft) {
highestValueOnRowFromLeft = value
}
}
// looking from the right
var highestValueOnRowFromRight = treeMatrix[i, colCount - 1]
treeMatrix.forEachInRow(i, startFromBeginning = false) { j, value ->
if (value > highestValueOnRowFromRight) {
visibleMatrix[i, j] = 1
}
if (value > highestValueOnRowFromRight) {
highestValueOnRowFromRight = value
}
}
}
for (j in 1 until colCount - 1) {
// looking from the top
var highestValueOnColumnFromTop = treeMatrix[0, j]
treeMatrix.forEachInColumn(j, startFromBeginning = true) { i, value ->
if (value > highestValueOnColumnFromTop) {
visibleMatrix[i, j] = 1
}
if (value > highestValueOnColumnFromTop) {
highestValueOnColumnFromTop = value
}
}
// looking from the bottom
var highestValueOnRowFromRight = treeMatrix[rowCount - 1, j]
treeMatrix.forEachInColumn(j, startFromBeginning = false) { i, value ->
if (value > highestValueOnRowFromRight) {
visibleMatrix[i, j] = 1
}
if (value > highestValueOnRowFromRight) {
highestValueOnRowFromRight = value
}
}
}
return outerCount + visibleMatrix.count(1)
}
fun part2(input: List<String>): Int {
val rowCount = input.size
val colCount = input.first().length
val treeMatrix = Matrix(rowCount, colCount)
buildMatrix(treeMatrix, input)
val scenicScore = Matrix(rowCount, colCount)
for (i in 0 until rowCount) {
// looking from the left
val viewedFromLeft = mutableListOf<Int>()
viewedFromLeft.add(treeMatrix[i, 0])
treeMatrix.forEachInRow(i, startFromBeginning = true) { j, value ->
if (j == 0) {
scenicScore[i, j] = 0
return@forEachInRow
}
var treeSeen = 0
for (tree in viewedFromLeft.reversed()) {
if (tree < value) {
treeSeen += 1
} else {
treeSeen += 1
break
}
}
scenicScore[i, j] = treeSeen
viewedFromLeft.add(value)
}
// looking from the right
val viewedFromRight = mutableListOf<Int>()
viewedFromRight.add(treeMatrix[i, colCount - 1])
treeMatrix.forEachInRow(i, startFromBeginning = false) { j, value ->
if (j == colCount - 1) {
scenicScore[i, j] = 0
return@forEachInRow
}
var treeSeen = 0
for (tree in viewedFromRight.reversed()) {
if (tree < value) {
treeSeen += 1
} else {
treeSeen += 1
break
}
}
scenicScore[i, j] *= treeSeen
viewedFromRight.add(value)
}
}
for (j in 1 until colCount - 1) {
// looking from the top
val viewedFromTop = mutableListOf<Int>()
viewedFromTop.add(treeMatrix[0, j])
treeMatrix.forEachInColumn(j, startFromBeginning = true) { i, value ->
if (i == 0) {
scenicScore[i, j] = 0
return@forEachInColumn
}
var treeSeen = 0
for (tree in viewedFromTop.reversed()) {
if (tree < value) {
treeSeen += 1
} else {
treeSeen += 1
break
}
}
scenicScore[i, j] *= treeSeen
viewedFromTop.add(value)
}
// looking from the bottom
val viewedFromBottom = mutableListOf<Int>()
viewedFromBottom.add(treeMatrix[rowCount - 1, j])
treeMatrix.forEachInColumn(j, startFromBeginning = false) { i, value ->
if (i == rowCount - 1) {
scenicScore[i, j] = 0
return@forEachInColumn
}
var treeSeen = 0
for (tree in viewedFromBottom.reversed()) {
if (tree < value) {
treeSeen += 1
} else {
treeSeen += 1
break
}
}
scenicScore[i, j] *= treeSeen
viewedFromBottom.add(value)
}
}
return scenicScore.max()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08/Day08_test")
// check(part1(testInput) == 21) { "Got instead : ${part1(testInput)}" }
check(part2(testInput) == 8) { "Got instead : ${part2(testInput)}" }
val input = readInput("Day08/Day08")
println("Answer for part 1 : ${part1(input)}")
println("Answer for part 2 : ${part2(input)}")
}
class Matrix(val rows: Int, val cols: Int) {
// stored in row-major
private val data = MutableList(rows * cols) { 0 }
// define a operator [] to access individual elements of the matrix
operator fun get(row: Int, col: Int): Int {
return data[row * cols + col]
}
operator fun set(row: Int, col: Int, value: Int) {
data[row * cols + col] = value
}
fun count(value: Int): Int {
return data.count { it == value }
}
// dont check outer edge
fun forEachInColumn(
col: Int,
startFromBeginning: Boolean = true,
action: (Int, Int) -> Unit
) {
val range = 0 until rows
for (i in if (startFromBeginning) range else range.reversed()) {
action(i, this[i, col])
}
}
// dont check outer edge
fun forEachInRow(
row: Int,
startFromBeginning: Boolean = true,
action: (Int, Int) -> Unit
) {
val range = 0 until cols
for (j in if (startFromBeginning) range else range.reversed()) {
action(j, this[row, j])
}
}
fun max(): Int {
return data.max()
}
}
| 0 | Kotlin | 0 | 0 | 3463c3228471e7fc08dbe6f89af33199da1ceac9 | 7,729 | aoc-2022 | Apache License 2.0 |
src.kt | Sladernom | 653,728,520 | false | null | package cinema
var totalIncome = 0
fun setupCinema(): Pair<Int, Int> {
println("Enter the number of rows:")
val numRows: Int = readln()!!.toInt()
println("Enter the number of seats in each row:")
val seatsInRow: Int = readln()!!.toInt()
return Pair(numRows, seatsInRow)
}
fun printCinema(topList: MutableList<MutableList<String>>) {
println("Cinema:")
print(" ")
for (rowInit in topList[0].indices) print(" ${rowInit + 1}")
for (rowIndex in topList.indices) {
print("\n${rowIndex + 1}")
for (seatIndex in topList[rowIndex].indices) print(" ${topList[rowIndex][seatIndex]}")
}
println()
}
fun pickSeat(numRows: Int, seatsInRow: Int, numSeats: Int, topList: MutableList<MutableList<String>>) {
while (true) {
println("\nEnter a row number:")
val rowPick = readln()!!.toInt()
println("Enter a seat number in that row:")
val seatPick = readln()!!.toInt()
if (rowPick !in 1..numRows || seatPick !in 1..seatsInRow) {
println("Wrong input!")
// pickSeat(numRows, seatsInRow, numSeats, topList)
continue
}
val holdingVar = topList[rowPick - 1][seatPick - 1]
if (holdingVar == "B") {
println("That ticket has already been purchased!")
// pickSeat(numRows, seatsInRow, numSeats, topList)
continue
}
var seatCost = if (numSeats <= 60 || rowPick <= numRows / 2) 10 else 8
println("Ticket price: $$seatCost")
topList[rowPick - 1][seatPick - 1] = "B"
totalIncome += seatCost
break
}
}
fun fetchStats(totalIncome: Int, topList: MutableList<MutableList<String>>, numRows: Int, seatsInRow: Int, numSeats: Int) {
val boughtTickets = topList.flatten().count { it == "B" }
println("Number of purchased tickets: $boughtTickets")
val boughtRoughP = boughtTickets.toDouble() / topList.flatten().size * 100
val boughtPercent: String = "%.2f".format(boughtRoughP)
println("Percentage: $boughtPercent%")
println("Current income: $$totalIncome")
val maxIncome = if (numSeats <= 60) numSeats * 10 else {
numRows / 2 * seatsInRow * 10 + (numRows / 2 + 1) * seatsInRow * 8
}
println("Total income: $$maxIncome")
}
fun main() {
val (numRows, seatsInRow) = setupCinema()
val topList = MutableList(numRows) { MutableList(seatsInRow) { "S" } }
val numSeats = topList.flatten().size
while(true) {
println("\n1. Show the seats\n2. Buy a ticket\n3. Statistics\n0. Exit\n")
when (readln()!!.toInt()) {
1 -> { printCinema(topList) }
2 -> { pickSeat(numRows, seatsInRow, numSeats, topList) }
3 -> { fetchStats(totalIncome, topList, numRows, seatsInRow, numSeats) }
0 -> return
}
}
}
| 0 | Kotlin | 0 | 0 | 90d3400445ad2c139d42299eef50f57bf3e1eb2b | 2,817 | Hyperskill-Cinema-Project | MIT License |
src/day01/Day01.kt | jacobprudhomme | 573,057,457 | false | {"Kotlin": 29699} | import java.io.File
fun main() {
fun readInput(name: String) = File("src/day01", name)
.readLines()
fun part1(input: List<String>): Int {
var maxSoFar = 0
var currentSum = 0
for (line in input) {
if (line.isEmpty()) {
if (currentSum > maxSoFar) {
maxSoFar = currentSum
}
currentSum = 0
} else {
currentSum += line.toInt()
}
}
return if (currentSum > maxSoFar) currentSum else maxSoFar
}
fun part2(input: List<String>): Int {
val maxesSoFar = intArrayOf(0, 0, 0)
var currentSum = 0
for (line in input) {
if (line.isEmpty()) {
val (idx, smallestMaxSoFar) = maxesSoFar.withIndex().minBy { (_, maxVal) -> maxVal }
if (currentSum > smallestMaxSoFar) {
maxesSoFar[idx] = currentSum
}
currentSum = 0
} else {
currentSum += line.toInt()
}
}
val (idx, smallestMaxSoFar) = maxesSoFar.withIndex().minBy { (_, maxVal) -> maxVal }
if (currentSum > smallestMaxSoFar) {
maxesSoFar[idx] = currentSum
}
return maxesSoFar.sum()
}
val input = readInput("input")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 9c2b080aea8b069d2796d58bcfc90ce4651c215b | 1,410 | advent-of-code-2022 | Apache License 2.0 |
src/adventofcode/blueschu/y2017/day13/solution.kt | blueschu | 112,979,855 | false | null | package adventofcode.blueschu.y2017.day13
import java.io.File
import kotlin.test.assertEquals
val input: List<String> by lazy {
File("resources/y2017/day13.txt")
.bufferedReader()
.use { r -> r.readLines() }
}
fun main(args: Array<String>) {
val exampleFirewall = listOf(
"0: 3",
"1: 2",
"4: 4",
"6: 4"
)
assertEquals(24, part1(parseFirewall(exampleFirewall)))
println("Part 1: ${part1(parseFirewall(input))}")
assertEquals(10, part2(parseFirewall(exampleFirewall)))
println("Part 2: ${part2(parseFirewall(input))}")
}
data class FirewallLayer(val depth: Int, val range: Int)
fun parseFirewall(description: List<String>): Array<FirewallLayer> {
return Array<FirewallLayer>(description.size) {
val (depth, range) = description[it].split(": ")
FirewallLayer(depth = depth.toInt(), range = range.toInt())
}
}
fun part1(firewall: Array<FirewallLayer>): Int {
fun FirewallLayer.severity() = depth * range
return firewall.filter {
it.depth % ((it.range * 2) - 2) == 0
}.map(FirewallLayer::severity).sum()
}
fun part2(firewall: Array<FirewallLayer>): Int {
var totalDelay = 0
nextDelay@ while (true) {
totalDelay++
for (layer in firewall) {
if ((totalDelay + layer.depth) % ((layer.range * 2) - 2) == 0) {
continue@nextDelay
}
}
return totalDelay
}
}
| 0 | Kotlin | 0 | 0 | 9f2031b91cce4fe290d86d557ebef5a6efe109ed | 1,460 | Advent-Of-Code | MIT License |
server/src/main/kotlin/models/LongestRouteManager.kt | jaydenmilne | 165,130,222 | false | {"HTML": 614644, "TypeScript": 160418, "Kotlin": 128363, "SCSS": 12884, "Java": 5447, "JavaScript": 1732, "Dockerfile": 569} | package models
import java.io.Serializable
import commands.CommandException
import commands.UpdatePlayerCommand
import kotlin.system.measureTimeMillis
class LongestRouteManager(private val game: Game): Serializable {
// Player id of the player who last got the longest route
private var currentPlayerWithLongestRoute = -1
private var longestRoute = 0
// All of the cities in the game
private var cities = mutableSetOf<String>()
// All of the outgoing edges associated with a particular city
private var adjacencyList = mutableMapOf<String, MutableSet<Route>>()
// Used to avoid loops when doing a DFS through the cities
private var markedRoutes = mutableMapOf<String, Boolean>()
fun init() {
// Create set of all cities
for ((routeId, route) in game.routes.routesByRouteId) {
cities.addAll(route.cities)
markedRoutes[routeId] = false
}
// Create adjacency list representation of the map
for ((_, route) in game.routes.routesByRouteId) {
for (city in route.cities) {
val cityList = adjacencyList.getOrPut(city) {
mutableSetOf()
}
cityList.add(route)
}
}
}
/**
* Convenience function to find the other city in the array of cities on a route
*/
private fun otherCity(route: Route, firstCity: String): String {
for (city in route.cities) {
if (city == firstCity) continue
return city
}
return "I know what I'm doing Kotlin"
}
/**
* Recursive function to compute the longest route possible from a given city
*/
private fun longestPathFromCity(city: String, longestSoFar: Int, playerid: Int): Int {
val outgoingRoutes = adjacencyList[city]
var longestFromThisCity = longestSoFar
// outgoingRoutes should never be empty but need to please the Kotlin gods
for (route in outgoingRoutes.orEmpty()) {
// If this route is not owned by this player or is marked (already used higher up in the stack),
// skip it.
if (route.ownerId != playerid || markedRoutes[route.routeId] == true)
continue
// Mark this route as used so that future calls to longestPathFromCity
// don't re-use it
markedRoutes[route.routeId] = true
// Recursively compute the longest possible route from this city taking
// this route
val longestTakingThisRoute = longestPathFromCity(
otherCity(route, city),
longestSoFar + route.numCars,
playerid)
// Check if this is longer than the current longest possible route
if (longestTakingThisRoute > longestFromThisCity) {
longestFromThisCity = longestTakingThisRoute
}
// At this point, the longest route possible by taking this route is
// longest, so unmark it
markedRoutes[route.routeId] = false
}
return longestFromThisCity
}
/**
* Called when a player claims a route. Recomputes who has the longest route
*/
fun playerClaimedRoute(playerid: Int) {
// Need to re-calculate the longest route for this given player
var playerLongest = 0
// Assuming that each city could be the start of the longest path, compute the
// longest path possible from each city
val time = measureTimeMillis {
for (city in cities) {
val longestFromCity = longestPathFromCity(city, 0, playerid)
if (longestFromCity > playerLongest) {
playerLongest = longestFromCity
}
}
}
// Ensure that this computation isn't taking too long (it is an N! algorithm after all)
if (time > 100) {
System.err.printf("!!! DANGER !!! COMPUTING LONGEST ROUTE TOOK %d MS", time)
}
if (playerLongest > longestRoute) {
// This player now has the longest route
currentPlayerWithLongestRoute = playerid
longestRoute = playerLongest
val user = Users.getUserById(playerid) ?: throw CommandException("REEE")
game.broadcastEvent(user.username + " now has the longest route with length " + longestRoute, user)
}
// Update the longest path value on the player
for (player in game.players) {
// Clear the longest route flag by default
player.hasLongestRoute = false
// The player that we just calculated the longest route needs to be updated
if (player.userId == playerid) {
player.longestRouteLength = playerLongest
}
// Allows for ties in having the longest route
if (player.longestRouteLength == longestRoute) {
player.hasLongestRoute = true
}
// Schedule an update player for everyone (we may have modified each player)
game.broadcast(UpdatePlayerCommand(player.toGamePlayer()))
}
// TODO: Put notification in chat that this player now has the longest route
}
} | 11 | HTML | 11 | 1 | 29e1d056ec02757bc1725fbbe843e9ef4ffdd004 | 5,319 | CS340 | MIT License |
src/main/kotlin/days/aoc2015/Day9.kt | bjdupuis | 435,570,912 | false | {"Kotlin": 537037} | package days.aoc2015
import days.Day
class Day9: Day(2015, 9) {
override fun partOne(): Any {
val segments: MutableList<Segment> = mutableListOf()
val startingPoints: MutableSet<Location> = mutableSetOf()
val destinations: MutableSet<Location> = mutableSetOf()
val locations: MutableSet<Location> = mutableSetOf()
inputList.forEach {
Regex("(\\w+) to (\\w+) = (\\d+)").matchEntire(it)?.destructured?.let { (start, destination, distance) ->
startingPoints.add(Location(start))
destinations.add(Location(destination))
Segment(startingPoints.first { it.name == start }, destinations.first { it.name == destination }, distance.toInt()).let { segment ->
segments.add(segment)
}
}
}
locations.addAll(startingPoints.plus(destinations))
return locations.mapIndexedNotNull { outerIndex, startingLocation ->
locations.filterIndexed { innerIndex, _ -> innerIndex > outerIndex }
.mapNotNull {
print("Trying ${startingLocation.name} to ${it.name}: ")
val result = calculateMinimumLengthToNode(startingLocation, it, segments, mutableListOf(), locations)
if (result == null) {
println(" invalid")
} else {
println(" valid [$result]")
}
result
}.minOrNull()
}.minOrNull()!!
}
data class Location(val name: String)
class Segment(val first: Location, val second: Location, val distance: Int)
fun calculateMinimumLengthToNode(startingPoint: Location, endingPoint: Location, segments: List<Segment>, visited: List<Location>, toVisit: Set<Location>): Int? {
if (startingPoint == endingPoint) {
return if (toVisit.isEmpty()) {
print("Visited ")
visited.forEach {
print("${it.name} -> " )
}
println("${startingPoint.name}")
println("** valid path found **")
0
} else {
null
}
}
return segments.asSequence().filter { ( it.first == startingPoint || it.second == startingPoint ) }
.filter { if (it.first == startingPoint) { it.second in toVisit } else { it.first in toVisit } }
.map {
val travelingTo = if (it.first == startingPoint) it.second else it.first
val distance = calculateMinimumLengthToNode(travelingTo, endingPoint, segments, visited.plus(startingPoint), toVisit.minus(startingPoint).minus(travelingTo))
if (distance == null) {
Int.MAX_VALUE
} else {
distance + it.distance
}
}
.filter { it != Int.MAX_VALUE }
.map {
println("Distance is $it")
it
}.minOrNull()
}
fun calculateMaximumLengthToNode(startingPoint: Location, endingPoint: Location, segments: List<Segment>, visited: List<Location>, toVisit: Set<Location>): Int? {
if (startingPoint == endingPoint) {
return if (toVisit.isEmpty()) {
print("Visited ")
visited.forEach {
print("${it.name} -> " )
}
println("${startingPoint.name}")
println("** valid path found **")
0
} else {
null
}
}
return segments.asSequence().filter { ( it.first == startingPoint || it.second == startingPoint ) }
.filter { if (it.first == startingPoint) { it.second in toVisit } else { it.first in toVisit } }
.map {
val travelingTo = if (it.first == startingPoint) it.second else it.first
val distance = calculateMaximumLengthToNode(travelingTo, endingPoint, segments, visited.plus(startingPoint), toVisit.minus(startingPoint).minus(travelingTo))
if (distance == null) {
Int.MIN_VALUE
} else {
distance + it.distance
}
}
.filter { it != Int.MIN_VALUE }
.map {
println("Distance is $it")
it
}.maxOrNull()
}
override fun partTwo(): Any {
val segments: MutableList<Segment> = mutableListOf()
val startingPoints: MutableSet<Location> = mutableSetOf()
val destinations: MutableSet<Location> = mutableSetOf()
val locations: MutableSet<Location> = mutableSetOf()
inputList.forEach {
Regex("(\\w+) to (\\w+) = (\\d+)").matchEntire(it)?.destructured?.let { (start, destination, distance) ->
startingPoints.add(Location(start))
destinations.add(Location(destination))
Segment(startingPoints.first { it.name == start }, destinations.first { it.name == destination }, distance.toInt()).let { segment ->
segments.add(segment)
}
}
}
locations.addAll(startingPoints.plus(destinations))
return locations.mapIndexedNotNull { outerIndex, startingLocation ->
locations.filterIndexed { innerIndex, _ -> innerIndex > outerIndex }
.mapNotNull {
print("Trying ${startingLocation.name} to ${it.name}: ")
val result = calculateMaximumLengthToNode(startingLocation, it, segments, mutableListOf(), locations)
if (result == null) {
println(" invalid")
} else {
println(" valid [$result]")
}
result
}.maxOrNull()
}.maxOrNull()!!
}
} | 0 | Kotlin | 0 | 1 | c692fb71811055c79d53f9b510fe58a6153a1397 | 6,193 | Advent-Of-Code | Creative Commons Zero v1.0 Universal |
src/main/kotlin/com/richodemus/advent_of_code/two_thousand_sixteen/day3_triangles/Main.kt | RichoDemus | 75,489,317 | false | null | package com.richodemus.advent_of_code.two_thousand_sixteen.day3_triangles
import com.richodemus.advent_of_code.two_thousand_sixteen.toFile
import java.util.*
fun main(args: Array<String>) {
val validTriangles = "day3/triangles.txt".toFile().readLines().map(::Triangle).filter { it.valid() }.count()
println("There are $validTriangles valid triangles")
assert(validTriangles == 869)
val columnOne = mutableListOf<Int>()
val columnTwo = mutableListOf<Int>()
val columnThree = mutableListOf<Int>()
"day3/triangles.txt".toFile().readLines().forEach {
val split = it.trim().split(" ").filterNot(String::isBlank)
columnOne.add(split[0].toInt())
columnTwo.add(split[1].toInt())
columnThree.add(split[2].toInt())
}
val queue: Queue<Int> = ArrayDeque((columnOne + columnTwo + columnThree))
val triangles = mutableListOf<Triangle>()
while (queue.isNotEmpty()) {
triangles.add(Triangle(queue.poll(), queue.poll(), queue.poll()))
}
val validColumnTriangles = triangles.filter { it.valid() }.count()
println("There are $validColumnTriangles valid triangles when looking at columns")
assert(validColumnTriangles == 1544)
}
private class Triangle(unparsed: String) {
val one: Int
val two: Int
val three: Int
constructor(one:Int, two:Int, three:Int) : this("$one $two $three")
init {
val split = unparsed.trim().split(" ").filterNot(String::isBlank).sorted()
one = split[0].toInt()
two = split[1].toInt()
three = split[2].toInt()
}
fun valid() = (one + two) > three && (one + three) > two && (two + three) > one
}
| 0 | Kotlin | 0 | 0 | 32655174f45808eb1530f00c4c49692310036395 | 1,665 | advent-of-code | Apache License 2.0 |
2020/day21/day21.kt | flwyd | 426,866,266 | false | {"Julia": 207516, "Elixir": 120623, "Raku": 119287, "Kotlin": 89230, "Go": 37074, "Shell": 24820, "Makefile": 16393, "sed": 2310, "Jsonnet": 1104, "HTML": 398} | /*
* Copyright 2021 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
package day21
import kotlin.time.ExperimentalTime
import kotlin.time.TimeSource
import kotlin.time.measureTimedValue
/* Input: lines of space-separated gibberish ingredients followed by "(contains …)" with a
comma-space separated list of English allergens. Each allergen comes from just one ingredient. */
val linePattern = Regex("""((?:\w+\s+)+)\(contains (\w+(?:,\s*\w+)*)\)""")
/* Count the number of ingredient occurrences that logically can't be any of the allergens. */
object Part1 {
fun solve(input: Sequence<String>): String {
val ingredientCounts = mutableMapOf<String, Int>()
val allergenCandidates = mutableMapOf<String, Set<String>>()
input.forEach { line ->
linePattern.matchEntire(line)!!.let { match ->
val ingredients = match.groupValues[1].trim().split(Regex("""\s+"""))
val allergens = match.groupValues[2].trim().split(Regex(""",\s*"""))
ingredients.forEach {
ingredientCounts[it] = ingredientCounts.getOrDefault(it, 0) + 1
}
allergens.forEach {
if (it in allergenCandidates) {
allergenCandidates[it] = allergenCandidates.getValue(it).intersect(ingredients)
} else {
allergenCandidates[it] = ingredients.toSet()
}
}
}
}
return (ingredientCounts.keys - allergenCandidates.values.flatten())
.map(ingredientCounts::getValue).sum().toString()
}
}
/* Output: comma-delimited list of unique gibberish ingredients sorted by English allergen. */
object Part2 {
fun solve(input: Sequence<String>): String {
val knownIngredients = mutableSetOf<String>()
val allergenCandidates = mutableMapOf<String, Set<String>>()
input.forEach { line ->
linePattern.matchEntire(line)!!.let { match ->
val ingredients = match.groupValues[1].trim().split(Regex("""\s+"""))
val allergens = match.groupValues[2].trim().split(Regex(""",\s*"""))
knownIngredients.addAll(ingredients)
allergens.forEach {
if (it in allergenCandidates) {
allergenCandidates[it] = allergenCandidates.getValue(it).intersect(ingredients)
} else {
allergenCandidates[it] = ingredients.toSet()
}
}
}
}
val allergens = mutableMapOf<String, String>()
val queue = allergenCandidates.mapValues { it.value.toMutableSet() }.toMutableMap()
while (queue.isNotEmpty()) {
// This makes things O(n^2) (and is kinda like a heap, but it changes several values on each
// iteration), but the size of the structure is really small so whatever
val (allergen, candidates) = checkNotNull(queue.entries.minByOrNull { it.value.size })
check(candidates.size == 1) { "$allergen != 1 $candidates" }
val ingredient = candidates.first()
allergens[allergen] = ingredient
queue.remove(allergen)
queue.values.forEach { it.remove(ingredient) }
}
// println("${allergens.keys.sorted().joinToString(",")} translate to")
return allergens.toSortedMap().values.joinToString(",")
}
}
@ExperimentalTime
@Suppress("UNUSED_PARAMETER")
fun main(args: Array<String>) {
val lines = generateSequence(::readLine).toList()
print("part1: ")
TimeSource.Monotonic.measureTimedValue { Part1.solve(lines.asSequence()) }.let {
println(it.value)
System.err.println("Completed in ${it.duration}")
}
print("part2: ")
TimeSource.Monotonic.measureTimedValue { Part2.solve(lines.asSequence()) }.let {
println(it.value)
System.err.println("Completed in ${it.duration}")
}
}
| 0 | Julia | 1 | 5 | f2d6dbb67d41f8f2898dbbc6a98477d05473888f | 3,760 | adventofcode | MIT License |
src/main/kotlin/com/hj/leetcode/kotlin/problem1129/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem1129
/**
* LeetCode page: [1129. Shortest Path with Alternating Colors](https://leetcode.com/problems/shortest-path-with-alternating-colors/);
*/
class Solution {
/* Complexity:
* Time O(n + e) and Space (e) where e is the sum of redEdges' size and blueEdges' size;
*/
fun shortestAlternatingPaths(n: Int, redEdges: Array<IntArray>, blueEdges: Array<IntArray>): IntArray {
val redEdgeMap = buildEdgesInMap(redEdges)
val blueEdgeMap = buildEdgesInMap(blueEdges)
val redEndQueue = ArrayDeque<Int>()
val blueEndQueue = ArrayDeque<Int>()
val shortestDistance = IntArray(n) { -1 }
var currDistance = 0
redEndQueue.add(0)
blueEndQueue.add(0)
while (redEndQueue.isNotEmpty() || blueEndQueue.isNotEmpty()) {
val numRedEnds = redEndQueue.size
val numBlueEnds = blueEndQueue.size
repeat(numRedEnds) {
val redEnd = redEndQueue.removeFirst()
if (shortestDistance[redEnd] == -1) {
shortestDistance[redEnd] = currDistance
}
val nextBlueEnds = blueEdgeMap[redEnd] ?: mutableListOf()
for (blueEnd in nextBlueEnds) {
blueEndQueue.addLast(blueEnd)
}
blueEdgeMap.remove(redEnd)
}
repeat(numBlueEnds) {
val blueEnd = blueEndQueue.removeFirst()
if (shortestDistance[blueEnd] == -1) {
shortestDistance[blueEnd] = currDistance
}
val nextRedEnds = redEdgeMap[blueEnd] ?: mutableListOf()
for (redEnd in nextRedEnds) {
redEndQueue.addLast(redEnd)
}
redEdgeMap.remove(blueEnd)
}
currDistance++
}
return shortestDistance
}
private fun buildEdgesInMap(edges: Array<IntArray>): MutableMap<Int, MutableList<Int>> {
val e = hashMapOf<Int, MutableList<Int>>()
for ((u, v) in edges) {
e.computeIfAbsent(u) { mutableListOf() }.add(v)
}
return e
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 2,214 | hj-leetcode-kotlin | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/TwoOutOfThree.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import java.util.stream.Collectors
import java.util.stream.IntStream
/**
* 2032. Two Out of Three
* @see <a href="https://leetcode.com/problems/two-out-of-three">Source</a>
*/
fun interface TwoOutOfThree {
operator fun invoke(nums1: IntArray, nums2: IntArray, nums3: IntArray): List<Int>
companion object {
const val ARR_SIZE = 101
}
}
class TwoOutOfThreeImpl : TwoOutOfThree {
override operator fun invoke(nums1: IntArray, nums2: IntArray, nums3: IntArray): List<Int> {
val list: MutableList<Int> = ArrayList()
val count = Array(3) { IntArray(TwoOutOfThree.ARR_SIZE) }
for (n in nums1) count[0][n] = 1
for (n in nums2) count[1][n] = 1
for (n in nums3) count[2][n] = 1
for (i in 1 until TwoOutOfThree.ARR_SIZE) {
if (count[0][i] + count[1][i] + count[2][i] > 1) list.add(i)
}
return list
}
}
class TwoOutOfThreeStream : TwoOutOfThree {
override operator fun invoke(nums1: IntArray, nums2: IntArray, nums3: IntArray): List<Int> {
val a = arrayOf(nums1, nums2, nums3)
val c = Array(3) { IntArray(TwoOutOfThree.ARR_SIZE) }
for (i in a.indices) for (n in a[i]) c[i][n] = 1
return IntStream.range(1, TwoOutOfThree.ARR_SIZE).filter { n -> c[0][n] + c[1][n] + c[2][n] >= 2 }.boxed()
.collect(Collectors.toList())
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,016 | kotlab | Apache License 2.0 |
src/main/kotlin/day04/solution.kt | bukajsytlos | 433,979,778 | false | {"Kotlin": 63913} | package day04
import java.io.File
fun main() {
var drawnNumbers: List<Int> = listOf()
var bingoBoards: List<BingoBoard> = listOf()
File("src/main/kotlin/day04/input.txt").useLines { seq ->
val iterator = seq.iterator()
drawnNumbers = List(1) { iterator.next() }.single().split(",").map { it.toInt() }
bingoBoards = iterator.asSequence()
.filter { it.isNotEmpty() }
.chunked(5)
.map { BingoBoard(it.map { it.split(" ").filter { it.isNotEmpty() }.map { it.toInt() } }.toList()) }
.toList()
}
for (drawnNumber in drawnNumbers) {
val indexOfWinningBoard = bingoBoards.indexOfFirst { it.isWinning(drawnNumber) }
if (indexOfWinningBoard != -1) {
println(drawnNumber * bingoBoards[indexOfWinningBoard].unmarkedNumbers().sum())
break
}
}
val notYetWonBoards = ArrayList(bingoBoards)
val wonBoards = mutableListOf<BingoBoard>()
for (drawnNumber in drawnNumbers) {
val wonBoardsForDrawnNumber = notYetWonBoards.filter { it.isWinning(drawnNumber) }
wonBoards.addAll(wonBoardsForDrawnNumber)
notYetWonBoards.removeAll(wonBoardsForDrawnNumber)
if (notYetWonBoards.isEmpty()) {
println(drawnNumber * wonBoards.last().unmarkedNumbers().sum())
break
}
}
}
class BingoBoard(private val board: List<List<Int>>) {
private val markedNumbers: MutableList<Int> = mutableListOf()
fun isWinning(drawnNumber: Int): Boolean {
board.forEach {
if (it.contains(drawnNumber)) {
markedNumbers.add(drawnNumber)
}
}
return checkBoard()
}
private fun checkBoard(): Boolean {
return board.any {
it.all { it in markedNumbers }
} || (0..4).map { column ->
board.map { it[column] }
}.any {
it.all { it in markedNumbers }
}
}
fun unmarkedNumbers(): List<Int> = board.flatten().filter { it !in markedNumbers }
} | 0 | Kotlin | 0 | 0 | f47d092399c3e395381406b7a0048c0795d332b9 | 2,060 | aoc-2021 | MIT License |
src/main/kotlin/days/Solution13.kt | Verulean | 725,878,707 | false | {"Kotlin": 62395} | package days
import adventOfCode.InputHandler
import adventOfCode.Solution
import adventOfCode.util.PairOf
import kotlin.math.min
object Solution13 : Solution<List<CharGrid>>(AOC_YEAR, 13) {
override fun getInput(handler: InputHandler) = handler.getInput("\n\n")
.map { it.split('\n').map(String::toCharArray).toTypedArray() }
private fun mirrorIndices(i: Int, length: Int) = (0 until min(i, length - i)).map { i - it - 1 to i + it }
private fun CharGrid.getReflectionScore(smudges: Int): Int {
(1 until this.size).forEach { i ->
val indices = mirrorIndices(i, this.size)
val errors = this[0].indices
.sumOf { j -> indices.filter { this[it.first][j] != this[it.second][j] }.size }
if (errors == smudges) return 100 * i
}
(1 until this[0].size).forEach { j ->
val indices = mirrorIndices(j, this[0].size)
val errors = this.sumOf { row -> indices.filter { row[it.first] != row[it.second] }.size }
if (errors == smudges) return j
}
throw Exception("unreachable")
}
override fun solve(input: List<CharGrid>): PairOf<Int> {
val ans1 = input.sumOf { it.getReflectionScore(0) }
val ans2 = input.sumOf { it.getReflectionScore(1) }
return ans1 to ans2
}
}
| 0 | Kotlin | 0 | 1 | 99d95ec6810f5a8574afd4df64eee8d6bfe7c78b | 1,336 | Advent-of-Code-2023 | MIT License |
backend/src/main/kotlin/Verifier.kt | lounres | 448,685,049 | true | {"Kotlin": 75138, "JavaScript": 2316, "HTML": 1022} | import java.lang.Integer.max
import java.lang.Integer.min
operator fun Coords.minus(other: Coords): Coords {
return Coords(this.row - other.row, this.column - other.column)
}
fun Coords.norm(): Int {
return this.row * this.row + this.column * this.column
}
infix fun Coords.cross(other: Coords): Int {
return this.row * other.column - this.column * other.row
}
fun area(A: Coords, B: Coords, C: Coords): Int {
return (B - A) cross (C - A)
}
fun intersect1(_a: Int, _b: Int, _c: Int, _d: Int): Boolean {
var a = _a
var b = _b
var c = _c
var d = _d
if (a > b) a = b.also { b = a }
if (c > d) c = d.also { d = c }
return max(a, c) <= min(b, d)
}
fun intersect(A: Coords, B: Coords, C: Coords, D: Coords): Boolean {
return intersect1 (A.row, B.row, C.row, D.row)
&& intersect1 (A.column, B.column, C.column, D.column)
&& area(A, B, C) * area(A, B, D) <= 0
&& area(C, D, A) * area(C, D, B) <= 0
}
fun checkPolyline(n: Int, m: Int, polyline: List<Coords>): Pair<Boolean, String> {
for (pt in polyline) {
if (!(pt.row >= 0 && pt.column >= 0 && pt.row < n && pt.column < m)) {
return Pair(false, "A point out of bounds")
}
}
for (i in 1..polyline.lastIndex) {
if ((polyline[i] - polyline[i - 1]).norm() != 5) {
return Pair(false, "A segment is not a knight move")
}
}
for (i in 2..polyline.lastIndex) {
for (j in 1..i - 2) {
if (intersect(polyline[i], polyline[i - 1], polyline[j], polyline[j - 1])) {
return Pair(false, "Segments intersect")
}
}
}
return Pair(true, "")
}
fun verify(claim: Claim): Pair<Boolean, String> {
if (claim.solution.isEmpty()) {
return Pair(false, "Empty solution")
}
if (claim.solution[0] != claim.field.start) {
return Pair(false, "The polyline doesn't start where it should")
}
if (claim.solution.last() != claim.field.end) {
return Pair(false, "The polyline doesn't end where it should")
}
if (claim.solution.toSet().size != claim.solution.size) {
return Pair(false, "Repeating nodes")
}
return checkPolyline(claim.field.size.rows, claim.field.size.columns, claim.solution)
}
| 0 | null | 0 | 0 | b11b94347644c8f2a03e585f862f538a22d95ae9 | 2,298 | KotlinLine | MIT License |
src/main/kotlin/org/deafsapps/adventofcode/day01/part02/Main.kt | pablodeafsapps | 733,033,603 | false | {"Kotlin": 6685} | package org.deafsapps.adventofcode.day01.part02
import org.deafsapps.adventofcode.day01.part01.concatFirstAndLastDigit
import java.io.File
import java.util.Scanner
fun main() {
val input = Scanner(File("src/main/resources/day01-data.txt"))
val digitsList = mutableListOf<Int>()
while (input.hasNext()) {
val updatedLine = input.nextLine().formatNonNumericDigits().parseDigits()
val twoDigitNumber = concatFirstAndLastDigit(line = updatedLine) ?: continue
digitsList.add(twoDigitNumber)
}
val sum = digitsList.reduce { acc, next -> acc + next }
println(sum)
}
private fun String.formatNonNumericDigits(): String = lowercase().replace(regex = allDigitsRegex) { matchResult ->
when (matchResult.value) {
"zero" -> "zeroo"
"one" -> "onee"
"two" -> "twoo"
"three" -> "threee"
"four" -> "fourr"
"five" -> "fivee"
"six" -> "sixx"
"seven" -> "sevenn"
"eight" -> "eightt"
"nine" -> "ninee"
else -> ""
}
}
private fun String.parseDigits(): String = lowercase().replace(regex = allDigitsRegex) { matchResult ->
when (matchResult.value) {
"zero" -> "0"
"one" -> "1"
"two" -> "2"
"three" -> "3"
"four" -> "4"
"five" -> "5"
"six" -> "6"
"seven" -> "7"
"eight" -> "8"
"nine" -> "9"
else -> ""
}
}
private val allDigitsRegex: Regex =
"""zero|one|two|three|four|five|six|seven|eight|nine|""".toRegex()
| 0 | Kotlin | 0 | 0 | 3a7ea1084715ab7c2ab1bfa8a1a7e357aa3c4b40 | 1,535 | advent-of-code_2023 | MIT License |
src/problems/day1/dayone.kt | klnusbaum | 733,782,662 | false | {"Kotlin": 43060} | package problems.day1
import java.io.File
private const val calibrationValues = "input/day1/calibration_values.txt"
fun main() {
part1()
part2()
}
private fun part1() {
val sum = File(calibrationValues)
.bufferedReader()
.useLines { sumLines(it) }
println("Sum of values is $sum")
}
private fun sumLines(lines: Sequence<String>) = lines.map { parseLine(it) }.sum()
private fun parseLine(input: String): Int {
val numbers = input.filter { c -> c in '0'..'9' }
return "${numbers.first()}${numbers.last()}".toInt()
}
private fun part2() {
val sum = File(calibrationValues)
.bufferedReader()
.useLines { sumLinesV2(it) }
println("Sum of values is $sum")
}
private fun sumLinesV2(lines: Sequence<String>) = lines.map { parseLineV2(it) }.sum()
private fun parseLineV2(input: String): Int {
val first = input.findAnyOf(numTargets)?.second?.toNumString()
val last = input.findLastAnyOf(numTargets)?.second?.toNumString()
return "$first$last".toInt()
}
private val numTargets = listOf(
"1", "2", "3", "4", "5", "6", "7", "8", "9",
"one", "two", "three", "four", "five", "six", "seven", "eight", "nine"
)
private fun String.toNumString() = when (this) {
"one" -> "1"
"two" -> "2"
"three" -> "3"
"four" -> "4"
"five" -> "5"
"six" -> "6"
"seven" -> "7"
"eight" -> "8"
"nine" -> "9"
else -> this
} | 0 | Kotlin | 0 | 0 | d30db2441acfc5b12b52b4d56f6dee9247a6f3ed | 1,421 | aoc2023 | MIT License |
src/main/kotlin/string/IsNumer.kt | ghonix | 88,671,637 | false | null | package string
/**
* https://leetcode.com/problems/valid-number/description/
*/
class IsNumer {
enum class TokenType {
DIGIT,
SIGN,
DOT,
EXPONENT,
INVALID
}
private val dfa = hashMapOf(
Pair(0, hashMapOf(Pair(TokenType.DIGIT, 1), Pair(TokenType.SIGN, 2), Pair(TokenType.DOT, 3))), // Start
Pair(1, hashMapOf(Pair(TokenType.DIGIT, 1), Pair(TokenType.DOT, 4), Pair(TokenType.EXPONENT, 5))), // digit
Pair(2, hashMapOf(Pair(TokenType.DIGIT, 1), Pair(TokenType.DOT, 3))), // optional sign
Pair(3, hashMapOf(Pair(TokenType.DIGIT, 4))), // dot
Pair(
4,
hashMapOf(Pair(TokenType.DIGIT, 4), Pair(TokenType.EXPONENT, 5))
), // this is the digit state after a dot
Pair(5, hashMapOf(Pair(TokenType.DIGIT, 7), Pair(TokenType.SIGN, 6))), // exponent
Pair(6, hashMapOf(Pair(TokenType.DIGIT, 7))), // sign after exponent e+
Pair(7, hashMapOf(Pair(TokenType.DIGIT, 7))) // digit after exponent e7
)
private val validStates = setOf(1, 4, 7)
fun isNumber(s: String): Boolean {
var state = 0
for (token in s) {
val tokenType = getTokenType(token)
if (tokenType == TokenType.INVALID) {
return false
} else {
val tempState = transition(state, tokenType)
if (tempState == null) {
return false
} else {
state = tempState
}
}
}
return isValidEndState(state)
}
private fun isValidEndState(state: Int): Boolean {
return validStates.contains(state)
}
private fun transition(state: Int, tokenType: TokenType): Int? {
val currentState = dfa[state]
return currentState?.let { it[tokenType] }
}
private fun getTokenType(token: Char): TokenType {
return when (token) {
'+' -> TokenType.SIGN
'-' -> TokenType.SIGN
'.' -> TokenType.DOT
in '0'..'9' -> TokenType.DIGIT
in "eE" -> TokenType.EXPONENT
else -> TokenType.INVALID
}
}
}
fun main() {
println(IsNumer().isNumber("a+1"))
println(IsNumer().isNumber("1"))
println(IsNumer().isNumber("+123"))
println(IsNumer().isNumber(".1"))
println(IsNumer().isNumber("+1e3"))
println(IsNumer().isNumber("+1e3.5"))
println(IsNumer().isNumber("+1E3.5"))
println(IsNumer().isNumber("+1E-356"))
println(IsNumer().isNumber("+1E+3"))
println(IsNumer().isNumber("+1.0E+3"))
println(IsNumer().isNumber("+1.234E+3"))
println(IsNumer().isNumber(".E3"))
} | 0 | Kotlin | 0 | 2 | 25d4ba029e4223ad88a2c353a56c966316dd577e | 2,794 | Problems | Apache License 2.0 |
src/main/kotlin/year2022/Day20.kt | forketyfork | 572,832,465 | false | {"Kotlin": 142196} | package year2022
import utils.nextIndexOf
import utils.prevIndexOf
class Day20(input: String) {
private val numbers = input.lines().map(String::toLong)
inner class Node(val value: Long) {
var prev: Node? = null
var next: Node? = null
fun shift() {
val shift = value.mod(numbers.size - 1)
if (shift == 0) {
return
}
val before = nextNode(shift)
val after = before.next!!
prev!!.next = next
next!!.prev = prev
before.next = this
after.prev = this
prev = before
next = after
}
fun nextNode(shift: Int) = generateSequence(this) { it.next }.take(shift + 1).last()
}
private fun List<Node>.mix(num: Int) = repeat(num) { forEach(Node::shift) }
private fun List<Node>.zero() = find { it.value == 0L }!!
fun part1() = solution(1, 1L)
fun part2() = solution(10, 811589153L)
fun solution(mixes: Int, multiplier: Long): Long {
val nodes = numbers.map { it * multiplier }.map(::Node)
nodes.forEachIndexed { idx, node ->
node.next = nodes[idx.nextIndexOf(nodes)]
node.prev = nodes[idx.prevIndexOf(nodes)]
}
nodes.mix(mixes)
return generateSequence(nodes.zero()) { it.nextNode(1000) }.drop(1).take(3).sumOf { it.value }
}
}
| 0 | Kotlin | 0 | 0 | 5c5e6304b1758e04a119716b8de50a7525668112 | 1,407 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/AlienDictionary.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import dev.shtanko.algorithms.ALPHABET_LETTERS_COUNT
import java.util.LinkedList
import java.util.Queue
import kotlin.math.min
/**
* 269. Alien Dictionary
* @see <a href="https://leetcode.com/problems/alien-dictionary">Source</a>
*/
fun interface AlienDictionary {
operator fun invoke(words: Array<String>): String
}
/**
* Approach 1: Breadth-First Search
* Time complexity : O(C).
*/
class AlienDictionaryBFS : AlienDictionary {
override fun invoke(words: Array<String>): String {
val adjList: MutableMap<Char, MutableList<Char>> = HashMap()
val counts: MutableMap<Char, Int> = HashMap()
initializeDataStructures(words, adjList, counts)
if (!findEdges(words, adjList, counts)) {
return ""
}
return breadthFirstSearch(adjList, counts)
}
private fun initializeDataStructures(
words: Array<String>,
adjList: MutableMap<Char, MutableList<Char>>,
counts: MutableMap<Char, Int>,
) {
for (word in words) {
for (c in word.toCharArray()) {
counts[c] = 0
adjList[c] = ArrayList()
}
}
}
private fun findEdges(
words: Array<String>,
adjList: MutableMap<Char, MutableList<Char>>,
counts: MutableMap<Char, Int>,
): Boolean {
for (i in 0 until words.size - 1) {
val word1 = words[i]
val word2 = words[i + 1]
if (word1.length > word2.length && word1.startsWith(word2)) {
return false
}
for (j in 0 until min(word1.length, word2.length)) {
if (word1[j] != word2[j]) {
adjList[word1[j]]?.add(word2[j])
counts[word2[j]] = counts.getOrDefault(word2[j], 0).plus(1)
break
}
}
}
return true
}
private fun breadthFirstSearch(
adjList: Map<Char, MutableList<Char>>,
counts: MutableMap<Char, Int>,
): String {
val sb = StringBuilder()
val queue: Queue<Char> = LinkedList()
for (c in counts.keys) {
if (counts[c] == 0) {
queue.add(c)
}
}
while (queue.isNotEmpty()) {
val c: Char = queue.remove()
sb.append(c)
for (next in adjList.getOrDefault(c, emptyList())) {
counts[next] = counts.getOrDefault(next, 0) - 1
if (counts[next] == 0) {
queue.add(next)
}
}
}
return if (sb.length < counts.size) {
""
} else {
sb.toString()
}
}
}
/**
* Approach 2: Depth-First Search
* Time complexity : O(C).
*/
class AlienDictionaryDFS : AlienDictionary {
override fun invoke(words: Array<String>): String {
val adj = Array(ALPHABET_LETTERS_COUNT) { BooleanArray(ALPHABET_LETTERS_COUNT) }
val visited = IntArray(ALPHABET_LETTERS_COUNT) { -1 }
buildGraph(words, adj, visited)
val sb = StringBuilder()
for (i in 0 until ALPHABET_LETTERS_COUNT) {
// unvisited
if (visited[i] == 0 && !dfs(adj, visited, sb, i)) {
return ""
}
}
return sb.reverse().toString()
}
/**
* Depth-first search (DFS) algorithm for traversing a graph.
*
* This method performs a depth-first search traversal starting from the given node `i`
* in the graph represented by the adjacent matrix `adj`.
*
* @param adj The adjacency matrix representing the connections between graph nodes.
* @param visited The array representing the visited status of graph nodes.
* @param sb The `StringBuilder` used to store the visited nodes in the DFS traversal order.
* @param i The index of the current node being visited.
* @return `true` if the DFS traversal is successful, `false` if a cycle is detected.
*/
private fun dfs(adj: Array<BooleanArray>, visited: IntArray, sb: StringBuilder, i: Int): Boolean {
visited[i] = 1 // 1 = visiting
for (j in 0 until ALPHABET_LETTERS_COUNT) {
if (adj[i][j]) {
if (visited[j] == 1) return false
if (visited[j] == 0 && !dfs(adj, visited, sb, j)) {
return false
}
}
}
visited[i] = 2 // 2 = visited
sb.append((i + 'a'.code).toChar())
return true
}
/**
* Builds a graph based on the given array of words, assigning adjacency values and visited status to the
* graph nodes.
*
* @param words The array of words representing the graph nodes.
* @param adj The adjacency matrix representing the connections between graph nodes.
* @param visited The array representing the visited status of graph nodes.
*/
private fun buildGraph(words: Array<String>, adj: Array<BooleanArray>, visited: IntArray) {
if (words.isEmpty()) return
var pre = words[0].toCharArray()
for (k in pre.indices) visited[pre[k] - 'a'] = 0
for (i in 1 until words.size) {
val cur = words[i].toCharArray()
for (k in cur.indices) visited[cur[k] - 'a'] = 0
val length = min(pre.size, cur.size)
for (j in 0 until length) {
if (cur[j] != pre[j]) {
adj[pre[j] - 'a'][cur[j] - 'a'] = true
break
}
}
pre = cur
}
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 6,239 | kotlab | Apache License 2.0 |
shared/src/commonMain/kotlin/io/github/andremion/slidingpuzzle/domain/puzzle/PuzzleState.kt | andremion | 750,744,594 | false | {"Kotlin": 62332, "Swift": 659} | package io.github.andremion.slidingpuzzle.domain.puzzle
import kotlin.math.sqrt
data class PuzzleState @Throws(IllegalArgumentException::class) constructor(
val tiles: List<Int>
) {
data class TilePosition(
val row: Int,
val column: Int
)
val matrixSize = sqrt(tiles.size.toDouble()).toInt()
init {
require(sqrt(tiles.size.toDouble()) % 1.0 == 0.0) {
"The tiles must represent a square matrix"
}
val check = List(tiles.size) { it }
require(tiles.sorted() == check) {
"The tiles must contain only a range from zero to the size - 1"
}
}
override fun toString(): String {
val maxTileLength = tiles.max().toString().length
return "\n" +
tiles.chunked(matrixSize)
.joinToString(separator = "\n") { row ->
row.joinToString(separator = "") { tile ->
"[${tile.toString().padStart(length = maxTileLength)}]"
}
}
}
}
/**
* Get the position of the tile in the matrix.
*/
fun PuzzleState.getPosition(tile: Int): PuzzleState.TilePosition {
val indexOf = tiles.indexOf(tile)
indexOf != -1 || error("Tile #$tile not found")
return PuzzleState.TilePosition(
row = indexOf / matrixSize,
column = indexOf % matrixSize
)
}
/**
* Get the next possible states (successors) which can be reached from the current state.
*/
fun PuzzleState.getSuccessors(): List<PuzzleState> {
val states = mutableListOf<PuzzleState>()
val blankPosition = getPosition(0)
var newPosition: PuzzleState.TilePosition
if (blankPosition.row > 0) { // can we move up?
newPosition = blankPosition.copy(row = blankPosition.row - 1)
states.add(permuted(blankPosition, newPosition))
}
if (blankPosition.row < matrixSize - 1) { // can we move down?
newPosition = blankPosition.copy(row = blankPosition.row + 1)
states.add(permuted(blankPosition, newPosition))
}
if (blankPosition.column > 0) { // can we move left?
newPosition = blankPosition.copy(column = blankPosition.column - 1)
states.add(permuted(blankPosition, newPosition))
}
if (blankPosition.column < matrixSize - 1) { // can we move right?
newPosition = blankPosition.copy(column = blankPosition.column + 1)
states.add(permuted(blankPosition, newPosition))
}
return states
}
fun PuzzleState.permuted(a: PuzzleState.TilePosition, b: PuzzleState.TilePosition): PuzzleState {
val indexA = indexOf(a)
val indexB = indexOf(b)
val permuted = buildList {
addAll(tiles)
val tmp = this[indexB]
this[indexB] = this[indexA]
this[indexA] = tmp
}
return PuzzleState(permuted)
}
fun PuzzleState.indexOf(position: PuzzleState.TilePosition): Int =
position.row * matrixSize + position.column
| 0 | Kotlin | 0 | 0 | 8f8b9c40b5e1e212fd99fd71e4f2a5f1ce63bf6c | 2,936 | SlidingPuzzle | Apache License 2.0 |
src/day03/Day03.kt | Ciel-MC | 572,868,010 | false | {"Kotlin": 55885} | package day03
import readInput
fun main() {
val charToIntMap =
(('a'..'z') + ('A'..'Z')).withIndex().associate { (i, c) -> c to i + 1 }
fun Char.charToInt(): Int {
return charToIntMap[this]!!
}
fun part1(input: List<String>): Int {
return input.sumOf {
assert(it.length % 2 == 0)
val a = it.subSequence(0, it.length / 2)
it.subSequence(it.length / 2, it.length).first { it in a }.charToInt()
}
}
fun part2(input: List<String>): Int {
return input.chunked(3).sumOf { (a, b, c) ->
a.first { it in b && it in c }.charToInt()
}
}
val testInput = readInput(3, true)
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput(3)
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 7eb57c9bced945dcad4750a7cc4835e56d20cbc8 | 849 | Advent-Of-Code | Apache License 2.0 |
src/day17/Day17.kt | HGilman | 572,891,570 | false | {"Kotlin": 109639, "C++": 5375, "Python": 400} | package day17
import lib.LeftDirection
import lib.DecreaseYDirection
import lib.Point2D
import lib.RightDirection
import lib.Vector2D
import readText
const val chamberWidth = 7
const val xStart = 2 // from 0 counting
const val yOffsetFromTop = 3
fun main() {
val day = 17
val testInput = readText("day$day/testInput")
// val res1 = part2(testInput, 2022)
// println(res1)
// check(res1 == 3068L)
val input = readText("day$day/input")
// println(part2(input, 20_000))
println(part2(input, 1752 + 1408))
}
// system of coordinate from bottom to top
// origin point of rocks is the leftest bottom point
data class Rock(val id: Int, val vectors: List<Vector2D>) {
fun width(): Int = vectors.maxOf { it.x }
fun height(): Int = vectors.maxOf { it.y } + 1
}
val firstRock = Rock(
0,
listOf(
Vector2D(0, 0), Vector2D(1, 0), Vector2D(2, 0), Vector2D(3, 0)
)
)
val secondRock = Rock(
1,
listOf(
Vector2D(1, 0), Vector2D(0, 1), Vector2D(1, 1), Vector2D(2, 1), Vector2D(1, 2)
)
)
val thirdRock = Rock(
2,
listOf(
Vector2D(0, 0), Vector2D(1, 0), Vector2D(2, 0), Vector2D(2, 1), Vector2D(2, 2)
)
)
val fouthRock = Rock(
3,
listOf(
Vector2D(0, 0), Vector2D(0, 1), Vector2D(0, 2), Vector2D(0, 3)
)
)
val fivthRock = Rock(
4,
listOf(
Vector2D(0, 0), Vector2D(1, 0), Vector2D(0, 1), Vector2D(1, 1)
)
)
val rocks = listOf<Rock>(
firstRock, secondRock, thirdRock, fouthRock, fivthRock
)
enum class PushDirection {
LEFT, RIGHT
}
data class TypedPoint(val point: Point2D, val isRock: Boolean) {
private val rockSymbol = '#'
private val airSymbol = '.'
fun getSymbol() = if (isRock) rockSymbol else airSymbol
}
fun parseInput(input: String): List<PushDirection> {
return input.map {
if (it == '<') {
PushDirection.LEFT
} else {
PushDirection.RIGHT
}
}
}
fun getRock(index: Long): Rock = rocks[(index % rocks.size).toInt()]
fun part1(input: String, rockAmount: Long): Int {
val dirs = parseInput(input)
var rockCounter = 1L
var directionIndex = 0
var currentTop = 0
val chamber: MutableList<MutableList<TypedPoint>> = MutableList(3) { y ->
MutableList(chamberWidth) { x ->
TypedPoint(Point2D(x, y), false)
}
}
while (rockCounter != rockAmount + 1) {
val rock = getRock(rockCounter - 1L)
val neededHeight = currentTop + yOffsetFromTop + rock.height()
val addAmount = neededHeight - chamber.size
// increase chamber height to rock's height
val currentChamberHeight = chamber.size
(1..addAmount).forEach { dy ->
chamber.add(MutableList(chamberWidth) { x ->
TypedPoint(Point2D(x, currentChamberHeight + dy), isRock = false)
})
}
// origin position of current rock (left, bottom point)
var position = Point2D(xStart, currentTop + yOffsetFromTop)
var rockIsStill = false
while (!rockIsStill) {
// first process direction
when (dirs[directionIndex]) {
PushDirection.LEFT -> {
val newPosition = position.toLeft()
// first check if there is wall
if (newPosition.x >= 0) {
// iterate over each point of rock, and try to move it left, if there is rock -> it is not possible
if (
rock.vectors.all { v ->
val checkPoint = position + v + LeftDirection
(checkPoint.x in (0 until chamberWidth) && !chamber[checkPoint.y][checkPoint.x].isRock)
}
) {
position = newPosition
}
}
}
PushDirection.RIGHT -> {
val newPosition = position.toRight()
// first check if there is wall
if (newPosition.x < chamberWidth) {
// iterate over each point of rock, and try to move it right, if there is rock -> it is not possible
if (
rock.vectors.all { v ->
val checkPoint = position + v + RightDirection
(checkPoint.x in (0 until chamberWidth) && !chamber[checkPoint.y][checkPoint.x].isRock)
}
) {
position = newPosition
}
}
}
}
directionIndex = (directionIndex + 1) % dirs.size
// try to move one step down
val newPosition = position.lower()
if (newPosition.y >= 0
&& rock.vectors.all { v ->
val checkPoint = position + v + DecreaseYDirection
!chamber[checkPoint.y][checkPoint.x].isRock
}
) {
position = newPosition
} else {
rockIsStill = true
}
}
// saving rock position to chamber array
rock.vectors.forEach { v ->
val p = position + v
val currentChamberPointState = chamber[p.y][p.x]
chamber[p.y][p.x] = currentChamberPointState.copy(isRock = true)
}
rockCounter++
val newTop = position.y + rock.height()
if (newTop > currentTop) {
currentTop = newTop
}
}
println()
println("rockIndex: $rockCounter")
println()
printChamber(chamber)
Thread.sleep(10L)
return currentTop
}
fun printChamber(chamber: List<List<TypedPoint>>) {
for (y in chamber.size - 1 downTo 0) {
for (x in 0 until chamberWidth) {
print(chamber[y][x].getSymbol() + " ")
}
println()
}
}
fun part2(input: String, rockAmount: Long): Long {
val dirs = parseInput(input)
var rockCounter = 1L
var lastEndDirRockCounter = 0L
var directionIndex = 0
var currentTop = 0
val tops = mutableListOf<Int>()
fun generateInitialState() = MutableList(3) { y ->
MutableList(chamberWidth) { x ->
TypedPoint(Point2D(x, y), false)
}
}
var chamber: MutableList<MutableList<TypedPoint>> = generateInitialState()
while (rockCounter != rockAmount + 1) {
val rock = getRock(rockCounter - 1)
val neededHeight = currentTop + yOffsetFromTop + rock.height()
val addAmount = neededHeight - chamber.size
// increase chamber height to rock's height
val currentChamberHeight = chamber.size
(1..addAmount).forEach { dy ->
chamber.add(MutableList(chamberWidth) { x ->
TypedPoint(Point2D(x, currentChamberHeight + dy), isRock = false)
})
}
// origin position of current rock (left, bottom point)
var position = Point2D(xStart, currentTop + yOffsetFromTop)
var rockIsStill = false
while (!rockIsStill) {
// first process direction
when (dirs[directionIndex]) {
PushDirection.LEFT -> {
val newPosition = position.toLeft()
// first check if there is wall
if (newPosition.x >= 0) {
// iterate over each point of rock, and try to move it left, if there is rock -> it is not possible
if (
rock.vectors.all { v ->
val checkPoint = position + v + LeftDirection
(checkPoint.x in (0 until chamberWidth) && !chamber[checkPoint.y][checkPoint.x].isRock)
}
) {
position = newPosition
}
}
}
PushDirection.RIGHT -> {
val newPosition = position.toRight()
// first check if there is wall
if (newPosition.x < chamberWidth) {
// iterate over each point of rock, and try to move it right, if there is rock -> it is not possible
if (
rock.vectors.all { v ->
val checkPoint = position + v + RightDirection
(checkPoint.x in (0 until chamberWidth) && !chamber[checkPoint.y][checkPoint.x].isRock)
}
) {
position = newPosition
}
}
}
}
directionIndex = (directionIndex + 1) % dirs.size
// try to move one step down
val newPosition = position.lower()
if (newPosition.y >= 0
&& rock.vectors.all { v ->
val checkPoint = position + v + DecreaseYDirection
!chamber[checkPoint.y][checkPoint.x].isRock
}
) {
position = newPosition
} else {
rockIsStill = true
}
}
// saving rock position to chamber array
rock.vectors.forEach { v ->
val p = position + v
val currentChamberPointState = chamber[p.y][p.x]
chamber[p.y][p.x] = currentChamberPointState.copy(isRock = true)
}
rockCounter++
val newTop = position.y + rock.height()
if (newTop > currentTop) {
currentTop = newTop
}
// cutoff chamber
if ((0 until 7).all { x ->
chamber[position.y][x].isRock
}) {
// println()
// println("Cutting off chamber, chamber now: ")
// printChamber(chamber)
val newChamberHeight = chamber.size - position.y - 1
// println("newChamberHeight: $newChamberHeight")
// copy all elements above cut offline
val leftPart = chamber.takeLast(newChamberHeight)
chamber = MutableList(newChamberHeight) { y ->
MutableList(chamberWidth) { x ->
TypedPoint(Point2D(x, y), isRock = leftPart[y][x].isRock)
}
}
// println("chamber after cutoff: ")
// printChamber(chamber)
// println("currentTop $currentTop")
// println()
val newCurrentTop = chamber.mapNotNull { it.find { it.isRock } }.lastOrNull()?.point?.y?.let { it + 1 } ?: 0
val newToAdd = currentTop - newCurrentTop
tops.add(newToAdd)
currentTop = newCurrentTop
// println("new currentTop $currentTop")
// println()
} // we processed last direction, if now surface is flat (new Current top == 0) then we found period
if (directionIndex == dirs.size - 1) {
println("end of directions, dirSize: ${dirs.size}")
println(tops)
printChamber(chamber)
println("rockcounter Diff: ${rockCounter - lastEndDirRockCounter}")
lastEndDirRockCounter = rockCounter
}
}
tops.add(currentTop)
println("tops: $tops")
return tops.fold(0L) { acc, it -> acc + it }
}
fun test(size: Long) {
var counter = 0L
// val list = (0..100).map { it * 2 }
while (counter < size) {
counter++
println(counter)
// list.forEach {}
}
} | 0 | Kotlin | 0 | 1 | d05a53f84cb74bbb6136f9baf3711af16004ed12 | 11,761 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/wtf/log/xmas2021/day/day12/Day12.kt | damianw | 434,043,459 | false | {"Kotlin": 62890} | package wtf.log.xmas2021.day.day12
import wtf.log.xmas2021.Day
import java.io.BufferedReader
object Day12 : Day<CaveSystem, Int, Int> {
override fun parseInput(reader: BufferedReader): CaveSystem {
return CaveSystem.parse(reader.lineSequence().asIterable())
}
override fun part1(input: CaveSystem): Int {
fun findAllPaths(
input: CaveSystem,
output: MutableSet<List<Cave>>,
path: List<Cave>,
currentCave: Cave,
) {
if (currentCave == Cave.END) {
output += path
return
}
for (adjacentCave in input[currentCave]) {
if (adjacentCave.type == Cave.Type.LARGE || adjacentCave !in path) {
findAllPaths(input, output, path + adjacentCave, adjacentCave)
}
}
}
val output = mutableSetOf<List<Cave>>()
findAllPaths(input, output, listOf(Cave.START), Cave.START)
return output.size
}
override fun part2(input: CaveSystem): Int {
fun findAllPaths(
input: CaveSystem,
output: MutableSet<List<Cave>>,
path: List<Cave>,
currentCave: Cave,
haveSelectedLuckyCave: Boolean,
) {
if (currentCave == Cave.END) {
output += path
return
}
for (adjacentCave in input[currentCave]) {
if (adjacentCave.type == Cave.Type.LARGE || adjacentCave !in path) {
findAllPaths(
input = input,
output = output,
path = path + adjacentCave,
currentCave = adjacentCave,
haveSelectedLuckyCave = haveSelectedLuckyCave,
)
} else if (!haveSelectedLuckyCave && adjacentCave != Cave.START && adjacentCave != Cave.END) {
findAllPaths(
input = input,
output = output,
path = path + adjacentCave,
currentCave = adjacentCave,
haveSelectedLuckyCave = true,
)
}
}
}
val output = mutableSetOf<List<Cave>>()
findAllPaths(input, output, listOf(Cave.START), Cave.START, false)
return output.size
}
}
class CaveSystem private constructor(
private val edges: Map<Cave, Set<Cave>>,
) {
operator fun get(cave: Cave): Set<Cave> = edges[cave].orEmpty()
companion object {
fun parse(lines: Iterable<String>): CaveSystem {
val edges = mutableMapOf<Cave, MutableSet<Cave>>()
for (line in lines) {
val split = line.split('-')
require(split.size == 2)
val left = Cave.parse(split[0])
val right = Cave.parse(split[1])
val leftEdges = edges.getOrPut(left, ::mutableSetOf)
val rightEdges = edges.getOrPut(right, ::mutableSetOf)
leftEdges += right
rightEdges += left
}
return CaveSystem(edges)
}
}
}
data class Cave(
val type: Type,
val symbol: String,
) {
enum class Type {
SMALL, LARGE,
}
companion object {
val START = Cave(Type.SMALL, "start")
val END = Cave(Type.SMALL, "end")
fun parse(text: String): Cave = Cave(
type = when {
text.isEmpty() -> error("Cave name must not be empty")
text.all { it.isUpperCase() } -> Type.LARGE
text.all { it.isLowerCase() } -> Type.SMALL
else -> error("Unsupported cave name: $text")
},
symbol = text,
)
}
}
| 0 | Kotlin | 0 | 0 | 1c4c12546ea3de0e7298c2771dc93e578f11a9c6 | 3,881 | AdventOfKotlin2021 | BSD Source Code Attribution |
src/Day09.kt | MerickBao | 572,842,983 | false | {"Kotlin": 28200} | import kotlin.math.abs
fun main() {
fun next(px: Int, py: Int, nx: Int, ny: Int): Array<Int> {
val diff = abs(px - nx) + abs(py - ny)
var x = nx
var y = ny
if (diff == 2) {
if (px == nx) {
if (py > ny) y++
else y--
} else if (py == ny) {
if (px > nx) x++
else x--
}
} else if (diff == 3) {
if (abs(px - nx) == 2) {
y = py
if (px > nx) x++
else x--
} else {
x = px
if (py > ny) y++
else y--
}
} else if (diff == 4) {
if (py > ny) y++
else y--
if (px > nx) x++
else x--
}
return arrayOf(x, y)
}
fun getDirection(s: String): Int {
if (s == "U") return 0
if (s == "D") return 1
if (s == "L") return 2
return 3
}
val dx = listOf(0, 0, -1, 1)
val dy = listOf(1, -1, 0, 0)
fun part(input: List<String>, size: Int): Int {
val queue = Array(size) { Array(2) { 0 } }
val all = HashSet<Int>()
all.add(0)
for (s in input) {
val now = s.split(" ")
val d = getDirection(now[0])
var step = now[1].toInt()
while (step-- > 0) {
queue[0][0] += dx[d]
queue[0][1] += dy[d]
for (i in 1 until size) {
queue[i] = next(queue[i - 1][0], queue[i - 1][1], queue[i][0], queue[i][1])
}
all.add(queue[size - 1][0] * 100000 + queue[size - 1][1])
}
}
return all.size
}
val input = readInput("Day09")
println(part(input, 2))
println(part(input, 10))
} | 0 | Kotlin | 0 | 0 | 70a4a52aa5164f541a8dd544c2e3231436410f4b | 1,851 | aoc-2022-in-kotlin | Apache License 2.0 |
dcp_kotlin/src/main/kotlin/dcp/day211/day211.kt | sraaphorst | 182,330,159 | false | {"C++": 577416, "Kotlin": 231559, "Python": 132573, "Scala": 50468, "Java": 34742, "CMake": 2332, "C": 315} | package dcp.day211
// day211.kt
// By <NAME>, 2019.
fun Char.hash(): Int = this.toInt() - 'a'.toInt() + 1
// Scan windows for substring.
fun findStartPoints(str: String, substr: String): Set<Int> {
require(str.length >= substr.length) { "Main string must be longer than substring" }
val strlen = str.length
val substrlen = substr.length
return (0..(strlen - substrlen)).filter {
start ->
str.subSequence(start, start + substrlen) == substr
}.toSet()
}
fun findStartPointsRollingHash(str: String, substr: String): Set<Int> {
require(str.length >= substr.length) { "Main string must be longer than substring" }
// Convert a character into an int.
val strLen = str.length
val substrLen = substr.length
// The hash of the substring.
val substrHash = substr.map { it.hash() }.sum()
// We start with a fully hashed string, so position 0 is the hash of the string str[0:substrLen].
val startHash = str.take(substrLen).map { it.hash() }.sum()
fun aux(pos: Int, hash: Int): Set<Int> {
// Check to see if the requirements are met for this to quality as a possible candidate.
val set = if (hash == substrHash && str.subSequence(pos, pos + substrLen) == substr) setOf (pos) else emptySet()
// Update the hash code if possible to get the new set of values.
val newset = if (pos + substrLen < strLen) {
val newHash = hash - str[pos].hash() + str[pos + substrLen].hash()
aux(pos + 1, newHash)
} else {
emptySet()
}
return set + newset
}
return aux(0, startHash)
}
| 0 | C++ | 1 | 0 | 5981e97106376186241f0fad81ee0e3a9b0270b5 | 1,648 | daily-coding-problem | MIT License |
src/Day01.kt | realpacific | 573,561,400 | false | {"Kotlin": 59236} | fun main() {
fun part1(input: List<String>): Int {
var currentCaloriesSum = 0
var maxCalories = Integer.MIN_VALUE
input.forEach {
if (it.isEmpty()) {
maxCalories = maxOf(maxCalories, currentCaloriesSum)
currentCaloriesSum = 0
} else {
currentCaloriesSum += it.toInt()
}
}
return maxCalories
}
fun part2(input: List<String>): Int {
val topThreeCalories = IntArray(3) { Integer.MIN_VALUE }
var currentCaloriesSum = 0
input.forEach {
if (it.isEmpty()) {
topThreeCalories.sort()
for (i in 0..topThreeCalories.lastIndex) {
if (topThreeCalories[i] < currentCaloriesSum) {
topThreeCalories[i] = currentCaloriesSum
break
}
}
currentCaloriesSum = 0
} else {
currentCaloriesSum += it.toInt()
}
}
return topThreeCalories.sum()
}
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f365d78d381ac3d864cc402c6eb9c0017ce76b8d | 1,194 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/day2/Day2.kt | alxgarcia | 435,549,527 | false | {"Kotlin": 91398} | package day2
import java.io.File
sealed interface SubmarineActions<out S : SubmarineActions<S>> {
fun moveForward(delta: Int): S
fun goUp(delta: Int): S
fun goDown(delta: Int): S = goUp(-delta)
}
data class Submarine1(val horizontal: Int, val depth: Int): SubmarineActions<Submarine1> {
companion object {
val fromStart: Submarine1
get() = Submarine1(0, 0)
}
override fun moveForward(delta: Int) = this.copy(horizontal = horizontal + delta)
override fun goUp(delta: Int) = this.copy(depth = depth - delta)
}
data class Submarine2(val horizontal: Int, val depth: Int, val aim: Int): SubmarineActions<Submarine2> {
companion object {
val fromStart: Submarine2
get() = Submarine2(0, 0, 0)
}
override fun moveForward(delta: Int) = this.copy(horizontal = horizontal + delta, depth = depth + aim * delta)
override fun goUp(delta: Int) = this.copy(aim = aim - delta)
}
fun <S : SubmarineActions<S>> processInstruction(current: S, instruction: String): S {
val (word, number) = instruction.split(" ")
val delta = number.toInt()
return when (word) {
"forward" -> current.moveForward(delta)
"up" -> current.goUp(delta)
"down" -> current.goDown(delta)
else -> current // ignore unrecognized command
}
}
fun computeFinalHorizontalPositionAndDepthProduct(instructions: List<String>): Int {
val s = instructions.fold(Submarine1.fromStart, ::processInstruction)
return s.horizontal * s.depth
}
fun computeFinalHorizontalPositionAndDepthProduct2(instructions: List<String>): Int {
val s = instructions.fold(Submarine2.fromStart, ::processInstruction)
return s.horizontal * s.depth
}
fun main() {
File("./input/day2.txt").useLines { lines ->
val instructions = lines.toList()
println("First value: ${computeFinalHorizontalPositionAndDepthProduct(instructions)}")
println("Second value: ${computeFinalHorizontalPositionAndDepthProduct2(instructions)}")
}
} | 0 | Kotlin | 0 | 0 | d6b10093dc6f4a5fc21254f42146af04709f6e30 | 1,936 | advent-of-code-2021 | MIT License |
src/day10/Day10.kt | easchner | 572,762,654 | false | {"Kotlin": 104604} | package day10
import readInputString
fun main() {
fun part1(input: List<String>): Int {
val cycles = Array(input.size * 2) { 1 }
var currentCycle = 1
var register = 1
for (line in input) {
if (line == "noop") {
currentCycle++
cycles[currentCycle] = register
} else {
val v = line.split(" ").last().toInt()
currentCycle++
cycles[currentCycle] = register
currentCycle++
register += v
cycles[currentCycle] = register
}
}
return listOf(20, 60, 100, 140, 180, 220).map { it * cycles[it] }.sum()
}
fun part2(input: List<String>): Int {
val cycles = Array(input.size * 2) { 1 }
var currentCycle = 0
var register = 1
for (line in input) {
if (line == "noop") {
currentCycle++
cycles[currentCycle] = register
} else {
val v = line.split(" ").last().toInt()
currentCycle++
cycles[currentCycle] = register
currentCycle++
register += v
cycles[currentCycle] = register
}
}
var output = ""
for (i in 0 until 6) {
for (j in 0 until 40) {
val spot = cycles[i*40 + j]
output += if (spot in (j-1)..(j+1)) {
"#"
} else {
" "
}
}
output += "\n"
}
println(output)
return 0
}
val testInput = readInputString("day10/test")
val input = readInputString("day10/input")
check(part1(testInput) == 13_140)
println(part1(input))
check(part2(testInput) == 0)
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 5966e1a1f385c77958de383f61209ff67ffaf6bf | 1,897 | Advent-Of-Code-2022 | Apache License 2.0 |
src/day19/Day19.kt | crmitchelmore | 576,065,911 | false | {"Kotlin": 115199} | package day19
import helpers.ReadFile
class Day19 {
class Blueprint {
val number: Int
val ore: Int
val clay: Int
val obsidian: Pair<Int, Int>
val geode: Pair<Int, Int>
val maxOre: Int
constructor(number: Int, ore: Int, clay: Int, obsidian: Pair<Int, Int>, geode: Pair<Int, Int>) {
this.number = number
this.ore = ore
this.clay = clay
this.obsidian = obsidian
this.geode = geode
this.maxOre = listOf(ore, clay, obsidian.first, geode.first).max()!!
}
}
//Blueprint 11: Each ore robot costs 2 ore. Each clay robot costs 4 ore. Each obsidian robot costs 4 ore and 17 clay. Each geode robot costs 3 ore and 11 obsidian.
val rlines = ReadFile.named("src/day19/input.txt")
val tlines = listOf(
// "1,4,4,4,14,3,16"
"1,4,2,3,14,2,7",
"2,2,3,3,8,3,12"
)
val lines = rlines.map {
val nums = it.split(",").map { it.toInt() }
Blueprint(nums[0], nums[1], nums[2], Pair(nums[3], nums[4]), Pair(nums[5], nums[6]))
}
val case = listOf(
"nothing", "nothing", "clay", "nothing", "clay", "nothing", "clay", "nothing", "nothing", "nothing", "obsidian", "clay", "nothing", "nothing", "obsidian", "nothing", "nothing", "geode", "nothing", "nothing", "geode", "nothing"
)
var currentBest = 0
fun stuff(blueprint: Blueprint, stepsRemaining: Int, ore: Pair<Int, Int>, clay: Pair<Int, Int>, obsidian: Pair<Int, Int>, geode: Pair<Int, Int>, path: List<String>) : Int {
if (stepsRemaining == 0) {
if (geode.second > currentBest) {
println("New best: ${geode.second} with path ${path}")
currentBest = geode.second
}
return geode.second
}
if (stepsRemaining < 10) {
val maxPotential = geode.second + geode.first * stepsRemaining + ((stepsRemaining-1) * (stepsRemaining)/2)
if (maxPotential < currentBest) {
return 0
}
}
var results = mutableListOf<Int>()
// if (path == case) {
// println(path)
// }
if (ore.second >= blueprint.ore && ore.first <= blueprint.maxOre) {
results.add(stuff(blueprint, stepsRemaining - 1, Pair(ore.first + 1, ore.second - blueprint.ore + ore.first), Pair(clay.first, clay.second + clay.first), Pair(obsidian.first, obsidian.second + obsidian.first), Pair(geode.first, geode.second + geode.first), path + "ore"))
}
if (ore.second >= blueprint.clay && clay.first <= blueprint.obsidian.second) {
results.add(stuff(blueprint, stepsRemaining - 1, Pair(ore.first, ore.second + ore.first - blueprint.clay), Pair(clay.first + 1, clay.second + clay.first), Pair(obsidian.first, obsidian.second + obsidian.first), Pair(geode.first, geode.second + geode.first), path + "clay"))
}
if (ore.second >= blueprint.obsidian.first && clay.second >= blueprint.obsidian.second && obsidian.first <= blueprint.geode.second) {
results.add(stuff(blueprint, stepsRemaining - 1, Pair(ore.first, ore.second + ore.first - blueprint.obsidian.first), Pair(clay.first, clay.second + clay.first - blueprint.obsidian.second), Pair(obsidian.first + 1, obsidian.second + obsidian.first), Pair(geode.first, geode.second + geode.first), path + "obsidian"))
}
if (ore.second >= blueprint.geode.first && obsidian.second >= blueprint.geode.second) {
results.add(stuff(blueprint, stepsRemaining - 1, Pair(ore.first, ore.second + ore.first - blueprint.geode.first), Pair(clay.first, clay.second + clay.first), Pair(obsidian.first, obsidian.second + obsidian.first - blueprint.geode.second), Pair(geode.first + 1, geode.second + geode.first), path + "geode"))
}
results.add(stuff(blueprint, stepsRemaining - 1, Pair(ore.first, ore.second + ore.first), Pair(clay.first, clay.second + clay.first), Pair(obsidian.first, obsidian.second + obsidian.first), Pair(geode.first, geode.second + geode.first),path + "nothing"))
return results.max()!!
}
fun result1() {
// val totals = lines.map { blueprint ->
// currentBest = 0
// val geodes = stuff(blueprint, 24, Pair(1, 0), Pair(0, 0), Pair(0, 0), Pair(0, 0), listOf())
// println("Blueprint ${blueprint.number}: $geodes")
// blueprint.number * geodes
// }
//
// println("High: ${totals.sum()}")
val totals = lines.take(3).map { blueprint ->
currentBest = 0
val geodes = stuff(blueprint, 32, Pair(1, 0), Pair(0, 0), Pair(0, 0), Pair(0, 0), listOf())
println("Blueprint ${blueprint.number}: $geodes")
geodes
}
println("High: ${totals[0] * totals[1] * totals[2]}")
}
}
| 0 | Kotlin | 0 | 0 | fd644d442b5ff0d2f05fbf6317c61ee9ce7b4470 | 4,866 | adventofcode2022 | MIT License |
utbot-fuzzing/src/main/kotlin/org/utbot/fuzzing/utils/Combinations.kt | UnitTestBot | 480,810,501 | false | {"Kotlin": 6661796, "Java": 2209528, "Python": 223199, "Go": 99696, "C#": 80947, "JavaScript": 42483, "Shell": 15961, "HTML": 8704, "Batchfile": 8586, "Dockerfile": 2057} | package org.utbot.fuzzing.utils
/**
* Enumerates all possible combinations for a given list of maximum numbers of elements for every position.
*
* For any index between 0 and [size] excluded it returns the unique combination as an array with
* values that are between 0 and corresponding maximum number from the `elementNumbers`.
*
* For example for a given list {2, 3} the following combinations get be found by corresponding index:
*
* ```
* 0 - {0, 0}
* 1 - {0, 1}
* 2 - {0, 2}
* 3 - {1, 0}
* 4 - {1, 1}
* 5 - {1, 2}
* ```
*
* Use this class to iterate through all combinations of some data, like this:
*
* ```
* val dataList = arrayListOf(
* listOf("One", "Two"),
* listOf(1.0, 2.0, Double.NaN),
* )
* Combinations(*dataList.map { it.size }.toIntArray()).forEach { combination ->
* println("${dataList[0][combination[0]]} ${dataList[1][combination[1]]}")
* }
* ```
*
* This example iterates through all values that are result of cartesian product of input lists:
*
* ```
* One 1.0
* One 2.0
* One NaN
* Two 1.0
* Two 2.0
* Two NaN
* ```
*
* Simpler way to iterate through all combinations by using [CartesianProduct]:
*
* ```
* CartesianProduct(listOf(
* listOf("One", "Two"),
* listOf(1.0, 2.0, Double.NaN)
* )).forEach {
* println("${it[0]} ${it[1]}")
* }
* ```
*/
class Combinations(vararg elementNumbers: Int): Iterable<IntArray> {
/**
* Internal field that keeps a count of combinations for particular position.
*
* The count is calculated from left to right for, for example with a given elementNumbers [4, 6, 2]
* the result is: `[4 * 6 * 2, 6 * 2, 2] = [48, 12, 2]`. Therefore, the total count can be obtained for a subarray by index:
* - `[..., ..., 2] = count[2] = 2`
* - `[..., 12, 2] = count[1] = 12`
* - `[48, 12, 2] = count[0] = 48`
*
* The total count of all possible combinations is therefore `count[0]`.
*/
private val count: LongArray
val size: Long
get() = if (count.isEmpty()) 0 else count[0]
init {
val badValue = elementNumbers.indexOfFirst { it <= 0 }
if (badValue >= 0) {
throw IllegalArgumentException("Max value must be at least 1 to build combinations, but ${elementNumbers[badValue]} is found at position $badValue (list: $elementNumbers)")
}
count = LongArray(elementNumbers.size) { elementNumbers[it].toLong() }
for (i in count.size - 2 downTo 0) {
try {
count[i] = StrictMath.multiplyExact(count[i], count[i + 1])
} catch (e: ArithmeticException) {
throw TooManyCombinationsException("Long overflow: ${count[i]} * ${count[i + 1]}")
}
}
}
override fun iterator(): Iterator<IntArray> {
return (0 until size).asSequence().map { get(it) }.iterator()
}
/**
* Returns combination by its index.
*
* Algorithm is similar to base conversion. Thus [Combinations] can be used to generate all numbers with given
* number of digits. This example prints all numbers from 000 to 999:
*
* ```
* Combinations(10, 10, 10).forEach { digits ->
* println(digits.joinToString(separator = "") { it.toString() })
* }
* ```
*/
operator fun get(value: Long, target: IntArray = IntArray(count.size)): IntArray {
if (value >= size) {
throw java.lang.IllegalArgumentException("Only $size values allowed")
}
if (target.size != count.size) {
throw java.lang.IllegalArgumentException("Different array sizes: ${target.size} != ${count.size} ")
}
var rem = value
for (i in target.indices) {
target[i] = if (i < target.size - 1) {
val res = checkBoundsAndCast(rem / count[i + 1])
rem %= count[i + 1]
res
} else {
checkBoundsAndCast(rem)
}
}
return target
}
private fun checkBoundsAndCast(value: Long): Int {
check(value >= 0 && value < Int.MAX_VALUE) { "Value is out of bounds: $value" }
return value.toInt()
}
}
class TooManyCombinationsException(msg: String) : RuntimeException(msg) | 410 | Kotlin | 37 | 110 | c7f2ac4286b9861485c67ad3b11cd14e2b3ab82f | 4,255 | UTBotJava | Apache License 2.0 |
src/main/kotlin/io/steinh/aoc/day01/Trebuchet.kt | daincredibleholg | 726,426,347 | false | {"Kotlin": 25396} | package io.steinh.aoc.day01
class Trebuchet {
fun String.replace(vararg pairs: Pair<String, String>): String =
pairs.fold(this) { acc, (old, new) -> acc.replace(old, new, ignoreCase = true) }
fun calibrate(input: List<String>): Int {
val transformedStrings = transform(input)
return transformedStrings.sumOf {
s -> "${ s.first { it.isDigit() }}${ s.last { it.isDigit() }}".toInt()
}
}
private fun transform(input: List<String>): List<String> {
val regex = Regex("^(one|two|three|four|five|six|seven|eight|nine)")
return buildList {
for (line in input) {
var transformed = ""
for (i in line.indices) {
if (line[i].isDigit()) {
transformed += line[i]
} else {
transformed += when (regex.find(line.substring(i))?.value) {
"one" -> "1"
"two" -> "2"
"three" -> "3"
"four" -> "4"
"five" -> "5"
"six" -> "6"
"seven" -> "7"
"eight" -> "8"
"nine" -> "9"
else -> ""
}
}
}
add(transformed)
}
}
}
}
fun main() {
val input = {}.javaClass.classLoader?.getResource("day01/input.txt")?.readText()?.lines()
val trebuchet = Trebuchet()
val sum = trebuchet.calibrate(input!!)
print("Result 1: $sum")
}
| 0 | Kotlin | 0 | 0 | 4aa7c684d0e337c257ae55a95b80f1cf388972a9 | 1,702 | AdventOfCode2023 | MIT License |
src/main/kotlin/se/saidaspen/aoc/aoc2016/Day14.kt | saidaspen | 354,930,478 | false | {"Kotlin": 301372, "CSS": 530} | package se.saidaspen.aoc.aoc2016
import se.saidaspen.aoc.util.*
fun main() = Day14.run()
object Day14 : Day(2016, 14) {
override fun part1(): Any {
val salt = input
var i = 0
val keys = mutableSetOf<P<String, Int>>()
val lastThousandHashes = mutableListOf<Triple<String, Char?, Int>>().toArrayDeque()
while (keys.size < 100) {
val hashed = md5(salt + i)
val tripleChar : Char? = hashed.e().windowed(3).map { it.distinct() }.filter { it.size == 1 }.map { it[0] }.firstOrNull()
lastThousandHashes.addLast(Triple(hashed, tripleChar, i))
if (lastThousandHashes.size > 1000)
lastThousandHashes.removeFirst()
val pents: List<Char>? = hashed.e().windowed(5).map { it.distinct() }.filter { it.size == 1 }?.map { it.get(0) }
if (pents!!.isNotEmpty()) {
val keysFound = lastThousandHashes
.filter {
pents.any {
p -> it.second != null && it.second == p
}
}
.filter {
it.first != hashed
}
.map { P(it.first, it.third) }
keys.addAll(keysFound)
}
i++
}
val tmp = keys.toMutableList().sortedBy { it.second }.toMutableList()
tmp.removeLast(keys.size - 64)
return tmp.last().second
}
override fun part2(): Any {
var memo = mutableMapOf<String, String>()
val salt = input
var i = 0
val keys = mutableSetOf<P<String, Int>>()
val lastThousandHashes = mutableListOf<Triple<String, Char?, Int>>().toArrayDeque()
while (keys.size < 70) {
var hashed = salt + i
repeat(2017) {
if (memo.containsKey(hashed)) {
hashed = memo[hashed]!!
}
else {
val newHash = md5(hashed)
memo[hashed] = newHash
hashed = newHash
}
}
val tripleChar : Char? = hashed.e().windowed(3).map { it.distinct() }.filter { it.size == 1 }.map { it[0] }.firstOrNull()
lastThousandHashes.addLast(Triple(hashed, tripleChar, i))
if (lastThousandHashes.size > 1000)
lastThousandHashes.removeFirst()
val pents: List<Char>? = hashed.e().windowed(5).map { it.distinct() }.filter { it.size == 1 }?.map { it.get(0) }
if (pents!!.isNotEmpty()) {
val keysFound = lastThousandHashes
.filter {
pents.any {
p -> it.second != null && it.second == p
}
}
.filter {
it.first != hashed
}
.map { P(it.first, it.third) }
if (keysFound.isNotEmpty()) {
keys.addAll(keysFound)
}
}
i++
}
val tmp = keys.toMutableList().sortedBy { it.second }.toMutableList()
tmp.removeLast(keys.size - 64)
return tmp.last().second
}
} | 0 | Kotlin | 0 | 1 | be120257fbce5eda9b51d3d7b63b121824c6e877 | 3,307 | adventofkotlin | MIT License |
Algorithm/coding_interviews/Kotlin/Questions48.kt | ck76 | 314,136,865 | false | {"HTML": 1420929, "Java": 723214, "JavaScript": 534260, "Python": 437495, "CSS": 348978, "C++": 348274, "Swift": 325819, "Go": 310456, "Less": 203040, "Rust": 105712, "Ruby": 96050, "Kotlin": 88868, "PHP": 67753, "Lua": 52032, "C": 30808, "TypeScript": 23395, "C#": 4973, "Elixir": 4945, "Pug": 1853, "PowerShell": 471, "Shell": 163} | package com.qiaoyuang.algorithm
/**
* 一个只包含小写字母的字符串的最大非重复子字符串的长度
*/
fun main() {
val str = "arabcacfr"
println("字符串:$str,最大子字符串的长度是:${longestSubstringWithoutDuplication(str)}")
}
fun longestSubstringWithoutDuplication(str: String): Int {
// 检查字符是否合法
fun Char.isLegal(): Boolean = toInt() in 97..122
// 获取字符在数组中的位置
fun Char.getPosition(): Int = toInt() - 97
// 计算逻辑
val array = IntArray(26) { 0 }
var curLength = 0
var maxLength = 0
for (i in str.indices) {
val c = str[i]
require(c.isLegal()) { "输入的字符串包含不合法字符" }
val position = c.getPosition()
if (array[position] == 0) {
curLength++
} else {
curLength = 1
for (j in array.indices)
array[j] = 0
}
array[position]++
if (curLength > maxLength) maxLength = curLength
}
return maxLength
} | 0 | HTML | 0 | 2 | 2a989fe85941f27b9dd85b3958514371c8ace13b | 940 | awesome-cs | Apache License 2.0 |
src/main/kotlin/days/Day7.kt | MisterJack49 | 574,081,723 | false | {"Kotlin": 35586} | package days
class Day7 : Day(7) {
override fun partOne(): Any {
val fileSystem = buildFileSystem()
return fileSystem.getAllDirectories(fileSystem.root)
.filter { it.size <= 100000 }
.sumOf { it.size }
}
override fun partTwo(): Any {
val fileSystem = buildFileSystem()
val totalSpace = 70000000
val requiredFreeSpace = 30000000
val currentUnusedSpace = totalSpace - fileSystem.root.size
val spaceToFind = requiredFreeSpace - currentUnusedSpace
return fileSystem.getAllDirectories(fileSystem.root)
.filter { it.size >= spaceToFind }
.minOf { it.size }
}
private fun buildFileSystem(): FileSystem {
val fileSystem = FileSystem(Directory("/"))
val iterator = inputList.listIterator()
while (iterator.hasNext()) {
var line = iterator.next().split(" ")
if (line.first() == "$") {
when (line[1]) {
"cd" -> {
when (line.last()) {
".." -> fileSystem.goToParent()
"/" -> fileSystem.goToRoot()
else -> fileSystem.goToChild(line.last())
}
}
"ls" -> {
while (iterator.hasNext()) {
var line = iterator.next().split(" ")
when (line.first()) {
"$" -> {
iterator.previous();
break
}
"dir" -> fileSystem.createDirectory(line.last())
else -> fileSystem.createFile(line.last(), line.first().toInt())
}
}
}
}
}
}
return fileSystem
}
}
private interface Content {
val name: String
val size: Int
}
private class File(override val name: String, override val size: Int = 0) : Content
private class Directory(override val name: String) : Content {
val content: MutableList<Content> = mutableListOf()
override val size: Int
get() = content.getSize()
}
private fun MutableList<Content>.getSize() =
this.sumOf { it.size }
private data class FileSystem(val root: Directory) {
private val currentPath: MutableList<Directory> = mutableListOf()
private val currentDirectory: Directory
get() = currentPath.lastOrNull() ?: root
fun goToRoot() = currentPath.clear()
fun goToParent() {
if (currentPath.isEmpty()) return
currentPath.removeLast()
}
fun goToChild(name: String) {
currentPath.add(currentDirectory.content.first { it is Directory && it.name == name } as Directory)
}
fun createFile(name: String, size: Int) {
currentDirectory.content.add(File(name, size))
}
fun createDirectory(name: String) {
currentDirectory.content.add(Directory(name))
}
fun getAllDirectories(directory: Directory): List<Directory> {
if (directory.content.none { it is Directory }) return listOf(directory)
return directory.content
.filterIsInstance<Directory>()
.map { getAllDirectories(it) }
.flatten() + listOf(directory)
}
}
| 0 | Kotlin | 0 | 0 | e82699a06156e560bded5465dc39596de67ea007 | 3,479 | AoC-2022 | Creative Commons Zero v1.0 Universal |
src/aoc2022/day15/Day15.kt | svilen-ivanov | 572,637,864 | false | {"Kotlin": 53827} | package aoc2022.day15
import aoc2022.day04.overlap
import com.google.common.collect.Comparators
import readInput
import java.util.*
import kotlin.math.absoluteValue
import kotlin.math.max
import kotlin.math.min
import kotlin.reflect.KClass
val number = "((?:-)?\\d+)"
val regex = Regex("Sensor at x=$number, y=$number: closest beacon is at x=$number, y=$number")
sealed class Point {
abstract val x: Int
abstract val y: Int
fun mdist(other: Point): Int {
return (x - other.x).absoluteValue + (y - other.y).absoluteValue
}
data class Sensor(override val x: Int, override val y: Int) : Point()
data class Beacon(override val x: Int, override val y: Int) : Point()
data class Coverage(override val x: Int, override val y: Int) : Point()
data class PossibleSource(override val x: Int, override val y: Int) : Point()
}
data class RangeWithPoint(
val range: IntRange,
val point: KClass<out Point>,
)
val comparatorFirst: Comparator<RangeWithPoint> = Comparator.comparing { it.range.first }
val comparatorLast: Comparator<RangeWithPoint> = Comparator.comparing { it.range.last }
class Day15(val input: List<String>) {
// var yLineIntestections = TreeMap<Int, KClass<out Point>>()
var yLine = 0
val ranges = mutableSetOf<RangeWithPoint>()
fun updateYLine(from: Int, to: Int, type: KClass<out Point>) {
check(from <= to)
if (to > 4000000 && from > 4000000) return
val f = max(0, from)
val t = min(to, 4000000)
// val f = from
// val t = to
ranges.add(RangeWithPoint(f..t, type))
// ranges.add(from..to)
//// val f = if (from < 0) 0 else from
//// val t = if (from >= 4000000) 4000000 else to
// val f = from
// val t = to
// for (i in f..t) {
// val pos = yLineIntestections[i]
// if (pos == null) {
// yLineIntestections.put(i, type)
// } else if (pos == Point::Beacon::class || pos == Point::Sensor::class) {
// continue
// }
// }
}
fun findIntesection(from: Point.Coverage, to: Point.Coverage): Int {
// println("Intersection from: ${from} to ${to}, yline=${yLine}")
val xDir = if (from.x < to.x) {
1
} else if (from.x > to.x) {
-1
} else {
0
}
return from.x + (xDir * (yLine - from.y).absoluteValue)
}
fun updateCoverage(sensor: Point.Sensor, beacon: Point.Beacon) {
val distance = sensor.mdist(beacon)
if (sensor.y == yLine) {
updateYLine(sensor.x - distance, sensor.x - 1, Point.Coverage::class)
updateYLine(sensor.x, sensor.x, Point.Sensor::class)
updateYLine(sensor.x + 1, sensor.x + distance, Point.Coverage::class)
return
}
if (beacon.y == yLine) {
updateYLine(beacon.x, beacon.x, Point.Beacon::class)
}
val north = Point.Coverage(sensor.x, sensor.y - distance)
val south = Point.Coverage(sensor.x, sensor.y + distance)
if (north.y > yLine || south.y < yLine) {
return
}
if (north.y == yLine) {
updateYLine(north.x, north.x, Point.Coverage::class)
return
}
if (south.y == yLine) {
updateYLine(south.x, south.x, Point.Coverage::class)
return
}
val east = Point.Coverage(sensor.x + distance, sensor.y)
val west = Point.Coverage(sensor.x - distance, sensor.y)
if (sensor.y > yLine) {
// println("find where n->w, n->e intersect the y line")
updateYLine(findIntesection(north, west), findIntesection(north, east), Point.Coverage::class)
} else {
// println("find where w->s, e->s intersect the y line")
updateYLine(findIntesection(west, south), findIntesection(east, south), Point.Coverage::class)
}
}
fun findCoverage() {
val possibleSources = mutableListOf<Point.PossibleSource>()
for (l in 0..4000000) {
yLine = l
ranges.clear()
for ((index, line) in input.withIndex()) {
val (x1, y1, x2, y2) = regex.find(line)!!.groupValues.drop(1).map { it.toInt() }
val sensor = Point.Sensor(x1, y1)
val beacon = Point.Beacon(x2, y2)
updateCoverage(sensor, beacon)
}
val before = ranges.map { it.range }
val mergedRanges = merge(before)
val count = mergedRanges.sumOf { it.size() }
println("-> ${yLine}: ${count}")
if (count <= 4000000) {
println(mergedRanges)
error("")
}
}
// println(possibleSources)
}
private fun merge(ranges: List<IntRange>): List<IntRange> {
// println("Merging: ${ranges.joinToString(", ")}")
val result = mutableListOf<IntRange>()
var merged = false
outer@ for (i in ranges.indices) {
for (j in i + 1 until ranges.size) {
// print("checking $i, $j => ${ranges[i]} and ${ranges[j]}...")
if (ranges[i].canMerge(ranges[j])) {
val newRange = ranges[i].merge(ranges[j])
// println("can merge -> ${newRange}")
result.add(newRange)
result.addAll(ranges.filterIndexed { index, _ -> index != i && index != j })
merged = true
break@outer
} else {
// println("can't merge :(")
}
}
}
if (merged) {
return merge(result)
} else {
return ranges
}
}
}
fun main() {
fun part1(input: List<String>) {
val day15 = Day15(input)
day15.findCoverage()
}
fun part2(input: List<String>) {
}
val testInput = readInput("day15/day15")
part1(testInput)
part2(testInput)
}
fun IntRange.size() = last - first + 1
//
fun IntRange.canMerge(other: IntRange): Boolean {
return !(last < other.first || other.last < first)
}
fun IntRange.merge(other: IntRange): IntRange {
if (first <= other.first && other.last <= last) {
return this
}
if (other.first <= first && last <= other.last) {
return other
}
val all = listOf(other.first, other.last, first, last)
return all.min()..all.max()
}
object Test {
@JvmStatic
fun main(args: Array<String>) {
val a = 16..24
val b = 14..18
println(a.canMerge(b))
println(a.merge(b))
}
}
| 0 | Kotlin | 0 | 0 | 456bedb4d1082890d78490d3b730b2bb45913fe9 | 6,688 | aoc-2022 | Apache License 2.0 |
src/day01/Solution.kt | abhabongse | 576,594,038 | false | {"Kotlin": 63915} | /* Solution to Day 1: Calorie Counting
* https://adventofcode.com/2022/day/1
*/
package day01
import utils.largest
import utils.splitAt
import java.io.File
fun main() {
val fileName =
// "day01_sample.txt"
"day01_input.txt"
val elves = readInput(fileName)
// Part 1: find the most calories carried by an elf
val p1Calories = elves.maxOfOrNull { elf -> elf.calories.sum() }
println("Part 1: $p1Calories")
// Part 2: find the sum of calories carried by top-3 elves
val p2Calories = elves
.map { elf -> elf.calories.sum() }
.asSequence()
.largest(3)
.sum()
println("Part 2: $p2Calories")
}
/**
* Reads and parses input data according to the problem statement.
*/
fun readInput(fileName: String): List<Elf> {
return File("inputs", fileName)
.readLines()
.asSequence()
.splitAt { line -> line.trim().isEmpty() }
.map { caloriesGroup -> Elf(caloriesGroup.map(String::toInt)) }
.toList()
}
| 0 | Kotlin | 0 | 0 | 8a0aaa3b3c8974f7dab1e0ad4874cd3c38fe12eb | 1,015 | aoc2022-kotlin | Apache License 2.0 |
src/day01/Day01.kt | LostMekka | 574,697,945 | false | {"Kotlin": 92218} | package day01
import util.readInput
import util.shouldBe
fun main() {
val day = 1
val testInput = readInput(day, testInput = true).parseInput()
part1(testInput) shouldBe 24000
part2(testInput) shouldBe 45000
val input = readInput(day).parseInput()
println("output for part1: ${part1(input)}")
println("output for part2: ${part2(input)}")
}
private class Input(
val calories: List<List<Int>>,
)
private fun List<String>.parseInput(): Input {
return Input(buildList {
var currInventory = mutableListOf<Int>()
for (line in this@parseInput) {
if (line.isEmpty()) {
add(currInventory)
currInventory = mutableListOf()
} else {
currInventory += line.toInt()
}
}
if (currInventory.isNotEmpty()) add(currInventory)
})
}
private fun part1(input: Input): Int {
return input.calories.maxOf { it.sum() }
}
private fun part2(input: Input): Int {
return input.calories
.map { it.sum() }
.sortedDescending()
.take(3)
.sum()
}
| 0 | Kotlin | 0 | 0 | 58d92387825cf6b3d6b7567a9e6578684963b578 | 1,113 | advent-of-code-2022 | Apache License 2.0 |
kotlin/src/com/daily/algothrim/leetcode/CountTriplets.kt | idisfkj | 291,855,545 | false | null | package com.daily.algothrim.leetcode
/**
* 1442. 形成两个异或相等数组的三元组数目
*
* 给你一个整数数组 arr 。
*
* 现需要从数组中取三个下标 i、j 和 k ,其中 (0 <= i < j <= k < arr.length) 。
*
* a 和 b 定义如下:
*
* a = arr[i] ^ arr[i + 1] ^ ... ^ arr[j - 1]
* b = arr[j] ^ arr[j + 1] ^ ... ^ arr[k]
* 注意:^ 表示 按位异或 操作。
*
* 请返回能够令 a == b 成立的三元组 (i, j , k) 的数目。
*/
class CountTriplets {
companion object {
@JvmStatic
fun main(args: Array<String>) {
println(CountTriplets().countTriplets(intArrayOf(2, 3, 1, 6, 7)))
println(CountTriplets().countTriplets(intArrayOf(1, 1, 1, 1, 1)))
println(CountTriplets().countTriplets(intArrayOf(2, 3)))
println(CountTriplets().countTriplets(intArrayOf(1, 3, 5, 7, 9)))
println(CountTriplets().countTriplets(intArrayOf(7, 11, 12, 9, 5, 2, 7, 17, 22)))
}
}
// a = arr[i] ^ arr[i + 1] ^ ... ^ arr[j - 1]
// b = arr[j] ^ arr[j + 1] ^ ... ^ arr[k]
// 输入:arr = [2,3,1,6,7]
// 输出:4
// 解释:满足题意的三元组分别是 (0,1,2), (0,2,2), (2,3,4) 以及 (2,4,4)
fun countTriplets(arr: IntArray): Int {
val xors = hashMapOf<Int, Int>()
val count = hashMapOf<Int, Int>()
var temp = 0
var result = 0
arr.forEachIndexed { index, i ->
if (xors.containsKey(temp.xor(i))) {
result += (xors[temp.xor(i)] ?: 0) * index - (count[temp.xor(i)] ?: 0)
}
xors[temp] = (xors[temp] ?: 0) + 1
count[temp] = (count[temp] ?: 0) + index
temp = temp.xor(i)
}
return result
}
} | 0 | Kotlin | 9 | 59 | 9de2b21d3bcd41cd03f0f7dd19136db93824a0fa | 1,773 | daily_algorithm | Apache License 2.0 |
src/day3/day3s.kt | bienenjakob | 573,125,960 | false | {"Kotlin": 53763} | package day3
import inputTextOfDay
import testTextOfDay
private val Char.priority: Int
get() = when (this) {
in 'a'..'z' -> this - 'a' + 1
in 'A'..'Z' -> this - 'A' + 27
else -> error("$this is unknown, check your input!")
}
fun part1s(text: String): Int =
text.lines()
.map { bag -> bag.chunked(bag.length / 2) { half -> half.toSet()} }
.map { (a, b) -> (a intersect b).single() }
.sumOf { it.priority }
fun part2s(text: String): Int =
text.lines()
.chunked(3) { elves -> elves.map { elf -> elf.toSet()} }
.map { (a, b, c) -> (a intersect b intersect c).single() }
.sumOf { it.priority }
fun main() {
val day = 3
val testInput = testTextOfDay(day)
check(part1s(testInput) == 157)
val input = inputTextOfDay(day)
println(part1s(input))
println(part2s(input))
}
| 0 | Kotlin | 0 | 0 | 6ff34edab6f7b4b0630fb2760120725bed725daa | 881 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/com/briarshore/aoc2022/day06/TuningTroublePuzzle.kt | steveswing | 579,243,154 | false | {"Kotlin": 47151} | package com.briarshore.aoc2022.day06
import println
import readInput
fun main() {
fun scanForStartPacket(noise: String, expectedIndex: Int): Int {
val startPacket = noise
.asSequence()
.windowed(4, 1)
.filter { it.size == 4 && it.toSet().size == 4 }
.first()
.toCharArray()
val result = 4 + noise.indexOf(startPacket.concatToString())
if (result == expectedIndex) {
"found start packet ${startPacket.concatToString()} in ${noise} at ${result}".println()
}
return result
}
fun scanForStartMessage(noise: String, expectedIndex: Int): Int {
val startPacket = noise
.asSequence()
.windowed(14, 1)
.filter { it.size == 14 && it.toSet().size == 14 }
.first()
.toCharArray()
val result = 14 + noise.indexOf(startPacket.concatToString())
if (result == expectedIndex) {
"found start message ${startPacket.concatToString()} in ${noise} at ${result}".println()
}
return result
}
fun part1(input: List<Pair<String, Int>>): Int {
input.stream().forEach {
check(scanForStartPacket(it.first, it.second) == it.second)
}
return 0
}
fun part2(input: List<Pair<String, Int>>): Int {
input.stream().forEach {
val actualIndex = scanForStartMessage(it.first, it.second)
check(actualIndex == it.second)
}
return 0
}
val sampleInputPart1 = listOf(
Pair("mjqjpqmgbljsphdztnvjfqwrcgsmlb", 7),
Pair("bvwbjplbgvbhsrlpgdmjqwftvncz", 5),
Pair("nppdvjthqldpwncqszvftbrmjlhg", 6),
Pair("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg", 10),
Pair("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw", 11)
)
check(part1(sampleInputPart1) == 0)
val input = readInput("d6p1-input")
val startPacket = scanForStartPacket(input.first(), 1702)
"startPacket $startPacket".println()
val sampleInputPart2 = listOf(
Pair("mjqjpqmgbljsphdztnvjfqwrcgsmlb", 19),
Pair("bvwbjplbgvbhsrlpgdmjqwftvncz", 23),
Pair("nppdvjthqldpwncqszvftbrmjlhg", 23),
Pair("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg", 29),
Pair("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw", 26)
)
check(part2(sampleInputPart2) == 0)
val startMessage = scanForStartMessage(input.first(), 3559)
"startMessage $startMessage".println()
}
| 0 | Kotlin | 0 | 0 | a0d19d38dae3e0a24bb163f5f98a6a31caae6c05 | 2,475 | 2022-AoC-Kotlin | Apache License 2.0 |
src/Day02.kt | nemethandor | 575,143,939 | false | {"Kotlin": 2854} | // https://adventofcode.com/2022/day/2
private val whoBeatsWho = mapOf("A" to "C", "B" to "A", "C" to "B")
private val pointsForTool = mapOf("X" to 1, "Y" to 2, "Z" to 3)
private val equivalentTools = mapOf("A" to "X", "B" to "Y", "C" to "Z")
fun main() {
fun getGameResult(tactic: String): Int = when (tactic) {
"Z" -> 6
"Y" -> 3
else -> 0
}
fun findYourTool(opponentPlay: String, tactic: String): String? {
val looser = whoBeatsWho[opponentPlay]
val winner = whoBeatsWho[looser]
val tactic = when (tactic) {
"Y" -> opponentPlay
"X" -> looser
else -> winner
}
return equivalentTools[tactic]
}
fun getTotalScore(input: String): Int {
return input.lines().sumOf { game ->
val plays = game.split(" ")
val gameResult = getGameResult(plays[1])
val extraPoints = findYourTool(plays[0], plays[1])?.let { pointsForTool[it] } ?: 0
gameResult.plus(extraPoints)
}
}
val testInput = readInputFile("Day02_test")
val testResult = getTotalScore(testInput)
println(testResult)
check(testResult == 12)
val input = readInputFile("Day02")
val result = getTotalScore(input)
println(result)
} | 0 | Kotlin | 0 | 0 | 42ce114850d08a741fae3fdd572506fdc3e43a3f | 1,297 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/com/chriswk/aoc/advent2021/Day13.kt | chriswk | 317,863,220 | false | {"Kotlin": 481061} | package com.chriswk.aoc.advent2021
import com.chriswk.aoc.AdventDay
import com.chriswk.aoc.util.Pos
import com.chriswk.aoc.util.report
class Day13: AdventDay(2021, 13) {
companion object {
@JvmStatic
fun main(args: Array<String>) {
val day = Day13()
report {
day.part1()
}
report {
day.part2()
}
}
}
fun runInstructions(points: Set<Pos>, instructions: List<Instruction>): Set<Pos> {
return instructions.fold(points) { prev, fold ->
fold(prev, fold)
}
}
fun fold(points: Set<Pos>, instruction: Instruction): Set<Pos> {
return points.map { p ->
when(instruction.alongY) {
true -> p.foldUp(instruction.point)
false -> p.foldLeft(instruction.point)
}
}.toSet()
}
val inputSet = parse(inputAsLines)
fun printGrid(points: Set<Pos>) {
val minX = points.minOf { it.x }
val minY = points.minOf { it.y }
val maxX = points.maxOf { it.x }
val maxY = points.maxOf { it.y }
(minY..maxY).forEach { y ->
println((minX..maxX).joinToString(separator = "") { x ->
if(points.contains(Pos(x, y))) {
"#"
} else {
"."
}
})
}
}
data class Instruction(val alongY: Boolean, val point: Int)
fun parse(input: List<String>): Pair<Set<Pos>, List<Instruction>> {
val points = input.takeWhile { it.isNotEmpty()}.map {
val (x, y) = it.split(",")
Pos(x.toInt(), y.toInt())
}.toSet()
val instructions = input.dropWhile { it.isNotEmpty() }.drop(1).map {
if (it.contains("y=")) {
Instruction(true, it.split("=").last().toInt())
} else {
Instruction(false, it.split("=").last().toInt())
}
}
return points to instructions
}
fun part1(): Int {
return fold(inputSet.first, inputSet.second.first()).size
}
fun part2(): Int {
val endResult = runInstructions(inputSet.first, inputSet.second)
printGrid(endResult)
return 0
}
}
| 116 | Kotlin | 0 | 0 | 69fa3dfed62d5cb7d961fe16924066cb7f9f5985 | 2,297 | adventofcode | MIT License |
puzzles/src/main/kotlin/com/kotlinground/puzzles/search/binarysearch/successfulpairsspellspotions/successfulPairs.kt | BrianLusina | 113,182,832 | false | {"Kotlin": 483489, "Shell": 7283, "Python": 1725} | package com.kotlinground.puzzles.search.binarysearch.successfulpairsspellspotions
import java.util.TreeMap
import java.util.Arrays
fun successfulPairs(spells: IntArray, potions: IntArray, success: Long): IntArray {
// O(mlogm) operation to sort potions
Arrays.sort(potions)
val treeMap = TreeMap<Long, Int>()
treeMap[Long.MAX_VALUE] = potions.size
for (i in potions.size - 1 downTo 0) {
treeMap[potions[i].toLong()] = i
}
for (i in spells.indices) {
val need = (success + spells[i] - 1) / spells[i]
spells[i] = potions.size - treeMap.ceilingEntry(need).value
}
return spells
}
fun successfulPairs2(spells: IntArray, potions: IntArray, success: Long): IntArray {
/**
* This retrieves the first position of a potion which if multiplied with a spell returns at least the give strength
* @param [IntArray] sortedPotions int array of sported potions
* @param [Long] target the target to find, i.e. success
* @param [Int] currentSpell, the current spell that we are iterating through
*/
val validPos = fun(sortedPotions: IntArray, target: Long, currentSpell: Int): Int {
val potionNeeded = (target + currentSpell - 1) / currentSpell
var left = 0
var right = sortedPotions.size
while (left < right) {
val middle = left + (right - left) / 2
if (sortedPotions[middle] >= potionNeeded) {
right = middle
} else {
left = middle + 1
}
}
return left
}
Arrays.sort(potions)
val result = IntArray(spells.size)
for (i in spells.indices) {
val count = potions.size - validPos(potions, success, spells[i])
result[i] = count
}
return result
}
| 1 | Kotlin | 1 | 0 | 5e3e45b84176ea2d9eb36f4f625de89d8685e000 | 1,795 | KotlinGround | MIT License |
src/main/kotlin/g0801_0900/s0813_largest_sum_of_averages/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g0801_0900.s0813_largest_sum_of_averages
// #Medium #Array #Dynamic_Programming #2023_03_17_Time_160_ms_(100.00%)_Space_35.3_MB_(100.00%)
class Solution {
fun largestSumOfAverages(nums: IntArray, k: Int): Double {
return helper(nums, k, 0, Array(k + 1) { arrayOfNulls(nums.size) })
}
private fun helper(nums: IntArray, k: Int, idx: Int, memo: Array<Array<Double?>>): Double {
if (memo[k][idx] != null) {
return memo[k][idx]!!
}
var maxAvg = 0.0
var sum = 0.0
for (i in idx..nums.size - k) {
sum += nums[i].toDouble()
if (k - 1 > 0) {
maxAvg = maxAvg.coerceAtLeast(sum / (i - idx + 1) + helper(nums, k - 1, i + 1, memo))
} else if (i == nums.size - 1) {
maxAvg = maxAvg.coerceAtLeast(sum / (i - idx + 1))
}
}
memo[k][idx] = maxAvg
return maxAvg
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 939 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/io/github/pshegger/aoc/y2015/Y2015D12.kt | PsHegger | 325,498,299 | false | null | package io.github.pshegger.aoc.y2015
import io.github.pshegger.aoc.common.BaseSolver
class Y2015D12 : BaseSolver() {
override val year = 2015
override val day = 12
private val tokenizedInput: Token by lazy { tokenize(parseInput()) }
override fun part1(): Int = tokenizedInput.sumNumbers(false)
override fun part2(): Int = tokenizedInput.sumNumbers(true)
private fun Token.sumNumbers(ignoreRedObjects: Boolean): Int = when (this) {
is Token.Array -> items.sumOf { it.sumNumbers(ignoreRedObjects) }
is Token.NumberLiteral -> value
is Token.Object -> {
val hasRed = members.any { (_, token) -> (token as? Token.StringLiteral)?.value == "red" }
if (ignoreRedObjects && hasRed) {
0
} else {
members.entries.sumOf { it.value.sumNumbers(ignoreRedObjects) }
}
}
is Token.StringLiteral -> 0
}
private fun tokenize(data: String): Token = when (data.first()) {
'"' -> Token.StringLiteral(data.drop(1).dropLast(1))
'[' -> {
val parts = smartSplit(data.drop(1).dropLast(1))
Token.Array(parts.map { tokenize(it) })
}
'{' -> {
val parts = smartSplit(data.drop(1).dropLast(1))
Token.Object(parts.associate { str ->
val (key, value) = str.split(':', limit = 2)
Pair(key, tokenize(value))
})
}
else -> Token.NumberLiteral(data.toInt())
}
private fun smartSplit(data: String): List<String> {
val result = mutableListOf<String>()
var ptr = 0
while (ptr < data.length) {
var ctr = 0
var doubleQuoteSign = 1
for (i in ptr until data.length) {
if (i == data.length - 1) {
result.add(data.drop(ptr))
ptr = data.length
break
}
when (data[i]) {
'[', '{' -> ctr++
']', '}' -> ctr--
'"' -> {
ctr += doubleQuoteSign
doubleQuoteSign *= -1
}
',' -> {
if (ctr == 0) {
result.add(data.substring(ptr, i))
ptr = i + 1
break
}
}
}
}
}
return result
}
private fun parseInput() = readInput {
readLines()[0]
}
private sealed class Token {
data class Array(val items: List<Token>) : Token()
data class Object(val members: Map<String, Token>) : Token()
data class StringLiteral(val value: String) : Token()
data class NumberLiteral(val value: Int) : Token()
}
} | 0 | Kotlin | 0 | 0 | 346a8994246775023686c10f3bde90642d681474 | 2,901 | advent-of-code | MIT License |
src/main/kotlin/co/csadev/advent2022/Day09.kt | gtcompscientist | 577,439,489 | false | {"Kotlin": 252918} | /**
* Copyright (c) 2022 by <NAME>
* Advent of Code 2022, Day 9
* Problem Description: http://adventofcode.com/2021/day/9
*/
package co.csadev.advent2022
import co.csadev.adventOfCode.BaseDay
import co.csadev.adventOfCode.Point2D
import co.csadev.adventOfCode.Resources.resourceAsList
import co.csadev.adventOfCode.printArea
import kotlin.math.sign
class Day09(override val input: List<String> = resourceAsList("22day09.txt")) :
BaseDay<List<String>, Int, Int> {
private val min = Point2D(-37, -62)
private val max = Point2D(212, 341)
private var minX = 0
private var maxX = 0
private var minY = 0
private var maxY = 0
private fun lastKnotVisits(knotCount: Int, print: Boolean = false): Int {
val knots = MutableList(knotCount) { Point2D.ORIGIN }
val visits = MutableList(knotCount) { mutableSetOf(Point2D.ORIGIN) }
input.forEach {
val (dir, dis) = it.split(" ")
val distance = dis.toInt()
val move = Moves.valueOf(dir).move
repeat(distance) {
knots[0] = knots[0].plus(move).apply { minMax() }
knots.drop(1).indices.forEach { index ->
val head = knots[index]
var tail = knots[index + 1]
if (tail !in head.neighbors) {
tail = Point2D(
tail.x + (head.x - tail.x).sign,
tail.y + (head.y - tail.y).sign
)
}
knots[index + 1] = tail.apply { minMax() }
}
// knots.printArea(min,max)
repeat(knotCount) { k ->
visits[k] += knots[k]
}
}
}
// println("Min: ${Point2D(minX, minY)}")
// println("Max: ${Point2D(maxX, maxY)}")
if (print) {
visits.last().printArea(min, max) { contained, _ -> if (contained) '#' else ' ' }
}
return visits.last().size
}
override fun solvePart1() = lastKnotVisits(2)
override fun solvePart2() = lastKnotVisits(10, true)
private fun Point2D.minMax() {
minX = minX.coerceAtMost(x)
minY = minY.coerceAtMost(y)
maxX = maxX.coerceAtLeast(x)
maxY = maxY.coerceAtLeast(y)
}
private enum class Moves(val move: Point2D) {
L(Point2D(-1, 0)),
R(Point2D(1, 0)),
U(Point2D(0, 1)),
D(Point2D(0, -1))
}
}
| 0 | Kotlin | 0 | 1 | 43cbaac4e8b0a53e8aaae0f67dfc4395080e1383 | 2,514 | advent-of-kotlin | Apache License 2.0 |
src/Day17/Day17.kt | Nathan-Molby | 572,771,729 | false | {"Kotlin": 95872, "Python": 13537, "Java": 3671} | package Day17
import readInput
import kotlin.math.*
class Chasm() {
var matrix: MutableList<Array<Boolean>> = mutableListOf()
fun resize(matrixVerticalSize: Int) {
for (i in matrix.size..matrixVerticalSize) {
matrix.add(Array(7) { false })
}
}
fun print() {
for(row in matrix.reversed()) {
for (element in row) {
if (element) {
print("X")
} else {
print(".")
}
}
println()
}
}
}
class TetrisSimulator() {
var directions: MutableList<Direction> = mutableListOf()
var directionIndex = 0
var topCurrentY = 0
var chasm = Chasm()
var memoizedTable: HashMap<Pair<Int, Int>, Int> = hashMapOf()
enum class Direction {
RIGHT, LEFT
}
fun readInput(input: List<String>) {
val actualInput = input[0]
for (char in actualInput) {
if (char == '>') {
directions.add(Direction.RIGHT)
} else {
directions.add(Direction.LEFT)
}
}
}
fun runSimulation() {
var lastHeight = 0
for(i in 0 until 10000) {
var rock: Rock? = null
if (i % 5 == 0) {
var additionalAddition = 0
if (i != 0) {
additionalAddition = 1
}
chasm.resize(topCurrentY + 3 + additionalAddition)
rock = HorizontalRock(chasm, topCurrentY + 3 + additionalAddition)
} else if (i % 5 == 1) {
chasm.resize(topCurrentY + 6)
rock = PlusRock(chasm, topCurrentY + 4)
} else if (i % 5 == 2) {
chasm.resize(topCurrentY + 6)
rock = LRock(chasm, topCurrentY + 4)
} else if (i % 5 == 3) {
chasm.resize(topCurrentY + 7)
rock = VerticalRock(chasm, topCurrentY + 4)
} else if (i % 5 == 4) {
chasm.resize(topCurrentY + 5)
rock = SquareRock(chasm, topCurrentY + 4)
}
while (true) {
if (directionIndex == directions.count()) {directionIndex = 0}
val currentDirection = directions[directionIndex]
when(currentDirection) {
Direction.RIGHT -> rock!!.moveRight()
Direction.LEFT -> rock!!.moveLeft()
}
val result = rock.moveDown()
topCurrentY = max(result.second, topCurrentY)
val currentHeight = topCurrentY + 1
println((i % 5).toString() + "," + directionIndex.toString() + "," + i.toString() + "," + (currentHeight - lastHeight).toString())
lastHeight = currentHeight
directionIndex++
//if rock failed to move down, move to next rock
if (!result.first) {
break
}
}
}
}
}
fun main() {
fun part1(input: List<String>): Int {
val tetrisSimulator = TetrisSimulator()
tetrisSimulator.readInput(input)
tetrisSimulator.runSimulation()
return tetrisSimulator.topCurrentY + 1
}
fun part2(input: List<String>): Int {
return 0
}
val testInput = readInput("Day17","Day17_test")
// part1(testInput)
// check(part1(testInput) == 1651)
// println(part2(testInput))
// check(part2(testInput) == 1707)
//
val input = readInput("Day17","Day17")
part1(input)
// println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 750bde9b51b425cda232d99d11ce3d6a9dd8f801 | 3,648 | advent-of-code-2022 | Apache License 2.0 |
src/week1/TwoSum.kt | anesabml | 268,056,512 | false | null | package week1
import java.util.*
import kotlin.system.measureNanoTime
class TwoSum {
/** Brute force
* Loop through each element x and find if there is a value that equals to target - x
* Time complexity : O(n2)
* Space complexity : O(1)
*/
fun twoSum(nums: IntArray, target: Int): IntArray {
for (i in nums.indices) {
for (j in i + 1 until nums.size) {
if (nums[j] == target - nums[i]) {
return intArrayOf(i, j)
}
}
}
throw IllegalArgumentException("No solution")
}
/** Using a HashTable
* Insert all the nums values and look for y
* Time complexity : O(n)
* Space complexity : O(n)
*/
fun twoSum2(nums: IntArray, target: Int): IntArray {
val map = HashMap<Int, Int>()
for (i in nums.indices) {
map[nums[i]] = i
}
for (i in nums.indices) {
val y = target - nums[i]
if (map.containsKey(y) && map[y] != i) {
return intArrayOf(i, map[y]!!)
}
}
throw IllegalArgumentException("No solution")
}
/** Using a HashTable
* Insert all the nums values and look for y
* Time complexity : O(n)
* Space complexity : O(n)
*/
fun twoSum3(nums: IntArray, target: Int): IntArray {
val map = hashMapOf<Int, Int>()
for (i in nums.indices) {
val y = target - nums[i]
map[y]?.let {
return intArrayOf(i, it).apply { sort() }
}
map[nums[i]] = i
}
throw IllegalArgumentException("No solution")
}
}
fun main() {
val twoSum = TwoSum()
val input = intArrayOf(2, 7, 11, 15)
val target = 9
val firstSolutionTime = measureNanoTime { println(twoSum.twoSum(input, target).contentToString()) }
val secondSolutionTime = measureNanoTime { println(twoSum.twoSum2(input, target).contentToString()) }
val thirdSolutionTime = measureNanoTime { println(twoSum.twoSum3(input, target).contentToString()) }
println("First Solution execution time: $firstSolutionTime")
println("Second Solution execution time: $secondSolutionTime")
println("Third Solution execution time: $thirdSolutionTime")
} | 0 | Kotlin | 0 | 1 | a7734672f5fcbdb3321e2993e64227fb49ec73e8 | 2,298 | leetCode | Apache License 2.0 |
src/main/kotlin/io/tree/LowestCommonAncestor.kt | jffiorillo | 138,075,067 | false | {"Kotlin": 434399, "Java": 14529, "Shell": 465} | package io.tree
import io.models.TreeNode
// https://leetcode.com/explore/learn/card/data-structure-tree/133/conclusion/932/
// https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/
class LowestCommonAncestor {
fun <T> execute(root: BinaryTree<T>?, p: T, q: T): BinaryTree<T>? = when {
root == null -> null
p == root.value || q == root.value -> root
else -> {
val left = execute(root.left, p, q)
val right = execute(root.right, p, q)
if (left != null && right != null) {
root
} else left ?: right
}
}
fun execute(root: TreeNode?, p: TreeNode?, q: TreeNode?): TreeNode? = when {
root == null -> null
root == p || root == q -> root
else -> {
val left = execute(root.left, p, q)
val right = execute(root.right, p, q)
if (left != null && right != null) root else left ?: right
}
}
}
fun main() {
val lowestCommonAncestor = LowestCommonAncestor()
val tree = BinaryTree(3,
left = BinaryTree(5,
left = BinaryTree(6),
right = BinaryTree(2, left = BinaryTree(7), right = BinaryTree(4))),
right = BinaryTree(1, left = BinaryTree(0), right = BinaryTree(8))
)
listOf(
IWrapper(tree, 5, 1, 3),
IWrapper(tree, 5, 4, 5),
IWrapper(tree, 6, 4, 5),
IWrapper(tree, 7, 0, 3)
).map { (tree, p, q, result) ->
val node = lowestCommonAncestor.execute(tree, p, q)
println("${node?.value == result}")
}
}
data class IWrapper<T>(val tree: BinaryTree<T>, val p: T, val q: T, val result: T) | 0 | Kotlin | 0 | 0 | f093c2c19cd76c85fab87605ae4a3ea157325d43 | 1,559 | coding | MIT License |
src/2020/Day7_1.kts | Ozsie | 318,802,874 | false | {"Kotlin": 99344, "Python": 1723, "Shell": 975} | import java.io.File
import kotlin.collections.ArrayList
data class Bag(val color: String, val contents: HashMap<Bag,Int> = HashMap<Bag,Int>()) {
fun findBagOrNew(color: String): Bag {
val x = contents.keys.filter { color == it.color }
val i = x.indexOfFirst { color == it.color }
return if (i >= 0) x[i] else Bag(color)
}
fun look(lookingFor: String, top: Bag, matches: HashSet<Bag>): Unit {
if (color == "TOP") {
contents.forEach { bag, count -> bag.look(lookingFor, bag, matches)}
} else {
contents.forEach { bag, count ->
if (bag.color == lookingFor) matches.add(top)
if (bag.contents.isNotEmpty()) bag.look(lookingFor, top, matches)
}
}
}
}
val bags = Bag("TOP", HashMap<Bag,Int>())
File("input/2020/day7").forEachLine {
val (color,inner) = it.split(" bags contain ")
val bag = bags.findBagOrNew(color)
bags.contents.put(bag, 1)
inner.trim().split(",")
.filter { it != "no other bags." }
.forEach {
val descriptors = it.trim().split(" ")
val count = descriptors[0].trim().toInt()
val color = descriptors.subList(1, descriptors.lastIndex).joinToString(" ").trim()
var innerBag = bags.findBagOrNew(color)
if (!bags.contents.keys.contains(innerBag)) bags.contents.put(innerBag, 1)
bag.contents.put(innerBag, count)
}
}
val lookingFor = "shiny gold"
val matches = HashSet<Bag>()
bags.look(lookingFor,bags,matches)
println(matches.size) | 0 | Kotlin | 0 | 0 | d938da57785d35fdaba62269cffc7487de67ac0a | 1,585 | adventofcode | MIT License |
src/main/kotlin/aoc2023/day11/day11Solver.kt | Advent-of-Code-Netcompany-Unions | 726,531,711 | false | {"Kotlin": 94973} | package aoc2023.day11
import aoc2022.day15.manhattanDistance
import lib.*
suspend fun main() {
setupChallenge().solveChallenge()
}
fun setupChallenge(): Challenge<Array<Array<Char>>> {
return setup {
day(11)
year(2023)
parser {
it.readLines().get2DArrayOfColumns()
}
partOne {
val expandedColumns = it.map { it.all { it == '.' } }
val expandedRows = it.first().indices.map { i -> it.map { it[i] }.all { it == '.' } }
val galaxies = mutableSetOf<Pair<Int, Int>>()
it.indices.forEach { i ->
it[i].indices.forEach { j ->
if(it[i][j] == '#') {
galaxies.add(i to j)
}
}
}
var sum = 0
galaxies.forEachIndexed{i, g ->
galaxies.drop(i + 1).forEach {
var dist = manhattanDistance(g, it)
dist += expandedColumns.subList(minOf(g.x(), it.x()), maxOf(g.x(), it.x())).count { it }
dist += expandedRows.subList(minOf(g.y(), it.y()), maxOf(g.y(), it.y())).count { it }
sum += dist
}
}
sum.toString()
}
partTwo {
val expandedColumns = it.map { it.all { it == '.' } }
val expandedRows = it.first().indices.map { i -> it.map { it[i] }.all { it == '.' } }
val galaxies = mutableSetOf<Pair<Int, Int>>()
it.indices.forEach { i ->
it[i].indices.forEach { j ->
if(it[i][j] == '#') {
galaxies.add(i to j)
}
}
}
var sum = 0L
galaxies.forEachIndexed{i, g ->
galaxies.drop(i + 1).forEach {
var dist = manhattanDistance(g, it).toLong()
dist += (expandedColumns.subList(minOf(g.x(), it.x()), maxOf(g.x(), it.x())).count { it } * 999999L)
dist += (expandedRows.subList(minOf(g.y(), it.y()), maxOf(g.y(), it.y())).count { it } * 999999L)
sum += dist
}
}
sum.toString()
}
}
} | 0 | Kotlin | 0 | 0 | a77584ee012d5b1b0d28501ae42d7b10d28bf070 | 2,269 | AoC-2023-DDJ | MIT License |
dataclass/src/main/kotlin/utils/CategoryUtils.kt | omarmiatello | 264,021,780 | false | null | package com.github.omarmiatello.noexp.utils
import com.github.omarmiatello.noexp.Category
import com.github.omarmiatello.noexp.ProductHome
data class CategoryProducts(
val category: Category,
val productsInCategory: List<ProductHome>,
val productsInChildren: List<ProductHome>
)
fun List<Category>.withProducts(products: List<ProductHome>, categoryWithNoProducts: Boolean) = sequence {
forEach { cat ->
val (productsInCategory, productsInChildren) = products
.filter { it.cat.first().let { mainCat -> cat.name == mainCat.name || cat.name in mainCat.allParents } }
.partition { cat == it.cat.first() }
if (categoryWithNoProducts || productsInCategory.isNotEmpty() || productsInChildren.isNotEmpty()) {
yield(CategoryProducts(cat, productsInCategory, productsInChildren))
}
}
}
fun List<Category>.filterWithProducts(products: List<ProductHome>): List<Category> = filter { cat ->
products.firstOrNull { cat == it.cat.first() || cat.name in it.cat.first().allParents } != null
}
fun String.extractCategories(categories: List<Category>, itemIfEmpty: Category? = null): List<Category> {
fun String.cleanString() = replace("'", " ")
fun findPosition(string: String, category: Category): Pair<Int, Category>? {
var idx: Int
idx = string.indexOf(" ${category.name.cleanString()} ", ignoreCase = true)
if (idx >= 0) return idx to category
category.alias.forEach {
idx = string.indexOf(" ${it.cleanString()} ", ignoreCase = true)
if (idx >= 0) return idx to category
}
return null
}
val sorted = categories
.mapNotNull { category -> findPosition(" ${cleanString()} ", category) }
.sortedByDescending { it.second.name }
.sortedBy { it.first }.map { it.second }
val parents = sorted.allParentsAsString
return sorted.filter { it.name !in parents }
.ifEmpty { if (itemIfEmpty != null) listOf(itemIfEmpty) else emptyList() }
}
val List<Category>.allParentsAsString
get() = flatMap { it.allParents }.distinct()
fun List<Category>.allParents(
categoriesMap: Map<String, Category>,
default: (String) -> Category = { error("Missing category $it") }
) = flatMap { it.allParents }.distinct().map { categoriesMap[it] ?: default(it) } | 0 | Kotlin | 0 | 0 | da932571df18ec333f56f26a4f01f9bfff9547fc | 2,354 | noexp | MIT License |
src/Day07.kt | mcrispim | 573,449,109 | false | {"Kotlin": 46488} | fun main() {
open class MyFile(val name: String, val type: String, val onDir: MyFile?) {
var size = 0
var subItens = mutableListOf<MyFile>()
override fun toString(): String {
return "$name ${if (type == "dir") "(dir [$size])" else "(file, $size)"}"
}
}
var fileSystem = MyFile("/", "dir", null)
var fsPointer = fileSystem
fun moveTo(dir: String): MyFile {
return when (dir) {
"/" -> fileSystem
".." -> fsPointer.onDir ?: fileSystem
else -> fsPointer.subItens.first { it.name == dir && it.type == "dir"}
}
}
fun includeDir(fsPointer: MyFile, dirName: String) {
val dir = fsPointer.subItens.find { it.name == dirName }
dir ?: fsPointer.subItens.add(MyFile(dirName, "dir", fsPointer))
}
fun includeFile(fsPointer: MyFile, line: String) {
val terms = line.split(" ")
val size = terms[0].toInt()
val fileName = terms[1]
var file = fsPointer.subItens.find { it.name == fileName }
if (file == null) {
file = MyFile(fileName, "file", fsPointer)
file.size = size
fsPointer.subItens.add(file)
var pointer = file.onDir
while (pointer != null) {
pointer.size += size
pointer = pointer.onDir
}
}
}
fun getListing(input: List<String>, index: Int): List<String> {
val listing = mutableListOf<String>()
var i = index
while (i < input.size && input[i].first() != '$') {
listing.add(input[i])
i++
}
return listing
}
fun processListing(fsPointer: MyFile, listing: List<String>) {
listing.forEach {line ->
if (line.startsWith("dir "))
includeDir(fsPointer, line.substringAfter("dir "))
else
includeFile(fsPointer, line)
}
}
fun printFSTree(dir: MyFile = fileSystem, spacing: Int = 0) {
println("${" ".repeat(spacing)}- $dir${if (dir == fsPointer) " <===" else ""}")
dir.subItens.forEach {printFSTree(it, spacing + 3) }
}
fun walkTree(dir: MyFile = fileSystem,
predicate: (MyFile) -> Boolean,
result: MutableList<MyFile> = mutableListOf()
): MutableList<MyFile> {
if (predicate(dir))
result.add(dir)
dir.subItens.forEach { walkTree(it, predicate, result)}
return result
}
fun processCommands(input: List<String>, printingTree: Boolean = true) {
var index = 0
while (index <= input.lastIndex) {
if (printingTree) println(input[index])
if (input[index].startsWith("$ cd "))
fsPointer = moveTo(input[index].substringAfter("$ cd "))
else { //input[index].startsWith("$ ls")
val listing = getListing(input, index + 1)
processListing(fsPointer, listing)
index += listing.size
}
if (printingTree) {
printFSTree()
println("======")
}
index++
}
}
fun part1(input: List<String>): Int {
fileSystem = MyFile("/", "dir", null)
fsPointer = fileSystem
processCommands(input, printingTree = false)
val filesDirs = walkTree(fileSystem, { it.type == "dir" && it.size < 100_000 } )
return filesDirs.sumOf { it.size }
}
fun part2(input: List<String>): Int {
fileSystem = MyFile("/", "dir", null)
fsPointer = fileSystem
processCommands(input, printingTree = false)
val totalSpace = 70_000_000
val freeSpace = totalSpace - fileSystem.size
val spaceToUpdate = 30_000_000
val spaceNeeded = spaceToUpdate - freeSpace
val filesDirs = walkTree(fileSystem, { it.type == "dir" && it.size >= spaceNeeded } )
val dirToDelete = filesDirs.minBy { it.size }
return dirToDelete.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07_test")
check(part1(testInput) == 95437)
check(part2(testInput) == 24933642)
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 5fcacc6316e1576a172a46ba5fc9f70bcb41f532 | 4,340 | AoC2022 | Apache License 2.0 |
src/Day10.kt | felldo | 572,233,925 | false | {"Kotlin": 76496} | fun main() {
fun generateCycles(input: List<String>, startCycle: Int): Array<Int> {
val cycles = Array(input.size * 2) { 1 }
var currentCycle = startCycle
var register = 1
for (line in input) {
if (line == "noop") {
currentCycle++
cycles[currentCycle] = register
} else {
val v = line.split(" ").last().toInt()
currentCycle++
cycles[currentCycle] = register
currentCycle++
register += v
cycles[currentCycle] = register
}
}
return cycles
}
fun part1(input: List<String>): Int {
val cycles = generateCycles(input, 1)
return listOf(20, 60, 100, 140, 180, 220).sumOf { it * cycles[it] }
}
fun part2(input: List<String>): String {
val cycles = generateCycles(input, 0)
val output = StringBuilder()
for (i in 0 until 6) {
for (j in 0 until 40) {
val spot = cycles[i * 40 + j]
output.append(
if (spot in (j - 1)..(j + 1)) {
"#"
} else {
" "
})
}
output.appendLine()
}
return output.toString()
}
val input = readInput("Day10")
println(part1(input))
println("\u001B[31m" + part2(input))
} | 0 | Kotlin | 0 | 0 | 0ef7ac4f160f484106b19632cd87ee7594cf3d38 | 1,465 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/questions/CountAndSay.kt | realpacific | 234,499,820 | false | null | package questions
import _utils.UseCommentAsDocumentation
import utils.shouldBe
import java.math.BigInteger
/**
* The count-and-say sequence is a sequence of digit strings defined by the recursive formula:
* * `countAndSay(1)` = "1"
* * `countAndSay(n)` is the way you would "say" the digit string from `countAndSay(n-1)`,which is then converted into a different digit string.
*
* To determine how you "say" a digit string, split it into the minimal number of substrings such that each substring
* contains exactly one unique digit. Then for each substring, say the number of digits, then say the digit.
* Finally, concatenate every said digit.
*
* [Source](https://leetcode.com/problems/count-and-say/)
*/
@UseCommentAsDocumentation
private fun countAndSay(n: Int): String {
if (n == 1) { // base case
return "1"
}
return _countAndSay(n, 2, "1")
}
typealias CharToConsecutiveCount = Pair<Char, Int>
private fun _countAndSay(n: Int, current: Int, value: String): String {
if (current > n) {
return value
}
return _countAndSay(n, current + 1, say(count(value.toBigInteger())))
}
/**
* Count the number of occurrence of a character in a consecutive manner
*/
private fun count(n: BigInteger): List<CharToConsecutiveCount> {
val str = n.toString()
var prevInt = str[0]
var count = 1
val result = mutableListOf<Pair<Char, Int>>()
for (index in 1..str.length) {
if (index == str.length) {
result.add(Pair(prevInt, count))
break
}
if (prevInt == str[index]) {
count++
} else {
result.add(Pair(prevInt, count))
prevInt = str[index]
count = 1
}
}
return result
}
private fun say(charToCount: List<CharToConsecutiveCount>): String {
val result = StringBuilder()
charToCount.forEach {
result.append(it.second.toString()).append(it.first) // occurrence + character
}
return result.toString()
}
fun main() {
countAndSay(11) shouldBe "11131221133112132113212221"
countAndSay(10) shouldBe "13211311123113112211"
countAndSay(1) shouldBe "1"
countAndSay(2) shouldBe "11"
countAndSay(3) shouldBe "21"
countAndSay(4) shouldBe "1211"
countAndSay(5) shouldBe "111221"
} | 4 | Kotlin | 5 | 93 | 22eef528ef1bea9b9831178b64ff2f5b1f61a51f | 2,303 | algorithms | MIT License |
algorithms/src/main/kotlin/algorithms/Quicksort.kt | yuriykulikov | 159,951,728 | false | {"Kotlin": 1666784, "Rust": 33275} | package algorithms
import java.util.*
fun <T : Comparable<T>> List<T>.quickSort(inPlace: Boolean = true): List<T> {
return if (inPlace) {
toMutableList().apply { quickSortInPlace() }
} else {
quickSortNewList()
}
}
fun <T : Comparable<T>> MutableList<T>.quickSortInPlace() {
if (size <= 1) return
val pivotIndex = partition()
subList(0, pivotIndex).quickSortInPlace()
subList(pivotIndex + 1, size).quickSortInPlace()
}
fun <T : Comparable<T>> MutableList<T>.partition(): Int {
val pivot = last()
var swapPosition = 0
(0 until lastIndex).forEach { i ->
if (get(i) <= pivot) {
Collections.swap(this, swapPosition, i)
swapPosition++
}
}
Collections.swap(this, swapPosition, lastIndex)
return swapPosition
}
private fun <T : Comparable<T>> List<T>.quickSortNewList(): List<T> {
return when {
size < 2 -> this
else -> {
val pivot = last()
val withoutPivot = dropLast(1)
val (before, after) = withoutPivot.partition { it < pivot }
before.quickSortNewList() + pivot + after.quickSortNewList()
}
}
}
| 0 | Kotlin | 0 | 1 | f5efe2f0b6b09b0e41045dc7fda3a7565cb21db3 | 1,134 | advent-of-code | MIT License |
y2022/src/main/kotlin/adventofcode/y2022/Day22.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2022
import adventofcode.io.AdventSolution
import adventofcode.util.vector.Direction
import adventofcode.util.vector.Vec2
import java.io.StreamTokenizer
import java.io.StringReader
object Day22 : AdventSolution(2022, 22, "Monkey Map") {
override fun solvePartOne(input: String): Int = solve(input) { grid ->
val xs = grid.flatMapIndexed { y, row ->
val xl = row.indexOfFirst { it != Terrain.Air }
val xr = row.indexOfLast { it != Terrain.Air }
listOf(
Turtle(Vec2(xl, y), Direction.LEFT) to Turtle(Vec2(xr, y), Direction.LEFT),
Turtle(Vec2(xr, y), Direction.RIGHT) to Turtle(Vec2(xl, y), Direction.RIGHT)
)
}
val ys = grid.first().indices.flatMap { x ->
val yt = grid.indexOfFirst { it.getOrElse(x) { Terrain.Air } != Terrain.Air }
val yb = grid.indexOfLast { it.getOrElse(x) { Terrain.Air } != Terrain.Air }
listOf(
Turtle(Vec2(x, yt), Direction.UP) to Turtle(Vec2(x, yb), Direction.UP),
Turtle(Vec2(x, yb), Direction.DOWN) to Turtle(Vec2(x, yt), Direction.DOWN)
)
}
(xs + ys).toMap()
}
override fun solvePartTwo(input: String) = solve(input) {
class Line(val start: Vec2, val dir: Direction, val size: Int) {
val exit = dir.turnRight
val enter = dir.turnLeft
fun asSource() =
generateSequence(start) { it + dir.vector }.take(size).map { Turtle(it, exit) }.toList().reversed()
fun asTarget() = generateSequence(start) { it + dir.vector }.take(size).map { Turtle(it, enter) }.toList()
}
fun stitch(one: Line, two: Line) = one.asSource().zip(two.asTarget()) + two.asSource().zip(one.asTarget())
//net:
// FR
// D
//LB
//U
val fl = Line(Vec2(50, 0), Direction.DOWN, 50)
val fu = Line(Vec2(99, 0), Direction.LEFT, 50)
val ru = Line(Vec2(149, 0), Direction.LEFT, 50)
val rr = Line(Vec2(149, 49), Direction.UP, 50)
val rd = Line(Vec2(100, 49), Direction.RIGHT, 50)
val dl = Line(Vec2(50, 50), Direction.DOWN, 50)
val dr = Line(Vec2(99, 99), Direction.UP, 50)
val ll = Line(Vec2(0, 100), Direction.DOWN, 50)
val lu = Line(Vec2(49, 100), Direction.LEFT, 50)
val br = Line(Vec2(99, 149), Direction.UP, 50)
val bd = Line(Vec2(50, 149), Direction.RIGHT, 50)
val ul = Line(Vec2(0, 150), Direction.DOWN, 50)
val ur = Line(Vec2(49, 199), Direction.UP, 50)
val ud = Line(Vec2(0, 199), Direction.RIGHT, 50)
val glueLines = sequenceOf(
fl, ll,
fu, ul,
rd, dr,
lu, dl,
ur, bd,
rr, br,
ru, ud
)
glueLines.chunked<Line, List<Pair<Turtle, Turtle>>>(2) { (a, b) -> stitch(a, b) }
.flatten()
.toMap()
}
private fun solve(input: String, map: (List<List<Terrain>>) -> Map<Turtle, Turtle>): Int {
val (grid, path) = parse(input)
val initial = Vec2(grid[0].indexOfFirst { it == Terrain.Floor }, 0)
val maze = MonkeyMap(grid, map(grid))
val stretchedPath = path.flatMap {
when (it) {
Move.Left -> listOf(Move.Left)
Move.Right -> listOf(Move.Right)
is Move.Forward -> List(it.steps) { Move.Forward(1) }
}
}
val end = stretchedPath.fold(Turtle(initial, Direction.RIGHT)) { old, move ->
when (move) {
Move.Left -> old.copy(d = old.d.turnLeft)
Move.Right -> old.copy(d = old.d.turnRight)
is Move.Forward -> maze.step(old).let { if (maze[it.p] == Terrain.Floor) it else old }
}
}
return 1000 * (end.p.y + 1) + 4 * (end.p.x + 1) + when (end.d) {
Direction.UP -> 3
Direction.RIGHT -> 0
Direction.DOWN -> 1
Direction.LEFT -> 2
}
}
private fun parse(input: String): Pair<List<List<Terrain>>, Sequence<Move>> {
val (mazeStr, pathStr) = input.split("\n\n")
val maze = parseMaze(mazeStr)
val path = tokenize(pathStr)
return maze to path
}
private fun parseMaze(input: String) = input.lines().map { line ->
line.map { ch ->
when (ch) {
' ' -> Terrain.Air
'.' -> Terrain.Floor
'#' -> Terrain.Wall
else -> throw IllegalStateException()
}
}
}
private fun tokenize(str: String): Sequence<Move> = sequence {
val reader = StringReader(str)
val tokenizer = StreamTokenizer(reader)
tokenizer.ordinaryChar('L'.code)
tokenizer.ordinaryChar('R'.code)
while (tokenizer.nextToken() != StreamTokenizer.TT_EOF) {
val tokenValue = when (tokenizer.ttype) {
StreamTokenizer.TT_NUMBER -> Move.Forward(tokenizer.nval.toInt())
'L'.code -> Move.Left
'R'.code -> Move.Right
else -> throw IllegalArgumentException(tokenizer.ttype.toString())
}
yield(tokenValue)
}
}
sealed class Move {
object Left : Move()
object Right : Move()
data class Forward(val steps: Int) : Move()
}
enum class Terrain { Air, Floor, Wall }
}
private class MonkeyMap(grid: List<List<Day22.Terrain>>, val wrap: Map<Turtle, Turtle>) {
val floor = grid
.flatMapIndexed { y, row ->
row.mapIndexed { x, terrain -> Vec2(x, y) to terrain }
}
.toMap()
.filterValues { it != Day22.Terrain.Air }
operator fun get(position: Vec2) = floor[position] ?: Day22.Terrain.Air
fun step(turtle: Turtle): Turtle =
(wrap[turtle] ?: turtle.copy(p = turtle.p + turtle.d.vector))
}
private data class Turtle(val p: Vec2, val d: Direction) | 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 6,054 | advent-of-code | MIT License |
src/day25/Day25.kt | martin3398 | 572,166,179 | false | {"Kotlin": 76153} | package day25
import readInput
import kotlin.math.pow
fun main() {
fun decToSnafu(dec: Long): String {
var cur = dec
var snafu = ""
while (cur > 0) {
val mod = cur % 5
snafu = when (mod) {
3L -> "="
4L -> "-"
else -> mod.toString()
} + snafu
cur = cur / 5 + mod / 3
}
return snafu
}
fun snafuToDec(snafu: String): Long = snafu.reversed().map {
when (it) {
'-' -> -1L
'=' -> -2L
else -> it.digitToInt().toLong()
}
}.mapIndexed { index, num -> num * 5.0.pow(index).toLong() }.sum()
fun part1(input: List<String>): String {
val dec = input.sumOf { snafuToDec(it) }
return decToSnafu(dec)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput(25, true)
check(part1(testInput) == "2=-1=0")
val input = readInput(25)
println(part1(input))
}
| 0 | Kotlin | 0 | 0 | 4277dfc11212a997877329ac6df387c64be9529e | 1,035 | advent-of-code-2022 | Apache License 2.0 |
src/Day20.kt | frozbiz | 573,457,870 | false | {"Kotlin": 124645} | class CircularList {
class Node(
val num: Long
) {
lateinit var prev: Node
lateinit var next: Node
}
lateinit var orderList: List<Node>
lateinit var zero: Node
var countNodes = 0L
inline fun makeNode(string: String, multiplier: Long): Node {
return Node(string.trim().toLong() * multiplier)
}
fun load(input: List<String>, multiplier: Long = 1) {
val nodeList = ArrayList<Node>(input.size)
val first = makeNode(input[0], multiplier)
var last = first
nodeList.add(last)
if (last.num == 0L) {
zero = last
}
for (line in input.subList(1, input.size)) {
last.next = makeNode(line, multiplier)
last.next.prev = last
last = last.next
nodeList.add(last)
if (last.num == 0L) {
zero = last
}
}
last.next = first
first.prev = last
countNodes = input.size.toLong()
orderList = nodeList
}
fun move(node: Node) {
val num = node.num % (countNodes - 1)
when {
num > 0 -> {
node.next.prev = node.prev
node.prev.next = node.next
for (i in 0 until num) {
node.next = node.next.next
}
node.prev = node.next.prev
node.next.prev = node
node.prev.next = node
}
num < 0 -> {
node.next.prev = node.prev
node.prev.next = node.next
for (i in 0 until -num) {
node.prev = node.prev.prev
}
node.next = node.prev.next
node.next.prev = node
node.prev.next = node
}
}
}
fun print() {
print("0")
var curr = zero.next
do {
print(", ${curr.num}")
curr = curr.next
} while (curr != zero)
println()
}
fun run(passes: Int = 1): Triple<Long, Long, Long> {
repeat(passes) { orderList.forEach { move(it) } }
var curr = zero
repeat(1000) { curr = curr.next }
val one = curr.num
repeat(1000) { curr = curr.next }
val two = curr.num
repeat(1000) { curr = curr.next }
val tre = curr.num
return Triple(one, two, tre)
}
}
fun main() {
fun part1(input: List<String>): Long {
val list = CircularList()
list.load(input)
val ans = list.run()
return ans.first + ans.second + ans.third
}
fun part2(input: List<String>): Long {
val list = CircularList()
list.load(input, 811589153)
val ans = list.run(10)
return ans.first + ans.second + ans.third
}
// test if implementation meets criteria from the description, like:
val testInput = listOf(
"1\n",
"2\n",
"-3\n",
"3\n",
"-2\n",
"0\n",
"4\n",
)
check(part1(testInput) == 3L)
check(part2(testInput) == 1623178306L)
val input = readInput("day20")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 4feef3fa7cd5f3cea1957bed1d1ab5d1eb2bc388 | 3,238 | 2022-aoc-kotlin | Apache License 2.0 |
Problems/Algorithms/200. Number of Islands/NumberOfIslands.kt | xuedong | 189,745,542 | false | {"Kotlin": 332182, "Java": 294218, "Python": 237866, "C++": 97190, "Rust": 82753, "Go": 37320, "JavaScript": 12030, "Ruby": 3367, "C": 3121, "C#": 3117, "Swift": 2876, "Scala": 2868, "TypeScript": 2134, "Shell": 149, "Elixir": 130, "Racket": 107, "Erlang": 96, "Dart": 65} | class Solution {
fun numIslands(grid: Array<CharArray>): Int {
val n = grid.size
val m = grid[0].size
val visited = Array(n) { BooleanArray(m) { false } }
val neighbors = arrayOf(intArrayOf(0, 1), intArrayOf(0, -1), intArrayOf(1, 0), intArrayOf(-1, 0))
var ans = 0
for (i in 0..n-1) {
for (j in 0..m-1) {
if (!visited[i][j] && grid[i][j] == '1') {
ans++
val queue = ArrayDeque<IntArray>()
queue.add(intArrayOf(i, j))
while (!queue.isEmpty()) {
for (k in 0..queue.size-1) {
val curr = queue.removeLast()
val row = curr[0]
val col = curr[1]
visited[row][col] = true
for (neighbor in neighbors) {
mark(queue, row+neighbor[0], col+neighbor[1], visited, grid)
}
}
}
}
}
}
return ans
}
private fun mark(queue: ArrayDeque<IntArray>, i: Int, j: Int, visited: Array<BooleanArray>, grid: Array<CharArray>): Unit {
if (i < 0 || i >= grid.size || j < 0 || j >= grid[0].size || grid[i][j] == '0' || visited[i][j]) return
visited[i][j] = true;
queue.add(intArrayOf(i, j))
}
}
| 0 | Kotlin | 0 | 1 | 5e919965b43917eeee15e4bff12a0b6bea4fd0e7 | 1,549 | leet-code | MIT License |
aoc/src/main/kotlin/com/bloidonia/aoc2023/day06/Main.kt | timyates | 725,647,758 | false | {"Kotlin": 45518, "Groovy": 202} | package com.bloidonia.aoc2023.day06
import com.bloidonia.aoc2023.lines
private const val example = """Time: 7 15 30
Distance: 9 40 200"""
private fun distance(time: Long, best: Long) = (0..time).map { it * (time - it) }.count { it > best }
private fun parse(input: List<String>) = input[0].split(Regex("\\s+")).drop(1).map { it.toLong() }
.zip(input[1].split(Regex("\\s+")).drop(1).map { it.toLong() })
private fun parse2(input: List<String>) = listOf(
input[0].split(Regex("\\s+")).drop(1).joinToString("").toLong() to
input[1].split(Regex("\\s+")).drop(1).joinToString("").toLong()
)
fun main() {
parse(example.lines()).map { (time, best) -> distance(time, best) }.reduce(Int::times).let(::println)
parse(lines("/day06.input")).map { (time, best) -> distance(time, best) }.reduce(Int::times).let(::println)
parse2(example.lines()).map { (time, best) -> distance(time, best) }.reduce(Int::times).let(::println)
parse2(lines("/day06.input")).map { (time, best) -> distance(time, best) }.reduce(Int::times).let(::println)
} | 0 | Kotlin | 0 | 0 | 158162b1034e3998445a4f5e3f476f3ebf1dc952 | 1,076 | aoc-2023 | MIT License |
aockt-test/src/test/kotlin/io/github/jadarma/aockt/test/integration/ExampleCompilesRunsAndPasses.kt | Jadarma | 324,646,170 | false | {"Kotlin": 38013} | package io.github.jadarma.aockt.test.integration
import io.github.jadarma.aockt.core.Solution
import io.github.jadarma.aockt.test.AdventDay
import io.github.jadarma.aockt.test.AdventSpec
/** A solution to a fictitious puzzle used for testing. */
class Y9999D01 : Solution {
private fun parseInput(input: String): List<Int> =
input
.splitToSequence(',')
.map(String::toInt)
.toList()
override fun partOne(input: String) = parseInput(input).filter { it % 2 == 1 }.sum()
override fun partTwo(input: String) = parseInput(input).reduce { a, b -> a * b }
}
/**
* A test for a fictitious puzzle.
*
* ```text
* The input is a string of numbers separated by a comma.
* Part 1: Return the sum of the odd numbers.
* Part 2: Return the product of the numbers.
* ```
*/
@AdventDay(9999, 1, "Magic Numbers")
class Y9999D01Test : AdventSpec<Y9999D01>({
partOne {
"1,2,3" shouldOutput 4
listOf("0", "2,4,6,8", "2,2,2,2") shouldAllOutput 0
"1,2,5" shouldOutput 6
}
partTwo {
"1,2,3" shouldOutput 6
}
})
| 0 | Kotlin | 0 | 4 | 1db6da68069a72256c3e2424a0d2729fc59eb0cf | 1,106 | advent-of-code-kotlin | MIT License |
solutions/aockt/y2021/Y2021D07.kt | Jadarma | 624,153,848 | false | {"Kotlin": 435090} | package aockt.y2021
import io.github.jadarma.aockt.core.Solution
import kotlin.math.absoluteValue
import kotlin.math.roundToInt
object Y2021D07 : Solution {
/** Return the median value of this collection of numbers, or `null` if the collection is empty. */
private fun Collection<Int>.medianOrNull(): Double? {
if (isEmpty()) return null
return sorted().run {
when (size % 2) {
0 -> (this[size / 2] + this[size / 2 - 1]) / 2.0
else -> this[size / 2].toDouble()
}
}
}
/** Parse the input and return the sequence of the crab's horizontal positions. */
private fun parseInput(input: String): List<Int> =
input
.splitToSequence(',')
.map { it.toIntOrNull() ?: throw IllegalArgumentException() }
.toList().also { require(it.isNotEmpty()) }
override fun partOne(input: String): Int {
val positions = parseInput(input)
val median = positions.medianOrNull()!!.roundToInt()
return positions.sumOf { (it - median).absoluteValue }
}
override fun partTwo(input: String): Any {
val positions = parseInput(input).sorted()
return (positions.first()..positions.last()).minOf { candidate ->
positions
.sumOf { (it - candidate).absoluteValue.let { n -> n * (n + 1) / 2.0 } }
.roundToInt()
}
}
}
| 0 | Kotlin | 0 | 3 | 19773317d665dcb29c84e44fa1b35a6f6122a5fa | 1,435 | advent-of-code-kotlin-solutions | The Unlicense |
src/iii_conventions/MyDate.kt | schnell18 | 150,126,108 | true | {"Kotlin": 74962, "Java": 4952} | package iii_conventions
data class RepeatedTimeInterval(val interval: TimeInterval, val repeat : Int = 1)
enum class TimeInterval {
DAY(),
WEEK(),
YEAR();
operator fun times(i: Int): RepeatedTimeInterval {
return RepeatedTimeInterval(this, i)
}
}
data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int) {
operator fun compareTo(date2: MyDate): Int {
return when {
this.year != date2.year -> this.year.compareTo(date2.year)
this.month != date2.month -> this.month.compareTo(date2.month)
else -> this.dayOfMonth.compareTo(date2.dayOfMonth)
}
}
fun nextDay(days : Int = 1) : MyDate {
var d = this.dayOfMonth
var m = this.month
var y = this.year
val daysOfMonth = when (m) {
1, 3, 5, 7, 8, 10, 12 -> 31
2 -> if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) 29 else 28
else -> 30
}
var remainder = 0
when {
days <= daysOfMonth - this.dayOfMonth -> d += days
days <= daysOfMonth - this.dayOfMonth + 28 -> {
d += days - daysOfMonth
m += 1
}
else -> {
remainder = days - 28 - (daysOfMonth - this.dayOfMonth)
d = 28
m += 1
}
}
if (m > 12) {
m = 1
y += 1
}
val result = MyDate(y, m, d)
if (remainder > 0) {
return result.nextDay(remainder)
}
return result
}
}
operator fun MyDate.rangeTo(other: MyDate): DateRange = DateRange(this, other)
class DateRange(val start: MyDate, val endInclusive: MyDate) {
operator fun contains(d: MyDate) = start <= d && d <= endInclusive
operator fun iterator(): Iterator<MyDate> {
return object : Iterator<MyDate> {
var currentDate = start.copy()
override fun hasNext(): Boolean {
return currentDate <= endInclusive
}
override fun next(): MyDate {
val retDate = currentDate
currentDate = currentDate.nextDay()
return retDate
}
}
}
}
| 0 | Kotlin | 0 | 0 | 7c1e281aba1627dbe646d3c2b870b53a914a8442 | 2,262 | kotlin-koans | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/GlobalAndLocalInversions.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import kotlin.math.abs
import kotlin.math.min
/**
* Global and Local Inversions
* @see <a href="https://leetcode.com/problems/global-and-local-inversions/">Source</a>
*/
fun interface GlobalAndLocalInversions {
fun isIdealPermutation(a: IntArray): Boolean
}
/**
* Approach #2: Remember Minimum
*/
class IdealPermutationRememberMinimum : GlobalAndLocalInversions {
override fun isIdealPermutation(a: IntArray): Boolean {
val n: Int = a.size
var floor = n
for (i in n - 1 downTo 2) {
floor = min(floor, a[i])
if (a[i - 2] > floor) return false
}
return true
}
}
/**
* Approach #3: Linear Scan
*/
class IdealPermutationLinearScan : GlobalAndLocalInversions {
override fun isIdealPermutation(a: IntArray): Boolean {
for (i in a.indices) if (abs(a[i] - i) > 1) return false
return true
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,537 | kotlab | Apache License 2.0 |
src/main/kotlin/aoc2019/DonutMaze.kt | komu | 113,825,414 | false | {"Kotlin": 395919} | package komu.adventofcode.aoc2019
import komu.adventofcode.utils.Point
import komu.adventofcode.utils.nonEmptyLines
import utils.shortestPathBetween
fun donutMaze1(input: String): Int {
val maze = DonutMaze.parse(input)
val path = shortestPathBetween(maze.start, maze.end) { it.directNeighbors + listOfNotNull(it.portalNeighbor) }
?: error("no path")
return path.size
}
fun donutMaze2(input: String): Int {
val maze = DonutMaze.parse(input)
val path = shortestPathBetween(
LeveledNode(maze.start, 0),
LeveledNode(maze.end, 0)) { it.neighbors }
?: error("no path")
return path.size
}
private data class LeveledNode(val node: DonutNode, val level: Int) {
val neighbors: List<LeveledNode>
get() {
val directNeighbors = node.directNeighbors.map { LeveledNode(it, level) }
val portalNeighbor = node.portalNeighbor?.let {
when {
node.portalDown && level < 25 -> LeveledNode(it, level + 1)
!node.portalDown && level > 0 -> LeveledNode(it, level - 1)
else -> null
}
}
return directNeighbors + listOfNotNull(portalNeighbor)
}
}
private class DonutMaze(
val start: DonutNode,
val end: DonutNode,
) {
companion object {
fun parse(input: String): DonutMaze {
val lines = input.nonEmptyLines()
val nodesByPoint = mutableMapOf<Point, DonutNode>()
var start: Point? = null
var end: Point? = null
val portalsInProgress = mutableMapOf<String, Point>()
val portals = mutableMapOf<Point, Point>()
fun get(x: Int, y: Int) = lines.getOrNull(y)?.getOrNull(x) ?: ' '
fun addPortal(label: String, point: Point) {
when (label) {
"AA" -> start = point
"ZZ" -> end = point
else -> {
val otherEnd = portalsInProgress.remove(label)
if (otherEnd != null) {
portals[point] = otherEnd
portals[otherEnd] = point
} else
portalsInProgress[label] = point
}
}
}
for ((y, line) in lines.withIndex()) {
for ((x, c) in line.withIndex()) {
when {
c == '.' ->
nodesByPoint[Point(x, y)] = DonutNode()
c.isLetter() -> {
when {
get(x + 1, y).isLetter() -> {
val label = "${c}${get(x + 1, y)}"
val point = if (get(x - 1, y) == '.') Point(x - 1, y) else Point(x + 2, y)
addPortal(label, point)
}
get(x, y + 1).isLetter() -> {
val label = "${c}${get(x, y + 1)}"
val point = if (get(x, y - 1) == '.') Point(x, y - 1) else Point(x, y + 2)
addPortal(label, point)
}
}
}
c in " #" -> {
// ignore
}
else -> error("unexpected '$c'")
}
}
}
check(portalsInProgress.isEmpty() && start != null && end != null)
for ((point, node) in nodesByPoint) {
val portal = portals[point]
if (portal != null) {
node.portalDown = point.x in 4..79 && point.y in 4..90
node.portalNeighbor = nodesByPoint[portal]!!
}
node.directNeighbors = point.neighbors.mapNotNull { nodesByPoint[it] }
}
val maze = DonutMaze(
start = nodesByPoint[start!!] ?: error("no start"),
end = nodesByPoint[end!!] ?: error("no end")
)
return maze
}
}
}
private class DonutNode {
var directNeighbors = emptyList<DonutNode>()
var portalNeighbor: DonutNode? = null
var portalDown = false
}
| 0 | Kotlin | 0 | 0 | 8e135f80d65d15dbbee5d2749cccbe098a1bc5d8 | 4,452 | advent-of-code | MIT License |
src/day11/Day11.kt | pnavais | 574,712,395 | false | {"Kotlin": 54079} | package day11
import readInput
import java.util.*
import kotlin.math.floor
enum class Operator {
SUM, MULTIPLY, SUBTRACT, DIVIDE, NONE;
companion object {
fun from(c: Char): Operator {
return when (c) {
'+' -> SUM
'*' -> MULTIPLY
'-' -> SUBTRACT
'/' -> DIVIDE
else -> NONE
}
}
}
}
class Factor(val isOld: Boolean = false, val value: Long = 0L) {
companion object {
fun from(s: String): Factor {
return if (s == "old") { Factor(true, 0L) } else {
Factor(false, s.toLong())
}
}
}
}
class Operation(private val first: Factor, private val operator: Operator, private val second: Factor) {
fun run(old: Long): Long {
val firstValue = if (first.isOld) { old } else { first.value }
val secondValue = if (second.isOld) { old } else { second.value }
return when (operator) {
Operator.SUM -> firstValue + secondValue
Operator.MULTIPLY -> firstValue * secondValue
Operator.SUBTRACT -> firstValue - secondValue
Operator.DIVIDE -> firstValue / secondValue
Operator.NONE -> firstValue
}
}
}
class Monkey(val id: Int,
var items: Queue<Long> = LinkedList(),
var operation: Operation? = null,
var tester: (new: Long) -> Int = { _ -> 0 },
var reducer: (new: Long) -> Long = { n -> n }) {
var visitor: ItemVisitor = MonkeyItemCounter()
}
interface ItemVisitor {
fun visitItem(item: Long)
fun getData(): Long
}
class MonkeyItemCounter : ItemVisitor {
private var counter: Long = 0L
override fun visitItem(item: Long) {
counter++
}
override fun getData(): Long {
return counter
}
}
class MonkeyGroup {
private val monkeyList: MutableList<Monkey> = mutableListOf()
private var lcm: Long = 0L
fun parseSpec(input: List<String>) {
var monkey: Monkey? = null
val dividers = mutableListOf<Long>()
var divider = 0L
var monkeyTargetId = 0
for (line in input) {
if (line.startsWith("Monkey")) {
val id = Regex("^Monkey (\\d+):$").find(line)?.groupValues?.get(1)?.toInt()
monkey = Monkey(id!!)
} else if ("^\\s*Starting items:".toRegex().containsMatchIn(line)) {
line.split(": ")[1].split(", ").map { i -> i.toLong() }.forEach { i -> monkey?.items?.add(i) }
} else if ("^\\s*Operation:".toRegex().containsMatchIn(line)) {
val (first, op, second) = line.split(" = ")[1].split(" ")
monkey?.operation = Operation(Factor.from(first), Operator.from(op.first()), Factor.from(second))
} else if ("^\\s*Test: divisible by".toRegex().containsMatchIn(line)) {
divider = Regex("divisible by (\\d+)").find(line)?.groupValues?.get(1)?.toLong()!!
dividers.add(divider)
} else if ("^\\s*If (true|false):".toRegex().containsMatchIn(line)) {
monkeyTargetId = parseTester(line, monkeyTargetId, monkey, divider)
}
}
lcm = computeLcm(dividers)
}
fun run(numRounds: Long, debug: Boolean = false, useReducer: Boolean = false, worryFunction: (n: Long) -> Long = { n -> n }) {
for (i in 1..numRounds) {
for (monkey in monkeyList) {
while (monkey.items.isNotEmpty()) {
monkey.visitor.visitItem(i)
val original = monkey.items.poll()
var newItem = monkey.operation?.run(original)?.let { worryFunction(it) }
val targetId = newItem?.let { monkey.tester(it) }
newItem = if (useReducer) { newItem?.let { monkey.reducer(it) } } else { newItem }
monkeyList[targetId!!].items.add(newItem)
}
}
if (debug) {
printStatus(i)
}
}
//if (debug) {
printVisitorStats()
//}
}
fun computeMonkeyBusiness(): Long {
return monkeyList.map { monkey -> monkey.visitor.getData() }.sortedDescending().take(2).reduce { x, y -> x * y }
}
private fun parseTester(line: String, monkeyTargetId: Int, monkey: Monkey?, divider: Long): Int {
val monkeyId = Regex("throw to monkey (\\d+)").find(line)?.groupValues?.get(1)?.toInt()!!
if (line.contains("If false")) {
monkey?.tester = { n -> if (n % divider == 0L) { monkeyTargetId} else { monkeyId } }
monkey?.reducer = { n -> n % lcm }
monkeyList.add(monkey!!)
}
return monkeyId
}
private fun computeLcm(nums: List<Long>): Long {
val lcmMap = mutableMapOf<Long, Int>()
var found = false
var mcm = -1L
var counter = 1L
while (!found) {
for (i in nums) {
val m = i * counter
lcmMap.merge(m, 1) { o, _ -> o + 1 }
if (lcmMap[m] == nums.size) {
mcm = m
found = true
}
}
counter++
}
return mcm
}
private fun printStatus(roundNum: Long) {
println("After round $roundNum, the monkeys are holding items with these worry levels:")
for (monkey in monkeyList) {
print("Monkey ${monkey.id}: ")
var prefix = ""
for (item in monkey.items) {
print("${prefix}${item}")
prefix = ", "
}
println()
}
println()
}
private fun printVisitorStats() {
for (monkey in monkeyList) {
println("Monkey ${monkey.id} inspected items ${monkey.visitor.getData()} times.")
}
}
}
fun part1(input: List<String>): Long {
val monkeyGroup = MonkeyGroup()
monkeyGroup.parseSpec(input)
monkeyGroup.run(20, worryFunction = { n -> n.toFloat().div(3.0f).let { floor(it).toLong() } })
return monkeyGroup.computeMonkeyBusiness()
}
fun part2(input: List<String>): Long {
val monkeyGroup = MonkeyGroup()
monkeyGroup.parseSpec(input)
monkeyGroup.run(10000, debug = false, useReducer = true)
return monkeyGroup.computeMonkeyBusiness()
}
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day11/Day11_test")
println(part1(testInput))
println(part2(testInput))
}
| 0 | Kotlin | 0 | 0 | ed5f521ef2124f84327d3f6c64fdfa0d35872095 | 6,789 | advent-of-code-2k2 | Apache License 2.0 |
src/nativeMain/kotlin/Day14.kt | rubengees | 576,436,006 | false | {"Kotlin": 67428} | import Day14.Material.ROCK
import Day14.Material.SAND
class Day14 : Day {
private data class Point(val x: Int, val y: Int) {
fun rangeTo(other: Point): List<Point> {
return (x toward other.x).flatMap { x ->
(y toward other.y).map { y -> Point(x, y) }
}
}
private infix fun Int.toward(to: Int): IntProgression {
val step = if (this > to) -1 else 1
return IntProgression.fromClosedRange(this, to, step)
}
}
private enum class Material { ROCK, SAND }
private class Matrix(data: Map<Point, Material>, private val floor: Int? = null) {
private val data = data.toMutableMap()
private val voidStart = floor?.plus(1) ?: data.maxOf { (point) -> point.y + 1 }
fun isBlocked(point: Point): Boolean {
return point.y == floor || data[point] != null
}
fun addSand(): Boolean {
var x = 500
var y = 0
while (y < voidStart) {
if (!isBlocked(Point(x, y + 1))) {
y += 1
} else if (!isBlocked(Point(x - 1, y + 1))) {
x -= 1
y += 1
} else if (!isBlocked(Point(x + 1, y + 1))) {
x += 1
y += 1
} else if (!isBlocked(Point(x, y))) {
data[Point(x, y)] = SAND
return true
} else {
return false
}
}
return false
}
fun withFloor(): Matrix {
return Matrix(data, voidStart + 1)
}
}
private fun parse(input: String): Matrix {
val data = mutableMapOf<Point, Material>()
for (line in input.lines()) {
val points = line.split(" -> ").map { point ->
val (x, y) = point.split(",").map { it.toInt() }
Point(x, y)
}
val ranges = points.fold(emptyList<Point>()) { acc, point ->
acc + (acc.lastOrNull()?.rangeTo(point) ?: listOf(point))
}
data.putAll(ranges.associateWith { ROCK })
}
return Matrix(data)
}
override suspend fun part1(input: String): String {
val matrix = parse(input)
return generateSequence { matrix.addSand() }.takeWhile { it }.count().toString()
}
override suspend fun part2(input: String): String {
val matrix = parse(input).withFloor()
return generateSequence { matrix.addSand() }.takeWhile { it }.count().toString()
}
}
| 0 | Kotlin | 0 | 0 | 21f03a1c70d4273739d001dd5434f68e2cc2e6e6 | 2,641 | advent-of-code-2022 | MIT License |
src/Day10.kt | aneroid | 572,802,061 | false | {"Kotlin": 27313} | import Operation.*
private enum class Operation(val cycleCost: Int) {
NOOP(1),
ADDX(2),
;
companion object {
fun fromString(s: String): Operation =
values().first { it.name == s.uppercase() }
}
}
private class CPU(var accX: Int = 1) {
private var cycle = 1
private val cyclesOfInterest = 20..220 step 40
val signalStrengths = mutableListOf<Int>()
// variables added for part 2
val pixels = mutableListOf(mutableListOf<Char>())
val spriteSize = 3
private fun processCycle() {
if (cycle in cyclesOfInterest) {
// println(" *** processCycle: $cycle")
signalStrengths += signalStrength()
}
// drawSprite
val crtPos = (cycle - 1) % 40
val spritePos = accX - 1
pixels.last().add(if (crtPos in spritePos until spritePos + spriteSize) '#' else '.')
if (cycle % 40 == 0) {
pixels.add(mutableListOf())
}
}
private fun signalStrength(): Int = accX * cycle
fun execute(op: Operation, arg: Int) {
repeat(op.cycleCost) {
// println(" cycle $cycle: accX = $accX")
processCycle()
cycle++
}
when (op) {
NOOP -> Unit
ADDX -> accX += arg
}
}
}
class Day10(input: List<String>) {
private val program = input.map {
it.substring(0, 4).toOP() to it.substringAfter(" ", "0").toInt()
}
private fun String.toOP() = Operation.fromString(this)
private fun processProgram(): CPU =
CPU().apply {
program.forEach { (instr, arg) ->
// println("${instr.name} $arg")
execute(instr, arg)
}
}
fun partOne(): Int {
val cpu = processProgram()
println("signal strengths: ${cpu.signalStrengths}")
return cpu.signalStrengths.sum()
}
fun partTwo(): List<String> {
val cpu = processProgram()
println(cpu.pixels.joinToString("\n") {
it.joinToString("")
// .replace(".", " ")
// .replace("#", "█")
.replace(".", "⚫️️")
.replace("#", "⚪")
})
return cpu.pixels.map { it.joinToString("") }
}
}
fun main() {
val testInput = readInput("Day10_test")
val input = readInput("Day10")
println("part One:")
assertThat(Day10(testInput).partOne()).isEqualTo(13140)
println("actual: ${Day10(input).partOne()}\n")
println("part Two:")
// uncomment when ready
val expectedOutputPart2 = """
##..##..##..##..##..##..##..##..##..##..
###...###...###...###...###...###...###.
####....####....####....####....####....
#####.....#####.....#####.....#####.....
######......######......######......####
#######.......#######.......#######.....
""".trimIndent().lines()
assertThat(Day10(testInput).partTwo().take(6)).isEqualTo(expectedOutputPart2)
println("actual: ${Day10(input).partTwo()}\n")
}
| 0 | Kotlin | 0 | 0 | cf4b2d8903e2fd5a4585d7dabbc379776c3b5fbd | 3,112 | advent-of-code-2022-kotlin | Apache License 2.0 |
calendar/day09/Day9.kt | starkwan | 573,066,100 | false | {"Kotlin": 43097} | package day09
import Day
import Lines
import kotlin.math.abs
import kotlin.math.sign
class Day9 : Day() {
override fun part1(input: Lines): Any {
val tailVisitedSet = mutableSetOf<Knot>()
var rope = Rope(Knot(0, 0), Knot(0, 0))
input.forEach {
val (action, times) = it.split(" ")
repeat(times.toInt()) {
rope = rope.move(action)
tailVisitedSet.add(rope.tail)
}
}
return tailVisitedSet.size
}
override fun part2(input: Lines): Any {
val tailVisitedSet = mutableSetOf<Knot>()
var longRope = LongRope(List(10) { Knot(0, 0) })
input.forEach {
val (action, times) = it.split(" ")
repeat(times.toInt()) {
longRope = longRope.move(action)
tailVisitedSet.add(longRope.knots.last())
}
}
return tailVisitedSet.size
}
class Rope(val head: Knot, val tail: Knot) {
fun move(action: String): Rope {
val newHead = moveHead(action)
return Rope(newHead, moveTailPart1(newHead))
}
fun move(newHead: Knot): Rope {
return Rope(newHead, moveTailPart2(newHead))
}
private fun moveHead(action: String): Knot {
return when (action) {
"U" -> head.copy(y = head.y + 1)
"D" -> head.copy(y = head.y - 1)
"R" -> head.copy(x = head.x + 1)
"L" -> head.copy(x = head.x - 1)
else -> error("wrong action")
}
}
private fun moveTailPart1(newHead: Knot): Knot {
// Works for part 1 only (since no diagonal move)
return if (abs(newHead.x - tail.x) == 2 || abs(newHead.y - tail.y) == 2) {
head
} else {
tail
}
}
private fun moveTailPart2(newHead: Knot): Knot {
// Works for part 1 and part 2
return if (abs(newHead.x - tail.x) == 2 || abs(newHead.y - tail.y) == 2) {
Knot(tail.x + (newHead.x - tail.x).sign, tail.y + (newHead.y - tail.y).sign)
} else {
tail
}
}
}
class LongRope(var knots: List<Knot>) {
fun move(action: String): LongRope {
val ropes = knots.windowed(2, 1).map { (a, b) -> Rope(a, b) }
val newKnots = mutableListOf<Knot>()
ropes.forEachIndexed { i, rope ->
if (i == 0) {
with(rope.move(action)) {
newKnots.add(this.head)
newKnots.add(this.tail)
}
} else {
newKnots.add(rope.move(newKnots.last()).tail)
}
}
return LongRope(newKnots.toList())
}
}
data class Knot(val x: Int, val y: Int)
} | 0 | Kotlin | 0 | 0 | 13fb66c6b98d452e0ebfc5440b0cd283f8b7c352 | 2,938 | advent-of-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/com/ikueb/advent18/Day02.kt | h-j-k | 159,901,179 | false | null | package com.ikueb.advent18
object Day02 {
fun getChecksum(input: List<String>) = input
.map { word -> word.groupingBy { it }.eachCount() }
.map { Pair(it.containsValue(2).toInt(), it.containsValue(3).toInt()) }
.reduce { a, b -> Pair(a.first + b.first, a.second + b.second) }
.let { it.first * it.second }
private fun Boolean.toInt() = if (this) 1 else 0
fun getCommonLetters(input: List<String>): String {
val sums = mutableMapOf<Int, Set<String>>()
for (current in input) {
val currentSum = current.sumBy { it.toInt() }
val found = sums.filterKeys { Math.abs(currentSum - it) <= 25 }
.flatMap { it.value }
.map { getCandidateResult(current, it) }
.find { it != null }
if (found != null) {
return found
} else {
sums.mergeSetValues(currentSum, current)
}
}
throw IllegalArgumentException("No results.")
}
private fun getCandidateResult(a: String, b: String): String? {
var differenceIndex = -1
var count = 1
for (i in a.indices) {
if (a[i] != b[i]) {
differenceIndex = i
count--
if (count < 0) {
return null
}
}
}
return a.substring(0, differenceIndex) + a.substring(differenceIndex + 1)
}
} | 0 | Kotlin | 0 | 0 | f1d5c58777968e37e81e61a8ed972dc24b30ac76 | 1,500 | advent18 | Apache License 2.0 |
src/2021/Day08.kt | nagyjani | 572,361,168 | false | {"Kotlin": 369497} | package `2021`
import java.io.File
import java.util.*
fun main() {
Day08().solve()
}
val input = """ be cfbegad cbdgef fgaecd cgeb fdcge agebfd fecdb fabcd edb | fdgacbe cefdb cefbgd gcbe
edbfga begcd cbg gc gcadebf fbgde acbgfd abcde gfcbed gfec | fcgedb cgb dgebacf gc
fgaebd cg bdaec gdafb agbcfd gdcbef bgcad gfac gcb cdgabef | cg cg fdcagb cbg
fbegcd cbd adcefb dageb afcb bc aefdc ecdab fgdeca fcdbega | efabcd cedba gadfec cb
aecbfdg fbg gf bafeg dbefa fcge gcbea fcaegb dgceab fcbdga | gecf egdcabf bgf bfgea
fgeab ca afcebg bdacfeg cfaedg gcfdb baec bfadeg bafgc acf | gebdcfa ecba ca fadegcb
dbcfg fgd bdegcaf fgec aegbdf ecdfab fbedc dacgb gdcebf gf | cefg dcbef fcge gbcadfe
bdfegc cbegaf gecbf dfcage bdacg ed bedf ced adcbefg gebcd | ed bcgafe cdgba cbgef
egadfb cdbfeg cegd fecab cgb gbdefca cg fgcdab egfdb bfceg | gbdfcae bgc cg cgb
gcafb gcf dcaebfg ecagb gf abcdeg gaef cafbge fdbac fegbdc | fgae cfgab fg bagce"""
fun Set<Char>.comp(): Set<Char> {
return "abcdefg".toSet().subtract(this)
}
fun List<Set<Char>>.toChar(f: (Set<Char>) -> Set<Char>): Char {
return this.map{f(it)}.filter{it.size == 1}.first().first()
}
fun Map<Int, List<Set<Char>>>.single(i: Int): Set<Char> {
return this[i]!![0]
}
fun Map<Int, List<Set<Char>>>.multi(i: Int): List<Set<Char>> {
return this[i]!!
}
class Coder {
val codeMap = mutableMapOf<Char, Char>()
val decodeMap = mutableMapOf<Char, Char>()
fun add(decoded: Char, coded: Char): Coder {
codeMap[decoded] = coded
decodeMap[coded] = decoded
return this
}
fun code(s: String): Set<Char> {
return code(s.toSet())
}
fun code(s: Set<Char>): Set<Char> {
return s.map{codeMap[it]!!}.toSet()
}
fun decode(s: String): Set<Char> {
return decode(s.toSet())
}
fun decode(s: Set<Char>): Set<Char> {
return s.map{decodeMap[it]!!}.toSet()
}
}
fun Set<Char>.toKey(): String {
return this.toList().sorted().joinToString("")
}
//7 - 8
//6 - 0 (abcefg) (d) 6 (abdefg) (c) 9 (abcdfg) (e)
//5 - 2 (acdeg) (bf) 3 (acdfg) (be) 5 (abdfg) (ce)
//4 - 4 (bcdf) (aeg)
//3 - 7 (acf) (bdeg)
//2 - 1 (cf)
//
//L3 - L2 = a
//oL6 - (L4+a) = g
//cL4 - a - g = e
//cL3 - e - g - coL6 = b
//cL3 - b - e - g = d
//ocL6 - d - e = c
//L2 - c = f
class Day08 {
fun solve() {
val f = File("src/2021/inputs/day08.in")
val s = Scanner(f)
// val s = Scanner(input)
val dm = mapOf(0 to "abcefg", 1 to "cf", 2 to "acdeg", 3 to "acdfg", 4 to "bcdf",
5 to "abdfg", 6 to "abdefg", 7 to "acf", 8 to "abcdefg", 9 to "abcdfg").mapValues { it.value.toSet().toKey() }
val rdm = dm.entries.associateBy({it.value }) {it.key}
var r = mutableListOf<Int>()
var r1 = mutableListOf<Int>()
while (s.hasNextLine()) {
val lineHalfs = s.nextLine().trim().split("|").map { it.trim() }
val allDigits = lineHalfs[0].split(" ").map{it.toSet()}
val interestingDigits = lineHalfs[1].split(" ").map{it.toSet()}
val lm = allDigits.groupBy{it.size}
val coder = Coder()
coder.add('a', lm.single(3).subtract(lm.single(2)).first())
coder.add('g', lm.multi(6).toChar{ it.subtract(lm.single(4)).subtract(coder.code("a")) })
coder.add('e', lm.single(4).comp().subtract(coder.code("ag")).first())
coder.add('b', lm.multi(6).toChar{lm.single(3).comp().subtract(coder.code("eg")).subtract(it.comp())})
coder.add('d', lm.single(3).comp().subtract(coder.code("beg")).first())
coder.add('c', lm.multi(6).toChar{it.comp().subtract(coder.code("de"))})
coder.add('f', lm.single(2).subtract(coder.code("c")).first())
r1.addAll(interestingDigits.map{rdm[coder.decode(it).toKey()]!!})
r.add(interestingDigits.map{rdm[coder.decode(it).toKey()]!!.toString()}.joinToString("").toInt())
}
println("${r1.filter{it == 1 || it == 4 || it == 7 || it ==8}.count()} ${r.sum()}")
}
}
//be cfbegad cbdgef(9) fgaecd cgeb fdcge agebfd fecdb fabcd edb |
//fdgacbe cefdb cefbgd gcbe
| 0 | Kotlin | 0 | 0 | f0c61c787e4f0b83b69ed0cde3117aed3ae918a5 | 4,316 | advent-of-code | Apache License 2.0 |
src/main/kotlin/g0901_1000/s0924_minimize_malware_spread/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g0901_1000.s0924_minimize_malware_spread
// #Hard #Array #Depth_First_Search #Breadth_First_Search #Matrix #Union_Find
// #2023_04_17_Time_791_ms_(100.00%)_Space_59.7_MB_(100.00%)
class Solution {
private lateinit var size: IntArray
private lateinit var par: IntArray
fun minMalwareSpread(graph: Array<IntArray>, initial: IntArray): Int {
size = IntArray(graph.size)
par = IntArray(graph.size)
for (i in graph.indices) {
size[i] = 1
par[i] = i
}
// create groups
for (i in graph.indices) {
for (j in graph[0].indices) {
if (graph[i][j] == 1) {
val p1 = find(i)
val p2 = find(j)
merge(p1, p2)
}
}
}
// no of infected in group
val infected = IntArray(graph.size)
for (e in initial) {
val p = find(e)
infected[p]++
}
var currSize = -1
var ans = -1
for (e in initial) {
val p = find(e)
if (infected[p] == 1 && size[p] >= currSize) {
ans = if (size[p] > currSize) {
e
} else {
ans.coerceAtMost(e)
}
currSize = size[p]
}
}
// all groups have more than 1 infected node then return min value from initial
if (ans == -1) {
ans = initial[0]
for (j in initial) {
ans = ans.coerceAtMost(j)
}
}
return ans
}
private fun merge(p1: Int, p2: Int) {
if (p1 != p2) {
if (size[p1] > size[p2]) {
par[p2] = p1
size[p1] += size[p2]
} else {
par[p1] = p2
size[p2] += size[p1]
}
}
}
private fun find(u: Int): Int {
if (par[u] == u) {
return u
}
par[u] = find(par[u])
return par[u]
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 2,074 | LeetCode-in-Kotlin | MIT License |
13/src/main/kotlin/TableSitting.kt | kopernic-pl | 109,750,709 | false | null | import com.google.common.collect.Collections2
import com.google.common.io.Resources
@Suppress("UnstableApiUsage")
fun main() {
val input = Resources.getResource("input.txt").readText()
val bestSittingWithoutMe = SittingPlan().findBestSitting(SittingPreferences(input))
println(bestSittingWithoutMe)
val bestSittingWithMe = SittingPlan().findBestSitting(SittingPreferences(input).withMyself())
println(bestSittingWithMe)
}
@Suppress("MagicNumber")
class SittingPreferences {
constructor(preferences: String) {
preferencesMap = preferences.lineSequence().map(::parsePreferenceLine).toMap()
}
constructor(preferences: Map<Pair<String, String>, Int>) {
preferencesMap = preferences
}
val preferencesMap: Map<Pair<String, String>, Int>
fun getPreference(name1: String, name2: String): Int? = preferencesMap[name1 to name2]
fun getPreference(p: Pair<String, String>): Int? = preferencesMap[p.first to p.second]
fun getAllNames(): Set<String> = preferencesMap.keys.flatMap { it.toList() }.toSet()
fun withMyself(): SittingPreferences {
val relationsToMe = getAllNames().flatMap { listOf(("me" to it) to 0, (it to "me") to 0) }.toMap()
return SittingPreferences(preferencesMap + relationsToMe)
}
private fun parsePreferenceLine(s: String): Pair<Pair<String, String>, Int> {
val splitLine = s.split(" ")
val name1 = splitLine.first()
val name2 = splitLine.last().removeSuffix(".")
val looseOrGain = when (splitLine[2]) {
"lose" -> -1
"gain" -> 1
else -> throw IllegalArgumentException("Input line not matching expectations")
}
val value = looseOrGain * splitLine[3].toInt()
return (name1 to name2) to value
}
}
@Suppress("UnstableApiUsage")
class SittingPlan {
// that gets factorial and will be very slow with higher diners number
fun findBestSitting(prefs: SittingPreferences): Pair<MutableList<String>, Int>? {
val sittingPossibilities = Collections2.permutations(prefs.getAllNames())
return sittingPossibilities.map { it to calculateHappiness(it, prefs) }
.maxByOrNull { (_, happiness) -> happiness }
}
internal fun calculateHappiness(sittingLayout: List<String>, prefs: SittingPreferences): Int {
return zipTwoWayInCircle(sittingLayout)
.mapNotNull { prefs.getPreference(it) }
.sum()
}
private fun <T> zipTwoWayInCircle(l: List<T>): List<Pair<T, T>> {
return l.zipWithNext() + (l.last() to l.first()) + l.reversed().zipWithNext() + (l.first() to l.last())
}
}
| 0 | Kotlin | 0 | 0 | 06367f7e16c0db340c7bda8bc2ff991756e80e5b | 2,659 | aoc-2015-kotlin | The Unlicense |
kotlin/graphs/shortestpaths/FloydWarshall.kt | polydisc | 281,633,906 | true | {"Java": 540473, "Kotlin": 515759, "C++": 265630, "CMake": 571} | package graphs.shortestpaths
import java.util.Arrays
object FloydWarshall {
val INF: Int = Integer.MAX_VALUE / 2
// precondition: d[i][i] == 0
fun floydWarshall(d: Array<IntArray>): Array<IntArray>? {
val n = d.size
val pred = Array(n) { IntArray(n) }
for (i in 0 until n) for (j in 0 until n) pred[i][j] = if (i == j || d[i][j] == INF) -1 else i
for (k in 0 until n) {
for (i in 0 until n) {
// if (d[i][k] == INF) continue;
for (j in 0 until n) {
// if (d[k][j] == INF) continue;
if (d[i][j] > d[i][k] + d[k][j]) {
d[i][j] = d[i][k] + d[k][j]
// d[i][j] = Math.max(d[i][j], -INF);
pred[i][j] = pred[k][j]
}
}
}
}
for (i in 0 until n) if (d[i][i] < 0) return null
return pred
}
fun restorePath(pred: Array<IntArray>?, i: Int, j: Int): IntArray {
var j = j
val n = pred!!.size
val path = IntArray(n)
var pos = n
while (true) {
path[--pos] = j
if (i == j) break
j = pred[i][j]
}
return Arrays.copyOfRange(path, pos, n)
}
// Usage example
fun main(args: Array<String?>?) {
val dist = arrayOf(intArrayOf(0, 3, 2), intArrayOf(0, 0, 1), intArrayOf(INF, 0, 0))
val pred = floydWarshall(dist)
val path = restorePath(pred, 0, 1)
System.out.println(0 == dist[0][0])
System.out.println(2 == dist[0][1])
System.out.println(2 == dist[0][2])
System.out.println(-1 == pred!![0][0])
System.out.println(2 == pred[0][1])
System.out.println(0 == pred[0][2])
System.out.println(Arrays.equals(intArrayOf(0, 2, 1), path))
}
}
| 1 | Java | 0 | 0 | 4566f3145be72827d72cb93abca8bfd93f1c58df | 1,878 | codelibrary | The Unlicense |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.