kt_path stringlengths 35 167 | kt_source stringlengths 626 28.9k | classes listlengths 1 17 |
|---|---|---|
n81ur3__kotlin-coding-challenges__fdc5941/src/main/kotlin/adventofcode2018/Day18SettlersOfTheNorthPole.kt | package adventofcode2018
import adventofcode2018.AreaElement.*
import java.lang.Math.min
import java.util.*
import kotlin.math.max
class Day18SettlersOfTheNorthPole
sealed class AreaElement(val sign: Char) {
object Open : AreaElement('.')
object Tree : AreaElement('|')
object Lumberyard : AreaElement('#')
override fun toString(): String = sign.toString()
}
fun List<List<AreaElement>>.hash(): Int {
return Arrays.deepHashCode(this.toTypedArray())
}
class NorthPoleArea(input: List<String>) {
var elements: List<List<AreaElement>>
val rounds = mutableMapOf<Int, List<List<AreaElement>>>()
val roundHashes = mutableMapOf<Int, Int>()
val totalResource: Int
get() {
val treeCount = elements.flatten().filter { it is Tree }.count()
val lumberyardCount = elements.flatten().filter { it is Lumberyard }.count()
return treeCount * lumberyardCount
}
init {
elements = input.map { line ->
line.toCharArray().map { sign ->
elementFromSign(sign)
}
}
}
private fun elementFromSign(sign: Char): AreaElement {
return when (sign) {
'|' -> Tree
'#' -> Lumberyard
else -> Open
}
}
fun transform(count: Long) {
var loop = 0
var counter = 0
while (loop == 0) {
val transformedElements = List(elements.size) {
elements[it].mapIndexed { x, element -> transformElement(element, it, x) }
}
if (roundHashes.values.contains(transformedElements.hash())) {
println("Loop found via hash at $counter")
}
if (rounds.values.contains(transformedElements)) {
loop = counter
println("Loop at iteration: $counter")
} else {
rounds[counter] = transformedElements
roundHashes[counter] = transformedElements.hash()
counter++
}
elements = transformedElements
}
if (loop > 0) {
val effectiveRound = Math.floorMod(count, loop) - 1
println("Effective round: $effectiveRound")
elements = rounds[effectiveRound]!!
}
}
private fun transformElement(element: AreaElement, posY: Int, posX: Int): AreaElement {
return when (element) {
is Open -> transformOpen(posY, posX)
is Tree -> transformTree(posY, posX)
is Lumberyard -> transformLumberyard(posY, posX)
}
}
private fun transformTree(posY: Int, posX: Int) =
if (neighborsAt(posY, posX).filter { it is Lumberyard }.count() > 2) Lumberyard else Tree
private fun transformOpen(posY: Int, posX: Int) =
if (neighborsAt(posY, posX).filter { it is Tree }.count() > 2) Tree else Open
private fun transformLumberyard(posY: Int, posX: Int): AreaElement {
val containsLumberyard = neighborsAt(posY, posX).any { it is Lumberyard }
val containsTree = neighborsAt(posY, posX).any { it is Tree }
return if (containsLumberyard && containsTree) Lumberyard else Open
}
fun neighborsAt(posY: Int, posX: Int): List<AreaElement> {
val minX = max(0, posX - 1)
val maxX = min(elements[0].size - 1, posX + 1)
val minY = max(0, posY - 1)
val maxY = min(elements.size - 1, posY + 1)
val result = mutableListOf<AreaElement>()
(minY..maxY).forEach { y ->
(minX..maxX).forEach { x ->
if (!(y == posY && x == posX)) result.add(elements[y][x])
}
}
return result.toList()
}
fun printArea() {
println()
elements.forEach { println(it.joinToString(separator = "")) }
println()
}
} | [
{
"class_path": "n81ur3__kotlin-coding-challenges__fdc5941/adventofcode2018/Day18SettlersOfTheNorthPoleKt.class",
"javap": "Compiled from \"Day18SettlersOfTheNorthPole.kt\"\npublic final class adventofcode2018.Day18SettlersOfTheNorthPoleKt {\n public static final int hash(java.util.List<? extends java.util... |
n81ur3__kotlin-coding-challenges__fdc5941/src/main/kotlin/adventofcode2018/Day04ReposeRecord.kt | package adventofcode2018
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
class Day04ReposeRecord
data class Guard(val id: Int)
data class SleepPeriod(val start: LocalDateTime, val stop: LocalDateTime)
sealed class ShiftEntry(
val dateTime: LocalDateTime,
val guard: Guard = Guard(-1),
val awake: Boolean = false,
val asleep: Boolean = false
) {
companion object {
val dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")
fun fromString(input: String): ShiftEntry {
val dateTime = LocalDateTime.parse(input.substring(1).substringBefore("] "), dateFormatter)
return when {
input.contains("Guard") -> NewGuardEntry(
dateTime,
Guard(input.substringAfter("#").substringBefore(" ").toInt())
)
input.contains("asleep") -> AsleepEntry(dateTime)
else -> AwakeEntry(dateTime)
}
}
}
override fun toString(): String {
return "ShiftEntry(dateTime=$dateTime, guard=$guard, awake=$awake, asleep=$asleep)"
}
}
class NewGuardEntry(dateTime: LocalDateTime, guard: Guard) : ShiftEntry(dateTime, guard, awake = true)
class AsleepEntry(dateTime: LocalDateTime) : ShiftEntry(dateTime, asleep = true)
class AwakeEntry(dateTime: LocalDateTime) : ShiftEntry(dateTime, awake = true)
class ShiftPlan(input: List<String>) {
val entries: List<ShiftEntry>
var currentGuard = Guard(-1)
var currentStartSleep = LocalDateTime.now()
val guardRecords = mutableMapOf<Guard, MutableList<SleepPeriod>>()
var guardSleeping = false
init {
entries = input.map { ShiftEntry.fromString(it) }.sortedBy { it.dateTime }
}
fun scheduleShifts() {
entries.forEach { entry ->
when (entry) {
is NewGuardEntry -> {
if (guardRecords[entry.guard] == null) {
guardRecords[entry.guard] = mutableListOf()
}
if (guardSleeping) {
recordSleep(entry.dateTime.minusMinutes(1))
guardSleeping = false
}
currentGuard = entry.guard
}
is AsleepEntry -> {
currentStartSleep = entry.dateTime
guardSleeping = true
}
is AwakeEntry -> {
recordSleep(entry.dateTime.minusMinutes(1))
guardSleeping = false
}
}
}
}
private fun recordSleep(endSleep: LocalDateTime) {
guardRecords[currentGuard]?.add(SleepPeriod(currentStartSleep, endSleep))
}
fun findBestGuardAndMinute(): Pair<Guard, Int> {
val bestGuard = findBestGuard()
val bestMinute = findBestMinute(bestGuard)
return bestGuard to bestMinute
}
private fun findBestGuard(): Guard {
val sleepTimes = guardRecords.map { records ->
val totalSleep = records.value.sumOf { it.stop.minute - it.start.minute }
records.key to totalSleep
}
return sleepTimes.maxBy { it.second }.first
}
private fun findBestMinute(guard: Guard): Int {
var result = 0
guardRecords[guard]?.let {
result = getMostFrequentMinute(it).first
}
return result
}
fun findBestGuardMostFrequentMinute(): Pair<Guard, Int> {
val groupedEntries = guardRecords
.filter { it.value.size > 0 }
.map { it.key to getMostFrequentMinute(it.value) }
val maxEntry = groupedEntries.maxBy { it.second.second }
return maxEntry.first to maxEntry.second.first
}
private fun getMostFrequentMinute(sleepPeriods: List<SleepPeriod>): Pair<Int, Int> {
val minutes = mutableListOf<Int>()
sleepPeriods.forEach { sleepPeriod ->
(sleepPeriod.start.minute..sleepPeriod.stop.minute).forEach {
minutes.add(it)
}
}
val sleepMinutesGroups = minutes.groupBy { it }
val result = sleepMinutesGroups.maxByOrNull { it.value.size }
return result?.let {
result.key to result.value.size
} ?: (-1 to 0)
}
} | [
{
"class_path": "n81ur3__kotlin-coding-challenges__fdc5941/adventofcode2018/Day04ReposeRecord.class",
"javap": "Compiled from \"Day04ReposeRecord.kt\"\npublic final class adventofcode2018.Day04ReposeRecord {\n public adventofcode2018.Day04ReposeRecord();\n Code:\n 0: aload_0\n 1: invokespeci... |
n81ur3__kotlin-coding-challenges__fdc5941/src/main/kotlin/adventofcode2018/Day06ChronalCoordinates.kt | package adventofcode2018
class Day06ChronalCoordinates
data class Coordinate(val id: Int, val x: Int, val y: Int) {
fun manhattanDistance(fromX: Int, fromY: Int): Int {
val xDist = if (fromX > x) (fromX - x) else (x - fromX)
val yDist = if (fromY > y) (fromY - y) else (y - fromY)
return xDist + yDist
}
companion object {
var counter = 0
fun fromString(input: String): Coordinate {
return Coordinate(counter++, input.substringBefore(",").toInt(), input.substringAfter(", ").toInt())
}
}
}
class CoordinateSystem(input: List<String>) {
val coordinates: List<Coordinate>
val fields = mutableListOf<Coordinate>()
val xMin: Int
val xMax: Int
val yMin: Int
val yMax: Int
init {
coordinates = input.map { Coordinate.fromString(it) }
xMin = coordinates.minOf { it.x }
xMax = coordinates.maxOf { it.x }
yMin = coordinates.minOf { it.y }
yMax = coordinates.maxOf { it.y }
}
fun innerCoordinates(): List<Coordinate> {
return coordinates.filter {
it.x > xMin && it.x < xMax && it.y > yMin && it.y < yMax
}
}
private fun mapFields() {
(0..xMax).forEach { x ->
(0..yMax).forEach { y ->
findClosestInnerCoordinate(x, y)?.run { fields.add(this) }
}
}
}
private fun findClosestInnerCoordinate(x: Int, y: Int): Coordinate? {
val inner = innerCoordinates()
val distances = coordinates.map { it to it.manhattanDistance(x, y) }.sortedBy { it.second }
.filter { x >= xMin && x <= xMax && y >= yMin && y <= yMax }
if (distances.isEmpty()) return Coordinate(-1, x, y)
if (distances[0].second == distances[1].second) return Coordinate(-1, x, y)
if (!(inner.contains(distances[0].first))) return Coordinate(-1, x, y)
return Coordinate(distances[0].first.id, x, y)
}
fun calcLargestInnerFieldSize(): Int {
mapFields()
val innerFields = fields.filterNot { it.id == -1 }
val groupedFields = innerFields.groupBy { it.id }
return groupedFields.filterNot { isInfiniteGroup(it.value) }.maxOf { it.value.size }
}
private fun isInfiniteGroup(group: List<Coordinate>) = group.any { outOfBounds(it) }
private fun outOfBounds(it: Coordinate) = it.x <= xMin || it.x >= xMax || it.y <= yMin || it.y >= yMax
fun printSystem() {
(0..yMax).forEach { y ->
(0..xMax).forEach { x ->
fields.firstOrNull { it.x == x && it.y == y }?.run {
if (id == -1) print('.') else print(id)
} ?: print('.')
}
println()
}
}
fun sizeOfLargestSafeRegion(range: Int): Int {
var counter = 0
(0..yMax).forEach { y ->
(0..xMax).forEach { x ->
if (calcTotalDistance(x, y) < range) counter++
}
}
return counter
}
private fun calcTotalDistance(x: Int, y: Int): Int {
return coordinates.sumOf { it.manhattanDistance(x, y) }
}
} | [
{
"class_path": "n81ur3__kotlin-coding-challenges__fdc5941/adventofcode2018/Day06ChronalCoordinates.class",
"javap": "Compiled from \"Day06ChronalCoordinates.kt\"\npublic final class adventofcode2018.Day06ChronalCoordinates {\n public adventofcode2018.Day06ChronalCoordinates();\n Code:\n 0: aload_... |
n81ur3__kotlin-coding-challenges__fdc5941/src/main/kotlin/adventofcode2018/Day23ExperimentalEmergencyTeleportation.kt | package adventofcode2018
import kotlin.math.abs
class Day23ExperimentalEmergencyTeleportation
data class TeleportCoordinate(val x: Int, val y: Int, val z: Int)
data class Nanobot(val x: Int, val y: Int, val z: Int, val radius: Int) {
fun inRange(otherBot: Nanobot): Boolean {
val manhattanDistance = distanceTo(otherBot.x, otherBot.y, otherBot.z)
return manhattanDistance <= otherBot.radius
}
fun withinRangeOfSharedPoint(otherBot: Nanobot) =
distanceTo(otherBot.x, otherBot.y, otherBot.z) <= radius + otherBot.radius
fun inRange(xDist: Int, yDist: Int, zDist: Int) = distanceTo(xDist, yDist, zDist) <= radius
internal fun distanceTo(xDist: Int, yDist: Int, zDist: Int) =
abs(x - xDist) + abs(y - yDist) + abs(z - zDist)
}
class TeleportationDevice(val input: List<String>) {
val bots: List<Nanobot>
val strongestBot: Nanobot
get() = bots.maxBy { it.radius }
init {
bots = input.map { parseBot(it) }
}
private fun parseBot(input: String): Nanobot {
val coordinates = input.substringAfter("<").substringBefore(">")
val (x, y, z) = coordinates.split(",").map { it.toInt() }
return Nanobot(x, y, z, input.substringAfterLast("=").toInt())
}
fun numberOfBotsInRangeOfStrongest() = bots.count { it.inRange(strongestBot) }
fun strongestCoordinate(): TeleportCoordinate {
var strongest = TeleportCoordinate(0, 0, 0)
var strongestCount = 0
val minX = bots.minOf { it.x }
val maxX = bots.maxOf { it.x }
val minY = bots.minOf { it.y }
val maxY = bots.maxOf { it.y }
val minZ = bots.minOf { it.z }
val maxZ = bots.maxOf { it.z }
var botsCount: Int
(minX..maxX).forEach { x ->
(minY..maxY).forEach { y ->
(minZ..maxZ).forEach { z ->
botsCount = bots.count { it.inRange(x, y, z) }
if (botsCount > strongestCount) {
strongestCount = botsCount
strongest = TeleportCoordinate(x, y, z)
}
}
}
}
return strongest
}
fun strongestDistance(): Int {
val neighbors: Map<Nanobot, Set<Nanobot>> = bots.map { bot ->
Pair(bot, bots.filterNot { it == bot }.filter { bot.withinRangeOfSharedPoint(it) }.toSet())
}.toMap()
val clique: Set<Nanobot> = BronKerbosch(neighbors).largestClique()
return clique.map { it.distanceTo(0, 0, 0) - it.radius }.max()
}
}
class BronKerbosch<T>(val neighbors: Map<T, Set<T>>) {
private var bestR: Set<T> = emptySet()
fun largestClique(): Set<T> {
execute(neighbors.keys)
return bestR
}
private fun execute(p: Set<T>, r: Set<T> = emptySet(), x: Set<T> = emptySet()) {
if (p.isEmpty() && x.isEmpty()) {
if (r.size > bestR.size) bestR = r
} else {
val mostNeighborsOfPandX: T = (p + x).maxBy { neighbors.getValue(it).size }!!
val pWithoutNeighbors = p.minus(neighbors[mostNeighborsOfPandX]!!)
pWithoutNeighbors.forEach { v ->
val neighborsOfV = neighbors[v]!!
execute(p.intersect(neighborsOfV), r + v, x.intersect(neighborsOfV))
}
}
}
} | [
{
"class_path": "n81ur3__kotlin-coding-challenges__fdc5941/adventofcode2018/Day23ExperimentalEmergencyTeleportation.class",
"javap": "Compiled from \"Day23ExperimentalEmergencyTeleportation.kt\"\npublic final class adventofcode2018.Day23ExperimentalEmergencyTeleportation {\n public adventofcode2018.Day23Ex... |
n81ur3__kotlin-coding-challenges__fdc5941/src/main/kotlin/adventofcode2018/Day15BeverageBandits.kt | package adventofcode2018
class Day15BeverageBandits
sealed class Token(val sign: Char, var posX: Int, var posY: Int) : Comparable<Token> {
open fun nextEnemy(): Token = NullToken()
override fun toString(): String = sign.toString()
override fun compareTo(other: Token): Int {
return when {
posY < other.posY -> -1
posY > other.posY -> 1
posX < other.posX -> -1
posX > other.posX -> 1
else -> 0
}
}
fun adjacentCoordinates(): List<Pair<Int, Int>> {
return listOf(posX to posY - 1, posX + 1 to posY, posX to posY + 1, posX - 1 to posY)
}
companion object {
fun fromChar(c: Char, posX: Int, posY: Int): Token {
return when (c) {
'#' -> Wall(posX, posY)
'.' -> Cavern(posX, posY)
'G' -> Goblin(posX, posY)
'E' -> Elf(posX, posY)
else -> NullToken()
}
}
}
}
class Wall(posX: Int, posY: Int) : Token('#', posX, posY)
class Cavern(posX: Int, posY: Int) : Token('.', posX, posY)
class Goblin(posX: Int, posY: Int) : Token('G', posX, posY)
class Elf(posX: Int, posY: Int) : Token('E', posX, posY)
class NullToken : Token(' ', -1, -1)
class Cave(input: List<String>) {
val caveMap: List<Token>
val caveWidth = input[0].length
val caveHeight = input.size
val sortedFighters: List<Token>
get() = caveMap.sorted().filter { it is Goblin || it is Elf }
init {
caveMap = input.flatMapIndexed { posY, line ->
line.mapIndexed { posX, token ->
Token.fromChar(token, posX, posY)
}
}
}
fun playRound() {
sortedFighters.forEach { fighter ->
val caverns = getAdjacentCaverns(fighter)
val enemies = findEnemies(fighter)
val targets = findTargets(fighter)
println(caverns)
}
}
private fun getAdjacentCaverns(token: Token): List<Token> {
return caveMap.filter { it is Cavern }.filter { it.posX to it.posY in token.adjacentCoordinates() }
}
private fun findEnemies(token: Token): List<Token> {
return when (token) {
is Goblin -> caveMap.filter { it is Elf }
is Elf -> caveMap.filter{ it is Goblin }
else -> emptyList()
}
}
private fun findTargets(token: Token): List<Token> {
val enemies = findEnemies(token)
return enemies.flatMap { getAdjacentCaverns(it) }
}
fun printCaveMap() {
caveMap.sorted().forEachIndexed { index, token ->
if (index % caveWidth == 0) { println() }
print(token)
}
println()
}
} | [
{
"class_path": "n81ur3__kotlin-coding-challenges__fdc5941/adventofcode2018/Day15BeverageBandits.class",
"javap": "Compiled from \"Day15BeverageBandits.kt\"\npublic final class adventofcode2018.Day15BeverageBandits {\n public adventofcode2018.Day15BeverageBandits();\n Code:\n 0: aload_0\n 1:... |
n81ur3__kotlin-coding-challenges__fdc5941/src/main/kotlin/adventofcode2018/Day22ModeMaze.kt | package adventofcode2018
class Day22ModeMaze
class MazeCalculator(val depth: Int, val targetX: Int, val targetY: Int) {
val regions: List<MutableList<Int>>
val errosionLevels: List<MutableList<Int>> = List(targetY + 1) { MutableList(targetX + 1) { 0 } }
val riskLevel: Int
get() = regions.map { line -> line.sum() }.sum()
init {
regions = (0..targetY).map { y ->
(0..targetX).map { x ->
0
}.toMutableList()
}
calculateErosionLevels()
}
private fun calculateErosionLevels() {
(0..targetY).forEach { y ->
(0..targetX).forEach { x ->
regions[y][x] = getRegionType(y, x)
}
}
}
private fun getRegionType(y: Int, x: Int): Int {
val erosionLevel = getErosionLevel(y, x)
return erosionLevel % 3
}
private fun getErosionLevel(y: Int, x: Int): Int {
val geologicalIndex = getGeologicalIndex(y, x)
val errosionLevel = (geologicalIndex + depth) % 20183
errosionLevels[y][x] = errosionLevel
return errosionLevel
}
private fun getGeologicalIndex(y: Int, x: Int): Int {
if (y == 0 && x == 0) return 0
if (y == targetY && x == targetX) return 0
if (y == 0) {
return x * 16807
}
if (x == 0) {
return y * 48271
}
return errosionLevels[y - 1][x] * errosionLevels[y][x - 1]
}
fun printMaze() {
regions.forEach { line ->
line.forEach { region ->
when (region) {
0 -> print(".")
1 -> print("=")
else -> print("|")
}
}
println()
}
}
} | [
{
"class_path": "n81ur3__kotlin-coding-challenges__fdc5941/adventofcode2018/Day22ModeMaze.class",
"javap": "Compiled from \"Day22ModeMaze.kt\"\npublic final class adventofcode2018.Day22ModeMaze {\n public adventofcode2018.Day22ModeMaze();\n Code:\n 0: aload_0\n 1: invokespecial #8 ... |
n81ur3__kotlin-coding-challenges__fdc5941/src/main/kotlin/adventofcode2018/Day12SubterraneanSustainability.kt | package adventofcode2018
class Day12SubterraneanSustainability
data class PotRule(val input: String, val result: Char) {
companion object {
fun fromString(rule: String): PotRule {
return PotRule(rule.substringBefore(" ="), rule.last())
}
}
}
class RulesSet(val rules: List<PotRule>) {
fun getResultForInput(input: List<Char>): Char {
val pattern = input.joinToString(separator = "")
return rules.firstOrNull { it.input == pattern }?.result ?: '.'
}
companion object {
fun fromRules(rules: List<String>): RulesSet {
val potRules = rules.map { PotRule.fromString(it) }
return RulesSet(potRules)
}
}
}
class Tunnel(initialState: String, rules: List<String>) {
var pots = ArrayDeque(initialState.toList())
var nullIndex = 0
val rulesSet: RulesSet = RulesSet.fromRules(rules)
private fun extendPots() {
repeat(3) {
pots.addFirst('.')
pots.addLast('.')
}
}
fun computeGenerations(iterations: Long): Long {
if (iterations < 2000) {
(0 until iterations).forEach {
computeNextGeneration()
}
return computeTotalPotsSum()
} else {
return computeVeryOldGeneration(iterations)
}
}
private fun computeVeryOldGeneration(iterations: Long): Long {
computeGenerations(1000)
val oneThousandGenerationCount = computeTotalPotsSum()
computeGenerations(1000)
val twoThousandGenerationCount = computeTotalPotsSum()
val oneThousandIntervalCount = twoThousandGenerationCount - oneThousandGenerationCount
val numberOfIntervalls = ((iterations - 1000)/1000)
return (numberOfIntervalls) * oneThousandIntervalCount + oneThousandGenerationCount
}
fun computeNextGeneration(): Boolean {
extendPots()
val newList = pots.windowed(5, 1, false).map {
rulesSet.getResultForInput(it)
}
if (newList.first() == '#') {
nullIndex++
pots = ArrayDeque(newList)
} else {
pots = ArrayDeque(newList.drop(1))
}
return false
}
fun computeTotalPotsSum(): Long {
var result = 0L
pots.forEachIndexed { index, pot ->
if (pot == '#') {
result += (index - nullIndex)
}
}
return result
}
} | [
{
"class_path": "n81ur3__kotlin-coding-challenges__fdc5941/adventofcode2018/Day12SubterraneanSustainability.class",
"javap": "Compiled from \"Day12SubterraneanSustainability.kt\"\npublic final class adventofcode2018.Day12SubterraneanSustainability {\n public adventofcode2018.Day12SubterraneanSustainability... |
n81ur3__kotlin-coding-challenges__fdc5941/src/main/kotlin/adventofcode2018/Day11ChronalCharge.kt | package adventofcode2018
class Day11ChronalCharge
data class FuelCell(val x: Int, val y: Int, val powerLevel: Int) {
companion object {
fun forSerialNumber(x: Int, y: Int, serialNumber: Int): FuelCell =
FuelCell(x, y, computePowerLevel(x, y, serialNumber))
private fun computePowerLevel(x: Int, y: Int, serialNumber: Int): Int {
var powerLevel = ((x + 10) * y + serialNumber) * (x + 10)
if (powerLevel > 99) {
powerLevel = (powerLevel / 100) % 10
} else {
powerLevel = 0
}
powerLevel -= 5
return powerLevel
}
}
}
class PowerGrid(val serialNumber: Int) {
val fuelCells: List<FuelCell>
val squareScores = mutableMapOf<FuelCell, Int>()
init {
fuelCells = (1..300).flatMap { x ->
(1..300).map { y ->
FuelCell.forSerialNumber(x, y, serialNumber)
}
}
}
fun calculateScores(maxGridSize: Int) {
(1..89397).forEach { index ->
squareScores[fuelCells[index]] = computeScoreAt(index, maxGridSize)
}
}
fun findLargestGrid(): String {
var largestGrid = ""
var maxScore = 0
(1 .. 300).forEach { gridSize ->
(0 until (300 - gridSize)).forEach { x ->
(0 until (300 - gridSize)).forEach { y ->
val currentScore = computeScoreAt(y + (300 * x), gridSize)
if (currentScore > maxScore) {
maxScore = currentScore
largestGrid = "${x + 1},${y + 1},$gridSize"
}
}
}
}
return largestGrid
}
private fun computeScoreAt(index: Int, gridSize: Int): Int {
var result = 0
(0 until gridSize).forEach { y ->
(300 * y until (300 * y + gridSize)).forEach { result += fuelCells[index + it].powerLevel }
}
return result
}
fun getHighestPowerLevelCoordinates(): String {
val highScoreCell = squareScores.maxBy { it.value }
return "${highScoreCell.key.x},${highScoreCell.key.y}"
}
} | [
{
"class_path": "n81ur3__kotlin-coding-challenges__fdc5941/adventofcode2018/Day11ChronalCharge.class",
"javap": "Compiled from \"Day11ChronalCharge.kt\"\npublic final class adventofcode2018.Day11ChronalCharge {\n public adventofcode2018.Day11ChronalCharge();\n Code:\n 0: aload_0\n 1: invokes... |
n81ur3__kotlin-coding-challenges__fdc5941/src/main/kotlin/adventofcode2018/Day07TheSumOfItsParts.kt | package adventofcode2018
class Day07TheSumOfItsParts
enum class Step {
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z
}
data class Instruction(val step: Step, val preSteps: MutableSet<Step> = mutableSetOf())
data class ConcurrentWorker(var executionTime: Int = 0, var busy: Boolean = false) {
fun isAvailable(processTime: Int) = executionTime <= processTime
}
class SleighProcessor(input: List<String>, private val numberOfSteps: Int) {
val instructions: MutableList<Instruction>
init {
instructions = Step.values().take(numberOfSteps).map { Instruction(it) }.toMutableList()
parseInput(input)
}
private fun parseInput(input: List<String>) {
input.forEach { instruction ->
val step = Step.valueOf(instruction.substringAfter("step ").substring(0, 1))
val preStep = Step.valueOf(instruction.substringAfter("Step ").substring(0, 1))
instructions.find { it.step == step }?.preSteps?.add(preStep)
}
}
fun executeInstructions(): String {
return buildString {
while (instructions.isNotEmpty()) {
val nextInstruction = instructions.first { it.preSteps.isEmpty() }
append(nextInstruction.step)
instructions.forEach { instruction -> instruction.preSteps.remove(nextInstruction.step) }
instructions.remove(nextInstruction)
}
}
}
fun executeConcurrently(numberOfWorkers: Int): Int {
var totalTime = 0
var maxTime = 0
val workers = List(numberOfWorkers) { ConcurrentWorker() }
while (instructions.isNotEmpty()) {
var subTime = 0
val pendingInstructions = instructions.filter { it.preSteps.isEmpty() }
pendingInstructions.forEach { nextInstruction ->
val availableWorker = workers.firstOrNull { !(it.busy) } ?: workers.minBy { it.executionTime }
val currentExecutionTime = nextInstruction.step.ordinal + 1
availableWorker.executionTime = totalTime + subTime + currentExecutionTime
subTime += currentExecutionTime
instructions.forEach { instruction -> instruction.preSteps.remove(nextInstruction.step) }
instructions.remove(nextInstruction)
workers.forEach { worker ->
worker.busy = worker.executionTime >= totalTime + subTime + 1
}
}
totalTime += subTime
}
println("total time: $totalTime")
return workers.maxOf { it.executionTime }
}
} | [
{
"class_path": "n81ur3__kotlin-coding-challenges__fdc5941/adventofcode2018/Day07TheSumOfItsParts.class",
"javap": "Compiled from \"Day07TheSumOfItsParts.kt\"\npublic final class adventofcode2018.Day07TheSumOfItsParts {\n public adventofcode2018.Day07TheSumOfItsParts();\n Code:\n 0: aload_0\n ... |
n81ur3__kotlin-coding-challenges__fdc5941/src/main/kotlin/adventofcode2020/Day21AllergenAssessment.kt | package adventofcode2020
class Day21AllergenAssessment
data class Food(val ingredients: Set<String>, val allergens: Set<String>) {
companion object {
fun fromString(input: String): Food {
val parts = input.split(" (contains ")
val ing = parts[0].split(" ").toHashSet()
val allg = parts[1].dropLast(1).split(" ").map { it.replace(",", "") }.toHashSet()
return Food(ing, allg)
}
}
}
class Grocery(val foods: List<Food>) {
companion object {
fun buildGroceryFromStrings(lines: List<String>): Grocery {
val goods = lines.map { Food.fromString(it) }
return Grocery(goods)
}
}
fun allAllergens(): Set<String> = foods.flatMap { food -> food.allergens }.toHashSet()
fun foodsContainingAllergen(allergen: String): Set<String> {
val foodCandidates = foods.filter { food -> food.allergens.contains(allergen) }
val ingredientCandidates = foodCandidates.map { food -> food.ingredients }
val intersection = ingredientCandidates.reduce { acc, current -> acc.intersect(current) }
return intersection
}
fun ingredientsWithAllergen(): Set<String> {
val candidates = allAllergens().map { allergen -> foodsContainingAllergen(allergen) }
return candidates.reduce { acc, current -> acc + current }
}
fun allIngredients(): List<String> =
foods.map { food -> food.ingredients.toList() }.reduce { acc, current -> acc + current }
fun allIngredientsWithoutAllergens(): List<String> {
val allIngredients = allIngredients()
val ingredientsWithAllergens = ingredientsWithAllergen()
return allIngredients.filter { ingredient -> ingredient !in ingredientsWithAllergens }
}
} | [
{
"class_path": "n81ur3__kotlin-coding-challenges__fdc5941/adventofcode2020/Day21AllergenAssessment.class",
"javap": "Compiled from \"Day21AllergenAssessment.kt\"\npublic final class adventofcode2020.Day21AllergenAssessment {\n public adventofcode2020.Day21AllergenAssessment();\n Code:\n 0: aload_... |
n81ur3__kotlin-coding-challenges__fdc5941/src/main/kotlin/adventofcode2020/Day19MonsterMessage.kt | package adventofcode2020
class Day19MonsterMessage
data class MessageRule(
var ruleExpression: String = "",
) {
val fullRule: String
get() = ruleExpression
override fun toString(): String = (ruleExpression).replace(" ", "")
val isEvaluated: Boolean
get() {
val regex = "[ab |()]*".toRegex()
return (regex.matches(ruleExpression))
}
fun substituteRule(ruleNumber: String, rule: String) {
val regex = " $ruleNumber ".toRegex()
ruleExpression = ruleExpression.replace(regex, " ( " + rule + " ) ")
ruleExpression = ruleExpression.replace(regex, " ( " + rule + " ) ")
}
fun matches(message: String): Boolean {
val regex = (ruleExpression.replace(" ", "")).toRegex()
return regex.matches(message)
}
}
class RulesChecker {
val rules = mutableMapOf<Int, MessageRule>()
fun buildRulesFromLines(rules: List<String>) {
rules.forEach { rule ->
this.rules.put(
rule.substringBefore(":").toInt(),
MessageRule(rule.substringAfter(":").replace("\"", "").replace("\"", "") + " ")
)
}
buildRulesFromRawRules()
}
private fun buildRulesFromRawRules() {
var evaluatedRules = mapOf<Int, MessageRule>()
val substitutedRules = mutableListOf<Int>()
do {
evaluatedRules = rules.filter { (_, messageRule) -> messageRule.isEvaluated }
if (evaluatedRules.isNotEmpty()) {
val rulesToReplace =
evaluatedRules.entries.filter { (ruleNumber, _) -> ruleNumber !in substitutedRules }
if (rulesToReplace.isNotEmpty()) {
rulesToReplace.forEach { nextRuleToReplace ->
rules.values.forEach {
it.substituteRule(
nextRuleToReplace.key.toString(),
nextRuleToReplace.value.fullRule
)
}
substitutedRules.add(nextRuleToReplace.key)
}
}
}
} while (evaluatedRules.size != rules.size)
}
fun evaluateMessage(message: String): Boolean {
return rules.get(0)?.matches(message) ?: false
}
}
| [
{
"class_path": "n81ur3__kotlin-coding-challenges__fdc5941/adventofcode2020/Day19MonsterMessage.class",
"javap": "Compiled from \"Day19MonsterMessage.kt\"\npublic final class adventofcode2020.Day19MonsterMessage {\n public adventofcode2020.Day19MonsterMessage();\n Code:\n 0: aload_0\n 1: inv... |
n81ur3__kotlin-coding-challenges__fdc5941/src/main/kotlin/adventofcode2020/Day07HandyHaversacks.kt | package adventofcode2020
class Day07HandyHaversacks
data class Bag(val type: String, val color: String, val canContain: Pair<Bag, Int>?) {
val bagName: String
get() = type + " " + color
fun containsBag(type: String, color: String, count: Int, recursive: Boolean = false): Boolean {
if (recursive) {
if (this.type == type && this.color == color) return true
}
val result = false
canContain ?: return false
val (containingBag, containingCount) = canContain
if (containingBag.type == type && containingBag.color == color) return true
else if (containingBag.canContain != null) return containingBag.canContain.first.containsBag(
type,
color,
count,
recursive = true
)
return result
}
fun containingBags(): List<Pair<Bag, Int>> {
val result = mutableListOf<Pair<Bag, Int>>()
var currentPair = canContain
while (currentPair != null) {
result.add(Bag(currentPair.first.type, currentPair.first.color, null) to currentPair.second)
currentPair = currentPair.first.canContain
}
return result
}
fun getNumberOfContainingBags(): Int {
canContain ?: return 1
return canContain.second + canContain.first.getNumberOfContainingBags()
}
}
object BagCreator {
fun createBag(input: String): Bag {
if (!input.contains(',')) {
val parts = input.split(" ")
val type = parts[0]
val color = parts[1]
if (parts.size == 3 || parts[4] == "no") return Bag(type, color, null)
val otherType = parts[5]
val otherColor = parts[6]
return Bag(type, color, Pair(Bag(otherType, otherColor, null), parts[4].toInt()))
} else {
val subbags = input.split(".")
val part = subbags[0].trim()
val parts = part.split(" ")
val type = parts[0]
val color = parts[1]
val count = parts[4]
val otherType = parts[5]
val otherColor = parts[6]
if (subbags.size == 1) {
return Bag(type, color, Pair(Bag(otherType, otherColor, null), count.toInt()))
} else {
val remaining = input.substringAfter(",").trim()
val (remainingCount, remainingBag) = createBagWithCount(remaining)
return Bag(
type,
color,
Pair(
Bag(
otherType,
otherColor,
Pair(remainingBag, remainingCount)
), count.toInt()
)
)
}
}
}
fun createBagWithCount(input: String): Pair<Int, Bag> {
val count = input.first { it.isDigit() }.toString()
var remaining = input.substring(input.indexOf(count) + 2).trim()
remaining = remaining.replaceFirst(", ", " contains ")
return Pair(Integer.parseInt(count), createBag(remaining))
}
}
data class HandBag(
val type: String,
val color: String,
val canContain: MutableList<Pair<HandBag, Int>> = mutableListOf()
) {
val name: String
get() = type + " " + color
companion object {
fun from(input: String): HandBag {
if (!input.contains(',')) {
val parts = input.split(" ")
val type = parts[0]
val color = parts[1]
if (parts.size == 3 || parts[4] == "no") return HandBag(type, color)
val otherCount = parts[4].toInt()
val otherType = parts[5]
val otherColor = parts[6]
return HandBag(type, color, mutableListOf(Pair(HandBag(otherType, otherColor), otherCount)))
} else {
val firstBag = input.substringBefore("contain").trim().split(" ")
val result = HandBag(firstBag[0], firstBag[1])
val subbags = input.substringAfter("contain").trim().split(",")
val containingBags = mutableListOf<Pair<HandBag, Int>>()
subbags.forEach { containingBags.add(handBagFromString(it)) }
result.canContain.addAll(containingBags)
return result
}
}
private fun handBagFromString(input: String): Pair<HandBag, Int> {
val parts = input.trim().split(" ")
return Pair(HandBag(parts[1], parts[2]), parts[0].toInt())
}
}
} | [
{
"class_path": "n81ur3__kotlin-coding-challenges__fdc5941/adventofcode2020/Day07HandyHaversacks.class",
"javap": "Compiled from \"Day07HandyHaversacks.kt\"\npublic final class adventofcode2020.Day07HandyHaversacks {\n public adventofcode2020.Day07HandyHaversacks();\n Code:\n 0: aload_0\n 1:... |
korilin__leetcode_kt_solution__1ce05ef/src/main/kotlin/q1_50/q21_30/Solution23.kt | package q1_50.q21_30
import java.util.*
/**
* https://leetcode-cn.com/problems/merge-k-sorted-lists
*/
class Solution23 {
/**
* 优先队列
* 时间复杂度:与分治合并算法一样都是 O(kn×log(k))
*/
fun mergeKLists(lists: Array<ListNode?>): ListNode? {
val nodePriorityQueue = PriorityQueue<ListNode> { a, b -> a.`val` - b.`val`}
for (node in lists) {
node?.let { nodePriorityQueue.add(node) }
}
val head = ListNode(0)
var tail = head
while (nodePriorityQueue.isNotEmpty()) {
tail.next = nodePriorityQueue.poll()
tail = tail.next!!
tail.next?.let { nodePriorityQueue.add(it) }
}
return head.next
}
/*
* 分治合并算法
*/
fun mergeKLists0(lists: Array<ListNode?>): ListNode? {
fun mergeTwoLinked(n1:ListNode?, n2:ListNode?): ListNode? {
val head = ListNode(0)
var tail = head
var node1 = n1
var node2 = n2
while (node1!=null || node2!=null) {
if (node2 == null || (node1!=null && node1.`val` <= node2.`val`)) {
tail.next = node1
node1 = node1!!.next
}else{
tail.next = node2
node2 = node2.next
}
tail = tail.next!!
}
return head.next
}
fun merging(ls: Array<ListNode?>): ListNode? {
if (ls.size == 1) return ls[0]
val mergeArray = arrayOfNulls<ListNode>(if (ls.size % 2 == 0) ls.size / 2 else ls.size / 2 + 1)
var i = 0
while (i < ls.size) {
if (i == ls.size - 1) mergeArray[i / 2] = ls[i]
else {
mergeTwoLinked(ls[i], ls[i+1])?.let { mergeArray[i / 2] = it }
}
i += 2
}
return merging(mergeArray)
}
if (lists.isEmpty()) return null
return merging(lists)
}
class ListNode(var `val`: Int) {
var next: ListNode? = null
}
} | [
{
"class_path": "korilin__leetcode_kt_solution__1ce05ef/q1_50/q21_30/Solution23.class",
"javap": "Compiled from \"Solution23.kt\"\npublic final class q1_50.q21_30.Solution23 {\n public q1_50.q21_30.Solution23();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/... |
korilin__leetcode_kt_solution__1ce05ef/src/main/kotlin/q1_50/q11_20/Solution18.kt | package q1_50.q11_20
import java.util.*
/**
* https://leetcode-cn.com/problems/4sum
*/
class Solution18 {
fun fourSum(nums: IntArray, target: Int): List<List<Int>> {
val result = LinkedList<List<Int>>()
if(nums.size < 4) return result
nums.sort()
val n = nums.size
for (i1 in 0 until n - 3) {
if (i1 > 0 && nums[i1] == nums[i1 - 1]) continue
if (nums[i1] + nums[n - 1] + nums[n - 2] + nums[n - 3] < target) continue
if (nums[i1] + nums[i1 + 1] + nums[i1 + 2] + nums[i1 + 3] > target) break
for (i2 in i1 + 1 until n - 2) {
if (i2 > i1 + 1 && nums[i2] == nums[i2 - 1]) continue
if (nums[i1] + nums[i2] + nums[n - 1] + nums[n - 2] < target) continue
if (nums[i1] + nums[i2] + nums[i2 + 1] + nums[i2 + 2] > target) break
var i3 = i2 + 1
var i4 = n - 1
while (i3 < i4) {
if (i3 > i2 + 1 && nums[i3] == nums[i3 - 1]) {
i3++
continue
}
if (i4 < n - 1 && nums[i4] == nums[i4 + 1]) {
i4--
continue
}
when {
nums[i1] + nums[i2] + nums[i3] + nums[i4] < target -> i3++
nums[i1] + nums[i2] + nums[i3] + nums[i4] > target -> i4--
else -> result.add(listOf(nums[i1], nums[i2], nums[i3++], nums[i4]))
}
}
}
}
return result
}
} | [
{
"class_path": "korilin__leetcode_kt_solution__1ce05ef/q1_50/q11_20/Solution18.class",
"javap": "Compiled from \"Solution18.kt\"\npublic final class q1_50.q11_20.Solution18 {\n public q1_50.q11_20.Solution18();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/... |
korilin__leetcode_kt_solution__1ce05ef/src/main/kotlin/q51_100/q61_70/Solution70.kt | package q51_100.q61_70
/**
* https://leetcode-cn.com/problems/climbing-stairs/
*/
class Solution70 {
/**
* f(x) = f(x1) + f(x2)
*
* f(x1) = 最后一步为 1 个台阶的个数 = f(x - 1)
* f(x2) = 最后一步为 2 个台阶的个数 = f(x - 2)
*
* f(x) = f(x-1) + f(x-2)
*
* 矩阵快速幂
*
* M^n * [1, 1].h = [f(n + 1), f(n)].h
*
* M^n = [f(n), f(n-1)]
*/
fun climbStairs(n: Int): Int {
val m = arrayOf(
arrayOf(1, 1),
arrayOf(1, 0)
)
var un = n
val r = arrayOf(
arrayOf(1, 0),
arrayOf(0, 1)
)
while (un != 0) {
if (un.and(1) == 1) matrix(m, r, r)
matrix(m, m, m)
un = un shr 1
}
return r[0][0]
}
private fun matrix(x: Array<Array<Int>>, y: Array<Array<Int>>, save: Array<Array<Int>>) {
val v1 = x[0][0] * y[0][0] + x[0][1] * y[1][0]
val v2 = x[0][0] * y[0][1] + x[0][1] * y[1][1]
val v3 = x[1][0] * y[0][0] + x[1][1] * y[1][0]
val v4 = x[1][0] * y[0][1] + x[1][1] * y[1][1]
save[0][0] = v1
save[0][1] = v2
save[1][0] = v3
save[1][1] = v4
}
} | [
{
"class_path": "korilin__leetcode_kt_solution__1ce05ef/q51_100/q61_70/Solution70.class",
"javap": "Compiled from \"Solution70.kt\"\npublic final class q51_100.q61_70.Solution70 {\n public q51_100.q61_70.Solution70();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java... |
SeanShubin__kotlin-tryme__abc67c5/domain/src/main/kotlin/com/seanshubin/kotlin/tryme/domain/dice/SpheresOfInfluenceDiceStatisticsApp.kt | package com.seanshubin.kotlin.tryme.domain.dice
object SpheresOfInfluenceDiceStatisticsApp {
fun List<Int>.incrementDieRoll(faces: Int): List<Int> {
val newValues = mutableListOf<Int>()
var carry = true
for (currentIndex in size - 1 downTo 0) {
val value = get(currentIndex)
if (carry) {
if (value == faces) {
newValues.add(1)
} else {
newValues.add(value + 1)
carry = false
}
} else {
newValues.add(value)
}
}
newValues.reverse()
return newValues
}
fun allRolls(quantity: Int, faces: Int): List<List<Int>> {
val startingValue = (1..quantity).map { 1 }
var currentValue = startingValue
val results = mutableListOf(currentValue)
currentValue = currentValue.incrementDieRoll(faces)
while (currentValue != startingValue) {
results.add(currentValue)
currentValue = currentValue.incrementDieRoll(faces)
}
return results
}
fun List<Int>.extractAtIndex(index: Int): Pair<Int, List<Int>> {
val value = get(index)
val before = subList(0, index)
val after = subList(index + 1, size)
val remain = before + after
return Pair(value, remain)
}
fun List<Int>.permutations(): List<List<Int>> {
if (size < 2) return listOf(this)
val allPermutations = mutableListOf<List<Int>>()
for (index in this.indices) {
val (atIndex, remain) = extractAtIndex(index)
remain.permutations().forEach {
val permutation = listOf(atIndex) + it
allPermutations.add(permutation)
}
}
return allPermutations
}
fun List<Int>.hitsForRoll(): Int {
var hits = 0
var accumulator = 0
for (index in indices) {
val current = get(index)
accumulator += current
if (accumulator >= 6) {
hits++
accumulator = 0
}
}
return hits
}
fun List<Int>.maxHitsForRoll(): Int {
val scores: List<Int> = permutations().map { it.hitsForRoll() }
return scores.max() ?: throw RuntimeException("unable to compute maximum of $scores")
}
fun List<List<Int>>.scoreHistogram(): Map<Int, Int> {
val histogram = mutableMapOf<Int, Int>()
forEach {
val score = it.maxHitsForRoll()
histogram[score] = (histogram[score] ?: 0) + 1
}
return histogram
}
fun Int.scoreHistogram(): Map<Int, Int> {
val allRolls = allRolls(this, 6)
return allRolls.scoreHistogram()
}
fun pluralize(quantity: Int, singular: String, plural: String): String {
return if (quantity == 1) singular else plural
}
fun <T> List<List<T>>.flattenWithSpacer(spacer: T): List<T> =
map { listOf(spacer) + it }.flatten().drop(1)
data class HistogramForQuantity(val quantity: Int, val histogram: Map<Int, Int>) {
fun summary(): List<String> {
val total = histogram.values.sum()
val keys = histogram.keys.sorted()
val diceString = pluralize(quantity, "die", "dice")
val caption = "$quantity $diceString"
val summaries = keys.map {
val possible = histogram.getValue(it)
val percent = possible.toDouble() / total.toDouble() * 100.0
val hitString = pluralize(it, "hit", "hits")
val summary = "$possible/$total (%.2f%%) chance of $it $hitString".format(percent)
summary
}
return listOf(caption) + summaries
}
}
@JvmStatic
fun main(args: Array<String>) {
val header = listOf(
"1 hit per grouping of dice that sums to 6 or greater",
""
)
val body = (1..5).map {
HistogramForQuantity(it, it.scoreHistogram())
}.map {
it.summary()
}.flattenWithSpacer("")
val lines = header + body
lines.forEach(::println)
}
}
/*
1 hit per grouping of dice that sums to 6 or greater
1 die
5/6 (83.33%) chance of 0 hits
1/6 (16.67%) chance of 1 hit
2 dice
10/36 (27.78%) chance of 0 hits
25/36 (69.44%) chance of 1 hit
1/36 (2.78%) chance of 2 hits
3 dice
10/216 (4.63%) chance of 0 hits
145/216 (67.13%) chance of 1 hit
60/216 (27.78%) chance of 2 hits
1/216 (0.46%) chance of 3 hits
4 dice
5/1296 (0.39%) chance of 0 hits
333/1296 (25.69%) chance of 1 hit
847/1296 (65.35%) chance of 2 hits
110/1296 (8.49%) chance of 3 hits
1/1296 (0.08%) chance of 4 hits
5 dice
1/7776 (0.01%) chance of 0 hits
456/7776 (5.86%) chance of 1 hit
4258/7776 (54.76%) chance of 2 hits
2885/7776 (37.10%) chance of 3 hits
175/7776 (2.25%) chance of 4 hits
1/7776 (0.01%) chance of 5 hits
*/
| [
{
"class_path": "SeanShubin__kotlin-tryme__abc67c5/com/seanshubin/kotlin/tryme/domain/dice/SpheresOfInfluenceDiceStatisticsApp.class",
"javap": "Compiled from \"SpheresOfInfluenceDiceStatisticsApp.kt\"\npublic final class com.seanshubin.kotlin.tryme.domain.dice.SpheresOfInfluenceDiceStatisticsApp {\n publi... |
SeanShubin__kotlin-tryme__abc67c5/domain/src/main/kotlin/com/seanshubin/kotlin/tryme/domain/ratio/Ratio.kt | package com.seanshubin.kotlin.tryme.domain.ratio
data class Ratio(val numerator: Int, val denominator: Int) : Comparable<Ratio> {
operator fun plus(that: Ratio): Ratio {
val lcm = leastCommonMultiple(denominator, that.denominator)
return Ratio(numerator * lcm / denominator + that.numerator * lcm / that.denominator, lcm).simplify()
}
operator fun minus(that: Ratio): Ratio = (this + -that).simplify()
operator fun times(that: Ratio): Ratio = Ratio(numerator * that.numerator, denominator * that.denominator).simplify()
operator fun div(that: Ratio): Ratio = (this * that.recriprocal()).simplify()
operator fun unaryMinus(): Ratio = Ratio(-numerator, denominator).simplify()
fun recriprocal(): Ratio = Ratio(denominator, numerator).simplify()
fun withDenominator(newDenominator: Int): Ratio = Ratio(numerator * newDenominator / denominator, newDenominator)
override fun compareTo(that: Ratio): Int {
val lcm = leastCommonMultiple(denominator, that.denominator)
return (numerator * lcm / denominator).compareTo(that.numerator * lcm / that.denominator)
}
override fun toString(): String = "$numerator/$denominator"
fun simplify(): Ratio = simplifyFactor().simplifySign()
private fun simplifySign(): Ratio =
if (denominator < 0) Ratio(-numerator, -denominator)
else this
private fun simplifyFactor(): Ratio {
val gcf = greatestCommonFactor(numerator, denominator)
return Ratio(numerator / gcf, denominator / gcf)
}
companion object {
fun greatestCommonFactor(a: Int, b: Int): Int =
if (b == 0) a
else greatestCommonFactor(b, a % b)
fun leastCommonMultiple(a: Int, b: Int): Int =
if (a == 0 && b == 0) 0
else a * b / greatestCommonFactor(a, b)
val regex = Regex("""(-?\d+)/(-?\d+)""")
fun parse(s: String): Ratio {
val matchResult = regex.matchEntire(s)
if (matchResult == null) throw RuntimeException("Value '$s' could did not match expression $regex")
val numerator = matchResult.groupValues[1].toInt()
val denominator = matchResult.groupValues[2].toInt()
return Ratio(numerator, denominator).simplify()
}
}
val toDouble: Double get() = numerator.toDouble() / denominator.toDouble()
}
| [
{
"class_path": "SeanShubin__kotlin-tryme__abc67c5/com/seanshubin/kotlin/tryme/domain/ratio/Ratio.class",
"javap": "Compiled from \"Ratio.kt\"\npublic final class com.seanshubin.kotlin.tryme.domain.ratio.Ratio implements java.lang.Comparable<com.seanshubin.kotlin.tryme.domain.ratio.Ratio> {\n public static... |
SeanShubin__kotlin-tryme__abc67c5/domain/src/main/kotlin/com/seanshubin/kotlin/tryme/domain/schulze/Schulze.kt | package com.seanshubin.kotlin.tryme.domain.schulze
import kotlin.math.max
import kotlin.math.min
object Schulze {
fun schulzeTally(candidates: List<String>, rows: List<List<Int>>): List<Pair<String, List<String>>> {
val strongestPaths = strongestPaths(rows)
val tallied = tally(strongestPaths, emptyList(), emptyList())
val result = mutableListOf<Pair<String, List<String>>>()
var place = 1
tallied.forEach { talliedRow ->
val candidatesAtPlace = talliedRow.map { candidates[it] }
val placeString = placeString(place)
result.add(Pair(placeString, candidatesAtPlace))
place += talliedRow.size
}
return result
}
fun strongestPaths(rows: List<List<Int>>): List<List<Int>> {
val size = rows.size
val strongestPaths = mutableList2(size, size)
for (i in 0 until size) {
for (j in 0 until size) {
strongestPaths[i][j] = rows[i][j]
}
}
for (i in 0 until size) {
for (j in 0 until size) {
if (i != j) {
for (k in 0 until size) {
if (i != k && j != k) {
strongestPaths[j][k] =
max(strongestPaths[j][k], min(strongestPaths[j][i], strongestPaths[i][k]))
}
}
}
}
}
return strongestPaths
}
tailrec fun tally(rows: List<List<Int>>, soFar: List<List<Int>>, indices: List<Int>): List<List<Int>> {
val size = rows.size
return if (indices.size == size) soFar
else {
val undefeated = (0 until size).filter { i ->
!indices.contains(i) && (0 until size).all { j ->
indices.contains(j) || rows[i][j] >= rows[j][i]
}
}
tally(rows, soFar + listOf(undefeated), indices + undefeated)
}
}
private fun mutableList2(rowCount: Int, colCount: Int): MutableList<MutableList<Int>> =
mutableListOf(*(0 until rowCount).map {
mutableListOf(*(0 until colCount).map {
0
}.toTypedArray())
}.toTypedArray())
private fun placeString(place: Int): String = when (place) {
1 -> "1st"
2 -> "2nd"
3 -> "3rd"
else -> "${place}th"
}
}
| [
{
"class_path": "SeanShubin__kotlin-tryme__abc67c5/com/seanshubin/kotlin/tryme/domain/schulze/Schulze.class",
"javap": "Compiled from \"Schulze.kt\"\npublic final class com.seanshubin.kotlin.tryme.domain.schulze.Schulze {\n public static final com.seanshubin.kotlin.tryme.domain.schulze.Schulze INSTANCE;\n\... |
Asaad27__adventOfCode2022__16f0187/src/main/kotlin/asaad/DayFour.kt | package asaad
import java.io.File
private fun IntRange.containsOneAnother(intRange: IntRange): Boolean {
return this.intersect(intRange).size == minOf(intRange.size, this.size)
}
private fun IntRange.overlap(intRange: IntRange): Boolean {
return this.intersect(intRange).isNotEmpty()
}
private val IntRange.size: Int
get() {
return this.last - this.first + 1
}
class DayFour(filePath: String) {
private val file = File(filePath)
private val input = readInput(file).map { it.asRanges() }
private fun readInput(file: File) = file.readLines()
private fun String.asRanges(): List<IntRange> {
return this.split(",").map { getFieldRange(it) }
}
private fun solve(func: IntRange.(IntRange) -> Boolean) =
input.count { it[0].func(it[1]) }
fun result() {
println("\tpart 1: ${solve(IntRange::containsOneAnother)}")
println("\tpart 2: ${solve(IntRange::overlap)}")
}
/**
* @param section: field section expression : "a-b"
*/
private fun getFieldRange(section: String): IntRange {
val (first, second) = section.split("-")
.map { it.toInt() }
return first..second
}
}
| [
{
"class_path": "Asaad27__adventOfCode2022__16f0187/asaad/DayFour$result$1.class",
"javap": "Compiled from \"DayFour.kt\"\nfinal class asaad.DayFour$result$1 extends kotlin.jvm.internal.FunctionReferenceImpl implements kotlin.jvm.functions.Function2<kotlin.ranges.IntRange, kotlin.ranges.IntRange, java.lang.... |
Asaad27__adventOfCode2022__16f0187/src/main/kotlin/asaad/DayThree.kt | package asaad
import java.io.File
class DayThree(filePath: String) {
private val file = File(filePath)
private val input = readInput(file)
private fun readInput(file: File) = file.readLines()
private fun Char.toPriority(): Int = when {
this.isLowerCase() -> this - 'a' + 1
this.isUpperCase() -> this - 'A' + 27
else -> throw Exception("char $this has no priority")
}
private fun solve1() =
input.fold(0) { acc, s -> acc + RuckSack(s).repeatedItem().toPriority() }
private fun solve2() =
input.chunked(3){ chunk ->
chunk.map { it.toSet() }
.reduce { acc, chars -> acc.intersect(chars) }
.firstOrNull()
}.fold(0) { acc, s -> acc + s?.toPriority()!! }
fun result() {
println("\tpart 1: ${solve1()}")
println("\tpart 2: ${solve2()}")
}
private class RuckSack(ruckSack: String) {
private val compartments: List<Set<Char>>
init {
val ruckSize = ruckSack.length
compartments = listOf(
ruckSack.substring(0 until ruckSize / 2).toHashSet(),
ruckSack.substring(ruckSize / 2 until ruckSize).toHashSet()
)
}
fun repeatedItem(): Char {
val intersection = compartments[0].intersect(compartments[1].toSet())
if (intersection.size > 1)
throw Exception("there is more than one repeated element in the compartments")
return intersection.first()
}
}
}
| [
{
"class_path": "Asaad27__adventOfCode2022__16f0187/asaad/DayThree.class",
"javap": "Compiled from \"DayThree.kt\"\npublic final class asaad.DayThree {\n private final java.io.File file;\n\n private final java.util.List<java.lang.String> input;\n\n public asaad.DayThree(java.lang.String);\n Code:\n ... |
Asaad27__adventOfCode2022__16f0187/src/main/kotlin/asaad/DayFive.kt | package asaad
import java.io.File
class DayFive(filePath: String) {
private val file = File(filePath)
private val input = readInput(file)
private fun readInput(file: File): Pair<List<String>, List<String>> {
val lines = file.readLines()
return lines.takeWhile { it.isNotBlank() } to lines.takeLastWhile { it.isNotBlank() }
}
fun result() {
println("\tpart 1: ${solve(Stacks::applyMove)}")
println("\tpart 2: ${solve(Stacks::applyMove2)}")
}
private fun solve(func: Stacks.(Move) -> Unit): String {
val stacks = Stacks(input.first)
for (line in input.second)
stacks.func(Move(line))
return stacks.getTops()
}
class Move(input: String){
operator fun component1(): Int = x
operator fun component2(): Int = from
operator fun component3(): Int = to
private val x: Int
private val from : Int
private val to: Int
init {
val split = input.split(" ")
x = split[1].toInt()
from = split[3].toInt()-1
to = split[5].toInt()-1
}
}
class Stacks(
input: List<String>
){
private val stacks :List<MutableList<String>>
init {
val stackNumbers = input.last().trim().split("\\s+".toRegex()).map { it.toInt() }
val maxNumber = stackNumbers.max()
stacks = List(maxNumber) { mutableListOf() }
for (line in input.size-2 downTo 0){
val split = input[line].chunked(4).map { it.trimEnd().removeSurrounding("[", "]") }
for (number in split.indices){
if (split[number] == "")
continue
stacks[number].add(split[number])
}
}
}
fun applyMove(move: Move){
val (x, from, to) = move
repeat(x){
stacks[to].add(stacks[from].last())
stacks[from].removeLast()
}
}
fun applyMove2(move: Move){
val (x, from, to) = move
stacks[to].addAll(stacks[from].takeLast(x))
repeat(x){
stacks[from].removeLast()
}
}
fun getTops() = stacks.joinToString("") { it.last() }
}
}
| [
{
"class_path": "Asaad27__adventOfCode2022__16f0187/asaad/DayFive$Stacks.class",
"javap": "Compiled from \"DayFive.kt\"\npublic final class asaad.DayFive$Stacks {\n private final java.util.List<java.util.List<java.lang.String>> stacks;\n\n public asaad.DayFive$Stacks(java.util.List<java.lang.String>);\n ... |
Asaad27__adventOfCode2022__16f0187/src/main/kotlin/asaad/DayTwo.kt | package asaad
import java.io.File
class DayTwo(filePath: String) {
/*
* rock -> Scissors -> paper ->rock... ->win, <-loose
*/
private val file = File(filePath)
private val input = readInput(file)
private fun readInput(file: File) = file.readLines()
private var part1 = true
private val handMapper = mapOf(
"A" to HAND.ROCK,
"X" to HAND.ROCK,
"Y" to HAND.PAPER,
"B" to HAND.PAPER,
"Z" to HAND.SCISSORS,
"C" to HAND.SCISSORS
)
private val outcomeMapper = mapOf(
"X" to OUTCOME.LOOSE,
"Y" to OUTCOME.DRAW,
"Z" to OUTCOME.WIN
)
private val handSize = HAND.values().size
fun result() {
println("\tpart 1: ${solve()}")
part1 = false
println("\tpart 2: ${solve()}")
}
private fun solve() =
input.fold(0) { acc: Int, round: String ->
acc + roundScore(round)
}
private fun roundScore(round: String): Int {
var score = 0
val (firstCol, secondCol) = round.split(" ")
val opponentHand = handParser(firstCol)
val myHand = if (part1) handParser(secondCol) else outcomeToHand(opponentHand, outcomeParser(secondCol))
score += myHand.score + roundOutcome(opponentHand, myHand).score
return score
}
private fun roundOutcome(opponent: HAND, mine: HAND): OUTCOME = when {
opponent == mine -> OUTCOME.DRAW
(opponent.ordinal + 1).mod(handSize)
== mine.ordinal -> OUTCOME.WIN
else -> OUTCOME.LOOSE
}
private fun outcomeToHand(opponent: HAND, outcome: OUTCOME): HAND = when (outcome) {
OUTCOME.LOOSE -> HAND.values()[(opponent.ordinal + handSize - 1).mod(handSize)]
OUTCOME.WIN -> HAND.values()[(opponent.ordinal + 1).mod(handSize)]
else -> opponent
}
private fun handParser(input: String) = handMapper[input]!!
private fun outcomeParser(input: String) = outcomeMapper[input]!!
private enum class OUTCOME(val score: Int) {
WIN(6),
LOOSE(0),
DRAW(3);
}
private enum class HAND(val score: Int) {
ROCK(1),
PAPER(2),
SCISSORS(3);
}
}
| [
{
"class_path": "Asaad27__adventOfCode2022__16f0187/asaad/DayTwo.class",
"javap": "Compiled from \"DayTwo.kt\"\npublic final class asaad.DayTwo {\n private final java.io.File file;\n\n private final java.util.List<java.lang.String> input;\n\n private boolean part1;\n\n private final java.util.Map<java.l... |
Asaad27__adventOfCode2022__16f0187/src/main/kotlin/asaad/DaySeven.kt | package asaad
import java.io.File
private const val MAX_STORAGE = 70000000
private const val REQUIRED_STORAGE = 30000000
private const val PART1 = 100000
class DaySeven(filePath: String) {
private val file = File(filePath)
private val input = readInput(file)
private var lineNumber = 0
private fun readInput(file: File) = file.bufferedReader().readLines()
fun result() {
val head = Node(name = "head")
val root = Node(name = "/")
head.children.add(root)
createFileTree(head)
val dirSizes = mutableListOf<Int>()
getDirsSizes(root, sizes = dirSizes)
dirSizes.sort()
println("\tpart 1: ${solve1(dirSizes)}")
println("\tpart 2: ${solve2(root, dirSizes)}")
}
/**
* Time complexity: O(Log(N)) where N is the number of directories
*/
private fun solve2(root: Node, sizes: MutableList<Int>): Int {
val used = root.dirSize
val available = MAX_STORAGE - used
if (available >= REQUIRED_STORAGE)
return 0
var answer = 0
var (left, right) = listOf(0, sizes.size - 1)
while (left <= right) {
val mid = left + (right - left) / 2
val current = sizes[mid]
if (available >= REQUIRED_STORAGE - current) {
answer = current
right = mid - 1
} else {
left = mid + 1
}
}
return answer
}
/**
* @param sizes: the list where the directory sizes will be appended
* gets the list of directory sizes
* Space Complexity : O(N) where N is the number of directories
*/
private fun getDirsSizes(node: Node, sizes: MutableList<Int>) {
sizes.add(node.dirSize)
for (child in node.children)
getDirsSizes(child, sizes)
}
/**
* Time Complexity: O(N) where N is the number of directories
*/
private fun solve1(dirSizes: List<Int>) = dirSizes.takeWhile { it <= PART1 }.sum()
/**
* Creates a dir tree, and computes the size of each directory
* Time Complexity: O(M) where M is the number of lines
*/
private fun createFileTree(current: Node): Int {
var nextLine = input.readNext()
val nodes = HashMap<String, Node>()
while (nextLine != null) {
when {
nextLine.startsWith("$") -> {
val command = parseCommand(nextLine)
when (command.first) {
Command.LS -> {}
Command.GOTO -> {
val dirNode = command.second!!
if (dirNode == "/")
nodes[dirNode] = current.children.first()
current.dirSize += createFileTree(nodes[dirNode]!!)
}
Command.BACK -> return current.dirSize
}
}
nextLine.startsWith("dir") -> {
val dirName = nextLine.split(" ")[1]
val dirNode = Node(name = dirName)
nodes[dirName] = dirNode
current.children.add(dirNode)
}
nextLine[0].isDigit() -> {
val fileSize = nextLine.split(" ")[0].toInt()
current.dirSize += fileSize
}
else -> {
throw Exception("unable to parse line $nextLine")
}
}
nextLine = input.readNext()
}
return current.dirSize
}
private fun parseCommand(line: String): Pair<Command, String?> {
val split = line.split(" ")
return when {
split.size > 1 && split[1] == "ls" -> Command.LS to null
split.size > 2 && split[1] == "cd" && split[2] == ".." -> Command.BACK to null
split.size > 2 && split[1] == "cd" -> Command.GOTO to split[2]
else -> throw Exception("unknown command $line")
}
}
enum class Command {
GOTO,
BACK,
LS
}
data class Node(
var name: String,
var dirSize: Int = 0,
var children: MutableList<Node> = mutableListOf(),
)
private fun <E> List<E>.readNext(): String? {
if (lineNumber > size - 1)
return null
return input[lineNumber].also { lineNumber++ }
}
}
| [
{
"class_path": "Asaad27__adventOfCode2022__16f0187/asaad/DaySeven$Command.class",
"javap": "Compiled from \"DaySeven.kt\"\npublic final class asaad.DaySeven$Command extends java.lang.Enum<asaad.DaySeven$Command> {\n public static final asaad.DaySeven$Command GOTO;\n\n public static final asaad.DaySeven$C... |
Asaad27__adventOfCode2022__16f0187/src/main/kotlin/asaad/DayNine.kt | package asaad
import java.io.File
import kotlin.math.abs
class DayNine(filePath: String) {
private val file = File(filePath)
private val input = readInput(file)
private fun readInput(file: File) = file.bufferedReader().readLines()
fun result() {
println("\tpart1: ${solve(2)}")
println("\tpart2: ${solve(10)}")
}
private fun solve(length: Int): Int {
val board = Board(length)
for (line in input) {
val (direction, steps) = line.split(" ")
when (direction) {
"R" -> board.move(1 to 0, steps.toInt())
"L" -> board.move(-1 to 0, steps.toInt())
"D" -> board.move(0 to -1, steps.toInt())
"U" -> board.move(0 to 1, steps.toInt())
else -> throw Exception("Unknown direction $direction")
}
}
return board.numberOfPositions()
}
class Board(length: Int) {
private var rope = Array(length) { 0 to 0 }
private val visitedPositions = HashSet<Pair<Int, Int>>()
private fun distanceBetween(tail: Pair<Int, Int>, head: Pair<Int, Int>) = maxOf(
abs(head.first - tail.first),
abs(head.second - tail.second)
)
fun numberOfPositions() = visitedPositions.size
private fun followNode(tail: Pair<Int, Int>, head: Pair<Int, Int>): Pair<Int, Int> {
if (distanceBetween(head, tail) != 2)
return tail
val newX = when {
head.first - tail.first > 0 -> tail.first + 1
head.first - tail.first < 0 -> tail.first - 1
else -> tail.first
}
val newY = when {
head.second - tail.second > 0 -> tail.second + 1
head.second - tail.second < 0 -> tail.second - 1
else -> tail.second
}
return newX to newY
}
fun move(direction: Pair<Int, Int>, steps: Int) {
for (step in 1..steps) {
rope[0] = rope[0].first + direction.first to rope[0].second + direction.second
for (i in 1 until rope.size) {
rope[i] = followNode(rope[i], rope[i - 1])
}
visitedPositions.add(rope.last())
}
}
}
}
| [
{
"class_path": "Asaad27__adventOfCode2022__16f0187/asaad/DayNine.class",
"javap": "Compiled from \"DayNine.kt\"\npublic final class asaad.DayNine {\n private final java.io.File file;\n\n private final java.util.List<java.lang.String> input;\n\n public asaad.DayNine(java.lang.String);\n Code:\n ... |
MariusSchmidt__adventofcode2021__2b70993/src/main/kotlin/adventofcode/PuzzleDay04.kt | package adventofcode
import java.io.File
class PuzzleDay04 {
fun determineWinningBoardOrder(file: File): List<BingoBoard> {
val pulls = readPulls(file)
val boards = readBoards(file)
return pulls.flatMap { pulledNumber ->
boards.filter { !it.won }
.onEach { it.drawNumber(pulledNumber) }
.filter { it.won }
}
}
private fun readPulls(file: File): List<Int> = file.useLines { seq ->
seq.first().split(",").map { it.toInt() }
}
private fun readBoards(file: File): List<BingoBoard> = file.useLines { seq ->
seq.drop(2)
.flatMap { it.split(" ") }
.filter { it.isNotEmpty() }
.map { it.toInt() }
.windowed(25, 25)
.mapIndexed { index, boardNumbers -> BingoBoard(index + 1, boardNumbers.toIntArray()) }
.toList()
}
class BingoBoard(val id: Int, numbers: IntArray) {
companion object {
const val X_SIZE = 5
const val Y_SIZE = 5
const val WINNING_COUNT = 5
}
private val fields: Array<BingoBoardField> = numbers.map { BingoBoardField(it) }.toTypedArray()
var won: Boolean = false
var drawsToWin: Int = 0
var lastNumber: Int = -1
fun score(): Int = if (!won) 0 else fields.filter { !it.pulled }.sumOf { it.number } * lastNumber
fun drawNumber(number: Int) {
if (won) return
fields.filter { it.number == number }.onEach { it.pulled = true }
drawsToWin++
won = checkWon()
lastNumber = number
}
private fun checkWon(): Boolean =
((0 until X_SIZE).map { columnFields(it) } + (0 until Y_SIZE).map { rowFields(it) }).any { it.checkWon() }
private fun List<BingoBoardField>.checkWon(): Boolean = count { it.pulled } >= WINNING_COUNT
private fun rowFields(rowIndex: Int): List<BingoBoardField> =
fields.slice(rowIndex * X_SIZE until rowIndex * X_SIZE + X_SIZE)
private fun columnFields(columnIndex: Int): List<BingoBoardField> =
fields.slice(columnIndex until X_SIZE * Y_SIZE step X_SIZE)
}
class BingoBoardField(val number: Int) {
var pulled: Boolean = false
}
} | [
{
"class_path": "MariusSchmidt__adventofcode2021__2b70993/adventofcode/PuzzleDay04$BingoBoard$Companion.class",
"javap": "Compiled from \"PuzzleDay04.kt\"\npublic final class adventofcode.PuzzleDay04$BingoBoard$Companion {\n private adventofcode.PuzzleDay04$BingoBoard$Companion();\n Code:\n 0: alo... |
MariusSchmidt__adventofcode2021__2b70993/src/main/kotlin/adventofcode/PuzzleDay07.kt | package adventofcode
import java.io.File
import kotlin.math.*
/**
*
* PART I
* Interestingly enough, for any series of numbers in R^1 the central point that minimizes the sum of distances to each
* other point is the median. In fact "The median minimizes the sum of absolute deviations". Until AoC 2021 I did not
* realize that and wanted to see proof:
*
* A explanatory and a formal proof can be found here https://math.stackexchange.com/questions/113270/the-median-minimizes-the-sum-of-absolute-deviations-the-ell-1-norm
* Also this paper https://tommasorigon.github.io/StatI/approfondimenti/Schwertman1990.pdf gives a similar proof
*
*
* PART II
* Mainly since the answer the first riddle was the median, I guessed, that the second might be the arithmetic average.
* I still search for an explanation why this works and why we need to introduce the +.0.5 variance and why for some
* it works without that adjustment. It might the difference between float and double based calculation
*
*/
class PuzzleDay07 {
fun findMostCentralPointForCrabsToRally(file: File, constantCost: Boolean): Pair<Int, Int> = file.useLines { seq ->
return if (constantCost) findForConstantCostPerDistance(seq)
else findForLinearIncreasingCostPerDistance(seq)
}
private fun findForConstantCostPerDistance(seq: Sequence<String>): Pair<Int, Int> {
val crabPositions = seq.first().split(",").map { it.toInt() }.sorted()
val medianIndex = crabPositions.size / 2
val median = crabPositions[medianIndex]
val sumOfDistances = crabPositions.fold(0) { sum, position -> sum + abs(position - median) }
return median to sumOfDistances
}
private fun findForLinearIncreasingCostPerDistance(seq: Sequence<String>): Pair<Int, Int> {
val crabPositions = seq.first().split(",").map { it.toInt() }
val arithmeticAverage = crabPositions.average()
val lowerBound = (arithmeticAverage - 0.5).roundToInt()
val upperBound = (arithmeticAverage + 0.5).roundToInt()
val resultLowerBound = calculateFuelUsage(crabPositions, lowerBound)
val resultUpperBound = calculateFuelUsage(crabPositions, upperBound)
return if (resultLowerBound.second < resultUpperBound.second) resultLowerBound else resultUpperBound
}
private fun calculateFuelUsage(crabPositions: List<Int>, rallyPoint: Int): Pair<Int, Int> {
val fuelUsed = crabPositions.fold(0) { fuelAggregator, position ->
val distance = abs(position - rallyPoint)
val fuelConsumption = (0..distance).sum()
fuelAggregator + fuelConsumption
}
return rallyPoint to fuelUsed
}
} | [
{
"class_path": "MariusSchmidt__adventofcode2021__2b70993/adventofcode/PuzzleDay07.class",
"javap": "Compiled from \"PuzzleDay07.kt\"\npublic final class adventofcode.PuzzleDay07 {\n public adventofcode.PuzzleDay07();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java... |
MariusSchmidt__adventofcode2021__2b70993/src/main/kotlin/adventofcode/PuzzleDay03.kt | package adventofcode
import java.io.File
class PuzzleDay03(significantBits: Int) {
private val histogramSize = significantBits * 2
fun readGammaAndEpsilon(input: File): Pair<Int, Int> =
input.useLines { bitsSequence ->
val gammaBits = bitsSequence.deriveBitmask(true)
val gamma = gammaBits.convertBitsToInt()
val epsilon = gammaBits.flipBitmask().convertBitsToInt()
gamma to epsilon
}
private fun Sequence<String>.deriveBitmask(mostCommonMode: Boolean) = calculateHistogramPerBitPosition()
.collectBitmaskFromHistogram(mostCommonMode)
private fun Sequence<String>.calculateHistogramPerBitPosition(): IntArray =
fold(IntArray(histogramSize)) { histogram, bitString ->
bitString.toCharArray().forEachIndexed { index, bit ->
val histogramPos = if ('0' == bit) 2 * index else 2 * index + 1
histogram[histogramPos]++
}
histogram
}
private fun IntArray.collectBitmaskFromHistogram(mostCommonMode: Boolean): CharArray =
asIterable().windowed(2, 2).map {
when (mostCommonMode) {
true -> if (it[1] >= it[0]) '1' else '0'
false -> if (it[1] < it[0]) '1' else '0'
}
}.toCharArray()
private fun CharArray.flipBitmask(): CharArray = map { if (it == '0') '1' else '0' }.toCharArray()
private fun CharArray.convertBitsToInt(): Int = fold(0) { int, bit ->
val bitValue = if ('0' == bit) 0 else 1
int * 2 + bitValue
}
fun readOxygenScrubberRatings(input: File): Int =
readRatingForMode(input, true)
fun readCO2ScrubberRatings(input: File): Int =
readRatingForMode(input, false)
fun readLifeSupportRating(file: File) = readOxygenScrubberRatings(file) * readCO2ScrubberRatings(file)
private fun readRatingForMode(input: File, mostCommonMode: Boolean) =
input.useLines { bitsSequence ->
var filteredNumbers = bitsSequence.toList()
var bitmask = filteredNumbers.asSequence().deriveBitmask(mostCommonMode)
for (bitPosition in bitmask.indices) {
filteredNumbers = filteredNumbers.filter { it[bitPosition] == bitmask[bitPosition] }
if (filteredNumbers.count() == 1) break
bitmask = filteredNumbers.asSequence().deriveBitmask(mostCommonMode)
}
filteredNumbers
}.first().toCharArray().convertBitsToInt()
} | [
{
"class_path": "MariusSchmidt__adventofcode2021__2b70993/adventofcode/PuzzleDay03.class",
"javap": "Compiled from \"PuzzleDay03.kt\"\npublic final class adventofcode.PuzzleDay03 {\n private final int histogramSize;\n\n public adventofcode.PuzzleDay03(int);\n Code:\n 0: aload_0\n 1: invokes... |
fabmax__kool__85fe1de/kool-core/src/commonMain/kotlin/de/fabmax/kool/math/Partition.kt | package de.fabmax.kool.math
import kotlin.math.*
fun <T> MutableList<T>.partition(k: Int, cmp: (T, T) -> Int) = partition(indices, k, cmp)
fun <T> MutableList<T>.partition(rng: IntRange, k: Int, cmp: (T, T) -> Int) {
partition(this, rng.first, rng.last, k, { get(it) }, cmp, { a, b -> this[a] = this[b].also { this[b] = this[a] } })
}
fun <T> Array<T>.partition(k: Int, cmp: (T, T) -> Int) = partition(indices, k, cmp)
fun <T> Array<T>.partition(rng: IntRange, k: Int, cmp: (T, T) -> Int) {
partition(this, rng.first, rng.last, k, { get(it) }, cmp, { a, b -> this[a] = this[b].also { this[b] = this[a] } })
}
/**
* Partitions items with the given comparator. After partitioning, all elements left of k are smaller
* than all elements right of k with respect to the given comparator function.
*
* This method implements the Floyd-Rivest selection algorithm:
* https://en.wikipedia.org/wiki/Floyd%E2%80%93Rivest_algorithm
*/
fun <L,T> partition(elems: L, lt: Int, rt: Int, k: Int, get: L.(Int) -> T, cmp: (T, T) -> Int, swap: L.(Int, Int) -> Unit) {
var left = lt
var right = rt
while (right > left) {
if (right - left > 600) {
val n = right - left + 1
val i = k - left + 1
val z = ln(n.toDouble())
val s = 0.5 * exp(2.0 * z / 3.0)
val sd = 0.5 * sqrt(z * s * (n - s) / n) * sign(i - n / 2.0)
val newLeft = max(left, (k - i * s / n + sd).toInt())
val newRight = min(right, (k + (n - i) * s / n + sd).toInt())
partition(elems, newLeft, newRight, k, get, cmp, swap)
}
val t = elems.get(k)
var i = left
var j = right
elems.swap(left, k)
if (cmp(elems.get(right), t) > 0) {
elems.swap(right, left)
}
while (i < j) {
elems.swap(i, j)
i++
j--
while (cmp(elems.get(i), t) < 0) {
i++
}
while (j >= 0 && cmp(elems.get(j), t) > 0) {
j--
}
}
if (cmp(elems.get(left), t) == 0) {
elems.swap(left, j)
} else {
j++
elems.swap(j, right)
}
if (j <= k) {
left = j + 1
}
if (k <= j) {
right = j - 1
}
}
} | [
{
"class_path": "fabmax__kool__85fe1de/de/fabmax/kool/math/PartitionKt.class",
"javap": "Compiled from \"Partition.kt\"\npublic final class de.fabmax.kool.math.PartitionKt {\n public static final <T> void partition(java.util.List<T>, int, kotlin.jvm.functions.Function2<? super T, ? super T, java.lang.Integ... |
korilin__DSA-kt__b96ba1b/src/main/kotlin/sort_algorithm/quickSort.kt | package sort_algorithm
/**
* 快速排序
* 时间复杂度:
* 最优时间复杂度:Ο(n*log(n))
* 平均时间复杂度:Ο(n*log(n))
* 最坏时间复杂度:Ο(n²)
* 空间复杂度:Ο(1)
*
* Quick Sort
* Time Complexity:
* Optimal Time Complexity: Ο(n*log(n))
* Average Time Complexity: Ο(n*log(n))
* Worst Time Complexity: Ο(n²)
* Space Complexity: Ο(1)
*/
fun quickSort(array: IntArray) {
fun partition(left: Int, right: Int): Int {
// 以最左边的值作为交换值
var pivotPreIndex = left
for (index in left..right) {
if (array[index] <= array[right]) {
array[pivotPreIndex] = array[index].also { array[index] = array[pivotPreIndex] }
pivotPreIndex += 1
}
}
return pivotPreIndex - 1
}
fun inner(left: Int, right: Int) {
if (left < right) {
val p = partition(left, right)
inner(left, p - 1)
inner(p + 1, right)
}
}
inner(0, array.size - 1)
} | [
{
"class_path": "korilin__DSA-kt__b96ba1b/sort_algorithm/QuickSortKt.class",
"javap": "Compiled from \"quickSort.kt\"\npublic final class sort_algorithm.QuickSortKt {\n public static final void quickSort(int[]);\n Code:\n 0: aload_0\n 1: ldc #9 // String array\n ... |
ErikHellman__advent-of-code-2021__37f54d5/day4/src/main/kotlin/day4/Main.kt | package day4
import java.io.File
import java.util.regex.Pattern
fun main(args: Array<String>) {
val lines = loadFile("input.txt")
val numbersDrawn = lines[0]
val boards = lines.drop(1)
.chunked(5)
.map { board ->
board.map { line -> line.map { it to false }.toMutableList() }.toMutableList()
}
traverseBoards(numbersDrawn, boards)
}
private fun traverseBoards(
numbersDrawn: MutableList<Int>,
boards: List<MutableList<MutableList<Pair<Int, Boolean>>>>
) {
var lastWinningBoard = boards[0]
var lastWinningNumber = -1
var mutableBoards = boards
numbersDrawn.forEach { numberDrawn ->
mutableBoards = mutableBoards.filter { board ->
updateBoard(numberDrawn, board)
val didWin = checkBoard(board)
if (didWin) {
lastWinningBoard = board
lastWinningNumber = numberDrawn
}
!didWin
}
}
println("Last board won at $lastWinningNumber")
lastWinningBoard.forEach { line ->
println(line)
}
val sum = sumOfUnmarked(lastWinningBoard)
println("Result: $sum x $lastWinningNumber = ${sum * lastWinningNumber}")
}
fun sumOfUnmarked(board: MutableList<MutableList<Pair<Int, Boolean>>>): Int {
return board.flatten().fold(0 to false) { acc, pair ->
if (!pair.second) {
acc.copy(acc.first + pair.first)
} else acc
}.first
}
fun checkBoard(board: MutableList<MutableList<Pair<Int, Boolean>>>): Boolean {
board.forEach { line ->
val win = line.reduce { acc, next ->
acc.copy(second = acc.second && next.second)
}.second
if (win) return true
}
for (column in board[0].indices) {
val win = board.indices
.map { line -> board[line][column].second }
.reduce { acc, marked -> acc && marked }
if (win) return true
}
return false
}
fun updateBoard(numberDrawn: Int, board: MutableList<MutableList<Pair<Int, Boolean>>>) {
for (line in board.indices) {
for (column in board[line].indices) {
if (board[line][column].first == numberDrawn) {
board[line][column] = numberDrawn to true
}
}
}
}
fun loadFile(input: String): MutableList<MutableList<Int>> {
val regex = Pattern.compile(" +|,")
return File(input)
.useLines { sequence ->
sequence.filter { line -> line.isNotBlank() }
.map { line ->
line.split(regex)
.map { entry -> entry.trim() }
.filter { it.isNotBlank() }
.map { it.toInt() }
.toMutableList()
}
.toMutableList()
}
} | [
{
"class_path": "ErikHellman__advent-of-code-2021__37f54d5/day4/MainKt.class",
"javap": "Compiled from \"Main.kt\"\npublic final class day4.MainKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 // String args\n 3: invo... |
ErikHellman__advent-of-code-2021__37f54d5/day5/src/main/kotlin/day5/Main.kt | package day5
import java.io.File
import kotlin.math.absoluteValue
data class Point(val x: Int, val y: Int)
fun main(args: Array<String>) {
val diagram = HashMap<Point, Int>()
File("input.txt").readLines().forEach { line ->
val (start, end) = line
.split("->")
.map { pair ->
val (x, y) = pair.trim()
.split(',')
.map { num -> num.toInt() }
Point(x, y)
}
println("Got $start $end")
val yRange = if (start.y <= end.y) start.y .. end.y else start.y downTo end.y
val xRange = if (start.x <= end.x) start.x..end.x else start.x downTo end.x
if (start.x == end.x) {
println("Check vertical")
for (i in yRange) {
val point = Point(start.x, i)
val intersects = (diagram[point] ?: 0) + 1
diagram[point] = intersects
println("$point $intersects")
}
} else if (start.y == end.y) {
println("Check horizontal")
for (i in xRange) {
val point = Point(i, start.y)
val intersects = (diagram[point] ?: 0) + 1
diagram[point] = intersects
println("$point $intersects")
}
} else if ((start.x - end.x).absoluteValue == (start.y - end.y).absoluteValue) {
println("Check diagonal $start $end")
xRange.zip(yRange).forEach {
val point = Point(it.first, it.second)
val intersects = (diagram[point] ?: 0) + 1
diagram[point] = intersects
println("$point $intersects")
}
} else {
println("Skip $start $end")
}
}
println(diagram.filter { it.value >= 2 }.size)
} | [
{
"class_path": "ErikHellman__advent-of-code-2021__37f54d5/day5/MainKt.class",
"javap": "Compiled from \"Main.kt\"\npublic final class day5.MainKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 // String args\n 3: invo... |
agapeteo__kotlin-data-algo__b5662c8/src/arrays/Experiment.kt | package arrays
import java.io.File
import java.util.*
fun main() {
printDirContent(File("/Users/emix/go/src/practicalalgo"))
}
fun printDirContent(dir: File, tabsCount: Int = 0, ignoreHidden: Boolean = true) {
require(dir.exists()) { "$dir must exist" }
require(dir.isDirectory) { "$dir must be directory" }
val tabs = StringBuilder()
repeat(tabsCount) { tabs.append("\t") }
val dirOutput = StringBuilder()
dirOutput.append(tabs).append(dir.name).append("/")
println(dirOutput.toString())
for (file in dir.listFiles()) {
if (ignoreHidden && file.name.startsWith(".")) continue
if (file.isDirectory) {
printDirContent(file, tabsCount + 1, ignoreHidden)
} else {
val fileOutput = StringBuilder()
fileOutput.append("\t").append(tabs).append(file.name)
println(fileOutput.toString())
}
}
}
fun <T> binarySearch(list: List<Comparable<in T>>, value: T): Int {
var lowIdx = 0
var highIdx = list.size - 1
while (lowIdx <= highIdx) {
val midIdx = lowIdx + (highIdx - lowIdx) / 2
when {
list[midIdx] == value -> return midIdx
list[midIdx] < value -> lowIdx = midIdx + 1
list[midIdx] > value -> highIdx = midIdx - 1
}
}
return -(lowIdx + 1)
}
fun <T> binarySearchRecursive(list: List<Comparable<in T>>, value: T, lowIdx: Int = 0, highIdx: Int = list.size - 1): Int {
val notFound = -(lowIdx + 1)
if (lowIdx > highIdx) {
return notFound
}
val midIdx = lowIdx + (highIdx - lowIdx) / 2
return when {
list[midIdx] == value -> midIdx
list[midIdx] < value -> binarySearchRecursive(list, value, midIdx + 1, highIdx)
list[midIdx] > value -> binarySearchRecursive(list, value, lowIdx, midIdx - 1)
else -> notFound
}
}
fun <T> binarySearchLowestIndex(list: List<Comparable<in T>>, value: T): Int {
var lowIdx = -1
var highIdx = list.size
while (lowIdx + 1 < highIdx) {
val midIdx = (lowIdx + highIdx) ushr 1 // shifting but to right is same as dividing by 2
if (list[midIdx] >= value) {
highIdx = midIdx
} else {
lowIdx = midIdx
}
}
return when (value) {
list[highIdx] -> highIdx
else -> -(highIdx + 1)
}
}
fun average(numbers: List<Int>): Int {
var sum = 0
for (n in numbers) {
sum += n
}
return sum / numbers.size
}
fun max(numbers: List<Int>): Int {
var max = Int.MIN_VALUE
for (n in numbers) {
if (n > max) {
max = n
}
}
return max
}
fun idxOf(value: Int, list: List<Int>): Int {
for ((idx, element) in list.withIndex()) {
if (element == value) return idx
}
return -1
} | [
{
"class_path": "agapeteo__kotlin-data-algo__b5662c8/arrays/ExperimentKt.class",
"javap": "Compiled from \"Experiment.kt\"\npublic final class arrays.ExperimentKt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc... |
benjaminknauer__advent-of-code-22-kotlin__fcf41be/src/day01/Day01.kt | package day01
import java.io.File
data class Sweet(val calories: Int)
data class Elf(val sweets: List<Sweet>) {
fun getCaloriesSum(): Int {
return sweets.sumOf { it.calories }
}
}
fun parseInput(input: String): List<Elf> {
return input.split("\n\n")
.map { elf ->
val sweets = elf.split("\n")
.map { it.toInt() }
.map { Sweet(it) }
.toList()
Elf(sweets)
}
}
fun getCaloriesOfTopNElves(elves: List<Elf>, n: Int): Int {
val elvesSortedByCalories = elves
.sortedByDescending { it.getCaloriesSum() }
return elvesSortedByCalories
.take(n)
.sumOf { it.getCaloriesSum() }
}
fun part1(input: String): Int {
val elves = parseInput(input)
return getCaloriesOfTopNElves(elves, 1)
}
fun part2(input: String): Int {
val elves = parseInput(input)
return getCaloriesOfTopNElves(elves, 3)
}
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = File("src/day01/Day01_test.txt").readText()
check(part1(testInput) == 24000)
val input = File("src/day01/Day01.txt").readText()
println("Result Part 1: %s".format(part1(input)))
println("Result Part 2: %s".format(part2(input)))
}
| [
{
"class_path": "benjaminknauer__advent-of-code-22-kotlin__fcf41be/day01/Day01Kt$getCaloriesOfTopNElves$$inlined$sortedByDescending$1.class",
"javap": "Compiled from \"Comparisons.kt\"\npublic final class day01.Day01Kt$getCaloriesOfTopNElves$$inlined$sortedByDescending$1<T> implements java.util.Comparator {... |
benjaminknauer__advent-of-code-22-kotlin__fcf41be/src/day02/Day02.kt | package day02
import java.io.File
import java.lang.IllegalArgumentException
enum class Move(val score: Int) {
ROCK(1), PAPER(2), SCISSORS(3);
companion object {
fun fromShortcode(shortcode: String): Move {
return when (shortcode) {
"A", "X" -> ROCK
"B", "Y" -> PAPER
"C", "Z" -> SCISSORS
else -> throw IllegalArgumentException("Ungültiger Code %s".format(shortcode))
}
}
}
}
enum class RoundOutcome(val score: Int) {
WIN(6), DRAW(3), LOOSE(0);
companion object {
fun fromShortcode(shortcode: String): RoundOutcome {
return when (shortcode) {
"X" -> LOOSE
"Y" -> DRAW
"Z" -> WIN
else -> throw IllegalArgumentException("Ungültiger Code %s".format(shortcode))
}
}
}
}
class Game(private val gameRounds: List<GameRound>) {
fun getScore(): Int {
return gameRounds.sumOf { it.getScore() }
}
}
class GameRound(private val yourMove: Move, private val opponentMove: Move) {
constructor(opponentMove: Move, expectedOutcome: RoundOutcome) : this(
calculateYourOption(
opponentMove,
expectedOutcome
), opponentMove
)
fun getScore(): Int {
return calculateOutcome().score + yourMove.score
}
companion object {
fun calculateYourOption(opponentMove: Move, expectedOutcome: RoundOutcome): Move {
return when (expectedOutcome) {
RoundOutcome.WIN -> {
when (opponentMove) {
Move.ROCK -> Move.PAPER
Move.PAPER -> Move.SCISSORS
Move.SCISSORS -> Move.ROCK
}
}
RoundOutcome.DRAW -> opponentMove
RoundOutcome.LOOSE -> {
when (opponentMove) {
Move.ROCK -> Move.SCISSORS
Move.PAPER -> Move.ROCK
Move.SCISSORS -> Move.PAPER
}
}
}
}
}
private fun calculateOutcome(): RoundOutcome {
return when (yourMove) {
Move.ROCK -> {
when (opponentMove) {
Move.ROCK -> RoundOutcome.DRAW
Move.PAPER -> RoundOutcome.LOOSE
Move.SCISSORS -> RoundOutcome.WIN
}
}
Move.PAPER -> {
when (opponentMove) {
Move.ROCK -> RoundOutcome.WIN
Move.PAPER -> RoundOutcome.DRAW
Move.SCISSORS -> RoundOutcome.LOOSE
}
}
Move.SCISSORS -> {
when (opponentMove) {
Move.ROCK -> RoundOutcome.LOOSE
Move.PAPER -> RoundOutcome.WIN
Move.SCISSORS -> RoundOutcome.DRAW
}
}
}
}
}
fun parseInputPart1(input: String): Game {
val gameRounds = input.split("\n")
.map { gameround: String ->
val selectedOptions = gameround.split(" ")
val opponentMove = Move.fromShortcode(selectedOptions[0])
val yourMove = Move.fromShortcode(selectedOptions[1])
return@map GameRound(yourMove, opponentMove)
}
return Game(gameRounds)
}
fun parseInputPart2(input: String): Game {
val gameRounds = input.split("\n")
.map { gameround: String ->
val shortcodes = gameround.split(" ")
val opponentMove = Move.fromShortcode(shortcodes[0])
val expectedOutcome = RoundOutcome.fromShortcode(shortcodes[1])
return@map GameRound(opponentMove, expectedOutcome)
}
return Game(gameRounds)
}
fun part1(input: String): Int {
val game = parseInputPart1(input)
return game.getScore()
}
fun part2(input: String): Int {
val game = parseInputPart2(input)
return game.getScore()
}
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = File("src/day02/Day02_test.txt").readText()
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = File("src/day02/Day02.txt").readText()
println("Result Part 1: %s".format(part1(input)))
println("Result Part 2: %s".format(part2(input)))
}
| [
{
"class_path": "benjaminknauer__advent-of-code-22-kotlin__fcf41be/day02/Day02Kt.class",
"javap": "Compiled from \"Day02.kt\"\npublic final class day02.Day02Kt {\n public static final day02.Game parseInputPart1(java.lang.String);\n Code:\n 0: aload_0\n 1: ldc #9 //... |
Sladernom__Hyperskill-Cinema-Project__90d3400/src.kt | 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
}
}
}
| [
{
"class_path": "Sladernom__Hyperskill-Cinema-Project__90d3400/cinema/SrcKt.class",
"javap": "Compiled from \"src.kt\"\npublic final class cinema.SrcKt {\n private static int totalIncome;\n\n public static final int getTotalIncome();\n Code:\n 0: getstatic #10 // Field totalIn... |
rafaelnogueiradev__Cinema-Room-Manager-Kotlin__b9a8d89/Stage_5/src/main/kotlin/Main.kt | package cinema
const val STANDARD: Int = 10
const val DISCOUNT: Int = 8
const val B_SYMBOL: Char = 'B'
const val S_SYMBOL: Char = 'S'
const val SMALL_ROOM: Int = 60
enum class Cinema(var number: Int) {
ROW(7), SEATS(8),
TOTAL_SEATS(ROW.number * SEATS.number),
SELECT_ROW(0), SELECT_SEAT(0),
PURCHASED_TICKET(0), CURRENT_INCOME(0),
TOTAL_INCOME(0),
}
var mappingSeats = MutableList(Cinema.ROW.number) { MutableList(Cinema.SEATS.number) { S_SYMBOL } }
fun userInput() {
println("Enter the number of rows:")
Cinema.ROW.number = readln().toInt()
println("Enter the number of seats in each row:")
Cinema.SEATS.number = readln().toInt()
Cinema.TOTAL_SEATS.number = Cinema.ROW.number * Cinema.SEATS.number
mappingSeats = MutableList(Cinema.ROW.number) { MutableList(Cinema.SEATS.number) { S_SYMBOL } }
if (Cinema.TOTAL_SEATS.number <= SMALL_ROOM) {
Cinema.TOTAL_INCOME.number = Cinema.TOTAL_SEATS.number * STANDARD
} else {
val frontHalf = (Cinema.ROW.number / 2) * Cinema.SEATS.number * STANDARD
val backHalf = ((Cinema.ROW.number / 2) + (Cinema.ROW.number % 2)) * Cinema.SEATS.number * DISCOUNT
Cinema.TOTAL_INCOME.number = frontHalf + backHalf
}
seatsPreview(mappingSeats)
}
fun buyTicket() {
try {
println("Enter a row number:")
Cinema.SELECT_ROW.number = readln().toInt()
println("Enter a seat number in that row:")
Cinema.SELECT_SEAT.number = readln().toInt()
println("Ticket price: $${ticketPrice()}")
if (mappingSeats[Cinema.SELECT_ROW.number - 1][Cinema.SELECT_SEAT.number - 1] == B_SYMBOL) {
throw Exception()
} else {
mappingSeats[Cinema.SELECT_ROW.number - 1][Cinema.SELECT_SEAT.number - 1] = B_SYMBOL
}
Cinema.PURCHASED_TICKET.number += 1
} catch (e: IndexOutOfBoundsException) {
println("Wrong input!")
buyTicket()
} catch (e: Exception) {
println("That ticket has already been purchased")
buyTicket()
}
Cinema.CURRENT_INCOME.number += ticketPrice()
}
fun seatsPreview(mappingSeats: MutableList<MutableList<Char>>) {
print("Cinema:\n ")
(1..mappingSeats[0].size).forEach { print("$it ") }
println()
for (i in 1..mappingSeats.size) {
print("$i ")
println(mappingSeats[i - 1].joinToString(separator = " "))
}
}
fun ticketPrice(): Int {
val ticketPrice =
if (Cinema.TOTAL_SEATS.number <= SMALL_ROOM || Cinema.SELECT_ROW.number <= mappingSeats.size / 2) {
STANDARD
} else {
DISCOUNT
}
return ticketPrice
}
fun main() {
userInput()
cinema@ while (true) {
println(
"""
1. Show the seats
2. Buy a ticket
0. Exit
""".trimIndent()
)
when (readln()) {
"1" -> seatsPreview(mappingSeats)
"2" -> buyTicket()
"0" -> break@cinema
}
}
} | [
{
"class_path": "rafaelnogueiradev__Cinema-Room-Manager-Kotlin__b9a8d89/cinema/MainKt.class",
"javap": "Compiled from \"Main.kt\"\npublic final class cinema.MainKt {\n public static final int STANDARD;\n\n public static final int DISCOUNT;\n\n public static final char B_SYMBOL;\n\n public static final c... |
callej__Search-Engine__81f9b14/Main.kt | package search
import java.io.File
const val MENU = "=== Menu ===\n" +
"1. Find a person\n" +
"2. Print all people\n" +
"0. Exit"
fun findPerson(people: List<String> ,pIndex: Map<String, Set<Int>>) {
println("\nSelect a matching strategy: ALL, ANY, NONE")
val strategy = readLine()!!.uppercase()
println("\nEnter a name or email to search all matching people.")
val query = readLine()!!.lowercase()
when (strategy) {
"ALL" -> printResult(people, searchAll(people, pIndex, query))
"ANY" -> printResult(people, searchAny(people, pIndex, query))
"NONE" -> printResult(people, searchNone(people, pIndex, query))
else -> println("\nNo such strategy: $strategy")
}
}
fun searchAll(people: List<String>, pIndex: Map<String, Set<Int>>, query: String): Set<Int> {
var result = people.indices.toSet()
for (q in query.split(" ")) result = result.intersect((pIndex[q] ?: emptySet()).toSet())
return result
}
fun searchAny(people: List<String>, pIndex: Map<String, Set<Int>>, query: String): Set<Int> {
var result = emptySet<Int>()
for (q in query.split(" ")) result = result.union((pIndex[q] ?: emptySet()).toSet())
return result
}
fun searchNone(people: List<String>, pIndex: Map<String, Set<Int>>, query: String): Set<Int> {
return people.indices.toSet().subtract(searchAny(people, pIndex, query))
}
fun printResult(people: List<String>, result: Set<Int>) {
if (result.isNotEmpty()) {
println("\n${result.size} person${if (result.size > 1) "s" else ""} found:")
for (index in result) println(people[index])
} else {
println("\nNo matching people found.")
}
}
fun printAll(people: List<String>) {
println("\n=== List of people ===")
println(people.joinToString("\n"))
}
fun createIndex(people: List<String>): Map<String, Set<Int>> {
val peopleIndex = emptyMap<String, Set<Int>>().toMutableMap()
for (index in people.indices)
for (entry in people[index].lowercase().split(" "))
peopleIndex[entry] = peopleIndex[entry]?.plus(index) ?: setOf(index)
return peopleIndex
}
fun main(args: Array<String>) {
val filename = args[args.indexOf("--data") + 1]
val people = File(filename).readLines()
val peopleIndex = createIndex(people)
while (true) {
println("\n$MENU")
when (readLine()!!) {
"0" -> break
"1" -> findPerson(people, peopleIndex)
"2" -> printAll(people)
else -> println("\nIncorrect option! Try again.")
}
}
println("\nBye!")
}
| [
{
"class_path": "callej__Search-Engine__81f9b14/search/MainKt.class",
"javap": "Compiled from \"Main.kt\"\npublic final class search.MainKt {\n public static final java.lang.String MENU;\n\n public static final void findPerson(java.util.List<java.lang.String>, java.util.Map<java.lang.String, ? extends jav... |
RichCodersAndMe__LeetCode-Solution__96119bb/src/_004/kotlin/Solution.kt | package _004.kotlin
/**
* @author relish
* @since 2018/10/20
*/
class Solution {
fun findMedianSortedArrays(nums1: IntArray, nums2: IntArray): Double {
val len = nums1.size + nums2.size
return if (len % 2 == 0) {
(fix(nums1, 0, nums2, 0, len / 2) + fix(nums1, 0, nums2, 0, len / 2 + 1)) / 2.0
} else {
fix(nums1, 0, nums2, 0, len / 2 + 1).toDouble()
}
}
fun fix(nums1: IntArray, n: Int, nums2: IntArray, m: Int, k: Int): Int {
if (n >= nums1.size) return nums2[m + k - 1]
if (m >= nums2.size) return nums1[n + k - 1]
if (k == 1) return Math.min(nums1[n], nums2[m])
val i1 = n + k / 2 - 1
val i2 = m + k / 2 - 1
val v1 = if (i1 < nums1.size) nums1[i1] else Int.MAX_VALUE
val v2 = if (i2 < nums2.size) nums2[i2] else Int.MAX_VALUE
return if (v1 < v2) {
fix(nums1, n + k / 2, nums2, m, k - k / 2)
} else {
fix(nums1, n, nums2, m + k / 2, k - k / 2)
}
}
}
fun main(args: Array<String>) {
val solution = Solution()
println(solution.findMedianSortedArrays(intArrayOf(2), intArrayOf(0)))
println(solution.findMedianSortedArrays(intArrayOf(1, 2), intArrayOf(3, 4)))
println(solution.findMedianSortedArrays(intArrayOf(1, 2), intArrayOf(-1, 3)))
} | [
{
"class_path": "RichCodersAndMe__LeetCode-Solution__96119bb/_004/kotlin/Solution.class",
"javap": "Compiled from \"Solution.kt\"\npublic final class _004.kotlin.Solution {\n public _004.kotlin.Solution();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object... |
amazon-ion__ion-schema-kotlin__bbab678/ion-schema/src/main/kotlin/com/amazon/ionschema/model/ContinuousRange.kt | package com.amazon.ionschema.model
import com.amazon.ionschema.model.ContinuousRange.Limit
interface IContinuousRange<T> where T : Comparable<T>, T : Any {
val start: Limit<T>
val end: Limit<T>
operator fun contains(value: T): Boolean
fun intersect(that: ContinuousRange<T>): Pair<Limit<T>, Limit<T>>?
}
/**
* A range over a type that is an uncountably infinite set.
*
* A `ContinuousRange` is a _bounded interval_ when both limits are non-null, and it is a _half-bounded interval_
* when one of the limits is `null`. At least one of [start] and [end] must be non-null.
*
* A `ContinuousRange` can be _open_, _half-open_, or _closed_ depending on [Limit.exclusive] of the limits.
*
* A `ContinuousRange` is allowed to be a _degenerate interval_ (i.e. `start == end` when both limits are closed),
* but it may not be an empty interval (i.e. `start == end` when either limit is open, or `start > end`).
*/
open class ContinuousRange<T : Comparable<T>> internal constructor(final override val start: Limit<T>, final override val end: Limit<T>) : IContinuousRange<T> {
private constructor(value: Limit.Closed<T>) : this(value, value)
internal constructor(value: T) : this(Limit.Closed(value))
sealed class Limit<out T> {
abstract val value: T?
interface Bounded<T> { val value: T }
data class Closed<T : Comparable<T>>(override val value: T) : Limit<T>(), Bounded<T>
data class Open<T : Comparable<T>>(override val value: T) : Limit<T>(), Bounded<T>
object Unbounded : Limit<Nothing>() {
override val value: Nothing? get() = null
override fun equals(other: Any?) = other is Unbounded
override fun hashCode() = 0
}
}
init {
require(start is Limit.Bounded<*> || end is Limit.Bounded<*>) { "range may not be unbounded both above and below" }
require(!isEmpty(start, end)) { "range may not be empty" }
}
/**
* Returns the intersection of `this` `DiscreteRange` with [other].
* If the two ranges do not intersect, returns `null`.
*/
final override fun intersect(that: ContinuousRange<T>): Pair<Limit<T>, Limit<T>>? {
val newStart = when {
this.start is Limit.Unbounded -> that.start
that.start is Limit.Unbounded -> this.start
this.start.value!! > that.start.value!! -> this.start
that.start.value!! > this.start.value!! -> that.start
this.start is Limit.Open -> this.start
that.start is Limit.Open -> that.start
else -> this.start // They are both closed and equal
}
val newEnd = when {
this.end is Limit.Unbounded -> that.end
that.end is Limit.Unbounded -> this.end
this.end.value!! < that.end.value!! -> this.end
that.end.value!! < this.end.value!! -> that.end
this.end is Limit.Open -> this.end
that.end is Limit.Open -> that.end
else -> this.end // They are both closed and equal
}
return if (isEmpty(newStart, newEnd)) null else newStart to newEnd
}
/**
* Checks whether the given value is contained within this range.
*/
final override operator fun contains(value: T): Boolean = start.isBelow(value) && end.isAbove(value)
private fun Limit<T>.isAbove(other: T) = when (this) {
is Limit.Closed -> value >= other
is Limit.Open -> value > other
is Limit.Unbounded -> true
}
private fun Limit<T>.isBelow(other: T) = when (this) {
is Limit.Closed -> value <= other
is Limit.Open -> value < other
is Limit.Unbounded -> true
}
/**
* Checks whether the range is empty. The range is empty if its start value is greater than the end value for
* non-exclusive endpoints, or if the start value equals the end value when either endpoint is exclusive.
*/
private fun isEmpty(start: Limit<T>, end: Limit<T>): Boolean {
if (start is Limit.Unbounded || end is Limit.Unbounded) return false
val exclusive = start is Limit.Open || end is Limit.Open
return if (exclusive) start.value!! >= end.value!! else start.value!! > end.value!!
}
final override fun toString(): String {
val lowerBrace = if (start is Limit.Closed) '[' else '('
val lowerValue = start.value ?: " "
val upperValue = end.value ?: " "
val upperBrace = if (end is Limit.Closed) ']' else ')'
return "$lowerBrace$lowerValue,$upperValue$upperBrace"
}
final override fun equals(other: Any?): Boolean {
return other is ContinuousRange<*> &&
other.start == start &&
other.end == end
}
override fun hashCode(): Int {
var result = start.hashCode()
result = 31 * result + end.hashCode()
return result
}
}
| [
{
"class_path": "amazon-ion__ion-schema-kotlin__bbab678/com/amazon/ionschema/model/ContinuousRange$Limit$Open.class",
"javap": "Compiled from \"ContinuousRange.kt\"\npublic final class com.amazon.ionschema.model.ContinuousRange$Limit$Open<T extends java.lang.Comparable<? super T>> extends com.amazon.ionsche... |
illarionov__strstr__2ead438/code/src/main/kotlin/substring/TwoWay.kt | package substring
import java.lang.Integer.MAX_VALUE
import kotlin.math.abs
private val IntProgression.length get() = when (this.step) {
1, -1 -> if (!this.isEmpty()) abs(this.last - this.first) + 1 else 0
else -> count()
}
class TwoWay {
internal data class Factorization(val pattern: String,
val left: IntRange,
val right: IntRange,
val rightPeriod: Int) {
val criticalPosition get() = left.last
fun leftIsSuffixOfRight(): Boolean {
return left.all { i -> pattern[i] == pattern[right.first + rightPeriod - left.length + i] }
}
init {
check(criticalPosition >= -1)
check(left.last + 1 == right.first)
}
}
fun isSubstring(text: String, pattern: String): Boolean {
when {
text.isEmpty() -> return pattern.isEmpty()
pattern.isEmpty() -> return true
}
return getAllSubstrings(text, pattern, 1).isNotEmpty()
}
internal fun getAllSubstrings(text: String, pattern: String, maxCount: Int = MAX_VALUE): List<Int> {
when {
text.isEmpty() -> return emptyList()
pattern.isEmpty() -> return text.indices.toList()
}
val result: MutableList<Int> = mutableListOf()
val factorization = factorize(pattern)
if (factorization.leftIsSuffixOfRight()) {
// CP1
val (_, left, right, period) = factorization
var pos = 0
var memPrefix = -1
while (pos + pattern.length <= text.length) {
// Сравнение правой части
val i = (maxOf(right.first, memPrefix + 1) .. right.last).find { i -> pattern[i] != text[pos + i] }
if (i != null) {
pos = pos + i - right.first + 1
memPrefix = -1
} else {
// Сравнение левой части
val match = (left.last downTo memPrefix + 1).all { j -> pattern[j] == text[pos + j] }
if (match) {
result.add(pos)
if (result.size >= maxCount) break
}
pos += period
memPrefix = pattern.length - period - 1
}
}
} else {
// CP2
val left = factorization.left.reversed()
val right = factorization.right
val q = maxOf(left.length, right.length) + 1
var pos = 0
while (pos + pattern.length <= text.length) {
// Сравнение правой части
val i = right.find { i -> pattern[i] != text[pos + i] }
if (i != null) {
pos = pos + i - right.first + 1
} else {
// Сравнение левой части
val match = left.all { j -> pattern[j] == text[pos + j] }
if (match) {
result.add(pos)
if (result.size >= maxCount) break
}
pos += q
}
}
}
return result
}
private fun factorize(pattern: String): Factorization {
val naturalOrder = computeMaxSuffixAndPeriod(pattern, naturalOrder())
val reverseOrder = computeMaxSuffixAndPeriod(pattern, reverseOrder())
return if (naturalOrder.right.length <= reverseOrder.right.length)
naturalOrder else reverseOrder
}
internal fun computeMaxSuffixAndPeriod(pattern: String, comparator: Comparator<in Char>): Factorization {
var maxSuffix = -1
var j = 0
var k = 1
var period = 1
while (j + k < pattern.length) {
val a = pattern[j + k]
val b = pattern[maxSuffix + k]
val abOrder = comparator.compare(a, b)
when {
// a < b
abOrder < 0 -> {
j += k
k = 1
period = j - maxSuffix
}
// a == b
abOrder == 0 -> {
if (k != period) {
k += 1
} else {
j += period
k = 1
}
}
// a > b
else -> {
maxSuffix = j
j = maxSuffix + 1
k = 1
period = 1
}
}
}
return Factorization(pattern,
0 .. maxSuffix,
maxSuffix + 1 .. pattern.lastIndex,
period
)
}
}
| [
{
"class_path": "illarionov__strstr__2ead438/substring/TwoWay.class",
"javap": "Compiled from \"TwoWay.kt\"\npublic final class substring.TwoWay {\n public substring.TwoWay();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n 4: ret... |
vaclavbohac__advent-of-code-2023__daa1feb/src/main/kotlin/com/vaclavbohac/advent2023/day3/GearRatios.kt | package com.vaclavbohac.advent2023.day3
class GearRatios(private val lines: List<String>) {
fun getSumOfAllParts(): Int {
val validNumbers = mutableListOf<Int>()
lines.forEachIndexed { i, line ->
var j = 0
var number = StringBuffer()
var indexStart = 0
while (j < line.length) {
if (line[j].isDigit()) {
if (number.isEmpty()) {
indexStart = j
}
number.append(line[j])
}
if (number.isNotEmpty() && (!line[j].isDigit() || j == line.length - 1)) {
if (isValidNumber(indexStart, j - 1, i)) {
validNumbers.add(number.toString().toInt())
}
number = StringBuffer()
}
j += 1
}
}
return validNumbers.sum()
}
fun getSumOfGears(): Int {
val stars: MutableMap<Pair<Int, Int>, MutableList<Int>> = mutableMapOf()
lines.forEachIndexed { i, line ->
var j = 0
var number = StringBuffer()
var indexStart = 0
while (j < line.length) {
if (line[j].isDigit()) {
if (number.isEmpty()) {
indexStart = j
}
number.append(line[j])
}
if (number.isNotEmpty() && (!line[j].isDigit() || j == line.length - 1)) {
val num = number.toString().toInt()
val star = getAdjacentStar(indexStart, j - 1, i)
if (star != null) {
if (stars[star].isNullOrEmpty()) {
stars[star] = mutableListOf(num)
} else {
stars[star]?.add(num)
}
}
number = StringBuffer()
}
j += 1
}
}
return stars
.filter { star -> star.value.size == 2 }
.map { star -> star.value.fold(1) { prod, num -> prod * num } }
.sum()
}
private fun isValidNumber(start: Int, end: Int, line: Int): Boolean {
val columnRange = maxOf(start - 1, 0).rangeTo(minOf(end + 1, lines[0].length))
val rowRange = maxOf(line - 1, 0).rangeTo(minOf(line + 1, lines.size - 1))
for (i in columnRange) {
for (j in rowRange) {
val c = lines[j][i]
if (!c.isDigit() && c != '.') {
return true
}
}
}
return false
}
private fun getAdjacentStar(start: Int, end: Int, line: Int): Pair<Int, Int>? {
val columnRange = maxOf(start - 1, 0).rangeTo(minOf(end + 1, lines[0].length))
val rowRange = maxOf(line - 1, 0).rangeTo(minOf(line + 1, lines.size - 1))
for (i in columnRange) {
for (j in rowRange) {
val c = lines[j][i]
if (c == '*') {
return Pair(j, i)
}
}
}
return null
}
} | [
{
"class_path": "vaclavbohac__advent-of-code-2023__daa1feb/com/vaclavbohac/advent2023/day3/GearRatios.class",
"javap": "Compiled from \"GearRatios.kt\"\npublic final class com.vaclavbohac.advent2023.day3.GearRatios {\n private final java.util.List<java.lang.String> lines;\n\n public com.vaclavbohac.advent... |
vaclavbohac__advent-of-code-2023__daa1feb/src/main/kotlin/com/vaclavbohac/advent2023/day1/Trebuchet.kt | package com.vaclavbohac.advent2023.day1
class Trebuchet(private val lines: List<String>) {
fun sumCalibratedValues(): Int =
lines.fold(0) { sum, line -> sum + (line.getFirstDigit() * 10 + line.reversed().getFirstDigit()) }
fun sumCalibratedValuesAfterInterpolation(): Int =
lines.fold(0) { sum, line -> sum + (line.getFirstInterpolatedNumber(INTERPOLATION_TABLE) * 10 + line.getLastInterpolatedNumber(INTERPOLATION_TABLE)) }
companion object {
val INTERPOLATION_TABLE = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4, "five" to 5, "six" to 6, "seven" to 7, "eight" to 8, "nine" to 9)
}
}
private fun String.getFirstDigit(): Int = this.first { c -> c.isDigit() }.digitToInt()
private fun String.getFirstInterpolatedNumber(numbers: Map<String, Int>): Int {
this.forEachIndexed { i, c ->
if (c.isDigit()) {
return c.digitToInt()
}
for (number in numbers) {
if (this.startsWith(number.key, i)) {
return number.value
}
}
}
return -1
}
private fun String.getLastInterpolatedNumber(numbers: Map<String, Int>): Int =
this.reversed().getFirstInterpolatedNumber(numbers.mapKeys { it.key.reversed() } )
| [
{
"class_path": "vaclavbohac__advent-of-code-2023__daa1feb/com/vaclavbohac/advent2023/day1/TrebuchetKt.class",
"javap": "Compiled from \"Trebuchet.kt\"\npublic final class com.vaclavbohac.advent2023.day1.TrebuchetKt {\n private static final int getFirstDigit(java.lang.String);\n Code:\n 0: aload_0... |
liueq__LeetCodePractice__dda0178/src/main/java/com/liueq/leetcode/easy/NextGreaterElementI.kt | package com.liueq.leetcode.easy
import java.util.*
/**
* 问题描述:给定两个数组 nums1, nums2。其中 1 是 2的子集。求nums1 每一个element 在 nums2 中的位置,往后最大的数字。如果不存在,用 -1 代替。
* 比如: [4, 1, 2]
* [1, 3, 4, 2]
* =
* [-1, 3, -1] 因为 4 在 nums2 中往后只有一个 2,不比4大,所以不存在;1在 nums2 中,往后第一个比 1 大的是3,所以返回3。同理。
*
* 解:先求出 nums2 每一个 element 往后的第一个更大的值,保存在 map 中。遍历 nums1,从 map 取出即可,如果不存在,说明是 -1
*/
class NextGreaterElementI
fun main(args: Array<String>) {
nextGreaterElement(intArrayOf(4, 1, 2), intArrayOf(1, 3, 4, 2)).apply {
for (i in this) {
print("$i,")
}
println()
}
nextGreaterElement(intArrayOf(2, 4), intArrayOf(1, 2, 3, 4)).apply {
for (i in this) {
print("$i,")
}
println()
}
}
fun nextGreaterElement(nums1: IntArray, nums2: IntArray): IntArray {
var map = HashMap<Int, Int>()
for (i in 0.until(nums2.size)) {
var nextGreater = -1
for (j in (i + 1).until(nums2.size)) {
if (nums2[i] < nums2[j]) {
nextGreater = nums2[j]
map[nums2[i]] = nextGreater
break
}
}
}
nums1.mapIndexed { index, value ->
if (map[value] == null)
nums1[index] = -1
else
nums1[index] = map[value]!!
}
return nums1
} | [
{
"class_path": "liueq__LeetCodePractice__dda0178/com/liueq/leetcode/easy/NextGreaterElementI.class",
"javap": "Compiled from \"NextGreaterElementI.kt\"\npublic final class com.liueq.leetcode.easy.NextGreaterElementI {\n public com.liueq.leetcode.easy.NextGreaterElementI();\n Code:\n 0: aload_0\n ... |
liminalitythree__bakadesu__6d5fbcc/src/main/kotlin/lain/Range.kt | package lain
import kotlin.math.abs
data class Range(val min:Int, val max: Int) {
init {
if (min > max) {
throw Exception("Range created with min greater than max, min: $min max: $max")
}
}
companion object {
fun and(a:Range, b:Range):Range {
val min = if (a.min <= b.min) b.min
else a.min
val max = if (a.max >= b.max) b.max
else a.max
return Range(min, max)
}
fun or(a:Range, b:Range):Range {
// lowest min, highest max
val min = if (a.min <= b.min) a.min
else b.min
val max = if (a.max <= b.max) b.max
else a.max
return Range(min, max)
}
// subtract b from a, will return values that are in a but not in b
fun subtract (a: Range, b: Range): List<Range> {
if (!overlaps(a, b)) return listOf(a)
// if b is completely inside a, eg it will split a into two ranges
if (b.min > a.min && b.max < a.max) {
return listOf(
Range(a.min, b.min - 1),
Range(b.max + 1, a.max)
)
}
// if b is overlapping the top of a
if (b.max >= a.max) return listOf(Range(a.min, b.min - 1))
// else, b is overlapping the bottom of a
return listOf(Range(b.max + 1, a.max))
}
// returns true if the two input ranges overlap, false if they don't
fun overlaps(a: Range, b:Range):Boolean {
if (a.min > b.max) return false
if (b.min > a.max) return false
return true
}
}
fun isEmpty():Boolean {
if (this.min >= this.max) return true
return false
}
// returns the difference between min and max
fun width(): Int {
return (abs(this.min - this.max))
}
}
| [
{
"class_path": "liminalitythree__bakadesu__6d5fbcc/lain/Range$Companion.class",
"javap": "Compiled from \"Range.kt\"\npublic final class lain.Range$Companion {\n private lain.Range$Companion();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\"... |
liminalitythree__bakadesu__6d5fbcc/src/main/kotlin/lain/RangeList.kt | package lain
import java.math.BigInteger
data class RangeList(val list: List<Range>) {
companion object {
// creates a rangelist from input range
// merges ranges that overlap
fun from(list: List<Range>):RangeList {
val first = RangeList(listOf(list[0]))
val rest = list.subList(1, list.size)
return rest.fold(first) { a, e -> a.plus(e) }
}
fun from(range: Range):RangeList {
return from(listOf(range))
}
// all values that are a member of a, b, or both
fun union(a: RangeList, b: RangeList): RangeList {
return from(a.list.plus(b.list))
}
// all values that are a member of both a and b
fun intersection(a: RangeList, b: RangeList): RangeList {
val aover = a.list.filter { b.hasOverlap(it) }
val bover = b.list.filter { a.hasOverlap(it) }
val both = aover.plus(bover)
val first = RangeList(listOf(both[0]))
val rest = both.subList(1, both.size)
return rest.fold(first) { q, e -> plusAnd(q, e) }
}
// All values of u that are not values of a
fun setDiff (u: RangeList, a: RangeList): RangeList {
val (match, rest) = u.list.partition { a.hasOverlap(it) }
val amatch = a.list.filter { u.hasOverlap(it) }
// rest are all not values of a
// just need to check match now...
// maybe
val res = match.map {
val muta = mutableListOf<List<Range>>()
for (q in amatch)
if (Range.overlaps(it, q))
muta.add(Range.subtract(it, q))
muta.toList()
}.flatten().flatten()
return RangeList(res.subList(1, res.size).fold(RangeList(listOf(res[0]))) {
q, e -> plusAnd(q, e)
}.list.plus(rest))
}
// Values that are in either a or b, but not both
fun symmetricDiff(a: RangeList, b: RangeList): RangeList {
// union minus intersection
return setDiff(union(a, b), intersection(a, b))
}
// idk how this works but uhh i think it does work...
// maybe
fun plusAnd (a: RangeList, b: Range): RangeList {
val (m, r) = a.list.partition { Range.overlaps(it, b) }
val c:Range = m.fold(b) { q, e -> Range.and(q, e) }
return RangeList(r.plus(c))
}
}
fun union(b: RangeList): RangeList {
return union(this, b)
}
fun intersection(b: RangeList): RangeList {
return intersection(this, b)
}
fun setDiff(b: RangeList): RangeList {
return setDiff(this, b)
}
fun symmetricDiff(b: RangeList): RangeList {
return symmetricDiff(this, b)
}
// returns a rangelist that is this list with range element added
// merges ranges if there is an overlap with range
fun plus(range: Range): RangeList {
// list of elements in the rangelist that overlap with range
val (match, rest) = this.list.partition { Range.overlaps(it, range) }
val c:Range = match.fold(range) { a, e -> Range.or(a, e) }
return RangeList(rest.plus(c))
}
// sorts the rangelist and returns it
fun sort(): RangeList {
return RangeList(this.list.sortedBy { it.min })
}
// returns true if range overlaps with any member of this
fun hasOverlap(range: Range): Boolean {
for (e in this.list)
if (Range.overlaps(e, range)) return true
return false
}
// prints the RangeList by turning the width of each range into a char array
fun print() {
val list = this.sort().list
val arr = list.subList(1, list.size).fold(BigInteger.valueOf(list[0].width().toLong()).toByteArray()) {
a, e -> a.plus(BigInteger.valueOf(e.width().toLong()).toByteArray())
}
for (a in arr) {
print(a.toChar())
}
}
}
| [
{
"class_path": "liminalitythree__bakadesu__6d5fbcc/lain/RangeList.class",
"javap": "Compiled from \"RangeList.kt\"\npublic final class lain.RangeList {\n public static final lain.RangeList$Companion Companion;\n\n private final java.util.List<lain.Range> list;\n\n public lain.RangeList(java.util.List<la... |
ZorteK__Yatzy-Refactoring-Kata__885ee1f/kotlin/src/main/kotlin/com/zortek/kata/yatzy/DiceRoll.kt | package com.zortek.kata.yatzy
import java.util.stream.Stream
class DiceRoll(private val dice: List<Int>) {
fun yatzy(): Boolean {
return groupByValue()
.values
.any { it == 5 }
}
fun isFullHouse(): Boolean {
val hasThreeOfAKind = getDiceWithCountGreaterThan(3) != 0
val hasPair = !findPairs().isEmpty()
val isYatzy = yatzy() //todo :it's debatable
return hasThreeOfAKind && hasPair && !isYatzy
}
fun countDice(dice: Int): Int {
return groupByValue()[dice] ?: 0
}
fun ones(roll: DiceRoll): Int {
return roll.countDice(1)
}
fun twos(roll: DiceRoll): Int {
return roll.countDice(2) * 2
}
fun threes(roll: DiceRoll): Int {
return roll.countDice(3) * 3
}
fun fours(roll: DiceRoll): Int {
return roll.countDice(4) * 4
}
fun fives(roll: DiceRoll): Int {
return roll.countDice(5) * 5
}
fun sixes(roll: DiceRoll): Int {
return roll.countDice(6) * 6
}
fun findPairs(): List<Int> {
return filterNumberOfDiceGreaterThan(2)
.sorted(Comparator.reverseOrder())
.toList()
}
fun getDiceWithCountGreaterThan(n: Int) = filterNumberOfDiceGreaterThan(n)
.findFirst()
.orElse(0)!!
fun sum() = dice.sum()
fun isSmallStraight() = sort() == SMALL_STRAIGHT
fun isLargeStraight() = sort() == LARGE_STRAIGHT
private fun sort() = dice.sorted()
private fun filterNumberOfDiceGreaterThan(n: Int): Stream<Int> {
return groupByValue()
.entries
.stream()
.filter { it.value >= n }
.map { it.key }
}
private fun groupByValue(): Map<Int, Int> {
return dice
.groupingBy { it }
.eachCount()
}
companion object {
private val SMALL_STRAIGHT: List<Int> = listOf(1, 2, 3, 4, 5)
private val LARGE_STRAIGHT: List<Int> = listOf(2, 3, 4, 5, 6)
fun of(d1: Int, d2: Int, d3: Int, d4: Int, d5: Int) = DiceRoll(listOf(d1, d2, d3, d4, d5))
}
} | [
{
"class_path": "ZorteK__Yatzy-Refactoring-Kata__885ee1f/com/zortek/kata/yatzy/DiceRoll$groupByValue$$inlined$groupingBy$1.class",
"javap": "Compiled from \"_Collections.kt\"\npublic final class com.zortek.kata.yatzy.DiceRoll$groupByValue$$inlined$groupingBy$1 implements kotlin.collections.Grouping<java.lan... |
MMauro94__media-merger__40a1d36/src/main/kotlin/com/github/mmauro94/media_merger/util/DurationUtils.kt | package com.github.mmauro94.media_merger.util
import java.math.BigDecimal
import java.time.Duration
import java.util.concurrent.TimeUnit
fun Duration.toTimeString(): String {
val abs = abs()
val firstPart = (if (isNegative) "-" else "") + mutableListOf<String>().apply {
fun add(v: Int) {
add(v.toString().padStart(2, '0'))
}
if (abs.toHoursPart() > 0) {
add(abs.toHoursPart())
}
add(abs.toMinutesPart())
add(abs.toSecondsPart())
}.joinToString(":")
val secondPart = if (abs.nano > 0) {
mutableListOf<String>().apply {
var added = false
fun add(v: Int) {
if (added || v > 0) {
add(v.toString().padStart(3, '0'))
added = true
}
}
add(abs.nano % 1000)
add((abs.nano / 1000) % 1000)
add(abs.toMillisPart())
reverse()
}.joinToString(separator = "", prefix = ".")
} else ""
return firstPart + secondPart
}
fun Duration?.toTimeStringOrUnknown(): String = this?.toTimeString() ?: "Unknown"
fun String.parseTimeStringOrNull(): Duration? {
val regex = "(-?)(?:(?:([0-9]{1,2}):)?([0-9]{1,2}):)?([0-9]{1,2})(?:\\.([0-9]{1,9}))?".toRegex()
val units = listOf(TimeUnit.HOURS, TimeUnit.MINUTES, TimeUnit.SECONDS)
return regex.matchEntire(this)?.let { m ->
val neg = m.groupValues[1] == "-"
val totalNanos =
m.groupValues.drop(2).zip(units).map { (match, unit) ->
unit.toNanos(match.toLongOrNull() ?: 0)
}.sum() + m.groupValues.last().padEnd(9, '0').toLong()
Duration.ofNanos(totalNanos * if (neg) -1 else 1)
}
}
/**
* Converts [this] double as a number of seconds and coverts it to a [Duration]
*/
fun Double.toSecondsDuration(onZero: Duration? = null): Duration? {
check(this >= 0)
return if (this == 0.0) onZero else Duration.ofSeconds(toLong(), ((this % 1) * 1000000000).toLong())!!
}
/**
* Converts [this] BigDecimal as a number of seconds and coverts it to a [Duration]
*/
fun BigDecimal.toSecondsDuration() = Duration.ofNanos(this.setScale(9).unscaledValue().longValueExact())!!
/**
* Converts this duration to a [BigDecimal] in seconds and returns its plain string representation.
*/
fun Duration.toTotalSeconds(): String = BigDecimal.valueOf(toNanos(), 9).toPlainString()
/**
* Sums this iterable of [Duration]s.
*/
fun Iterable<Duration>.sum(): Duration = fold(Duration.ZERO) { acc, it -> acc + it }
| [
{
"class_path": "MMauro94__media-merger__40a1d36/com/github/mmauro94/media_merger/util/DurationUtilsKt.class",
"javap": "Compiled from \"DurationUtils.kt\"\npublic final class com.github.mmauro94.media_merger.util.DurationUtilsKt {\n public static final java.lang.String toTimeString(java.time.Duration);\n ... |
ch8n__Big-Brain-Kotlin__e0619eb/src/main/kotlin/final_450/arrays/exam.kt | package final_450.arrays
fun main() {
val input = "23"
val numbers = arrayOf<String>("123", "234", "567")
val names = arrayOf<String>("chetan", "pokemon", "sokemon")
val result = numbers
.zip(names)
.sortedBy { it.second }
.firstOrNull {
it.first.contains(input)
} ?: "No Contact"
println(result)
val input0 = "00-44 48 5555 8361".apply { println(length % 2 == 0) }
val input2 = "0 - 22 1985--324".trim().apply { println(length) } // even
val result2 = input2.split("")
.filter { it.toIntOrNull() != null }
.chunked(3)
.let {
if (it.last().size == 1) {
val newFormat = it.takeLast(2)
.joinToString("")
.split("")
.filter { it.toIntOrNull() != null }
.chunked(2)
return@let it.dropLast(2) + newFormat
}
it
}
.joinToString(separator = "-") {
it.joinToString(separator = "")
}
//022-198-53-24
println(result2)
val yearOfVacation: Int = 2014
val startMonth: String = "April"
val endMonth: String = "May"
val dayOfWeek: String = "Wednesday"
// answer = 7
val holidays = getDays(startMonth, endMonth, yearOfVacation, dayOfWeek)
println(holidays / 7)
val target = 3
val nodes1 = listOf(1, 3)
val nodes2 = listOf(2, 2)
val links = nodes1.zip(nodes2)
val sorted = links.map {
val (first,second) = it
listOf(first,second).sorted()
}
println(sorted)
}
fun getDays(startMonth: String, endMonth: String, year: Int, startDay: String): Int {
val weekIndex = listOf(
"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"
)
val monthIndex = listOf(
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
)
val dayInMonth = mapOf(
"January" to 31,
"February" to if (isLeapYear(year)) 29 else 28,
"March" to 31,
"April" to 30,
"May" to 31,
"June" to 30,
"July" to 31,
"August" to 31,
"September" to 30,
"October" to 31,
"November" to 30,
"December" to 31,
)
val indexOfStartMonth = monthIndex.indexOf(startMonth)
val indexOfEndMonth = monthIndex.indexOf(endMonth)
val result = (indexOfStartMonth..indexOfEndMonth).map {
val month = monthIndex.get(it)
dayInMonth.get(month) ?: 0
}.sum()
val startedOn = weekIndex.indexOf(startDay)
return result - startedOn
}
fun isLeapYear(year: Int): Boolean {
return when {
year % 4 != 0 -> false
year % 400 == 0 -> true
else -> year % 100 != 0
}
} | [
{
"class_path": "ch8n__Big-Brain-Kotlin__e0619eb/final_450/arrays/ExamKt$main$$inlined$sortedBy$1.class",
"javap": "Compiled from \"Comparisons.kt\"\npublic final class final_450.arrays.ExamKt$main$$inlined$sortedBy$1<T> implements java.util.Comparator {\n public final_450.arrays.ExamKt$main$$inlined$sorte... |
ch8n__Big-Brain-Kotlin__e0619eb/src/main/kotlin/final_450/arrays/kthSmallOrLargeElement.kt | package final_450.arrays
fun main() {
// Given an array arr[] and a number K where K is smaller
// than size of array, the task is to find the Kth smallest
// element in the given array.
// It is given that all array elements are distinct.
/**
* * N = 6 arr[] = 7 10 4 3 20 15 K = 3 Output : 7 Explanation : 3rd smallest element in the
* given array is 7.
*/
val k = 3
val input = arrayOf(7, 10, 4, 3, 20, 15)
val kSmallest = input.sorted().get(k - 1)
println(kSmallest)
mergesort(input.toList(), mutableListOf())
}
// 7,10,4,3,20,15
// 7 10 4 | 3 20 15
fun mergesort(list: List<Int>, acc: MutableList<List<Int>>) {
sliceOrAdd(list, acc)
println(acc)
}
fun sliceOrAdd(list: List<Int>, acc: MutableList<List<Int>>) {
val (first, last) = list.equalSplit()
val isFirstHavingOneItem = first.size == 1
val isLastHavingOneItem = last.size == 1
if (!isFirstHavingOneItem) {
sliceOrAdd(first, acc)
} else {
val index = acc.indexOfFirst { it[0] < first[0] }
acc.add(index, first)
}
if (!isLastHavingOneItem) {
sliceOrAdd(last, acc)
} else {
val index = acc.indexOfFirst { it[0] < last[0] }
acc.add(index, last)
}
}
fun merge() {
val input = listOf(0, 0, 0, 1, 2, 2, 2, 1, 0, 1).toMutableList()
var pointer0 = 0
var pointer1 = pointer0
var pointer2 = input.lastIndex
while (pointer0 <= pointer2) {
val value = input[pointer0]
when (value) {
0 -> {
val first = input[pointer0]
val mid = input[pointer1]
input.set(pointer0, mid)
input.set(pointer1, first)
++pointer0
++pointer1
}
1 -> {
++pointer1
}
2 -> {
val last = input[pointer2]
val mid = input[pointer1]
input.set(pointer2, mid)
input.set(pointer1, last)
--pointer2
}
}
}
}
fun List<Int>.equalSplit(): Pair<List<Int>, List<Int>> {
val length = size
return take(length / 2) to drop(length / 2)
}
| [
{
"class_path": "ch8n__Big-Brain-Kotlin__e0619eb/final_450/arrays/KthSmallOrLargeElementKt.class",
"javap": "Compiled from \"kthSmallOrLargeElement.kt\"\npublic final class final_450.arrays.KthSmallOrLargeElementKt {\n public static final void main();\n Code:\n 0: iconst_3\n 1: istore_0\n ... |
marc-bouvier-katas__aoc-02__2198922/kotlin/src/elves/day03/RuckSack.kt | package elves.day03
class RuckSack(private val elveEncodedContent: String) {
val priorityOfSharedCategory: Int?
init {
val firstCompartment = Compartment(elveEncodedContent.take(elveEncodedContent.length / 2))
val secondCompartment = Compartment(elveEncodedContent.takeLast(elveEncodedContent.length / 2))
priorityOfSharedCategory =
firstCompartment.intersectionWith(secondCompartment).categoryInBothCompartments?.priority
}
fun badge(vararg rucksacksOfTheSameGroup: RuckSack): ItemCategory? {
return rucksacksOfTheSameGroup
.map { it.elveEncodedContent }
.map { it.asIterable() }
.fold(elveEncodedContent.asIterable()) { acc, cur -> acc.intersect(cur) }
.map { ItemCategory(it) }
.firstOrNull()
}
}
private class Compartment(s: String) {
fun intersectionWith(secondCompartment: Compartment): PackingReport {
val other: CharArray = secondCompartment.content.toCharArray()
val intersect: Set<Char> = content.toCharArray().intersect(other.asIterable().toSet())
return PackingReport(intersect.firstOrNull())
}
private var content: String
init {
content = s
}
}
const val ASCIICODE_FOR_A_LOWERCASE = 97
const val ASCIICODE_FOR_A_UPPERCASE = 65
class ItemCategory(categoryCode: Char) {
val priority: Int
init {
priority = priorityOf(categoryCode)
}
private fun priorityOf(typeObjet: Char): Int {
val asciiCode = typeObjet.code
return if (asciiCode in (97..122))
asciiCode - ASCIICODE_FOR_A_LOWERCASE + 1 // ici le 1 c'est la priorité de départ depuis "a"
else {
asciiCode - ASCIICODE_FOR_A_UPPERCASE + 27 // 27 c'est la priorité de départ depuis "A"
}
// c'est bien ici, on peut s'errêter là.
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as ItemCategory
if (priority != other.priority) return false
return true
}
override fun hashCode(): Int {
return priority
}
override fun toString(): String {
return "ItemCategory(priority=$priority)"
}
}
private class PackingReport(s: Char?) {
val categoryInBothCompartments: ItemCategory?
init {
if (s != null) {
categoryInBothCompartments = ItemCategory(s)
} else {
categoryInBothCompartments = null
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as PackingReport
if (categoryInBothCompartments != other.categoryInBothCompartments) return false
return true
}
override fun hashCode(): Int {
return categoryInBothCompartments?.hashCode() ?: 0
}
override fun toString(): String {
return "PackingReport(categoryInBothCompartments=$categoryInBothCompartments)"
}
}
| [
{
"class_path": "marc-bouvier-katas__aoc-02__2198922/elves/day03/RuckSackKt.class",
"javap": "Compiled from \"RuckSack.kt\"\npublic final class elves.day03.RuckSackKt {\n public static final int ASCIICODE_FOR_A_LOWERCASE;\n\n public static final int ASCIICODE_FOR_A_UPPERCASE;\n\n}\n",
"javap_err": ""
... |
OpenSrcerer__aoc-2022__84b9b62/AoC2022/src/main/kotlin/xyz/danielstefani/Day8.kt | package xyz.danielstefani
import java.util.function.Function
lateinit var trees: List<List<Int>>
const val GRID_SIZE = 4
fun main() {
trees = object {}.javaClass
.classLoader
.getResource("Day8Input.in")!!
.readText()
.split("\n")
.map { it.map { it.digitToInt() }.toList() }
// Part 1
var visible = 0
for (row in trees.indices) {
for (column in trees.indices) {
val top = isVisible(trees[row][column], row - 1, column, rowFunction = { r -> r - 1 })
val bottom = isVisible(trees[row][column], row + 1, column, rowFunction = { r -> r + 1 })
val left = isVisible(trees[row][column], row, column - 1, columnFunction = { c -> c - 1 })
val right = isVisible(trees[row][column], row, column + 1, columnFunction = { c -> c + 1 })
if (top || bottom || left || right) visible++
}
}
println(visible)
// Part 2
var maxScenicScore = 0
for (row in trees.indices) {
for (column in trees.indices) {
val top = getScenicScore(row - 1, column, rowFunction = { r -> r - 1 })
val bottom = getScenicScore(row + 1, column, rowFunction = { r -> r + 1 })
val left = getScenicScore(row, column - 1, columnFunction = { c -> c - 1 })
val right = getScenicScore(row, column + 1, columnFunction = { c -> c + 1 })
val score = top * bottom * left * right
if (score > maxScenicScore) maxScenicScore = score
}
}
println(maxScenicScore)
}
fun isVisible(treeHeight: Int, row: Int, column: Int,
rowFunction: Function<Int, Int> = Function { r -> r },
columnFunction: Function<Int, Int> = Function { c -> c }
): Boolean {
if (column < 0 || column > GRID_SIZE || row < 0 || row > GRID_SIZE) return true
if (treeHeight <= trees[row][column]) return false
if (column == 0 || column == GRID_SIZE || row == 0 || row == GRID_SIZE) return true
return isVisible(treeHeight, rowFunction.apply(row), columnFunction.apply(column), rowFunction, columnFunction)
}
fun getScenicScore(row: Int, column: Int,
rowFunction: Function<Int, Int> = Function { r -> r },
columnFunction: Function<Int, Int> = Function { c -> c }
): Int {
if (column <= 0 || column >= GRID_SIZE || row <= 0 || row >= GRID_SIZE) return 0
return 1 + getScenicScore(rowFunction.apply(row), columnFunction.apply(column), rowFunction, columnFunction)
} | [
{
"class_path": "OpenSrcerer__aoc-2022__84b9b62/xyz/danielstefani/Day8Kt$main$1.class",
"javap": "Compiled from \"Day8.kt\"\npublic final class xyz.danielstefani.Day8Kt$main$1 {\n xyz.danielstefani.Day8Kt$main$1();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/la... |
OpenSrcerer__aoc-2022__84b9b62/AoC2022/src/main/kotlin/xyz/danielstefani/Day3.kt | package xyz.danielstefani
import java.util.stream.IntStream
import kotlin.streams.asSequence
val priorityMap = mutableMapOf<Int, Int>()
fun main() {
// Prep
fillMapWithPriorities(97, 122, 1)
fillMapWithPriorities(65, 90, 27)
val splitRucksacks = object {}.javaClass
.classLoader
.getResource("Day3Input.in")
?.readText()
?.split("\n")
?.map { twoRucksacks ->
listOf(twoRucksacks.substring(0, twoRucksacks.length / 2).toCharSet(),
twoRucksacks.substring(twoRucksacks.length / 2).toCharSet())
}
// Part 1
val splitRucksacksCommonItemsSum = splitRucksacks?.sumOf {
priorityMap[it[0].intersect(it[1]).elementAt(0)]!!
}
// Part 2
val groupedBy3CommonItemsSum = splitRucksacks
?.map { twoRuckSacks -> twoRuckSacks[0].union(twoRuckSacks[1]) }
?.chunked(3)
?.sumOf { groupOfThree ->
priorityMap[groupOfThree.reduce { acc, set -> acc.intersect(set) }.elementAt(0)]!! as Int
}
println(splitRucksacksCommonItemsSum)
println(groupedBy3CommonItemsSum)
}
fun fillMapWithPriorities(lowerInclusive: Int, upperInclusive: Int, foldInit: Int) {
IntStream.range(lowerInclusive, upperInclusive + 1)
.asSequence()
.fold(foldInit) { acc, code ->
priorityMap[code] = acc
acc + 1
}
}
fun String.toCharSet(): Set<Int> {
return this.chars().collect({ mutableSetOf() }, { s, c -> s.add(c) }, { s1, s2 -> s1.addAll(s2) })
} | [
{
"class_path": "OpenSrcerer__aoc-2022__84b9b62/xyz/danielstefani/Day3Kt.class",
"javap": "Compiled from \"Day3.kt\"\npublic final class xyz.danielstefani.Day3Kt {\n private static final java.util.Map<java.lang.Integer, java.lang.Integer> priorityMap;\n\n public static final java.util.Map<java.lang.Intege... |
OpenSrcerer__aoc-2022__84b9b62/AoC2022/src/main/kotlin/xyz/danielstefani/Day2.kt | package xyz.danielstefani
import kotlin.math.abs
val shapeToScore = mapOf(
Pair("A", 1), // Rock
Pair("B", 2), // Paper
Pair("C", 3), // Scissors
Pair("X", 1), // Rock
Pair("Y", 2), // Paper
Pair("Z", 3) // Scissors
)
fun main(args: Array<String>) {
// Prep
val rounds = object {}.javaClass
.classLoader
.getResource("Day2Input.in")
?.readText()
?.split("\n")
?.map {
it.split(", ")[0].split(" ")
.map { letter -> shapeToScore[letter]!! }
}
// Part 1
val scoreFirstAssumption = rounds?.sumOf { extractScoreFromRound(it) }
// Part 2
val scoreSecondAssumption = rounds?.map { convertToShapeToPlay(it) }
?.sumOf { extractScoreFromRound(it) }
println(scoreFirstAssumption)
println(scoreSecondAssumption)
}
fun extractScoreFromRound(elfMyChoices: List<Int>): Int {
val minChoiceDelta = abs(elfMyChoices[0] - elfMyChoices[1]) <= 1
val roundOutcome =
if (elfMyChoices[0] > elfMyChoices[1] && minChoiceDelta) 0
else if (elfMyChoices[0] < elfMyChoices[1] && !minChoiceDelta) 0
else if (elfMyChoices[0] == elfMyChoices[1]) 3
else 6
return elfMyChoices[1] + roundOutcome
}
fun convertToShapeToPlay(elfEndChoices: List<Int>): List<Int> {
return when (elfEndChoices[1]) {
1 -> listOf(
elfEndChoices[0],
if (elfEndChoices[0] == 1) 3 else elfEndChoices[0] - 1
)
2 -> listOf(elfEndChoices[0], elfEndChoices[0])
3 -> listOf(
elfEndChoices[0],
if (elfEndChoices[0] == 3) 1 else elfEndChoices[0] + 1
)
else -> emptyList() // won't happen
}
} | [
{
"class_path": "OpenSrcerer__aoc-2022__84b9b62/xyz/danielstefani/Day2Kt.class",
"javap": "Compiled from \"Day2.kt\"\npublic final class xyz.danielstefani.Day2Kt {\n private static final java.util.Map<java.lang.String, java.lang.Integer> shapeToScore;\n\n public static final java.util.Map<java.lang.String... |
gualtierotesta__PlayWithKotlin__8366bb3/kata/src/main/kotlin/kata/ColorChoice.kt | package kata
import java.math.BigInteger
/*
You know combinations: for example, if you take 5 cards from a 52 cards deck you have 2,598,960
different combinations.
In mathematics the number of x combinations you can take from a set of n elements is called the
binomial coefficient of n and x, or more often n choose x.
The formula to compute m = n choose x is: m = n! / (x! * (n - x)!) where ! is the factorial operator.
You are a renowned poster designer and painter.
You are asked to provide 6 posters all having the same design each in 2 colors.
Posters must all have a different color combination and you have the choice of 4 colors:
red, blue, yellow, green.
How many colors can you choose for each poster?
The answer is two since 4 choose 2 = 6.
The combinations will be: {red, blue}, {red, yellow}, {red, green}, {blue, yellow}, {blue, green}, {yellow, green}.
Now same question but you have 35 posters to provide and 7 colors available.
How many colors for each poster?
If you take combinations 7 choose 2 you will get 21 with the above formula.
But 21 schemes aren't enough for 35 posters.
If you take 7 choose 5 combinations you will get 21 too.
Fortunately if you take 7 choose 3 or 7 choose 4 combinations you get 35 and so each poster
will have a different combination of 3 colors or 5 colors.
You will take 3 colors because it's less expensive.
Hence the problem is:
knowing m (number of posters to design),
knowing n (total number of available colors),
let us search x (number of colors for each poster so that each poster has a unique combination of
colors and the number of combinations is exactly the same as the number of posters).
In other words we must find x such as n choose x = m (1) for a given m and a given n; m >= 0 and n > 0.
If many x are solutions give as result the smallest x.
It can happen that when m is given at random there are no x satisfying equation (1) then return -1.
Examples:
checkchoose(6, 4) --> 2
checkchoose(4, 4) --> 1
checkchoose(4, 2) --> -1
checkchoose(35, 7) --> 3
checkchoose(36, 7) --> -1
a = 47129212243960
checkchoose(a, 50) --> 20
checkchoose(a + 1, 50) --> -1
clojure: Use big integers in the calculation of n choose k!
*/
fun fact(num: Int): BigInteger {
var factorial: BigInteger = BigInteger.ONE
for (i in 1..num) {
factorial = factorial.multiply(BigInteger.valueOf(i.toLong()))
}
return factorial
}
fun nChooseX(n: Int, x: Int): BigInteger {
// m = n! / (x! * (n - x)!)
return fact(n).div(fact(x).multiply(fact(n - x)))
}
fun checkchoose(m: Long, n: Int): Long {
for (x in 1..n) {
val mCurrent = nChooseX(n, x)
if (mCurrent.longValueExact() == m) {
return x.toLong()
}
}
return -1
} | [
{
"class_path": "gualtierotesta__PlayWithKotlin__8366bb3/kata/ColorChoiceKt.class",
"javap": "Compiled from \"ColorChoice.kt\"\npublic final class kata.ColorChoiceKt {\n public static final java.math.BigInteger fact(int);\n Code:\n 0: getstatic #13 // Field java/math/BigInteger... |
gualtierotesta__PlayWithKotlin__8366bb3/kata/src/main/kotlin/kata/HowGreenIsMyValley.kt | package kata
import java.util.*
import java.util.stream.Collectors.toList
/*
Input : an array of integers.
Output : this array, but sorted in such a way that there are two wings:
the left wing with numbers decreasing,
the right wing with numbers increasing.
the two wings have the same length. If the length of the array is odd the wings are around the bottom, if the length is even the bottom is considered to be part of the right wing.
each integer l of the left wing must be greater or equal to its counterpart r in the right wing, the difference l - r being as small as possible. In other words the right wing must be nearly as steeply as the left wing.
The function is make_valley or makeValley or make-valley.
*/
fun makeValley(arr: IntArray): IntArray {
val sarr = arr.sortedArrayDescending()
val n = sarr.size
val half = n / 2 + (n % 2)
val last = n - if (n % 2 == 0) 1 else 0
return (0 until n)
.map { i -> if (i < half) sarr[i * 2] else sarr[last - ((i - n / 2) * 2)] }
.toList().toIntArray()
}
fun makeValley2(arr:IntArray) = when (arr.size) {
1 -> arr
else -> arr.sortedArrayDescending().withIndex().groupBy { it.index % 2 }.map { it.value.map { it.value } }.windowed(2) { it[0] + it[1].sorted() }.flatten().toIntArray()
}
fun makeValley3(arr:IntArray):IntArray {
val answer = IntArray(arr.size)
arr.sort()
for (i in 0 until arr.size) {
if (i % 2 == 0) {
answer[i / 2] = arr[arr.size - 1 - i]
} else {
answer[arr.size - 1 - i / 2] = arr[arr.size - 1 - i]
}
}
return answer
}
fun main(args: Array<String>) {
val arr = arrayOf(79, 35, 54, 19, 35, 25)
//val arr = arrayOf(67, 93, 100, -16, 65, 97, 92)
val x =
arr
.sortedArrayDescending()
.withIndex()
.groupBy { it.index % 2 }
//.map { it.value }
//.map { it.value.map { it.value } }
//.windowed(2) { it[0] + it[1].sorted() }
//.flatten()
//.forEach { println(it) }
//.forEach { t, u -> println("t=$t u=$u") }
//.forEach { i -> System.out.println("index=${i.index} value=${i.value}")}
// else -> arr.sortedArrayDescending().withIndex().groupBy { it.index % 2 }
// .map { it.value.map { it.value } }.windowed(2) { it[0] + it[1].sorted() }.flatten().toIntArray()
} | [
{
"class_path": "gualtierotesta__PlayWithKotlin__8366bb3/kata/HowGreenIsMyValleyKt.class",
"javap": "Compiled from \"HowGreenIsMyValley.kt\"\npublic final class kata.HowGreenIsMyValleyKt {\n public static final int[] makeValley(int[]);\n Code:\n 0: aload_0\n 1: ldc #9 ... |
CristianoVecchi__MikroKanon__291915e/app/src/main/java/com/cristianovecchi/mikrokanon/dataAnalysis/Kmeans.kt | package com.cristianovecchi.mikrokanon.dataAnalysis
// version 1.2.21
import java.util.Random
import kotlin.math.*
data class Point(var x: Double, var y: Double, var group: Int, val partIndex: Int, val noteIndex: Int)
typealias LPoint = List<Point>
typealias MLPoint = MutableList<Point>
val origin get() = Point(0.0, 0.0, 0, 0, 0)
val r = Random()
val hugeVal = Double.POSITIVE_INFINITY
const val RAND_MAX = Int.MAX_VALUE
const val PTS = 40
const val K = 10 // number of groups
const val W = 400
const val H = 400
fun main() {
val points = genXY(PTS, 10.0)
val centroids = lloyd(points, PTS, K)
// println("POINTS(${points.size}): $points")
// println("CENTROIDS(${centroids.size}): $centroids")
points.forEach{
println("$it -> ${centroids[it.group]}")
}
val sums = points.groupingBy { it.group }.eachCount().toSortedMap()
println(sums)
//printEps(points, PTS, centroids, K)
}
fun rand() = r.nextInt(RAND_MAX)
fun randf(m: Double) = m * rand() / (RAND_MAX - 1)
fun genXY(count: Int, radius: Double): LPoint {
val pts = List(count) { origin }
/* note: this is not a uniform 2-d distribution */
for (i in 0 until count) {
val ang = randf(2.0 * PI)
val r = randf(radius)
pts[i].x = r * cos(ang)
pts[i].y = r * sin(ang)
}
return pts
}
fun dist2(a: Point, b: Point): Double {
val x = a.x - b.x
val y = a.y - b.y
return x * x + y * y
}
fun nearest(pt: Point, cent: LPoint, nCluster: Int): Pair<Int, Double> {
var minD = hugeVal
var minI = pt.group
for (i in 0 until nCluster) {
val d = dist2(cent[i], pt)
if (minD > d) {
minD = d
minI = i
}
}
return minI to minD
}
fun kpp(pts: LPoint, len: Int, cent: MLPoint) {
if (pts.isEmpty() || len == 0) return
val nCent = cent.size
val d = DoubleArray(len)
//println("points size:${pts.size} length:$len")
cent[0] = pts[rand() % len].copy()
for (nCluster in 1 until nCent) {
var sum = 0.0
for (j in 0 until len) {
d[j] = nearest(pts[j], cent, nCluster).second
sum += d[j]
}
sum = randf(sum)
for (j in 0 until len) {
sum -= d[j]
if (sum > 0.0) continue
cent[nCluster] = pts[j].copy()
break
}
}
for (j in 0 until len) pts[j].group = nearest(pts[j], cent, nCent).first
}
fun lloyd(pts: LPoint, len: Int, nCluster: Int): LPoint {
val cent = MutableList(nCluster) { origin }
kpp(pts, len, cent)
do {
/* group element for centroids are used as counters */
for (i in 0 until nCluster) {
with (cent[i]) { x = 0.0; y = 0.0; group = 0 }
}
for (j in 0 until len) {
val p = pts[j]
val c = cent[p.group]
with (c) { group++; x += p.x; y += p.y }
}
for (i in 0 until nCluster) {
val c = cent[i]
c.x /= c.group
c.y /= c.group
}
var changed = 0
/* find closest centroid of each point */
for (j in 0 until len) {
val p = pts[j]
val minI = nearest(p, cent, nCluster).first
if (minI != p.group) {
changed++
p.group = minI
}
}
}
while (changed > (len shr 10)) /* stop when 99.9% of points are good */
for (i in 0 until nCluster) cent[i].group = i
return cent
}
fun printEps(pts: LPoint, len: Int, cent: LPoint, nCluster: Int) {
val colors = DoubleArray(nCluster * 3)
for (i in 0 until nCluster) {
colors[3 * i + 0] = (3 * (i + 1) % 11) / 11.0
colors[3 * i + 1] = (7 * i % 11) / 11.0
colors[3 * i + 2] = (9 * i % 11) / 11.0
}
var minX = hugeVal
var minY = hugeVal
var maxX = -hugeVal
var maxY = -hugeVal
for (j in 0 until len) {
val p = pts[j]
if (maxX < p.x) maxX = p.x
if (minX > p.x) minX = p.x
if (maxY < p.y) maxY = p.y
if (minY > p.y) minY = p.y
}
val scale = minOf(W / (maxX - minX), H / (maxY - minY))
val cx = (maxX + minX) / 2.0
val cy = (maxY + minY) / 2.0
print("%%!PS-Adobe-3.0\n%%%%BoundingBox: -5 -5 %${W + 10} ${H + 10}\n")
print("/l {rlineto} def /m {rmoveto} def\n")
print("/c { .25 sub exch .25 sub exch .5 0 360 arc fill } def\n")
print("/s { moveto -2 0 m 2 2 l 2 -2 l -2 -2 l closepath ")
print(" gsave 1 setgray fill grestore gsave 3 setlinewidth")
print(" 1 setgray stroke grestore 0 setgray stroke }def\n")
val f1 = "%g %g %g setrgbcolor"
val f2 = "%.3f %.3f c"
val f3 = "\n0 setgray %g %g s"
for (i in 0 until nCluster) {
val c = cent[i]
println(f1.format(colors[3 * i], colors[3 * i + 1], colors[3 * i + 2]))
for (j in 0 until len) {
val p = pts[j]
if (p.group != i) continue
println(f2.format((p.x - cx) * scale + W / 2, (p.y - cy) * scale + H / 2))
}
println(f3.format((c.x - cx) * scale + W / 2, (c.y - cy) * scale + H / 2))
}
print("\n%%%%EOF")
}
| [
{
"class_path": "CristianoVecchi__MikroKanon__291915e/com/cristianovecchi/mikrokanon/dataAnalysis/KmeansKt$main$$inlined$groupingBy$1.class",
"javap": "Compiled from \"_Collections.kt\"\npublic final class com.cristianovecchi.mikrokanon.dataAnalysis.KmeansKt$main$$inlined$groupingBy$1 implements kotlin.coll... |
umrhiumrhi__skt-summer-internship-2022__6c4bc15/app/src/main/java/com/skt/nugu/sampleapp/utils/SimilarityChecker.kt | package com.skt.nugu.sampleapp.utils
import java.lang.Integer.max
import java.lang.Math.min
class SimilarityChecker {
companion object {
private const val korBegin = 44032
private const val korEnd = 55203
private const val chosungBase = 588
private const val jungsungBase = 28
private const val jaumBegin = 12593
private const val jaumEnd = 12622
private const val moumBegin = 12623
private const val moumEnd = 12643
private val chosungList = listOf('ㄱ', 'ㄲ', 'ㄴ', 'ㄷ', 'ㄸ', 'ㄹ', 'ㅁ', 'ㅂ', 'ㅃ',
'ㅅ', 'ㅆ', 'ㅇ' , 'ㅈ', 'ㅉ', 'ㅊ', 'ㅋ', 'ㅌ', 'ㅍ', 'ㅎ')
private val jungsungList = listOf('ㅏ', 'ㅐ', 'ㅑ', 'ㅒ', 'ㅓ', 'ㅔ', 'ㅕ', 'ㅖ', 'ㅗ', 'ㅘ', 'ㅙ', 'ㅚ',
'ㅛ', 'ㅜ', 'ㅝ', 'ㅞ', 'ㅟ', 'ㅠ', 'ㅡ', 'ㅢ', 'ㅣ')
private val jongsungList = listOf(' ', 'ㄱ', 'ㄲ', 'ㄳ', 'ㄴ', 'ㄵ', 'ㄶ', 'ㄷ', 'ㄹ', 'ㄺ', 'ㄻ', 'ㄼ', 'ㄽ', 'ㄾ', 'ㄿ', 'ㅀ',
'ㅁ', 'ㅂ', 'ㅄ', 'ㅅ', 'ㅆ', 'ㅇ', 'ㅈ', 'ㅊ', 'ㅋ', 'ㅌ', 'ㅍ', 'ㅎ')
}
private fun getLevenshteinDistance(s1 : List<Char>, s2 : List<Char>): Int {
val m = s1.size
val n = s2.size
val dp = Array(m + 1) { IntArray(n + 1) }
for (i in 1..m) {
dp[i][0] = i
}
for (j in 1..n) {
dp[0][j] = j
}
var cost : Int
for (i in 1..m) {
for (j in 1..n) {
cost = if (s1[i - 1] == s2[j - 1]) 0 else 1
dp[i][j] = min(min(dp[i - 1][j] + 1, dp[i][j - 1] + 1), dp[i - 1][j - 1] + cost)
}
}
return dp[m][n]
}
private fun getJamoLevenshteinDistance(s1 : String, s2 : String): Double {
val m = s1.length
val n = s2.length
val dp = Array(m + 1) { DoubleArray(n + 1) }
for (i in 1..m) {
dp[i][0] = i.toDouble()
}
for (j in 1..n) {
dp[0][j] = j.toDouble()
}
var cost : Double
for (i in 1..m) {
for (j in 1..n) {
cost = subCost(s1[i-1], s2[j-1])
dp[i][j] = min(min(dp[i - 1][j] + 1, dp[i][j - 1] + 1), dp[i - 1][j - 1] + cost)
}
}
return dp[m][n]
}
private fun subCost(c1 : Char, c2 : Char) : Double {
if (c1 == c2) {
return 0.0
}
return getLevenshteinDistance(decompose(c1), decompose(c2)) / 3.0
}
fun findSimilarity(s1: String?, s2: String?): Double {
if (s1.isNullOrEmpty() or s2.isNullOrEmpty()) return -1.0
var result = -1.0
val maxLength = max(s1!!.length, s2!!.length)
if (maxLength > 0) {
result = (maxLength * 1.0 - getJamoLevenshteinDistance(s1, s2)) / maxLength * 1.0
} else {
result = 1.0
}
return result
}
fun decompose(c : Char) : List<Char> {
if (!checkKorean(c)) {
return emptyList()
}
var i = c.code
if (i in jaumBegin..jaumEnd) {
return listOf(c, ' ', ' ')
}
if (i in moumBegin..moumEnd) {
return listOf(' ', c, ' ')
}
i -= korBegin
val cho : Int = i / chosungBase
val jung : Int = ( i - cho * chosungBase ) / jungsungBase
val jong : Int = ( i - cho * chosungBase - jung * jungsungBase)
return listOf(chosungList[cho], jungsungList[jung], jongsungList[jong])
}
fun compose(chosung : Char, jungsung : Char, jongsung : Char) : Char {
val tmp = korBegin + chosungBase * chosungList.indexOf(chosung) + jungsungBase * jungsungList.indexOf(jungsung) +
jongsungList.indexOf(jongsung)
return tmp.toChar()
}
fun checkKorean(c : Char) : Boolean {
val i = c.code
return (i in korBegin..korEnd) or (i in jaumBegin..jaumEnd) or (i in moumBegin..moumEnd)
}
} | [
{
"class_path": "umrhiumrhi__skt-summer-internship-2022__6c4bc15/com/skt/nugu/sampleapp/utils/SimilarityChecker.class",
"javap": "Compiled from \"SimilarityChecker.kt\"\npublic final class com.skt.nugu.sampleapp.utils.SimilarityChecker {\n public static final com.skt.nugu.sampleapp.utils.SimilarityChecker$... |
stellake__git-training__d4b42d8/src/main/kotlin/com/gitTraining/Fibbonaci.kt | package com.gitTraining
fun computeFibbonaciNumber(position: Int?, recursion: Boolean = false): Int {
var notNullPosition = position
if (notNullPosition == null) {
notNullPosition = 1
}
if (recursion) return recursiveFibbonachi(1, 1, notNullPosition - 2)
if (notNullPosition == 0) return 0
if (notNullPosition < 0) {
return computeNegativeFibbonachi(notNullPosition)
}
if (notNullPosition == 1 || notNullPosition == 2) return 1
var smallFibbonachiNumber = 1
var largeFibbonachiNumber = 1
var currentPosition = 2
while (currentPosition < notNullPosition) {
val nextFibbonachiNumber = smallFibbonachiNumber + largeFibbonachiNumber
smallFibbonachiNumber = largeFibbonachiNumber
largeFibbonachiNumber = nextFibbonachiNumber
currentPosition ++
}
return largeFibbonachiNumber
}
fun computeFibbonachiArray(start: Int, end: Int, efficient: Boolean = false): List<Int> {
if (!efficient) return (start..end).map { computeFibbonaciNumber(it) }
if (start > end) return listOf()
if (start == end) return listOf(computeFibbonaciNumber(start))
val output = mutableListOf(computeFibbonaciNumber(start), computeFibbonaciNumber(start + 1))
(2..(end-start)).forEach { output.add(output[it-2] + output[it-1]) }
return output
}
fun recursiveFibbonachi(previous: Int, current: Int, stepsLeft: Int): Int {
if (stepsLeft < 0) return 1
return when (stepsLeft) {
0 -> current
else -> recursiveFibbonachi(current, previous + current, stepsLeft - 1)
}
}
fun computeNegativeFibbonachi(position:Int): Int {
if (position >= 0) throw Exception("potition must be smaller than zero!")
val resultIsNegative = position % 2 == 0
val absoluteResult = computeFibbonaciNumber(-position)
return if (resultIsNegative) (absoluteResult * -1) else absoluteResult
}
| [
{
"class_path": "stellake__git-training__d4b42d8/com/gitTraining/FibbonaciKt.class",
"javap": "Compiled from \"Fibbonaci.kt\"\npublic final class com.gitTraining.FibbonaciKt {\n public static final int computeFibbonaciNumber(java.lang.Integer, boolean);\n Code:\n 0: aload_0\n 1: astore_2\n ... |
justnero__university__14f58f1/semestr.06/ТРСиПВ/bellman/src/main/kotlin/bellman/graph/util.kt | package bellman.graph
val INFINITE = Int.MAX_VALUE
val NO_EDGE = INFINITE
typealias AdjacencyMatrix = Array<IntArray>
typealias AdjacencyMatrix1D = IntArray
typealias AdjacencyList = Array<Adjacency>
typealias PlainAdjacencyList = IntArray
typealias Adjacency = Triple<Int, Int, Int>
data class InputGraph(val adjacencyMatrix: AdjacencyMatrix,
val sourceVertex: Int,
val vertexNumber: Int = adjacencyMatrix.size)
enum class PlainAdjacency(val number: Int) {
SOURCE(0), DESTINATION(1), WEIGHT(2)
}
object Util {
object AdjacencyUtil {
val Adjacency.source: Int
get() = this.first
val Adjacency.destination: Int
get() = this.second
val Adjacency.weight: Int
get() = this.third
}
object AdjacencyMatrixUtil {
inline fun AdjacencyMatrix.vertexNumber() = this.size
fun AdjacencyMatrix.toPlainAdjacencyList(): PlainAdjacencyList =
this.mapIndexed { rowNum, row ->
row.mapIndexed { colNum, weight -> if (weight != INFINITE) intArrayOf(rowNum, colNum, weight) else null }
.filterNotNull()
.reduce { acc, ints -> acc + ints }
}
.reduce { acc, list -> acc + list }
fun AdjacencyMatrix.toAdjacencyList() = this.mapIndexed { row, ints ->
ints.mapIndexed { col, w -> if (w != INFINITE) Triple(row, col, w) else null }
.filterNotNull()
}
.reduce { acc, list -> acc + list }
.toTypedArray()
}
object PlainAdjacencyListUtil {
inline operator fun PlainAdjacencyList.get(index: Int, col: Int) = this[3 * index + col]
inline operator fun PlainAdjacencyList.get(index: Int, content: PlainAdjacency) = this[index, content.number]
val PlainAdjacencyList.edgeNumber: Int
get() = (this.size + 1) / 3
}
}
| [
{
"class_path": "justnero__university__14f58f1/bellman/graph/Util$PlainAdjacencyListUtil.class",
"javap": "Compiled from \"util.kt\"\npublic final class bellman.graph.Util$PlainAdjacencyListUtil {\n public static final bellman.graph.Util$PlainAdjacencyListUtil INSTANCE;\n\n private bellman.graph.Util$Plai... |
justnero__university__14f58f1/semestr.06/ТРСиПВ/bellman/src/main/kotlin/bellman/graph/algorithm/plainBellmanFord.kt | package bellman.graph.algorithm
import bellman.graph.INFINITE
import bellman.graph.InputGraph
import bellman.graph.PlainAdjacency
import bellman.graph.PlainAdjacencyList
import bellman.graph.Util.AdjacencyMatrixUtil.toPlainAdjacencyList
import bellman.graph.Util.PlainAdjacencyListUtil.edgeNumber
import bellman.graph.Util.PlainAdjacencyListUtil.get
fun bellmanFord(graph: InputGraph) = with(graph) {
bellmanFord(
adjacencyMatrix.toPlainAdjacencyList(),
sourceVertex,
vertexNumber)
}
fun bellmanFord(plainAdjacencyList: PlainAdjacencyList,
sourceVertex: Int,
vertexNumber: Int): IntArray =
IntArray(vertexNumber, { INFINITE })
.apply { this[sourceVertex] = 0 }
.apply { while (plainAdjacencyList.relaxAll(this)); }
//TODO:Need optimization
fun PlainAdjacencyList.relaxAll(distance: IntArray, from: Int = 0, to: Int = edgeNumber - 1) =
(from..to)
.map { relax(it, distance) }
.onEach { if (it) return@relaxAll true }
.let { false }
fun PlainAdjacencyList.relax(index: Int, distance: IntArray): Boolean {
val lastValue = distance[get(index, PlainAdjacency.DESTINATION)]
if (distance[get(index, PlainAdjacency.SOURCE)] < INFINITE) {
distance[get(index, PlainAdjacency.DESTINATION)] =
minOf(distance[get(index, PlainAdjacency.DESTINATION)].toLong(),
distance[get(index, PlainAdjacency.SOURCE)].toLong()
+ get(index, PlainAdjacency.WEIGHT))
.toInt()
}
val isRelaxed = lastValue != distance[get(index, PlainAdjacency.DESTINATION)]
return isRelaxed
}
| [
{
"class_path": "justnero__university__14f58f1/bellman/graph/algorithm/PlainBellmanFordKt.class",
"javap": "Compiled from \"plainBellmanFord.kt\"\npublic final class bellman.graph.algorithm.PlainBellmanFordKt {\n public static final int[] bellmanFord(bellman.graph.InputGraph);\n Code:\n 0: aload_0... |
justnero__university__14f58f1/semestr.06/ТРСиПВ/bellman/src/main/kotlin/bellman/graph/algorithm/bellmanFord.kt | package bellman.graph.algorithm
import bellman.graph.Adjacency
import bellman.graph.AdjacencyList
import bellman.graph.INFINITE
import bellman.graph.Util.AdjacencyUtil.destination
import bellman.graph.Util.AdjacencyUtil.source
import bellman.graph.Util.AdjacencyUtil.weight
fun bellmanFord(adjacencyList: AdjacencyList,
sourceVertex: Int,
vertexNumber: Int,
edgeNumber: Int = adjacencyList.size): IntArray {
val distance = IntArray(vertexNumber, { INFINITE }).apply { this[sourceVertex] = 0 }
for (i in 0..vertexNumber - 1) {
if (!adjacencyList.relaxAll(distance))
return distance
}
return distance
}
inline fun AdjacencyList.relaxAll(distance: IntArray, from: Int = 0, to: Int = lastIndex) =
(from..to).map { get(it).relax(distance) }.onEach { if (it) return@relaxAll true }.let { false }
fun Adjacency.relax(distance: IntArray): Boolean {
val lastValue = distance[destination]
if (distance[source] < INFINITE) {
distance[destination] =
minOf(distance[destination].toLong(), distance[source].toLong() + weight).toInt()
}
val isRelaxed = lastValue != distance[destination]
return isRelaxed
}
| [
{
"class_path": "justnero__university__14f58f1/bellman/graph/algorithm/BellmanFordKt.class",
"javap": "Compiled from \"bellmanFord.kt\"\npublic final class bellman.graph.algorithm.BellmanFordKt {\n public static final int[] bellmanFord(kotlin.Triple<java.lang.Integer, java.lang.Integer, java.lang.Integer>[... |
CDCgov__data-exchange-hl7__e859ed7/deprecated/fn-mmg-validator/src/main/kotlin/gov/cdc/dex/hl7/model/ValidationIssue.kt | package gov.cdc.dex.hl7.model
enum class ValidationIssueCategoryType(val message: String) {
ERROR("Error"),
WARNING("Warning");
}
enum class ValidationIssueType(val message: String) {
DATA_TYPE("data_type"),
CARDINALITY("cardinality"),
VOCAB("vocabulary"),
SEGMENT_NOT_IN_MMG("segment_not_in_mmg"),
OBSERVATION_SUB_ID_VIOLATION("observation_sub_id_violation"),
DATE_CONTENT("date_content"),
MMWR_WEEK("mmwr_week_violation")
}
enum class ValidationErrorMessage(val message: String) {
DATA_TYPE_NOT_FOUND("Element data type not found"),
DATA_TYPE_MISMATCH("Element data type is not matching the MMG data type"),
CARDINALITY_UNDER("Element has less repeats than allowed by MMG cardinality"),
CARDINALITY_OVER("Element has more repeats than allowed by MMG cardinality"),
VOCAB_NOT_AVAILABLE("Vocabulary not available for code system code"),
VOCAB_ISSUE("Vocabulary code system code and code concept not found in vocabulary entries"),
SEGMENT_NOT_IN_MMG("HL7 segment found in the message that is not part of the MMG definitions"),
OBSERVATION_SUB_ID_MISSING("Observation Sub-Id must be populated for data elements in a repeating group."),
OBSERVATION_SUB_ID_NOT_UNIQUE("The combination of the data element identifier (OBX-3) and the observation sub-id (OBX-4) must be unique."),
DATE_INVALID("Date/time provided is not a valid date/time"),
WEEK_INVALID("Week provided is not a valid week")
}
data class ValidationIssue(
val classification: ValidationIssueCategoryType, // ERROR (for required fields) or WARNING
val category: ValidationIssueType, // DATA_TYPE, CARDINALITY, VOCAB
val fieldName: String, // mmg field Name
val path: String, // HL7 path to extract value
val line: Int,
val errorMessage: ValidationErrorMessage, // error message
val description: String, // custom message to add value in question
) // .ValidationIssue
| [
{
"class_path": "CDCgov__data-exchange-hl7__e859ed7/gov/cdc/dex/hl7/model/ValidationIssue.class",
"javap": "Compiled from \"ValidationIssue.kt\"\npublic final class gov.cdc.dex.hl7.model.ValidationIssue {\n private final gov.cdc.dex.hl7.model.ValidationIssueCategoryType classification;\n\n private final g... |
lorenzo-piersante__HackerRank-ProjectEuler__6159bb4/src/main/problem7/solution.kt | package problem7
import java.util.Scanner
import kotlin.math.ceil
import kotlin.math.sqrt
private fun isPrime(n: Int) : Boolean {
val maxDivider = ceil(sqrt(n.toDouble())).toInt()
for (i in 2..maxDivider) {
if (n % i == 0) return false
}
return true
}
val primeNumbers = mutableSetOf(2, 3, 5, 7, 11)
/**
* this function create the list of prime numbers with the highest input provided as size
* despite the fact that the list creation has a relevant complexity ...
* ... every subsequent testcase perform the fetch with a O(1) complexity
*
* "someone would say BLAZINGLY FAST!" -<NAME>
*/
fun warmup(n : Int) : MutableSet<Int> {
var candidate = 12
while (primeNumbers.count() <= n) {
if (isPrime(candidate)) {
primeNumbers.add(candidate)
}
candidate++
}
return primeNumbers
}
fun getNthPrimeNumber(n : Int) : Int {
return primeNumbers.elementAt(n - 1)
}
fun main() {
val sc = Scanner(System.`in`)
val numberOfInputs = sc.nextInt()
val inputs = mutableListOf<Int>()
for (i in 0 until numberOfInputs) {
inputs.add(i, sc.nextInt())
}
// HackerRank uses older kotlin version, so you need to use the following syntax to pass the test:
// warmup(inputs.max<Int>() ?: 0)
warmup(inputs.maxOrNull() ?: 0)
for (input in inputs) {
println(getNthPrimeNumber(input))
}
}
| [
{
"class_path": "lorenzo-piersante__HackerRank-ProjectEuler__6159bb4/problem7/SolutionKt.class",
"javap": "Compiled from \"solution.kt\"\npublic final class problem7.SolutionKt {\n private static final java.util.Set<java.lang.Integer> primeNumbers;\n\n private static final boolean isPrime(int);\n Code:... |
lorenzo-piersante__HackerRank-ProjectEuler__6159bb4/src/main/problem4/solution2.kt | package problem4
import java.util.Scanner
private fun isPalindrome(n : Int) : Boolean {
val straight = n.toString()
val reversed = straight.reversed()
return straight == reversed
}
private fun getPreviousPalindrome(n : Int) : Int {
var prev = n
while (! isPalindrome(prev)) prev--
return prev
}
private fun is3DigitTermsProduct(n : Int) : Boolean {
for (i in 111..999) {
for (j in 111..999) {
if (i * j == n) return true
}
}
return false
}
/**
* this solution is way better, in fact we use the nested loops only to find the product terms only for palindrome nums
* the optimization seems to be enough to pass tests
*/
fun largestPalindromeProductV2(input : Int) : Int {
var candidate = getPreviousPalindrome(input - 1)
while (! is3DigitTermsProduct(candidate)) {
candidate = getPreviousPalindrome(candidate - 1)
}
return candidate
}
fun main() {
val sc = Scanner(System.`in`)
val numberOfInputs = sc.nextInt()
for (i in 0 until numberOfInputs) {
val input = sc.nextInt()
val result = largestPalindromeProductV2(input)
println(result)
}
}
| [
{
"class_path": "lorenzo-piersante__HackerRank-ProjectEuler__6159bb4/problem4/Solution2Kt.class",
"javap": "Compiled from \"solution2.kt\"\npublic final class problem4.Solution2Kt {\n private static final boolean isPalindrome(int);\n Code:\n 0: iload_0\n 1: invokestatic #12 ... |
Undiy__hyperskill-kotlin-core__70695fb/Phone Book (Kotlin)/Phone Book (Kotlin)/task/src/phonebook/Main.kt | package phonebook
import java.io.BufferedReader
import java.io.File
import java.io.FileReader
import java.lang.Integer.min
import java.util.*
import kotlin.math.sqrt
import kotlin.streams.asSequence
const val FIND_FILENAME = "find.txt"
const val DIRECTORY_FILENAME = "directory.txt"
fun getRecordName(record: String) = record.substringAfter(" ", record)
fun linearSearchFn(value: String): Boolean {
BufferedReader(FileReader(DIRECTORY_FILENAME)).use { directoryReader ->
return directoryReader.lines().anyMatch {
getRecordName(it) == value
}
}
}
fun jumpSearch(data: List<String>, value: String): Boolean {
val blockSize = sqrt(data.size.toDouble()).toInt()
for (i in 0..data.size / blockSize) {
val boundary = min(data.lastIndex, (i + 1) * blockSize - 1)
if (getRecordName(data[boundary]) >= value) {
for (j in boundary downTo i * blockSize) {
if (getRecordName(data[j]) == value) {
return true
}
}
}
}
return false
}
fun binarySearch(data: List<String>, value: String): Boolean {
if (data.isEmpty()) {
return false
}
val pivotIndex = data.size / 2
val pivot = getRecordName(data[pivotIndex])
return if (pivot == value) {
true
} else if (pivot > value) {
binarySearch(data.subList(0, pivotIndex), value)
} else {
binarySearch(data.subList(pivotIndex, data.size), value)
}
}
fun search(searchFn: (String) -> Boolean) = search(searchFn, System.currentTimeMillis())
fun search(searchFn: (String) -> Boolean, start: Long): Long {
var count = 0
var found = 0
BufferedReader(FileReader(FIND_FILENAME)).use { findReader ->
findReader.lines().forEach {
count++
if (searchFn(it)) {
found++
}
}
}
val time = System.currentTimeMillis() - start
println("Found $found / $count entries. Time taken: ${formatTimeMillis(time)}")
return time
}
fun bubbleAndJumpSearch(limit: Long): Long {
val start = System.currentTimeMillis()
val directory = File(DIRECTORY_FILENAME).readLines()
val (isSorted, sortTime) = bubbleSort(directory, limit)
val time = search(if (isSorted) {
{ jumpSearch(directory, it) }
} else {
::linearSearchFn
}, start)
if (isSorted) {
println("Sorting time: ${formatTimeMillis(sortTime)}")
} else {
println("Sorting time: ${formatTimeMillis(sortTime)} - STOPPED, moved to linear search")
}
println("Searching time: ${formatTimeMillis(time - sortTime)}")
return time
}
fun formatTimeMillis(millis: Long) = "${millis / 1000_000} min. ${millis % 1000_000 / 1000} sec. ${millis % 1000} ms."
fun bubbleSort(data: List<String>, timeLimit: Long): Pair<Boolean, Long> {
val start = System.currentTimeMillis()
var isSorted: Boolean
do {
isSorted = true
for (i in 0 until data.lastIndex) {
val time = System.currentTimeMillis() - start
if (time > timeLimit) {
return Pair(false, time)
}
if (getRecordName(data[i]) > getRecordName(data[i + 1])) {
isSorted = false
Collections.swap(data, i, i + 1)
}
}
} while (!isSorted)
return Pair(true, System.currentTimeMillis() - start)
}
fun quickSort(data: List<String>) {
if (data.size < 2) {
return
}
val pivot = getRecordName(data.random())
var boundary = 0
for (i in data.indices) {
if (getRecordName(data[i]) < pivot) {
Collections.swap(data, i, boundary)
boundary++
}
}
quickSort(data.subList(0, boundary))
quickSort(data.subList(boundary, data.size))
}
fun quickAndBinarySearch(): Long {
val start = System.currentTimeMillis()
val directory = File(DIRECTORY_FILENAME).readLines()
quickSort(directory)
val sortTime = System.currentTimeMillis() - start
val time = search({ binarySearch(directory, it) }, start)
println("Sorting time: ${formatTimeMillis(sortTime)}")
println("Searching time: ${formatTimeMillis(time - sortTime)}")
return time
}
fun hashSearch(): Long {
val start = System.currentTimeMillis()
val table = BufferedReader(FileReader(DIRECTORY_FILENAME)).use { directoryReader ->
directoryReader.lines().asSequence().groupBy(
::getRecordName
) { it.substringBefore(" ", it) }
}
val createTime = System.currentTimeMillis() - start
val time = search({ it in table }, start)
println("Creating time: ${formatTimeMillis(createTime)}")
println("Searching time: ${formatTimeMillis(time - createTime)}")
return time
}
fun main() {
println("Start searching (linear search)...")
val linearTime = search(::linearSearchFn)
println()
println("Start searching (bubble sort + jump search)...")
bubbleAndJumpSearch(linearTime * 10)
println()
println("Start searching (quick sort + binary search)...")
quickAndBinarySearch()
println("Start searching (hash table)...")
hashSearch()
}
| [
{
"class_path": "Undiy__hyperskill-kotlin-core__70695fb/phonebook/MainKt$main$linearTime$1.class",
"javap": "Compiled from \"Main.kt\"\nfinal class phonebook.MainKt$main$linearTime$1 extends kotlin.jvm.internal.FunctionReferenceImpl implements kotlin.jvm.functions.Function1<java.lang.String, java.lang.Boole... |
Simplation__OpenSourceRepository__d45feaa/算法/两数之和1.kt | package com.example.rain_demo.algorithm
/**
*@author: Rain
*@time: 2022/7/14 9:40
*@version: 1.0
*@description: 给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
*/
/**
* 输入:nums = [2,7,11,15], target = 9
* 输出:[0,1]
* 解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
*
* 输入:nums = [3,2,4], target = 6
* 输出:[1,2]
*
* 输入:nums = [3,3], target = 6
* 输出:[0,1]
*
*/
fun main() {
// val time1 = System.currentTimeMillis()
val newInt = IntArray(2)
// sum(newInt, intArrayOf(3, 2, 3), 0, 6)
// println(System.currentTimeMillis() - time1)
// println(newInt.toString())
val nums = intArrayOf(3, 2, 3)
val target = 6
// val size = nums.size
// repeat(size) { index0 ->
// var index = index0 + 1
// while (index < size) {
// if (nums[index0] + nums[index] == target) {
// newInt[0] = index0
// newInt[1] = index
// return
// }
// index++
// }
// }
val map = mutableMapOf<Int, Int>()
var index = 0
while (index < nums.size) {
if (map.containsKey(target - nums[index])) {
val intArrayOf = intArrayOf(map[target - nums[index]]!!, index)
println(intArrayOf[0])
println(intArrayOf[1])
}
map[nums[index]] = index
index++
}
// nums.forEachIndexed { index, i ->
// if (map.containsKey(target - i)) {
// val intArrayOf = intArrayOf(map[target - i]!!, index)
// }
// map[i] = index
// }
}
fun sum(newInt: IntArray, nums: IntArray, index: Int, target: Int) {
val size = nums.size
if (index == size - 1) {
return
}
var newIndex = index + 1
// floor(newInt, nums, index, target, size, newIndex)
while (newIndex < size) {
val i = nums[index] + nums[newIndex]
if (i == target) {
newInt[0] = index
newInt[1] = newIndex
return
}
newIndex++
}
if (newInt[1] == 0) {
sum(newInt, nums, index + 1, target)
}
}
/**
* 二层递归
* @param newIndex 后一个index
*/
fun floor(newInt: IntArray, nums: IntArray, index: Int, target: Int, size: Int, newIndex: Int) {
if (newIndex == size) {
return
}
val i = nums[index] + nums[newIndex]
if (i == target) {
newInt[0] = index
newInt[1] = newIndex
return
} else {
floor(newInt, nums, index, target, size, newIndex + 1)
}
}
| [
{
"class_path": "Simplation__OpenSourceRepository__d45feaa/com/example/rain_demo/algorithm/两数之和1Kt.class",
"javap": "Compiled from \"两数之和1.kt\"\npublic final class com.example.rain_demo.algorithm.两数之和1Kt {\n public static final void main();\n Code:\n 0: iconst_2\n 1: newarray int\n ... |
Simplation__OpenSourceRepository__d45feaa/算法/寻找两个正序数组的中位数4.kt | package com.example.rain_demo.algorithm
/**
*@author: Rain
*@time: 2022/7/20 14:34
*@version: 1.0
*@description: 寻找两个正序数组的中位数
*/
fun main() {
val nums1 = intArrayOf(1, 3)
val nums2 = intArrayOf(2)
val size1 = nums1.size
val size2 = nums2.size
val size = size1 + size2
if (size % 2 == 0) {
val midIndex1 = size / 2 - 1
val midIndex2 = size / 2
val d = (getKthElement(nums1, nums2, midIndex1 + 1) + getKthElement(nums1,
nums2,
midIndex2 + 1)) / 2.0
println(d)
} else {
val midIndex = size / 2
val kthElement = getKthElement(nums1, nums2, midIndex + 1).toDouble()
println(kthElement)
}
}
fun getKthElement(nums1: IntArray, nums2: IntArray, k: Int): Int {
val size1 = nums1.size
val size2 = nums2.size
var index1 = 0
var index2 = 0
var ele = k
while (true) {
if (index1 == size1) {
return nums2[index2 + ele - 1]
}
if (index2 == size2) {
return nums1[index1 + ele - 1]
}
if (ele == 1) {
return Math.min(nums1[index1], nums2[index2])
}
val h = ele / 2
val newIndex1 = Math.min(index1 + h, size1) - 1
val newIndex2 = Math.min(index2 + h, size2) - 1
val p1 = nums1[newIndex1]
val p2 = nums2[newIndex2]
if (p1 <= p2) {
ele -= (newIndex1 - index1 + 1)
index1 = newIndex1 + 1
} else {
ele -= (newIndex2 - index2 + 1)
index2 = newIndex2 + 1
}
}
}
//region 调用 list api
fun findMedianSortedArrays() {
val nums1 = intArrayOf(1, 2)
val nums2 = intArrayOf(3, 4)
val newNum = DoubleArray(nums1.size + nums2.size)
val index = add(newNum, nums1, 0)
val size = second(newNum, nums2, 0, index)
newNum.sort()
if (size % 2 == 0) {
val i = size / 2
val i1 = i - 1
val i2: Double = ((newNum[i] + newNum[i1]) / 2)
println(i2)
} else {
val i = (size - 1) / 2
val i1 = newNum[i]
println(i1)
}
}
fun add(newNum: DoubleArray, l: IntArray, index: Int): Int {
return if (index < l.size) {
newNum[index] = l[index].toDouble()
add(newNum, l, index + 1)
} else {
index
}
}
fun second(newNum: DoubleArray, l: IntArray, index: Int, newIndex: Int): Int {
return if (index < l.size) {
newNum[newIndex] = l[index].toDouble()
second(newNum, l, index + 1, newIndex + 1)
} else {
newIndex
}
}
//endregion | [
{
"class_path": "Simplation__OpenSourceRepository__d45feaa/com/example/rain_demo/algorithm/寻找两个正序数组的中位数4Kt.class",
"javap": "Compiled from \"寻找两个正序数组的中位数4.kt\"\npublic final class com.example.rain_demo.algorithm.寻找两个正序数组的中位数4Kt {\n public static final void main();\n Code:\n 0: iconst_2\n 1: ... |
Simplation__OpenSourceRepository__d45feaa/算法/一维数组的动态和1480.kt | package com.example.rain_demo.algorithm
/**
*@author: Rain
*@time: 2022/7/14 9:33
*@version: 1.0
*@description: 一维数组的动态和
* 给你一个数组 nums 。数组「动态和」的计算公式为:runningSum[i] = sum(nums[0]…nums[i])。请返回 nums 的动态和。
* val nums = intArrayOf(3, 1, 2, 10, 1)
* val nums = intArrayOf(1,2,3,4)
*/
fun main() {
val nums = intArrayOf(1, 1, 1, 1, 1)
var index = 1
while (index < nums.size) {
nums[index] += nums[index - 1]
index++
}
// val mapIndexed = nums.mapIndexed { index, i ->
// i.plus(nums.take(index).sum())
// }
// val size = nums.size
// val newNum = IntArray(size)
// nums.forEachIndexed { index, i ->
// newNum[index] = i.plus(nums.take(index).sum())
// }
// mapIndexed.toIntArray()
// sumArr(newNum, nums, size - 1)
println(nums.toString())
}
/**
* 递归方案
*/
fun sumArr(newNum: IntArray, nums: IntArray, index: Int): Int {
if (index == 0) {
newNum[0] = nums[0]
return nums[0]
}
newNum[index] = nums[index] + sumArr(newNum, nums, index - 1)
return newNum[index]
} | [
{
"class_path": "Simplation__OpenSourceRepository__d45feaa/com/example/rain_demo/algorithm/一维数组的动态和1480Kt.class",
"javap": "Compiled from \"一维数组的动态和1480.kt\"\npublic final class com.example.rain_demo.algorithm.一维数组的动态和1480Kt {\n public static final void main();\n Code:\n 0: iconst_5\n 1: new... |
li2__android-architecture__010d25e/hikotlin/src/main/java/me/li2/android/hikotlin/kotlin/Calculator.kt | package me.li2.android.hikotlin.kotlin
import me.li2.android.hikotlin.kotlin.Operator.*
import java.util.*
/** + */
fun operatorPlus(input: Int): Int {
return input + MY_PLUS
}
/** - */
fun operatorMinus(input: Int): Int {
return input + MY_MINUS
}
/** x */
fun operatorMultiply(input: Int): Int {
return input * MY_MULTIPLY
}
/** / */
fun operatorDivider(input: Int): Int {
return input / MY_DIVIDER
}
/** reverse : 12 to 21 */
fun operatorReverse(input: Int): Int {
var num = input
var reversed = 0
while (num != 0) {
val digit = num % 10
reversed = reversed * 10 + digit
num /= 10
}
return reversed
}
/** +/- */
fun operatorConvert(input: Int): Int {
return -input
}
/** << */
fun operatorShift(input: Int): Int {
return input / 10
}
fun operatorInsert(input: Int): Int {
return input * 10 + 1
}
/**
* THE METHOD THAT TAKES AN ARRAY OF STRINGS AND PRINTS THE
* POSSIBLE COMBINATIONS.
*/
fun genOperatorsCombinations(operators: Array<Operator>): List<List<Operator>> {
val results = ArrayList<List<Operator>>()
/*COMBINATIONS OF LENGTH THREE*/
for (i in operators.indices) {
for (j in operators.indices) {
for (k in operators.indices) {
for (l in operators.indices) {
for (m in operators.indices) {
// for (n in operators.indices) {
// for (o in operators.indices) {
val element = ArrayList<Operator>()
element.add(operators[i])
element.add(operators[j])
element.add(operators[k])
element.add(operators[l])
element.add(operators[m])
// element.add(operators[n])
// element.add(operators[o])
results.add(element)
}
// }
// }
}
}
}
}
return results
}
enum class Operator(val alias: String) {
PLUS("+"),
MINUS("-"),
MULTIPLY("x"),
DIVIDE("/"),
REVERSE("Reverse"),
CONVERT("+/-"),
SHIFT("<<"),
INSERT("1");
}
fun calculate(input: Int, operator: Operator): Int {
return when(operator) {
Operator.PLUS -> operatorPlus(input)
Operator.MINUS-> operatorMinus(input)
Operator.MULTIPLY -> operatorMultiply(input)
Operator.REVERSE -> operatorReverse(input)
Operator.CONVERT -> operatorConvert(input)
Operator.SHIFT -> operatorShift(input)
Operator.INSERT -> operatorInsert(input)
else -> {
0
}
}
}
fun chainCalculate(input: Int, operators: List<Operator>): Int {
var result = input
for (operator in operators) {
result = calculate(result, operator)
}
return result
}
fun printGoal(operators: List<Operator>) {
var result = ""
for (operator in operators) {
result += " ${operator.alias}"
}
println("Goal $MY_GOAL achieved with operators: $result")
}
var MY_MOVES: Int = 7
var MY_INIT: Int = 0
var MY_GOAL: Int = 136
var MY_OPERATORS: Array<Operator> = arrayOf(PLUS, MULTIPLY, REVERSE, INSERT)
var MY_PLUS: Int = 2
var MY_MINUS: Int = -3
var MY_MULTIPLY: Int = 3
var MY_DIVIDER: Int = 2
// Goal 28 achieved with operators: + + << + + Reverse -
fun main(args: Array<String>) {
var result: Int
var combinations = genOperatorsCombinations(MY_OPERATORS)
for (operators in combinations) {
result = chainCalculate(MY_INIT, operators)
if (result == MY_GOAL) {
printGoal(operators)
break
}
}
}
| [
{
"class_path": "li2__android-architecture__010d25e/me/li2/android/hikotlin/kotlin/CalculatorKt$WhenMappings.class",
"javap": "Compiled from \"Calculator.kt\"\npublic final class me.li2.android.hikotlin.kotlin.CalculatorKt$WhenMappings {\n public static final int[] $EnumSwitchMapping$0;\n\n static {};\n ... |
Josef-TL__app-dev__f613326/hand-ins/app/src/main/java/com/example/handins/hand_in_1.kt | package com.example.handins
import java.util.Scanner
fun main(){
checkAge()
val max : Int = getMax(1,18,8);
val min : Int = getMin(1,18,-8);
println(max); //18
println(min); //-8
val numList: List<Int> = listOf(0,-12,4,6,123)
println("Average of the list ${numList} is: " + calculateAverage(numList))
val cpr: String = "3203139999"
println("Is $cpr a valid CPR Number?")
println(isCprValid(cpr))
fizzBuzz()
abbrevName("<NAME>")
val testStringList: List<String> = listOf("Hello", "banana", "elephant", "pizza", "computer", "mountain", "butterfly", "galaxy", "happiness", "freedom")
filterWordsByLength(testStringList,3)
}
/*********************
* Opgave 1
* A person is elligible to vote if his/her age is greater than or equal to 18.
* Define a method to find out if he/she is elligible to vote
*********************/
fun checkAge(){
val reader = Scanner(System.`in`)
println("Please enter age: ")
val userAge: Int = reader.nextInt()
if(userAge < 18) println("You cannot vote") else println("Vote NOW!")
}
/*********************
* Opgave 2
* Define two functions to print the maximum and the minimum number respectively
* among three numbers
*********************/
fun getMax(a:Int,b:Int,c:Int):Int{
return maxOf(a,b,c)
}
fun getMin(a:Int,b:Int,c:Int):Int{
return minOf(a,b,c)
}
/*********************
* Opgave 3
* Write a Kotlin function named calculateAverage
* that takes in a list of numbers and returns their average.
*********************/
fun calculateAverage(l:List<Int>):Double{
val listLeng: Double = l.size.toDouble()
val listSum: Double = l.sumOf { it.toDouble() }
return listSum/listLeng
}
/*
Opgave 4
Write a method that returns if a user has input a valid CPR number.
A valid CPR number has:
* 10 Digits.
* The first 2 digits are not above 31.
* The middle 2 digits are not above 12.
* The method returns true if the CPR number is valid, false if it is not.
Bruger RegEx. Bruger ChatGPT til at finde en Expression
*/
fun isCprValid(cprString: String):Boolean{
val validationExpression = "^(0[1-9]|[12][0-9]|3[01])(0[1-9]|1[0-2])(\\d{2})\\d{4}\$".toRegex()
return validationExpression.matches(cprString)
}
/*
Opgave 5
Write a program that prints the numbers from 1 to 100.
But for multiples of three print “Fizz” instead of the number
and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.
*/
fun fizzBuzz(){
for (l in 1..100){
if(l%3 == 0 && l%5 != 0){
println("Fizz")
} else if(l%3!=0 && l%5 == 0){
println("Buzz")
} else if(l%3==0 && l%5==0){
println("FizzBuzz")
}
else{ println(l) }
}
}
/*
Opgave 6
Write a program that takes your full name as input and displays
the abbreviations of the first and middle names except the last name which is displayed as it is.
For example, if your name is <NAME>, then the output should be <NAME>.
Or <NAME> will be <NAME>
*/
fun abbrevName(name:String){
val nameArr = name.split(" ")
val returnArr = nameArr.mapIndexed { index, s ->
if(index == nameArr.lastIndex) s else s[0]
}
println(returnArr.joinToString(separator = ". "))
}
/*
Opgave 7
Write a program that takes a numerical grade (0-100) as input
and prints out the corresponding american letter grade.
Implement a function calculateGrade that takes an integer parameter representing the grade
and returns a string representing the letter grade according to the following scale:
90-100: "A"
80-89: "B"
70-79: "C"
60-69: "D"
Below 60: "F"
*/
fun calculateGrade(grade:Int):String{
return when{
grade > 100 -> "Enter valid number"
grade < 0 -> "Enter valid number"
grade in 90..100 -> "A"
grade in 80..89 -> "B"
grade in 70..79 -> "C"
grade in 60..69 -> "D"
else -> "F"
}
}
/*
Opgave 8
Write a Kotlin function named filterWordsByLength that takes in a list of strings and a minimum length,
and returns a list containing only the words that have a length greater than or equal to
the specified minimum length.
Use filter function and lambda expressions
*/
fun filterWordsByLength(l:List<String>,minLen:Int):List<String>{
return l.filter { str -> str.length >= minLen }
} | [
{
"class_path": "Josef-TL__app-dev__f613326/com/example/handins/Hand_in_1Kt.class",
"javap": "Compiled from \"hand_in_1.kt\"\npublic final class com.example.handins.Hand_in_1Kt {\n public static final void main();\n Code:\n 0: invokestatic #9 // Method checkAge:()V\n 3: ico... |
KingChampion36__data-structures-and-algorithms__a276937/src/main/kotlin/com/kingchampion36/dsa/arrays/KthSmallestAndLargestElement.kt | package com.kingchampion36.dsa.arrays
import java.util.PriorityQueue
/**
* Sort the list and find kth smallest element
* Time complexity - O(n * log(n))
*/
fun List<Int>.kthSmallestElementBySorting(k: Int) = when {
isEmpty() -> throw IllegalArgumentException("List should not be empty")
k <= 0 || k >= size -> throw IllegalArgumentException("Invalid value $k of k")
else -> sorted()[k - 1]
}
/**
* Time Complexity - O(n * log(k))
*/
fun List<Int>.kthSmallestElementByUsingMaxHeap(k: Int): Int {
require(isNotEmpty()) { "List should not be empty" }
// k should be between 0 and size (0 < k <= size)
require(k in 1..size) { "Invalid value of k" }
val maxHeap = PriorityQueue<Int>(reverseOrder())
// Build a max heap with first k elements
for (i in 0 until k) {
maxHeap.offer(this[i])
}
for (i in k until size) {
// If current element is smaller than the top element of max heap,
// pop it and insert current element in the max heap
if (this[i] < maxHeap.peek()) {
maxHeap.poll()
maxHeap.offer(this[i])
}
}
return maxHeap.peek()
}
/**
* Time Complexity - O(n * log(k))
*/
fun List<Int>.kthLargestElementByUsingMinHeap(k: Int): Int {
require(isNotEmpty()) { "List should not be empty" }
// k should be between 0 and size (0 < k <= size)
require(k in 1..size) { "Invalid value of k" }
val minHeap = PriorityQueue<Int>()
// Build a min heap with first k elements
for (i in 0 until k) {
minHeap.offer(this[i])
}
for (i in k until size) {
// If current element is greater than the top element of min heap,
// pop it and insert current element in the min heap
if (this[i] > minHeap.peek()) {
minHeap.poll()
minHeap.offer(this[i])
}
}
return minHeap.peek()
}
| [
{
"class_path": "KingChampion36__data-structures-and-algorithms__a276937/com/kingchampion36/dsa/arrays/KthSmallestAndLargestElementKt.class",
"javap": "Compiled from \"KthSmallestAndLargestElement.kt\"\npublic final class com.kingchampion36.dsa.arrays.KthSmallestAndLargestElementKt {\n public static final ... |
rafaeltoledo__aoc2023__7bee985/src/main/kotlin/net/rafaeltoledo/kotlin/advent/Day04.kt | package net.rafaeltoledo.kotlin.advent
import kotlin.math.pow
class Day04 {
fun invoke(input: List<String>): Int {
val cards = input.map { it.toScratchCard() }
return cards
.map { card -> card.numbers.filter { card.winningNumbers.contains(it) } }
.sumOf { it.size.calculateCardValue() }
}
fun invoke2(input: List<String>): Int {
val cards = input.map { it.toScratchCard() }
val cardCounter = cards.associate { it.identifier to 1 }.toMutableMap()
cards
.forEachIndexed { index, card ->
val id = index + 1
val multiplier = cardCounter[id] ?: 1
val extras = card.numbers.filter { card.winningNumbers.contains(it) }.count()
for (i in 0 until extras) {
val targetId = id + (i + 1)
cardCounter[targetId]?.let { current ->
cardCounter[targetId] = current + multiplier
}
}
}
return cardCounter.toList().sumOf { it.second }
}
}
private fun Int.calculateCardValue(): Int {
return 2.0.pow((this - 1).toDouble()).toInt()
}
private fun String.toScratchCard(): ScratchCard {
val parts = split(":")
val identifier = parts.first().replace("Card", "").trim().toInt()
val content = parts.last().split("|")
val winningNumbers =
content.first().split(" ").filter { it.isNotEmpty() }.map { it.trim().toInt() }
val numbers = content.last().split(" ").filter { it.isNotEmpty() }.map { it.trim().toInt() }
return ScratchCard(identifier, numbers, winningNumbers)
}
data class ScratchCard(
val identifier: Int,
val numbers: List<Int>,
val winningNumbers: List<Int>,
)
| [
{
"class_path": "rafaeltoledo__aoc2023__7bee985/net/rafaeltoledo/kotlin/advent/Day04Kt.class",
"javap": "Compiled from \"Day04.kt\"\npublic final class net.rafaeltoledo.kotlin.advent.Day04Kt {\n private static final int calculateCardValue(int);\n Code:\n 0: ldc2_w #7 // dou... |
rafaeltoledo__aoc2023__7bee985/src/main/kotlin/net/rafaeltoledo/kotlin/advent/Day03.kt | package net.rafaeltoledo.kotlin.advent
class Day03 {
fun invoke(input: List<String>): Int {
val positioning = input.toPositioning()
return positioning.filter { it.checkBoundaries(input) }.sumOf { it.number }
}
fun invoke2(input: List<String>): Int {
val positioning = input.toPositioning()
return positioning
.map { it.fillAsteriskData(input) }
.filter { it.symbolPosition != null }
.groupBy { it.symbolPosition }
.filter { it.value.size >= 2 }
.map { it.value.first().number * it.value.last().number }
.sum()
}
fun NumberPositioning.checkBoundaries(input: List<String>): Boolean {
val lines = listOf(this.start.first - 1, this.start.first, this.start.first + 1).filter { it >= 0 }.filter { it <= input.size - 1 }
val range = ((start.second - 1)..(end.second + 1)).toList().filter { it >= 0 }.filter { it <= input.first().length - 1 }
lines.forEach { line ->
range.forEach { column ->
if (input.get(line).get(column).isValid()) {
return true
}
}
}
return false
}
fun NumberPositioning.fillAsteriskData(input: List<String>): NumberPositioning {
val lines = listOf(this.start.first - 1, this.start.first, this.start.first + 1).filter { it >= 0 }.filter { it <= input.size - 1 }
val range = ((start.second - 1)..(end.second + 1)).toList().filter { it >= 0 }.filter { it <= input.first().length - 1 }
lines.forEach { line ->
range.forEach { column ->
if (input.get(line).get(column).isAsterisk()) {
return this.copy(
symbolPosition = Pair(line, column),
)
}
}
}
return this
}
}
fun NumberPositioning.prettyPrint(input: List<String>) {
val lines = listOf(this.start.first - 1, this.start.first, this.start.first + 1).filter { it >= 0 }.filter { it <= input.size - 1 }
val range = ((start.second - 1)..(end.second + 1)).toList().filter { it >= 0 }.filter { it <= input.first().length - 1 }
lines.forEach { line ->
range.forEach { column ->
print(input.get(line).get(column))
}
println()
}
println()
}
private fun Char.isValid(): Boolean {
return (!isDigit() && this != '.')
}
private fun Char.isAsterisk(): Boolean {
return this == '*'
}
private fun List<String>.toPositioning(): List<NumberPositioning> {
val list = mutableListOf<NumberPositioning>()
this.forEachIndexed { line, value ->
var tempStr = ""
var startIndex = -1
value.forEachIndexed { strIndex, char ->
if (char.isDigit()) {
tempStr += char
if (startIndex == -1) {
startIndex = strIndex
}
} else {
if (tempStr.isNotEmpty()) {
list.add(NumberPositioning(tempStr.toInt(), Pair(line, startIndex), Pair(line, strIndex - 1)))
}
tempStr = ""
startIndex = -1
}
}
if (tempStr.isNotEmpty()) {
list.add(NumberPositioning(tempStr.toInt(), Pair(line, startIndex), Pair(line, value.length - 1)))
}
}
return list.toList()
}
data class NumberPositioning(
val number: Int,
val start: Pair<Int, Int>,
val end: Pair<Int, Int>,
var symbolPosition: Pair<Int, Int>? = null,
)
| [
{
"class_path": "rafaeltoledo__aoc2023__7bee985/net/rafaeltoledo/kotlin/advent/Day03Kt.class",
"javap": "Compiled from \"Day03.kt\"\npublic final class net.rafaeltoledo.kotlin.advent.Day03Kt {\n public static final void prettyPrint(net.rafaeltoledo.kotlin.advent.NumberPositioning, java.util.List<java.lang.... |
rafaeltoledo__aoc2023__7bee985/src/main/kotlin/net/rafaeltoledo/kotlin/advent/Day02.kt | package net.rafaeltoledo.kotlin.advent
class Day02 {
val validRound = Round(red = 12, green = 13, blue = 14)
fun invoke(input: List<String>): Int {
val games = input.map { it.toGame() }
return games.filter { it.isValid() }.sumOf { it.id }
}
fun invoke2(input: List<String>): Int {
val games = input.map { it.toGame() }
return games.map { it.rounds.optimal() }.sumOf { it.red * it.green * it.blue }
}
private fun Game.isValid(): Boolean {
return rounds.map { it.isValid() }.reduce { acc, value -> acc && value }
}
private fun Round.isValid(): Boolean {
return red <= validRound.red
&& blue <= validRound.blue
&& green <= validRound.green
}
private fun String.toGame(): Game {
val parts = split(":")
val id = parts.first().replace("Game ", "").toInt()
val rounds = parts.last().split(";").map { it.toRound() }
return Game(id = id, rounds = rounds)
}
private fun String.toRound(): Round {
val parts = split(",").map { it.trim() }
return Round(
red = parts.findAndParse("red"),
blue = parts.findAndParse("blue"),
green = parts.findAndParse("green"),
)
}
private fun List<String>.findAndParse(key: String): Int {
return find { it.endsWith(key) }?.replace(key, "")?.trim()?.toInt() ?: 0
}
}
private fun List<Round>.optimal(): Round {
return Round(
red = maxOf { it.red },
green = maxOf { it.green },
blue = maxOf { it.blue },
)
}
data class Round(
val red: Int,
val blue: Int,
val green: Int,
)
data class Game(
val id: Int,
val rounds: List<Round>,
)
| [
{
"class_path": "rafaeltoledo__aoc2023__7bee985/net/rafaeltoledo/kotlin/advent/Day02Kt.class",
"javap": "Compiled from \"Day02.kt\"\npublic final class net.rafaeltoledo.kotlin.advent.Day02Kt {\n private static final net.rafaeltoledo.kotlin.advent.Round optimal(java.util.List<net.rafaeltoledo.kotlin.advent.... |
rafaeltoledo__aoc2023__7bee985/src/main/kotlin/net/rafaeltoledo/kotlin/advent/Day01.kt | package net.rafaeltoledo.kotlin.advent
private val numbers = mapOf(
"one" to 1,
"two" to 2,
"three" to 3,
"four" to 4,
"five" to 5,
"six" to 6,
"seven" to 7,
"eight" to 8,
"nine" to 9,
)
class Day01 {
fun invoke(rawInput: String): Int {
val lines = rawInput.split("\n").filter { it.isNotEmpty() }
return lines.sumOf {
"${
it.findDigit(
{ str -> str.substring(1) },
{ first() },
{ startsWith(it) },
)
}${
it.findDigit(
{ str -> str.substring(0, str.length - 1) },
{ last() },
{ endsWith(it) })
}".toInt()
}
}
}
private fun String.findDigit(
substring: (String) -> String,
charPicker: String.() -> Char,
stringEval: String.(String) -> Boolean
): String {
var value = this
do {
if (value.isEmpty()) break
val digit = value.findDigit({ charPicker() }, { stringEval(it) })
if (digit == -1) value = substring(value)
else return digit.toString()
} while (true)
return ""
}
private fun String.findDigit(
charPicker: String.() -> Char,
stringEval: String.(String) -> Boolean
): Int {
if (isEmpty()) {
return -1
}
if (charPicker().isDigit()) {
return charPicker().digitToInt()
}
numbers.keys.forEach {
if (stringEval(it)) return numbers.getOrDefault(it, -1)
}
return -1
}
| [
{
"class_path": "rafaeltoledo__aoc2023__7bee985/net/rafaeltoledo/kotlin/advent/Day01.class",
"javap": "Compiled from \"Day01.kt\"\npublic final class net.rafaeltoledo.kotlin.advent.Day01 {\n public net.rafaeltoledo.kotlin.advent.Day01();\n Code:\n 0: aload_0\n 1: invokespecial #8 ... |
fachammer__tuwea__bc880bc/src/commonMain/kotlin/dev/achammer/tuwea/core/Core.kt | package dev.achammer.tuwea.core
import kotlin.random.Random
data class StudentCheckmarksEntry(
val firstName: String,
val lastName: String,
val idNumber: String,
val checkmarks: Set<String>
)
data class ParseConfiguration(
val csvDelimiter: Char,
val csvLineOffset: Int,
val preCheckmarksFieldOffset: Int,
val firstNameKey: String,
val lastNameKey: String,
val idNumberKey: String,
val exerciseEndSignifierKey: String,
val checkmarkSignifiers: Set<String>
)
val tuwelParseConfiguration = ParseConfiguration(
csvDelimiter = ';',
csvLineOffset = 6,
preCheckmarksFieldOffset = 3,
firstNameKey = "Vorname",
lastNameKey = "Nachname",
idNumberKey = "ID-Nummer",
exerciseEndSignifierKey = "Kreuzerl",
checkmarkSignifiers = setOf("X", "(X)")
)
data class ParseResult(val exercises: List<String>, val studentCheckmarksEntries: List<StudentCheckmarksEntry>)
typealias ExerciseStudentAssignment = List<Pair<String, StudentCheckmarksEntry>>
fun findExerciseAssignment(
parseResult: ParseResult,
isStudentPresent: (StudentCheckmarksEntry) -> Boolean
): ExerciseStudentAssignment {
val exercises = parseResult.exercises
val entries = parseResult.studentCheckmarksEntries
return exercises
.sortedBy { exercise -> entries.count { it.checkmarks.contains(exercise) } }
.fold(emptyList()) { chosenAssignments, exercise ->
val potentialEntries = entries
.filter { it.checkmarks.contains(exercise) }
.filter { isStudentPresent(it) }
.filterNot { entry -> chosenAssignments.firstOrNull { it.second == entry } != null }
if (potentialEntries.isEmpty()) {
chosenAssignments
} else {
chosenAssignments + Pair(exercise, potentialEntries[Random.nextInt(potentialEntries.size)])
}
}
}
fun parseCsvContent(parseConfiguration: ParseConfiguration, csvContent: String): ParseResult {
parseConfiguration.apply {
val csvLines = csvContent.split("\n")
val sanitizedCsvLines = csvLines.drop(csvLineOffset)
val headerRow = sanitizedCsvLines.first()
val fields = headerRow.split(csvDelimiter)
val exercises = fields
.drop(preCheckmarksFieldOffset)
.takeWhile { s -> s != exerciseEndSignifierKey }
.map { sanitizeExerciseName(it) }
val entries = sanitizedCsvLines
.drop(1)
.map { line -> fields.zip(line.split(csvDelimiter)).toMap() }
.map { entry -> parseCsvLine(entry) }
return ParseResult(exercises, entries)
}
}
private fun ParseConfiguration.parseCsvLine(entry: Map<String, String>): StudentCheckmarksEntry {
val checkmarks = entry.keys
.filterNot { it in setOf(firstNameKey, lastNameKey, idNumberKey) }
.filter { entry[it] in checkmarkSignifiers }
.map { sanitizeExerciseName(it) }
.toSet()
return StudentCheckmarksEntry(
firstName = sanitizeFirstName(entry[firstNameKey]!!),
lastName = entry[lastNameKey]!!,
idNumber = entry[idNumberKey]!!,
checkmarks = checkmarks
)
}
private fun sanitizeExerciseName(exerciseName: String): String = firstWordOf(exerciseName)
private fun sanitizeFirstName(firstName: String): String = firstWordOf(firstName)
private fun firstWordOf(string: String) = string.trim().split(" ").first() | [
{
"class_path": "fachammer__tuwea__bc880bc/dev/achammer/tuwea/core/CoreKt.class",
"javap": "Compiled from \"Core.kt\"\npublic final class dev.achammer.tuwea.core.CoreKt {\n private static final dev.achammer.tuwea.core.ParseConfiguration tuwelParseConfiguration;\n\n public static final dev.achammer.tuwea.c... |
KosmX__advent-of-code23__ad01ab8/src/main/kotlin/dev/kosmx/aoc23/differential/OhMoarMath.kt | package dev.kosmx.aoc23.differential
import kotlin.math.*
// It's beautiful how mathematical functions can be written down in functional programming :D
fun distance(totalTime: Int, buttonPress: Int): Int = (totalTime - buttonPress) * buttonPress // travel time times speed
// -(buttonPress^2) + totalTime*buttonPress
// dl/dp -- differentiated by buttonPress
fun dDistance(totalTime: Int, buttonPress: Int) = 2*buttonPress - totalTime
// this one is quite useless
// quadratic solution
// val x = buttonPress
// x^2 - totalTime*x + equals
fun zeroOfDistanceMinusTravel(totalTime: Double, equals: Double): Pair<Double, Double> {
val discriminant = sqrt(totalTime * totalTime - 4 * equals) // -4ac => -4*1*-equals
return (totalTime + discriminant)/2 to (totalTime - discriminant)/2
}
fun main() {
// This input is simple, I don't see its necessary to use files
val input = """
Time: 7 15 30
Distance: 9 40 200
""".trimIndent().lines()
val races = run {
val times = input[0].split(" ").asSequence().mapNotNull { it.toLongOrNull() }.toList()
val distances = input[1].split(" ").asSequence().mapNotNull { it.toLongOrNull() }.toList()
times.indices.map { times[it] to distances[it] }
}
races.fold(1L) { acc, (time, distance) ->
val solutions = zeroOfDistanceMinusTravel(time.toDouble(), distance.toDouble())
val margin = (solutions.first.nextDown().toLong() - (solutions.second.toLong()))
println("solutions: $solutions margin: $margin")
acc * margin
}.let {
println("part1: $it")
}
// for part2, just remove spaces
}
| [
{
"class_path": "KosmX__advent-of-code23__ad01ab8/dev/kosmx/aoc23/differential/OhMoarMathKt.class",
"javap": "Compiled from \"OhMoarMath.kt\"\npublic final class dev.kosmx.aoc23.differential.OhMoarMathKt {\n public static final int distance(int, int);\n Code:\n 0: iload_0\n 1: iload_1\n ... |
KosmX__advent-of-code23__ad01ab8/src/main/kotlin/dev/kosmx/aoc23/poker/WellItsNot.kt | package dev.kosmx.aoc23.poker
import java.io.File
import java.math.BigInteger
fun main() {
val games = File("poker.txt").readLines().map {
var (cards, score) = it.split(" ")
//cards = cards.replace("J", "X") Uncomment it to solve Part1
Hand(cards) to score.toInt()
}.sortedByDescending { it.first }
println(games.filter { game -> game.first.cards.any { it == WILDCARD } }.joinToString("\n"))
var score = BigInteger.ZERO
for (i in games.indices) {
score += BigInteger.valueOf(games[i].second.toLong()) * BigInteger.valueOf(i.toLong()+1)
}
println("Part1: Total score is $score")
}
data class Card(val letter: Char) : Comparable<Card> {
private companion object {
val ordering = arrayOf('A', 'K', 'Q', 'X', 'T', '9', '8', '7', '6', '5', '4', '3', '2', 'J')
}
override fun compareTo(other: Card): Int {
return ordering.indexOf(this.letter).compareTo(ordering.indexOf(other.letter))
}
}
val WILDCARD = Card('J')
class Hand(input: String): Comparable<Hand> {
val cards: Array<Card>
init {
cards = input.map { Card(it) }.toTypedArray()
assert(cards.size == 5)
}
override fun compareTo(other: Hand): Int {
if (type == other.type) {
for (i in 0..<5) {
val c = cards[i].compareTo(other.cards[i])
if (c != 0) return c
}
}
return other.type.compareTo(type) // compare but inverted
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Hand
return cards.contentEquals(other.cards)
}
override fun hashCode(): Int {
return cards.contentHashCode()
}
override fun toString(): String {
return "Hand(cards=${cards.joinToString(separator = "") { it.letter.toString() }}, type=$type)"
}
val type: Int
get() {
val groups = cards.asSequence().groupingBy { it }.eachCount()
val wildcard = groups[Card('J')] ?: 0
return when {
//Only one type or two types including wildcard type. Any number of wildcard can exist in this case
// edge-case here: all joker
groups.size == 1 || groups.filter { it.key != WILDCARD }.any { it.value + wildcard == 5 } -> 6
// Max 3 wildcards here
//There is at least one group with size of four including wildcards.
//Max 3 wildcards, if there is more, that would make a five
// If there are 3 wildcards, this will happen anyway
groups.filter { it.key != WILDCARD }.any { it.value + wildcard == 4 } -> 5
// Max 2 wildcards and at least 3 groups
// 2 groups are easy: If the sizes are 1 and 4, it is a four, it can't be. Only 2 and 3 or 3 and 2 are possible...
// Wildcard case:
// 1 single element can't be again
// only possibility: 2, 2 and 1 wildcard which is matched
//groups.size == 2 || groups.size == 3 && wildcard != 0 -> 4 // there are only two types or three types with wildcards
groups.filter { it.key != WILDCARD }.size == 2 -> 4
// There is any three with wildcards
groups.any { it.value + wildcard == 3 } -> 3
// Max 1 wildcard
// if there would be more wildcards than 1, it would be a three
// 3 groups are impossible
// the wildcard will pair with a single card creating 1 extra group
else -> (groups.count { it.value >= 2 } + wildcard).coerceAtMost(2) // 2 1 or 0 // if we have at least 2 wildcards, it'll be a three in a kind, only one wildcard can exist
// which will increase the amount of groups but only to two
}
}
} | [
{
"class_path": "KosmX__advent-of-code23__ad01ab8/dev/kosmx/aoc23/poker/WellItsNotKt.class",
"javap": "Compiled from \"WellItsNot.kt\"\npublic final class dev.kosmx.aoc23.poker.WellItsNotKt {\n private static final dev.kosmx.aoc23.poker.Card WILDCARD;\n\n public static final void main();\n Code:\n ... |
KosmX__advent-of-code23__ad01ab8/src/main/kotlin/dev/kosmx/aoc23/garden/VirtualMemory.kt | package dev.kosmx.aoc23.garden
import java.io.File
import java.math.BigInteger
import kotlin.math.abs
typealias Offset = Pair<OpenEndRange<BigInteger>, BigInteger>
val OpenEndRange<BigInteger>.size: BigInteger
get() = endExclusive - start
val Offset.destination: OpenEndRange<BigInteger>
get() = (first.start + second) ..< (first.endExclusive + second)
fun List<Offset>.binarySearch(i: BigInteger) = binarySearch { (range, _) ->
if (i in range) {
0
} else {
range.start.compareTo(i)
}
}
operator fun List<OpenEndRange<BigInteger>>.contains(item: BigInteger): Boolean {
val idx = binarySearch { range ->
if (item in range) {
0
} else {
range.start.compareTo(item)
}
}
return this.getOrNull(idx)?.contains(item) ?: false
}
fun min(a: BigInteger, b: BigInteger): BigInteger = if (a < b) a else b
class RangeMapping(ranges: List<Offset> = listOf()) {
val rangesList: List<Offset>
init {
rangesList = ranges.sortedBy { it.first.start }
}
operator fun get(i: BigInteger): BigInteger {
val r = this.rangesList.binarySearch(i)
return if (r >= 0) {
i + rangesList[r].second
} else i
}
override fun toString(): String {
return "RangeMapping(rangesList=$rangesList)"
}
// one step of simplify
operator fun plus(rhs: RangeMapping): RangeMapping {
val newRanges = mutableListOf<Offset>()
val newRangesB = rhs.rangesList.toMutableList()
for (range in rangesList) {
val currentRange = range.destination
var current = currentRange.start
var targetRangeIdx = abs(newRangesB.binarySearch(current))
while (current < currentRange.endExclusive && targetRangeIdx < newRangesB.size) {
val dest = newRangesB[targetRangeIdx]
if (current in dest.first) { // two ranges intersect, cut both range
// cut destination range if necessary
if (current > dest.first.start) {
newRangesB.add(targetRangeIdx, dest.first.start ..< current to dest.second)
targetRangeIdx++
}
val newEnd = min(currentRange.endExclusive, dest.first.endExclusive)
newRanges += current-range.second ..< newEnd-range.second to range.second + dest.second
current = newEnd
if (newEnd < dest.first.endExclusive) {
newRangesB[targetRangeIdx] = newEnd ..< dest.first.endExclusive to dest.second
targetRangeIdx++
} else {
newRangesB.removeAt(targetRangeIdx)
}
} else {
val newEnd = min(currentRange.endExclusive, dest.first.start)
newRanges += current-range.second ..< newEnd-range.second to range.second
current = newEnd
}
}
if (current < range.first.endExclusive) {
newRanges += current-range.second ..< range.first.endExclusive to range.second
}
}
newRanges.removeIf { it.first.isEmpty() }
run {
var i = 0
while (i < newRangesB.size) {
val r = newRangesB[i]
val pos = abs(newRanges.binarySearch(r.first.start))
if (r.first.isEmpty() || newRanges.size > pos && newRanges[pos].first.start < r.first.endExclusive) {
// there is some intersection
// new r range start after the other range
if (r.first.isEmpty() || r.first.start >= newRanges[pos].first.start) {
if (r.first.isEmpty() || r.first.endExclusive <= newRanges[pos].first.endExclusive) {
newRangesB.removeAt(i) // just throw it away
} else {
newRangesB[i] = newRanges[pos].first.endExclusive ..< r.first.endExclusive to r.second // trim it
}
} else { // the current range starts before the other, we cut it always
newRangesB[i] = r.first.start ..< newRanges[pos].first.start to r.second // this range is okay
// add the following part, next iteration can handle it.
newRangesB.add(i + 1, newRanges[pos].first.start ..< r.first.endExclusive to r.second)
i++
}
} else {
i++
}
}
}
newRanges += newRangesB // now, these shouldn't intersect
// make it sorted
newRanges.sortBy { it.first.start }
// optimise this mess
var i = 0
while (i < newRanges.size - 1) {
val current = newRanges[i]
val next by lazy { newRanges[i + 1] }
when {
current.second == BigInteger.ZERO || current.first.isEmpty() -> {
newRanges.removeAt(i)
}
current.first.endExclusive == next.first.start && current.second == next.second -> {
newRanges[i] = current.first.start ..< next.first.endExclusive to current.second
newRanges.removeAt(i + 1)
}
else -> i++
}
}
return RangeMapping(newRanges)
}
}
fun main() {
val lines = File("mapping.txt").readLines().filter { it.isNotBlank() }
val seeds = mutableListOf<BigInteger>()
val conversionSequence = mutableListOf<RangeMapping>()
// parse seeds
seeds += lines[0].split(" ").drop(1).map { BigInteger(it) }
val p = Regex("^(?<from>\\w+)-to-(?<to>\\w+) map:$")
var i = 1
while (lines.size > i) {
val rangeList = mutableListOf<Pair<OpenEndRange<BigInteger>, BigInteger>>()
while (lines.size > i && !p.matches(lines[i])) {
val l = lines[i].split(" ").map { BigInteger(it) }
rangeList += (l[1] ..< (l[1] + l[2])) to l[0] - l[1]
i++
}
if (rangeList.isNotEmpty()) {
conversionSequence += RangeMapping(rangeList)
}
i++
}
println(conversionSequence)
val min = seeds.map { conversionSequence[it] }.toList().min()
println("The lowest number Id is $min")
val range = conversionSequence.simplify()
val seedRanges = lines[0].split(" ").asSequence().drop(1).map { BigInteger(it) }.windowed(2, 2).map { (start, len) ->
start ..< start + len
}.sortedBy { it.start }.toList()
var minSeed = range[seedRanges[0].start]
(range.rangesList.asSequence().map { it.first.start } + seedRanges.asSequence().map { it.start }).filter {
it in seedRanges
}.forEach {
val new = conversionSequence[it]
if (new < minSeed) {
minSeed = new
}
}
println("Part2: $minSeed")
}
// This is the key for Part2
// Something is still not okay, but I don't care right now
fun List<RangeMapping>.simplify(): RangeMapping = fold(RangeMapping()) { acc, rangeMapping ->
acc + rangeMapping
}
operator fun List<RangeMapping>.get(i: BigInteger, debug: Boolean = false): BigInteger {
if (debug) print(i)
return fold(i) {acc, rangeMapping ->
rangeMapping[acc].also {
if(debug) print(" -> $it")
}
}.also {
if (debug) println()
}
}
| [
{
"class_path": "KosmX__advent-of-code23__ad01ab8/dev/kosmx/aoc23/garden/VirtualMemoryKt$main$$inlined$sortedBy$1.class",
"javap": "Compiled from \"Comparisons.kt\"\npublic final class dev.kosmx.aoc23.garden.VirtualMemoryKt$main$$inlined$sortedBy$1<T> implements java.util.Comparator {\n public dev.kosmx.ao... |
KosmX__advent-of-code23__ad01ab8/src/main/kotlin/dev/kosmx/aoc23/stars/StarField.kt | package dev.kosmx.aoc23.stars
import java.io.File
import java.math.BigInteger
import kotlin.math.abs
operator fun MutableList<MutableList<Char>>.get(x: Int, y: Int): Char {
return this[y][x]
}
fun <T> List<T>.allPairings() = sequence {
for (a in indices) {
for (b in a + 1 ..< size) {
yield(get(a) to get(b))
}
}
}
fun main() {
val starMap = File("stars.txt").useLines {
it.map { it.toCharArray().toMutableList() }.toMutableList()
}
// insert rows
for (x in starMap.indices.reversed()) {
if (starMap.all { it[x] == '.' }) {
starMap.forEach {
it.add(x, '+')
}
}
}
// insert columns
for (y in starMap.indices.reversed()) {
if (starMap[y].all { it == '.' || it == '+' }) {
starMap.add(y, MutableList(starMap[y].size) { '+' })
}
}
// print map for debug
//*
starMap.forEach {
println(it.joinToString(""))
}// */
// collect stars
val stars = mutableListOf<Pair<Int, Int>>()
for (y in starMap.indices) {
for (x in starMap[y].indices) {
if (starMap[x, y] == '#') {
stars.add(x to y)
}
}
}
val distances = stars.allPairings().map { (a, b) ->
abs(a.first - b.first) + abs(a.second - b.second)
}.toList()
println(distances.fold(BigInteger.ZERO) { acc, i -> acc + i.toBigInteger() })
// now part 2
val distances2 = stars.allPairings().map { (a, b) ->
var holes = 0
for (i in a.first progress b.first) {
if (starMap[i, a.second] == '+') {
holes++
}
}
for (i in a.second progress b.second) {
if (starMap[b.first, i] == '+') {
holes++
}
}
abs(a.first - b.first) + abs(a.second - b.second) + (holes*(1000000-2))
}.toList()
println(distances2.fold(BigInteger.ZERO) { acc, i -> acc + i.toBigInteger() })
}
private infix fun Int.progress(first: Int): IntProgression {
return if (this < first) {
first downTo this
} else {
first..this
}
}
| [
{
"class_path": "KosmX__advent-of-code23__ad01ab8/dev/kosmx/aoc23/stars/StarFieldKt.class",
"javap": "Compiled from \"StarField.kt\"\npublic final class dev.kosmx.aoc23.stars.StarFieldKt {\n public static final char get(java.util.List<java.util.List<java.lang.Character>>, int, int);\n Code:\n 0: a... |
KosmX__advent-of-code23__ad01ab8/src/main/kotlin/dev/kosmx/aoc23/springs/Sets.kt | package dev.kosmx.aoc23.springs
import java.io.File
import java.math.BigInteger
import javax.swing.Spring
fun <T> Collection<T>.subsets(k: Int): Sequence<Collection<T>> = sequence {
if (k > size) throw IllegalArgumentException("k must be smaller than the superset size")
if (k == size) yield(this@subsets)
else if (k > 0) {
subsets(k, this@subsets)
} else {
yield(emptyList()) // if request is 0 size subset(s), there is one and always one
}
}
private suspend fun <T> SequenceScope<Collection<T>>.subsets(k: Int, set: Collection<T>, subset: Collection<T> = emptyList()) {
if (k == 1) {
yieldAll(set.map { subset + it })
} else {
set.forEachIndexed { index, t ->
subsets(k - 1, set.drop(index + 1), subset + t)
}
}
}
// memoized solver
private class Variations(val rules: List<Int>, val springs: String) {
private val memory: MutableMap<Pair<Int, Int>, BigInteger> = mutableMapOf()
val variation: Int = springs.length - rules.sum() - rules.size + 1
val offset = List(rules.size) { index ->
rules.take(index).sum() + index
}.toIntArray()
init {
assert(offset.last() + rules.last() + variation == springs.length) // sanity check
}
// This should be not simply recursive, but as recursive as possible.
// That's how memoization became powerful
fun getVariations(rulePos: Int = 0, startPos: Int = 0): BigInteger {
assert(rulePos < rules.size)
return memory.getOrPut(rulePos to startPos) {
// step1: check if pos 0 is valid
val offs = offset[rulePos]
val zeroValid = (0 ..< rules[rulePos]).all {i ->
springs[offs + startPos + i] != '.'
}
&& (rulePos + 1 == rules.size || springs[offs + startPos + rules[rulePos]] != '#')
&& (rulePos != 0 || springs.substring(0 ..< startPos).all { it != '#' })
val size = if (zeroValid) {
if (rulePos == rules.size - 1) {
val remainingValid = (offs + startPos + rules[rulePos]..< springs.length).all { i ->
springs[i] != '#'
}
if (remainingValid) BigInteger.ONE else BigInteger.ZERO
} else {
getVariations(rulePos + 1, startPos)
}
} else BigInteger.ZERO
size + (if (startPos < variation && springs[offs + startPos] != '#' ) getVariations(rulePos, startPos + 1) else BigInteger.ZERO)
}
}
}
fun main() {
val games = File("springs.txt").readLines().filter { it.isNotBlank() }.map { it }
val p = Regex("#+")
val sums = games.map { game ->
var variations = 0
val (springs, rules) = game.split(" ").let {
it[0].let { s ->
List(5) {s}.joinToString("?")
} to it[1].let { s ->
val tmp = s.split(",").map { i -> i.toInt() }
(0 ..< 5).flatMap { tmp }
}
}
val v = Variations(rules, springs)
val variation = v.getVariations()
/* //
val check = run {
val totalWrong = rules.sum()
val missing = totalWrong - springs.count { it == '#' }
val options = springs.mapIndexedNotNull { index, c -> if (c == '?') index else null }
for (subset in options.subsets(missing)) {
val newSprings = springs.toCharArray()
for (index in subset) {
newSprings[index] = '#'
}
val matches = p.findAll(newSprings.joinToString("")).map { it.value.length }.toList()
if (matches == rules) {
variations++
}
}
variations
}
assert(check.toLong() == variation) // */
variation
}
println("Part1: $sums\nsum is ${sums.sum()}")
}
private fun Collection<BigInteger>.sum(): BigInteger = fold(BigInteger.ZERO) { acc, i -> acc + i}
| [
{
"class_path": "KosmX__advent-of-code23__ad01ab8/dev/kosmx/aoc23/springs/SetsKt$subsets$2.class",
"javap": "Compiled from \"Sets.kt\"\nfinal class dev.kosmx.aoc23.springs.SetsKt$subsets$2<T> extends kotlin.coroutines.jvm.internal.ContinuationImpl {\n java.lang.Object L$0;\n\n java.lang.Object L$1;\n\n j... |
KosmX__advent-of-code23__ad01ab8/src/main/kotlin/dev/kosmx/aoc23/cubes/Cubes.kt | package dev.kosmx.aoc23.cubes
import java.io.File
import kotlin.math.max
fun main() {
val games = File("cubes.txt").readLines().map { Game.of(it) }
println(games)
games.sumOf { game ->
val r = game.rounds.fold(Round()) { acc, round ->
Round(max(acc.red, round.red), max(acc.green, round.green), max(acc.blue, round.blue))
}
r.red * r.green * r.blue
}
.let { println(it) }
}
data class Round(val red: Int = 0, val green: Int = 0, val blue: Int = 0)
data class Game(
val gameId: Int,
val rounds: List<Round>,
) {
companion object {
private val linePattern = Regex("^Game (?<gameid>\\d+): (?<rounds>.+)\$")
private val redPattern = Regex("((?<num>\\d+) red)")
private val greenPattern = Regex("((?<num>\\d+) green)")
private val bluePattern = Regex("((?<num>\\d+) blue)")
fun of(line: String): Game {
val match = linePattern.find(line)!!
val gameId = match.groups["gameid"]!!.value.toInt()
val rounds = match.groups["rounds"]!!.value.split(";").map {
Round(
red = redPattern.find(it)?.groups?.get("num")?.value?.toInt() ?: 0,
green = greenPattern.find(it)?.groups?.get("num")?.value?.toInt() ?: 0,
blue = bluePattern.find(it)?.groups?.get("num")?.value?.toInt() ?: 0,
)
}
return Game(gameId, rounds)
}
}
}
| [
{
"class_path": "KosmX__advent-of-code23__ad01ab8/dev/kosmx/aoc23/cubes/CubesKt.class",
"javap": "Compiled from \"Cubes.kt\"\npublic final class dev.kosmx.aoc23.cubes.CubesKt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n ... |
KosmX__advent-of-code23__ad01ab8/src/main/kotlin/dev/kosmx/aoc23/graphs/BFS.kt | package dev.kosmx.aoc23.graphs
import java.io.File
import java.util.PriorityQueue
operator fun List<String>.get(x: Int, y: Int): Char = this.getOrNull(y)?.getOrNull(x) ?: '.'
operator fun List<String>.get(xy: Pair<Int, Int>): Char = this[xy.first, xy.second]
operator fun List<String>.contains(xy: Pair<Int, Int>): Boolean = xy.second in indices && xy.first in this[0].indices
val deltas = listOf(-1 to 0, 0 to -1, 1 to 0, 0 to 1)
val neighbours: Map<Char, Collection<Pair<Int, Int>>> = mapOf(
'.' to listOf(),
'S' to deltas,
'L' to listOf(0 to -1, 1 to 0),
'F' to listOf(1 to 0, 0 to 1),
'J' to listOf(0 to -1, -1 to 0),
'7' to listOf(-1 to 0, 0 to 1),
'-' to listOf(-1 to 0, 1 to 0),
'|' to listOf(0 to -1, 0 to 1)
)
fun main() {
val map = File("pipes.txt").readLines()
val start = map.indexOfFirst { 'S' in it }.let { y -> map[y].indexOf('S') to y }
println("Start at $start")
val lengths = mutableMapOf(start to 0)
val seen = PriorityQueue<Pair<Int, Int>> { a, b -> lengths[a]!!.compareTo(lengths[b]!!) }.apply {
this += start
}
// coordinate to vector
val directions: MutableMap<Pair<Int, Int>, Pair<Int, Int>> = mutableMapOf(start to (0 to 0))
// Let's BFS
piece@while (seen.any()) {
val head: Pair<Int, Int> = seen.remove()
for (delta in neighbours[map[head]]!!) {
val newPos = head + delta
if (newPos !in lengths && neighbours[map[newPos]]!!.contains(-delta)) {
lengths[newPos] = lengths[head]!! + 1
// update direction vectors for part2
directions[head] = directions.getOrDefault(head, 0 to 0) + delta
directions[newPos] = directions.getOrDefault(newPos, 0 to 0) + delta
seen += newPos
continue@piece
}
}
}
println("Part1: ${lengths.maxBy { (it.value+1)/2 }}")
// part 2, false for negative true for positive area
val areas = mutableMapOf<Pair<Int, Int>, Boolean>()
// last created list
var lastUpdate = listOf<Pair<Pair<Int, Int>, Boolean>>()
run { // Round 0
val new = mutableListOf<Pair<Pair<Int, Int>, Boolean>>()
for (y in map.indices) {
for (x in map[y].indices) {
if ((x to y) !in directions) {
deltas.asSequence().map { d -> d to (x to y) + d }
.mapNotNull { directions[it.second]?.let { (dx, dy) -> it.first * (dy to -dx) } }
.firstOrNull()?.let { side ->
if (side != 0) {
new += (x to y) to (side > 0)
}
}
}
}
}
lastUpdate = new
areas += lastUpdate
}
//*
while (lastUpdate.isNotEmpty()) {
val new = mutableListOf<Pair<Pair<Int, Int>, Boolean>>()
lastUpdate.forEach { (pos, side) ->
deltas.forEach { delta ->
val p = pos + delta
if (p !in directions && p !in areas && p in map) {
areas += p to side
new += p to side
}
}
}
lastUpdate = new
}// */
//*
for (y in map.indices) {
for (x in map[y].indices) {
val area = areas[x to y]
val areaCode = if (area != null) if(area) "I" else "O" else "X"
val direction = directions[x to y]?.let {
when(it) {
(1 to 0), (2 to 0) -> '→'
-1 to 0, -2 to 0 -> '←'
0 to 1, 0 to 2 -> '↓'
0 to -1, 0 to -2 -> '↑'
1 to 1, -> '↘'
1 to -1 -> '↗'
-1 to -1 -> '↖'
-1 to 1 -> '↙'
else -> '↻'
}
}
print((direction ?: areaCode).toString().padEnd(1, ' '))
}
println()
}// */
val groups = areas.asSequence().groupingBy { it.value }.eachCount()
println(groups)
}
// Math!
operator fun Pair<Int, Int>.plus(other: Pair<Int, Int>): Pair<Int, Int> = first + other.first to second + other.second
operator fun Pair<Int, Int>.minus(other: Pair<Int, Int>): Pair<Int, Int> = first - other.first to second - other.second
operator fun Pair<Int, Int>.unaryMinus(): Pair<Int, Int> = -first to -second
// Mathematical dot product
operator fun Pair<Int, Int>.times(other: Pair<Int, Int>): Int = this.first * other.first + this.second * other.second
| [
{
"class_path": "KosmX__advent-of-code23__ad01ab8/dev/kosmx/aoc23/graphs/BFSKt.class",
"javap": "Compiled from \"BFS.kt\"\npublic final class dev.kosmx.aoc23.graphs.BFSKt {\n private static final java.util.List<kotlin.Pair<java.lang.Integer, java.lang.Integer>> deltas;\n\n private static final java.util.M... |
Monkey-Maestro__earcut-kotlin-multiplatform__51396cd/src/commonMain/kotlin/urbanistic.transform/AnyToXY.kt | package urbanistic.transform
import kotlin.math.sqrt
class Point3(var x: Double = 0.0, var y: Double = 0.0, var z: Double = 0.0) {
fun set(x: Double, y: Double, z: Double) {
this.x = x
this.y = y
this.z = z
}
operator fun minus(v2: Point3): Point3 {
return Point3(x - v2.x, y - v2.y, z - v2.z)
}
operator fun plus(v2: Point3): Point3 {
return Point3(v2.x + x, v2.y + y, v2.z + z)
}
operator fun times(sc: Double): Point3 {
return Point3(x * sc, y * sc, z * sc)
}
operator fun div(sc: Double): Point3 {
return Point3(x / sc, y / sc, z / sc)
}
fun normalize() {
val d = sqrt(x * x + y * y + z * z)
if (d != 0.0) {
x /= d
y /= d
z /= d
}
}
fun cross(b: Point3): Point3 {
return Point3(
y * b.z - b.y * z,
z * b.x - b.z * x,
x * b.y - b.x * y
)
}
}
fun normal(vertices: DoubleArray): DoubleArray {
val ccw = true // counterclockwise normal direction
val points = arrayListOf<Point3>()
for (i in 0 until (vertices.size / 3)) {
points.add(Point3(vertices[i * 3], vertices[i * 3 + 1], vertices[i * 3 + 2]))
}
var m3: Point3 = points[points.size - 2]
var m2 = points[points.size - 1]
var c123 = Point3()
var v32: Point3
var v12: Point3
for (i in points.indices) {
val m1 = points[i]
v32 = m3 - m2
v12 = m1 - m2
c123 = if (!ccw) {
c123 + v32.cross(v12)
} else {
c123 + v12.cross(v32)
}
m3 = m2
m2 = m1
}
c123.normalize()
return doubleArrayOf(c123.x, c123.y, c123.z)
}
class AnyToXYTransform(nx: Double, ny: Double, nz: Double) {
protected var m00 = 0.0
protected var m01 = 0.0
protected var m02 = 0.0
protected var m10 = 0.0
protected var m11 = 0.0
protected var m12 = 0.0
protected var m20 = 0.0
protected var m21 = 0.0
protected var m22 = 0.0
/**
* normal must be normalized
*
* @param nx
* @param ny
* @param nz
*/
fun setSourceNormal(nx: Double, ny: Double, nz: Double) {
val h: Double
val f: Double
val hvx: Double
val vx: Double = -ny
val vy: Double = nx
val c: Double = nz
h = (1 - c) / (1 - c * c)
hvx = h * vx
f = if (c < 0) -c else c
if (f < 1.0 - 1.0E-4) {
m00 = c + hvx * vx
m01 = hvx * vy
m02 = -vy
m10 = hvx * vy
m11 = c + h * vy * vy
m12 = vx
m20 = vy
m21 = -vx
m22 = c
} else {
// if "from" and "to" vectors are nearly parallel
m00 = 1.0
m01 = 0.0
m02 = 0.0
m10 = 0.0
m11 = 1.0
m12 = 0.0
m20 = 0.0
m21 = 0.0
m22 = if (c > 0) {
1.0
} else {
-1.0
}
}
}
/**
* Assumes source normal is normalized
*/
init {
setSourceNormal(nx, ny, nz)
}
fun transform(p: Point3) {
val px: Double = p.x
val py: Double = p.y
val pz: Double = p.z
p.set(
m00 * px + m01 * py + m02 * pz,
m10 * px + m11 * py + m12 * pz,
m20 * px + m21 * py + m22 * pz
)
}
fun transform(data: DoubleArray) {
for (i in 0 until (data.size / 3)) {
val point = Point3(data[i * 3], data[i * 3 + 1], data[i * 3 + 2])
transform(point)
data[i * 3] = point.x
data[i * 3 + 1] = point.y
data[i * 3 + 2] = point.z
}
}
}
| [
{
"class_path": "Monkey-Maestro__earcut-kotlin-multiplatform__51396cd/urbanistic/transform/AnyToXYKt.class",
"javap": "Compiled from \"AnyToXY.kt\"\npublic final class urbanistic.transform.AnyToXYKt {\n public static final double[] normal(double[]);\n Code:\n 0: aload_0\n 1: ldc #9... |
CokeLee777__algorithm__919d623/src/main/kotlin/shortestpath/전보.kt | package shortestpath
import java.util.*
import kotlin.math.*
private const val INF = 1e9.toInt()
fun main(){
val sc = Scanner(System.`in`)
val n = sc.nextInt()
val m = sc.nextInt()
val start = sc.nextInt()
//최단거리 테이블 초기화
val distances = IntArray(n + 1) { INF }
//그래프 초기화
val graph = mutableListOf<MutableList<City>>()
for(i in 0..n){
graph.add(mutableListOf())
}
//그래프 입력받기
for(i in 0 until m){
val x = sc.nextInt()
val y = sc.nextInt()
val z = sc.nextInt()
graph[x].add(City(y, z))
}
fun dijkstra(start: Int){
val pq = PriorityQueue<City>()
//시작 노드 삽입 및 거리 0으로 초기화
pq.offer(City(start, 0))
distances[start] = 0
//큐가 빌 때까지 반복
while(!pq.isEmpty()){
val city = pq.poll()
val now = city.index
val distance = city.distance
//이미 처리된 도시라면 무시
if(distances[now] < distance) continue
//아니라면 연결되어있는 도시들 탐색
for(i in 0 until graph[now].size){
val cost = distances[now] + graph[now][i].distance
//더 거리가 짧다면 업데이트
if(cost < distances[graph[now][i].index]){
distances[graph[now][i].index] = cost
pq.offer(City(graph[now][i].index, cost))
}
}
}
}
dijkstra(start)
val cityCount = distances.count { it != INF && it != 0 }
val time = distances.maxBy { it != INF && it != 0 }
println("$cityCount $time")
}
data class City(val index: Int, val distance: Int): Comparable<City> {
override fun compareTo(other: City): Int = this.distance - other.distance
} | [
{
"class_path": "CokeLee777__algorithm__919d623/shortestpath/전보Kt.class",
"javap": "Compiled from \"전보.kt\"\npublic final class shortestpath.전보Kt {\n private static final int INF;\n\n public static final void main();\n Code:\n 0: new #8 // class java/util/Scanner\n ... |
CokeLee777__algorithm__919d623/src/main/kotlin/shortestpath/개선된_다익스트라_알고리즘.kt | package shortestpath
import java.util.*
import kotlin.Comparator
import kotlin.math.*
private const val INF = 1e9.toInt()
fun main(){
val sc = Scanner(System.`in`)
//노드의 개수와 간선의 개수 입력받기
val n = sc.nextInt()
val m = sc.nextInt()
//시작노드 번호 입력받기
val start = sc.nextInt()
//최단거리 테이블 초기화
val distances = IntArray(n + 1) { INF }
//그래프 입력받기
val graph = mutableListOf<MutableList<Node>>()
for(i in 0 .. n){
graph.add(mutableListOf())
}
for(i in 0 until m){
val a = sc.nextInt()
val b = sc.nextInt()
val cost = sc.nextInt()
graph[a].add(Node(b, cost))
}
fun dijkstra(start: Int){
val pq = PriorityQueue<Node>()
//시작 노드는 최단 경로를 0으로 설정
pq.add(Node(start, 0))
distances[start] = 0
//큐가 빌 때까지 반복
while(!pq.isEmpty()){
val node = pq.poll()
val now = node.index
val distance = node.distance
//현재 노드가 이미 처리된 적이 있다면 무시
if(distances[now] < distance) continue
//현재 노드와 연결된 다른 인접한 노드들을 확인
for(i in 0 until graph[now].size){
val cost = distance + graph[now][i].distance
//비용이 더 적게 든다면
if(cost < distances[graph[now][i].index]){
distances[graph[now][i].index] = cost
pq.offer(Node(graph[now][i].index, cost))
}
}
}
}
dijkstra(start)
for(i in 1 .. n){
when(distances[i]){
INF -> println("INFINITY")
else -> println(distances[i])
}
}
}
data class Node(val index: Int, val distance: Int): Comparable<Node> {
override fun compareTo(other: Node): Int = this.distance - other.distance
} | [
{
"class_path": "CokeLee777__algorithm__919d623/shortestpath/개선된_다익스트라_알고리즘Kt.class",
"javap": "Compiled from \"개선된_다익스트라_알고리즘.kt\"\npublic final class shortestpath.개선된_다익스트라_알고리즘Kt {\n private static final int INF;\n\n public static final void main();\n Code:\n 0: new #8 ... |
CokeLee777__algorithm__919d623/src/main/kotlin/dfsbfs/특정_거리의_도시_찾기.kt | package dfsbfs
import java.util.*
import kotlin.math.*
fun main(){
val sc = Scanner(System.`in`)
val n = sc.nextInt() //도시의 개수
val m = sc.nextInt() //도로의 개수
val k = sc.nextInt() //거리 정보
val x = sc.nextInt() //출발 도시의 번호
//최단거리 테이블 초기화
val distances = IntArray(n + 1) { 1e9.toInt() }
//그래프 초기화
val graph = mutableListOf<MutableList<City>>()
for(i in 0..n){
graph.add(mutableListOf())
}
//그래프 입력받기
for(i in 0 until m){
val a = sc.nextInt()
val b = sc.nextInt()
graph[a].add(City(b, 1))
}
fun dijkstra(start: Int){
val pq = PriorityQueue<City>()
//시작 도시 큐에 삽입
pq.offer(City(start, 0))
distances[start] = 0
//큐가 빌 때까지 반복
while(!pq.isEmpty()){
val now = pq.poll()
val cityNumber = now.number
val distance = now.distance
//이미 처리된 도시라면 무시
if(distances[cityNumber] < distance) continue
//현재 도시와 연결되어있는 도시 방문
for(city in graph[cityNumber]){
val cost = distance + city.distance
//거리가 더 가깝다면
if(cost < distances[city.number]){
pq.offer(City(city.number, cost))
distances[city.number] = cost
}
}
}
}
//다익스트라 최단경로 알고리즘 수행
dijkstra(x)
if(distances.count{ it == k } == 0) {
println(-1)
return
}
for(i in distances.indices){
if(distances[i] == k) println(i)
}
}
data class City(val number: Int, val distance: Int): Comparable<City> {
override fun compareTo(other: City): Int = this.distance - other.distance
}
| [
{
"class_path": "CokeLee777__algorithm__919d623/dfsbfs/특정_거리의_도시_찾기Kt.class",
"javap": "Compiled from \"특정_거리의_도시_찾기.kt\"\npublic final class dfsbfs.특정_거리의_도시_찾기Kt {\n public static final void main();\n Code:\n 0: new #8 // class java/util/Scanner\n 3: dup\n ... |
daniilsjb__advent-of-code-2021__bcdd709/src/main/kotlin/day09/Day09.kt | package day09
import java.io.File
fun main() {
val data = parse("src/main/kotlin/day09/Day09.txt")
val answer1 = part1(data.toHeightmap())
val answer2 = part2(data.toHeightmap())
println("🎄 Day 09 🎄")
println()
println("[Part 1]")
println("Answer: $answer1")
println()
println("[Part 2]")
println("Answer: $answer2")
}
private fun parse(path: String): Triple<Int, Int, List<Int>> {
val lines = File(path).readLines()
val width = lines.first().length
val height = lines.size
val locations = lines.flatMap { line ->
line.map(Char::digitToInt)
}
return Triple(width, height, locations)
}
private fun Triple<Int, Int, List<Int>>.toHeightmap() =
let { (width, height, locations) ->
Heightmap(width, height, locations.map(::Location))
}
private data class Heightmap(
val width: Int,
val height: Int,
val locations: List<Location>,
)
private data class Location(
val height: Int,
var visited: Boolean = false,
)
private operator fun Heightmap.get(x: Int, y: Int) =
locations[y * width + x]
private fun adjacentNodes(x: Int, y: Int, width: Int, height: Int) =
listOfNotNull(
if (x - 1 >= 0) x - 1 to y else null,
if (x + 1 < width) x + 1 to y else null,
if (y - 1 >= 0) x to y - 1 else null,
if (y + 1 < height) x to y + 1 else null,
)
private fun part1(heightmap: Heightmap): Int {
var sum = 0
val (width, height) = heightmap
for (y in 0 until height) {
for (x in 0 until width) {
val node = heightmap[x, y]
val isLowestPoint = adjacentNodes(x, y, width, height)
.all { (nx, ny) -> heightmap[nx, ny].height > node.height }
if (isLowestPoint) {
sum += node.height + 1
}
}
}
return sum
}
private fun Location.isInsideUnexploredBasin() =
!visited && height != 9
private fun Location.visit() {
visited = true
}
private fun countNodesInBasin(heightmap: Heightmap, x: Int, y: Int): Int {
val nodesToVisit = ArrayDeque(listOf(x to y))
var count = 0
while (nodesToVisit.isNotEmpty()) {
val (nx, ny) = nodesToVisit.removeLast()
val node = heightmap[nx, ny]
if (node.isInsideUnexploredBasin()) {
node.visit()
count += 1
adjacentNodes(nx, ny, heightmap.width, heightmap.height)
.forEach(nodesToVisit::addLast)
}
}
return count
}
private fun part2(heightmap: Heightmap): Int {
val basins = mutableListOf<Int>()
val (width, height) = heightmap
for (y in 0 until height) {
for (x in 0 until width) {
val node = heightmap[x, y]
if (node.isInsideUnexploredBasin()) {
basins.add(countNodesInBasin(heightmap, x, y))
}
}
}
return basins
.sortedDescending()
.take(3)
.fold(1, Int::times)
}
| [
{
"class_path": "daniilsjb__advent-of-code-2021__bcdd709/day09/Day09Kt.class",
"javap": "Compiled from \"Day09.kt\"\npublic final class day09.Day09Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String src/main/kotlin/day09/Day09.txt\n 2: invokestati... |
daniilsjb__advent-of-code-2021__bcdd709/src/main/kotlin/day08/Day08.kt | package day08
import java.io.File
fun main() {
val data = parse("src/main/kotlin/day08/Day08.txt")
val answer1 = part1(data)
val answer2 = part2(data)
println("🎄 Day 08 🎄")
println()
println("[Part 1]")
println("Answer: $answer1")
println()
println("[Part 2]")
println("Answer: $answer2")
}
private typealias Segments = Set<Char>
private typealias Entry = Pair<List<Segments>, List<Segments>>
private fun parse(path: String): List<Entry> =
File(path)
.readLines()
.map(String::toEntry)
private fun String.toEntry(): Entry =
this.split("|")
.map { part -> part
.trim()
.split(" ")
.map(String::toSet)
}
.let { (patterns, digits) -> Entry(patterns, digits) }
private fun part1(entries: List<Entry>) =
entries.sumOf { (_, digits) ->
digits.count { digit -> digit.size in arrayOf(2, 3, 4, 7) }
}
private fun part2(entries: List<Entry>) =
entries.sumOf { (patterns, digits) ->
// The approach of this solution is to directly determine which
// combinations of letters map to which digits.
val mappings = Array(10) { setOf<Char>() }
// First, we partition the unique digit patterns:
// 1) digit '1' maps to the pattern with length 2
// 2) digit '4' maps to the pattern with length 4
// 3) digit '7' maps to the pattern with length 3
// 4) digit '8' maps to the pattern with length 7
//
// Out of all digits, only 6 now remain:
// - 3 of them have length 5 and may be one of '2','3','5'
// - 3 of them have length 6 and may be one of '0','6','9'
val patternsWithLength5 = mutableListOf<Segments>()
val patternsWithLength6 = mutableListOf<Segments>()
for (pattern in patterns) {
when (pattern.size) {
2 -> mappings[1] = pattern
3 -> mappings[7] = pattern
4 -> mappings[4] = pattern
7 -> mappings[8] = pattern
5 -> patternsWithLength5.add(pattern)
6 -> patternsWithLength6.add(pattern)
}
}
// Second, we can observe that there are overlaps between digit
// patterns. We may use them to deduce new patterns from the
// ones we already know.
// 5) digit '6' maps to the pattern of length 6 that does not
// contain all segments of digit '1'.
mappings[6] = patternsWithLength6.first { pattern ->
!pattern.containsAll(mappings[1])
}
// 6) digit '9' maps to the pattern of length 6 that contains
// all segments of digit '4'
mappings[9] = patternsWithLength6.first { pattern ->
pattern.containsAll(mappings[4])
}
// 7) digit '0' maps to the last remaining pattern of length 6
mappings[0] = patternsWithLength6.first { pattern ->
pattern != mappings[6] && pattern != mappings[9]
}
// 8) digit '3' maps to the pattern of length 5 that contains
// both segments of digit '1'
mappings[3] = patternsWithLength5.first { pattern ->
pattern.containsAll(mappings[1])
}
// Here the situation becomes trickier. I could not find a fitting
// overlap to differentiate between digits 2 and 5, so we're going
// to use another trick. Each pattern contains a segment initially
// labelled 'f', except for digit '2'. If we find that segment,
// the '2' is simply the pattern without it.
val foundPatterns = mappings.filter(Set<Char>::isNotEmpty)
val f = ('a'..'g').first { label ->
foundPatterns.all { pattern -> pattern.contains(label) }
}
// 9) digit '2' maps to the pattern of length 5 that does not contain
// segment initially labelled 'f'
mappings[2] = patternsWithLength5.first { pattern ->
!pattern.contains(f)
}
// 10) digit '5' maps to the last remaining pattern of length 5
mappings[5] = patternsWithLength5.first { pattern ->
pattern != mappings[3] && pattern != mappings[2]
}
// At this point it is enough to apply the mapping to each output
// digit and combine them into an integer.
digits.fold(0) { acc: Int, digit ->
acc * 10 + mappings.indexOfFirst { it == digit }
}
}
| [
{
"class_path": "daniilsjb__advent-of-code-2021__bcdd709/day08/Day08Kt.class",
"javap": "Compiled from \"Day08.kt\"\npublic final class day08.Day08Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String src/main/kotlin/day08/Day08.txt\n 2: invokestati... |
daniilsjb__advent-of-code-2021__bcdd709/src/main/kotlin/day12/Day12.kt | package day12
import java.io.File
fun main() {
val data = parse("src/main/kotlin/day12/Day12.txt")
val answer1 = part1(data)
val answer2 = part2(data)
println("🎄 Day 12 🎄")
println()
println("[Part 1]")
println("Answer: $answer1")
println()
println("[Part 2]")
println("Answer: $answer2")
}
private typealias Label = String
private typealias Graph = Map<Label, List<Label>>
private fun parse(path: String): Graph {
val graph = mutableMapOf<Label, List<Label>>()
for (line in File(path).readLines()) {
val (lhs, rhs) = line.split("-")
graph.merge(lhs, listOf(rhs)) { a, b -> a + b }
graph.merge(rhs, listOf(lhs)) { a, b -> a + b }
}
return graph
}
// Depth-first count of all possible paths from a node to the end of the graph.
// When bias is set to true, a single small cave is allowed to be visited twice.
private fun countPaths(
graph: Graph,
current: Label,
visited: List<Label> = listOf(current),
bias: Boolean = false
): Int =
graph.getValue(current).sumOf { neighbour ->
if (neighbour == "end") {
1
} else if (neighbour == "start") {
0
} else if (neighbour.all(Char::isLowerCase)) {
if (!visited.contains(neighbour)) {
countPaths(graph, neighbour, visited + neighbour, bias)
} else if (bias) {
countPaths(graph, neighbour, visited + neighbour)
} else {
0
}
} else {
countPaths(graph, neighbour, visited + neighbour, bias)
}
}
fun part1(graph: Graph) =
countPaths(graph, "start")
fun part2(graph: Graph) =
countPaths(graph, "start", bias = true)
| [
{
"class_path": "daniilsjb__advent-of-code-2021__bcdd709/day12/Day12Kt.class",
"javap": "Compiled from \"Day12.kt\"\npublic final class day12.Day12Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String src/main/kotlin/day12/Day12.txt\n 2: invokestati... |
daniilsjb__advent-of-code-2021__bcdd709/src/main/kotlin/day15/Day15.kt | package day15
import java.io.File
import java.util.*
fun main() {
val data = parse("src/main/kotlin/day15/Day15.txt")
val answer1 = part1(data)
val answer2 = part2(data)
println("🎄 Day 15 🎄")
println()
println("[Part 1]")
println("Answer: $answer1")
println()
println("[Part 2]")
println("Answer: $answer2")
}
private data class Graph(
val size: Int,
val vertices: List<Int>,
)
private data class Vertex(
val x: Int,
val y: Int,
)
private data class Path(
val target: Vertex,
val distance: Int,
) : Comparable<Path> {
override fun compareTo(other: Path): Int =
distance.compareTo(other.distance)
}
private fun parse(path: String): Graph {
val lines = File(path).readLines()
val size = lines.size
val nodes = lines.flatMap { line ->
line.map(Char::digitToInt)
}
return Graph(size, nodes)
}
private fun Graph.distanceAt(vertex: Vertex): Int {
val dx = vertex.x / size
val dy = vertex.y / size
val px = vertex.x % size
val py = vertex.y % size
val combinedCost = vertices[py * size + px] + dx + dy
return (combinedCost - 1) % 9 + 1
}
private fun Vertex.edges(target: Vertex): List<Vertex> =
listOfNotNull(
if (x - 1 > 0) Vertex(x - 1, y) else null,
if (x + 1 <= target.x) Vertex(x + 1, y) else null,
if (y - 1 > 0) Vertex(x, y - 1) else null,
if (y + 1 <= target.y) Vertex(x, y + 1) else null,
)
private fun findPath(graph: Graph, target: Vertex): Int {
val source = Vertex(0, 0)
val distances = mutableMapOf(source to 0)
val frontier = PriorityQueue<Path>()
.apply { add(Path(target = source, distance = 0)) }
while (frontier.isNotEmpty()) {
val (vertex, distance) = frontier.poll()
if (vertex == target) {
return distance
}
if (distance > distances.getValue(vertex)) continue
for (edge in vertex.edges(target)) {
val distanceToEdge = distance + graph.distanceAt(edge)
if (distanceToEdge < distances.getOrDefault(edge, Int.MAX_VALUE)) {
distances[edge] = distanceToEdge
frontier.add(Path(edge, distanceToEdge))
}
}
}
error("Could not find the shortest path.")
}
private fun part1(graph: Graph): Int =
findPath(graph, target = Vertex(graph.size - 1, graph.size - 1))
private fun part2(graph: Graph): Int =
findPath(graph, target = Vertex(graph.size * 5 - 1, graph.size * 5 - 1))
| [
{
"class_path": "daniilsjb__advent-of-code-2021__bcdd709/day15/Day15Kt.class",
"javap": "Compiled from \"Day15.kt\"\npublic final class day15.Day15Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String src/main/kotlin/day15/Day15.txt\n 2: invokestati... |
daniilsjb__advent-of-code-2021__bcdd709/src/main/kotlin/day14/Day14.kt | package day14
import java.io.File
fun main() {
val (template, rules) = parse("src/main/kotlin/day14/Day14.txt")
val answer1 = part1(template, rules)
val answer2 = part2(template, rules)
println("🎄 Day 14 🎄")
println()
println("[Part 1]")
println("Answer: $answer1")
println()
println("[Part 2]")
println("Answer: $answer2")
}
private typealias Template = String
private typealias Rules = Map<String, Char>
private fun parse(path: String): Pair<Template, Rules> {
val (template, rulesPart) = File(path)
.readText()
.trim()
.split("""(\n\n)|(\r\n\r\n)""".toRegex())
val rules = rulesPart
.lines()
.associate(String::toRule)
return template to rules
}
private fun String.toRule() =
this.split(" -> ")
.let { (match, element) -> match to element.first() }
private fun expand(template: Template, rules: Rules, iterations: Int): Long {
val frequencies = template
.groupingBy { it }
.eachCount()
.mapValuesTo(mutableMapOf()) { (_, v) -> v.toLong() }
var patterns = template
.zipWithNext { a, b -> "$a$b" }
.groupingBy { it }
.eachCount()
.mapValues { (_, v) -> v.toLong() }
repeat(iterations) {
val next = mutableMapOf<String, Long>()
for ((pattern, count) in patterns) {
val element = rules.getValue(pattern)
val lhs = "${pattern[0]}$element"
val rhs = "$element${pattern[1]}"
next.merge(lhs, count, Long::plus)
next.merge(rhs, count, Long::plus)
frequencies.merge(element, count, Long::plus)
}
patterns = next
}
val max = frequencies.maxOf { it.value }
val min = frequencies.minOf { it.value }
return max - min
}
private fun part1(template: Template, rules: Rules) =
expand(template, rules, iterations = 10)
private fun part2(template: Template, rules: Rules) =
expand(template, rules, iterations = 40)
| [
{
"class_path": "daniilsjb__advent-of-code-2021__bcdd709/day14/Day14Kt$expand$1$3.class",
"javap": "Compiled from \"Day14.kt\"\nfinal class day14.Day14Kt$expand$1$3 extends kotlin.jvm.internal.FunctionReferenceImpl implements kotlin.jvm.functions.Function2<java.lang.Long, java.lang.Long, java.lang.Long> {\n... |
daniilsjb__advent-of-code-2021__bcdd709/src/main/kotlin/day13/Day13.kt | package day13
import java.io.File
import kotlin.math.abs
fun main() {
val (points, folds) = parse("src/main/kotlin/day13/Day13.txt")
val answer1 = part1(points, folds)
val answer2 = part2(points, folds)
println("🎄 Day 13 🎄")
println()
println("[Part 1]")
println("Answer: $answer1")
println()
println("[Part 2]")
println("Answer:\n$answer2")
}
private enum class Axis {
X, Y
}
private data class Point(
val x: Int,
val y: Int,
)
private data class Fold(
val axis: Axis,
val line: Int,
)
private data class Instructions(
val points: Set<Point>,
val folds: List<Fold>,
)
private fun parse(path: String): Instructions {
val (pointsPart, foldsPart) = File(path)
.readText()
.split("""(\n\n)|(\r\n\r\n)""".toRegex())
.map(String::trim)
val points = pointsPart
.lines()
.mapTo(HashSet(), String::toPoint)
val folds = foldsPart
.lines()
.map(String::toFold)
return Instructions(points, folds)
}
private fun String.toPoint(): Point =
this.split(",")
.let { (lhs, rhs) -> Point(lhs.toInt(), rhs.toInt()) }
private fun String.toFold(): Fold =
this.removePrefix("fold along ")
.split("=")
.let { (lhs, rhs) -> Fold(lhs.toAxis(), rhs.toInt()) }
private fun String.toAxis(): Axis =
when (this) {
"x" -> Axis.X
"y" -> Axis.Y
else -> error("Invalid folding axis")
}
private fun Point.reflect(axis: Axis, line: Int): Point =
when (axis) {
Axis.X -> Point(line - abs(x - line), y)
Axis.Y -> Point(x, line - abs(y - line))
}
private fun part1(points: Set<Point>, folds: List<Fold>): Int {
val (axis, line) = folds.first()
return points
.mapTo(HashSet()) { it.reflect(axis, line) }
.count()
}
private fun part2(points: Set<Point>, folds: List<Fold>): String {
val code = folds.fold(points) { dots, (axis, line) ->
dots.mapTo(HashSet()) { it.reflect(axis, line) }
}
return buildString {
for (y in 0 until 6) {
for (x in 0 until 40) {
if (x % 5 == 0) {
append(" ")
}
append(if (code.contains(Point(x, y))) '#' else ' ')
}
append('\n')
}
}
}
| [
{
"class_path": "daniilsjb__advent-of-code-2021__bcdd709/day13/Day13Kt$WhenMappings.class",
"javap": "Compiled from \"Day13.kt\"\npublic final class day13.Day13Kt$WhenMappings {\n public static final int[] $EnumSwitchMapping$0;\n\n static {};\n Code:\n 0: invokestatic #14 // Meth... |
daniilsjb__advent-of-code-2021__bcdd709/src/main/kotlin/day25/Day25.kt | package day25
import java.io.File
fun main() {
val data = parse("src/main/kotlin/day25/Day25.txt")
val answer = solve(data)
println("🎄 Day 25 🎄")
println("Answer: $answer")
}
private data class Area(
val width: Int,
val height: Int,
val cells: List<Char>,
)
private fun Area.getIndex(x: Int, y: Int): Int {
val xi = if (x >= width) {
x - width
} else if (x < 0) {
x + width
} else {
x
}
val yi = if (y >= height) {
y - height
} else if (y < 0) {
y + height
} else {
y
}
return yi * width + xi
}
private fun parse(path: String): Area =
File(path)
.readLines()
.let { lines ->
val height = lines.size
val width = lines[0].length
val cells = lines.flatMap(String::toList)
Area(width, height, cells)
}
private fun move(area: Area, herd: Char): Area {
val dx = if (herd == '>') 1 else 0
val dy = if (herd == '>') 0 else 1
val prev = area.cells
val next = prev.toMutableList()
for (y in 0 until area.height) {
for (x in 0 until area.width) {
val index = area.getIndex(x, y)
if (prev[index] == herd) {
val nextIndex = area.getIndex(x + dx, y + dy)
if (prev[nextIndex] == '.') {
next[nextIndex] = herd
next[index] = '.'
}
}
}
}
return area.copy(cells = next)
}
private fun step(previous: Area): Area {
return move(move(previous, '>'), 'v')
}
private fun solve(area: Area): Int {
return 1 + generateSequence(area) { step(it) }
.zipWithNext()
.indexOfFirst { (a1, a2) -> a1 == a2 }
}
| [
{
"class_path": "daniilsjb__advent-of-code-2021__bcdd709/day25/Day25Kt.class",
"javap": "Compiled from \"Day25.kt\"\npublic final class day25.Day25Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String src/main/kotlin/day25/Day25.txt\n 2: invokestati... |
daniilsjb__advent-of-code-2021__bcdd709/src/main/kotlin/day22/Day22.kt | package day22
import java.io.File
import kotlin.math.max
import kotlin.math.min
fun main() {
val data = parse("src/main/kotlin/day22/Day22.txt")
val answer1 = part1(data)
val answer2 = part2(data)
println("🎄 Day 22 🎄")
println()
println("[Part 1]")
println("Answer: $answer1")
println()
println("[Part 2]")
println("Answer: $answer2")
}
private data class Cuboid(
val x0: Int, val x1: Int,
val y0: Int, val y1: Int,
val z0: Int, val z1: Int,
val on: Boolean = true,
)
private fun Cuboid.overlap(other: Cuboid): Cuboid? {
val (ax0, ax1, ay0, ay1, az0, az1) = this
val (bx0, bx1, by0, by1, bz0, bz1) = other
val ox0 = max(ax0, bx0)
val ox1 = min(ax1, bx1)
val oy0 = max(ay0, by0)
val oy1 = min(ay1, by1)
val oz0 = max(az0, bz0)
val oz1 = min(az1, bz1)
return if (ox0 <= ox1 && oy0 <= oy1 && oz0 <= oz1) {
Cuboid(ox0, ox1, oy0, oy1, oz0, oz1)
} else {
null
}
}
/*
* A recursive solution based on the principle of exclusion and inclusion.
* To be fair, this is not the first solution I came up with. My initial idea
* was to maintain a list of non-overlapping cuboids by splitting every cuboid
* into smaller ones whenever overlaps occur, and then calculating the sum of
* their volumes.
*
* However, I found out about this principle and thought that this was a much
* neater way of implementing this, and it works quite fast, too. There is
* always something new to learn! :)
*/
private fun count(cuboids: List<Cuboid>): Long {
if (cuboids.isEmpty()) {
return 0
}
val (head, rest) = cuboids.first() to cuboids.drop(1)
return if (head.on) {
val intersections = rest.mapNotNull(head::overlap)
head.volume() + count(rest) - count(intersections)
} else {
count(rest)
}
}
private fun Cuboid.volume(): Long {
val xs = (x1 - x0 + 1).toLong()
val ys = (y1 - y0 + 1).toLong()
val zs = (z1 - z0 + 1).toLong()
return xs * ys * zs
}
private fun parse(path: String): List<Cuboid> =
File(path)
.readLines()
.map(String::toCuboid)
private fun String.toCuboid(): Cuboid {
val (valuePart, coordinatesPart) = this.split(" ")
val (x, y, z) = coordinatesPart
.split(",")
.map { it.drop(2) }
val (x0, x1) = x.toBounds()
val (y0, y1) = y.toBounds()
val (z0, z1) = z.toBounds()
val on = valuePart == "on"
return Cuboid(x0, x1, y0, y1, z0, z1, on)
}
private fun String.toBounds(): Pair<Int, Int> =
this.split("..")
.map(String::toInt)
.let { (a, b) -> a to b }
private fun part1(cuboids: List<Cuboid>): Long =
cuboids
.filter { (x0, x1, y0, y1, z0, z1) -> arrayOf(x0, x1, y0, y1, z0, z1).all { it in -50..50 } }
.let(::count)
private fun part2(cuboids: List<Cuboid>): Long =
count(cuboids)
| [
{
"class_path": "daniilsjb__advent-of-code-2021__bcdd709/day22/Day22Kt.class",
"javap": "Compiled from \"Day22.kt\"\npublic final class day22.Day22Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String src/main/kotlin/day22/Day22.txt\n 2: invokestati... |
daniilsjb__advent-of-code-2021__bcdd709/src/main/kotlin/day04/Day04.kt | package day04
import java.io.File
fun main() {
val (numbers, boards) = parse("src/main/kotlin/day04/Day04.txt")
val answer1 = part1(numbers, boards.map(List<Int>::toMutableList))
val answer2 = part2(numbers, boards.map(List<Int>::toMutableList))
println("🎄 Day 04 🎄")
println()
println("[Part 1]")
println("Answer: $answer1")
println()
println("[Part 2]")
println("Answer: $answer2")
}
private fun parse(path: String): Pair<List<Int>, List<List<Int>>> {
val entries = File(path)
.readText()
.trim()
.split("""\s+""".toRegex())
val numbers = entries.first()
.split(",")
.map(String::toInt)
val boards = entries.subList(1, entries.size)
.map(String::toInt)
.chunked(25)
return Pair(numbers, boards)
}
// We need to keep track of each board's state as the game progresses.
// The simplest and most effective approach would be to mutate the board itself.
private typealias Board = MutableList<Int>
// Boards have a sense of dimensionality, but all numbers are stored as flat lists.
// This structure allows us to fully describe a given number's position.
private data class Position(
val col: Int,
val row: Int,
val idx: Int,
)
// It is important to remember that a number is not guaranteed to appear on every
// board, therefore it may not always have a position.
private fun Board.findPosition(number: Int): Position? =
(0 until 5).firstNotNullOfOrNull { row ->
(0 until 5).firstNotNullOfOrNull { col ->
val index = row * 5 + col
if (this[index] == number)
Position(col, row, index)
else
null
}
}
// There are several approaches we could use to signify that a given number was
// marked, here's one of them: all numbers that appear on boards are always positive;
// therefore, we can use the sign of the number as the "marked" flag.
//
// Since a marked number is never needed again, we are free to discard it during
// the calculations and replace it with something completely different. This may
// not be the cleanest approach, but it lets us reuse space efficiently, avoid
// introducing extra data classes, etc.
private fun Board.mark(idx: Int) {
this[idx] = -1
}
// Naturally, the board may be put into a winning position only after a number
// was marked, and the number can only affect one row and one column. It's enough
// to just check these two, without bothering the rest of the board.
private fun Board.hasWon(col: Int, row: Int) =
(0 until 5).all { i -> this[row * 5 + i] < 0 } ||
(0 until 5).all { i -> this[i * 5 + col] < 0 }
// For the first part of the problem, the algorithm is straightforward:
// we mark each number, in turn, on each board, until we encounter a winning
// position, in which case the result is directly returned.
private fun part1(numbers: List<Int>, boards: List<Board>) =
numbers.firstNotNullOf { number ->
boards.firstNotNullOfOrNull { board ->
board.findPosition(number)?.let { (col, row, idx) ->
board.mark(idx)
if (board.hasWon(col, row))
number * board.sumOf { i -> if (i >= 0) i else 0 }
else
null
}
}
}
// For the second part, the approach is a little more involved: we go through
// each board and find the first winning turn (each board is guaranteed to win
// at some point); we then find the victory that happened on the latest turn
// and use it to calculate the final result.
private data class Victory(
val turn: Int,
val number: Int,
val board: Board
)
private fun part2(numbers: List<Int>, boards: List<Board>) =
boards.map { board ->
numbers.indexOfFirst { number ->
board.findPosition(number)?.let { (col, row, idx) ->
board.mark(idx)
board.hasWon(col, row)
} ?: false
}
.let { turn -> Victory(turn, numbers[turn], board) }
}
.maxByOrNull(Victory::turn)!!
.let { (_, number, board) ->
number * board.sumOf { i -> if (i >= 0) i else 0 }
} | [
{
"class_path": "daniilsjb__advent-of-code-2021__bcdd709/day04/Day04Kt.class",
"javap": "Compiled from \"Day04.kt\"\npublic final class day04.Day04Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String src/main/kotlin/day04/Day04.txt\n 2: invokestati... |
daniilsjb__advent-of-code-2021__bcdd709/src/main/kotlin/day03/Day03.kt | package day03
import java.io.File
fun main() {
val data = parse("src/main/kotlin/day03/Day03.txt")
val answer1 = part1(data)
val answer2 = part2(data)
println("🎄 Day 03 🎄")
println()
println("[Part 1]")
println("Answer: $answer1")
println()
println("[Part 2]")
println("Answer: $answer2")
}
private fun parse(path: String): List<String> =
File(path).readLines()
private fun part1(lines: List<String>): Int {
val bitCount = lines[0].length
val gamma = (0 until bitCount)
.map { index -> lines.count { line -> line[index] == '1' } }
.map { count -> if (2 * count > lines.size) 1 else 0 }
.fold(0) { acc, bit -> (acc shl 1) or bit }
val epsilon = gamma xor ((1 shl bitCount) - 1)
return gamma * epsilon
}
private fun part2(lines: List<String>): Int {
val calculateRating = { criteria: Char, complement: Char ->
var index = 0
val values = lines.toMutableList()
while (values.size != 1) {
val count = values.count { it[index] == '1' }
val bit = if (2 * count >= values.size) criteria else complement
values.removeAll { it[index] == bit }
++index
}
values.first().toInt(radix = 2)
}
val o2 = calculateRating('1', '0')
val co2 = calculateRating('0', '1')
return o2 * co2
}
| [
{
"class_path": "daniilsjb__advent-of-code-2021__bcdd709/day03/Day03Kt.class",
"javap": "Compiled from \"Day03.kt\"\npublic final class day03.Day03Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String src/main/kotlin/day03/Day03.txt\n 2: invokestati... |
daniilsjb__advent-of-code-2021__bcdd709/src/main/kotlin/day02/Day02.kt | package day02
import java.io.File
fun main() {
val data = parse("src/main/kotlin/day02/Day02.txt")
val answer1 = part1(data)
val answer2 = part2(data)
println("🎄 Day 02 🎄")
println()
println("[Part 1]")
println("Answer: $answer1")
println()
println("[Part 2]")
println("Answer: $answer2")
}
private enum class Action {
Up, Down, Forward,
}
private data class Command(
val action: Action,
val number: Int,
)
private fun parse(path: String): List<Command> =
File(path)
.readLines()
.map(String::toCommand)
private fun String.toCommand(): Command {
val (actionPart, numberPart) = this.split(" ")
val action = when (actionPart) {
"up" -> Action.Up
"down" -> Action.Down
"forward" -> Action.Forward
else -> error("Invalid action")
}
val number = numberPart.toInt()
return Command(action, number)
}
private fun part1(commands: List<Command>): Int {
var (horizontal, depth) = arrayOf(0, 0)
for ((action, number) in commands) {
when (action) {
Action.Up -> depth -= number
Action.Down -> depth += number
Action.Forward -> horizontal += number
}
}
return horizontal * depth
}
private fun part2(commands: List<Command>): Int {
var (horizontal, depth, aim) = arrayOf(0, 0, 0)
for ((action, number) in commands) {
when (action) {
Action.Up -> aim -= number
Action.Down -> aim += number
Action.Forward -> {
horizontal += number
depth += aim * number
}
}
}
return horizontal * depth
}
| [
{
"class_path": "daniilsjb__advent-of-code-2021__bcdd709/day02/Day02Kt.class",
"javap": "Compiled from \"Day02.kt\"\npublic final class day02.Day02Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String src/main/kotlin/day02/Day02.txt\n 2: invokestati... |
daniilsjb__advent-of-code-2021__bcdd709/src/main/kotlin/day05/Day05.kt | package day05
import java.io.File
import kotlin.math.min
import kotlin.math.max
fun main() {
val data = parse("src/main/kotlin/day05/Day05.txt")
val answer1 = part1(data)
val answer2 = part2(data)
println("🎄 Day 05 🎄")
println()
println("[Part 1]")
println("Answer: $answer1")
println()
println("[Part 2]")
println("Answer: $answer2")
}
private data class Point(
val x: Int,
val y: Int,
)
private data class Line(
val x1: Int,
val y1: Int,
val x2: Int,
val y2: Int,
)
private fun parse(path: String): List<Line> =
File(path)
.readLines()
.map(String::toLine)
private fun String.toLine(): Line {
val regex = """(\d+),(\d+) -> (\d+),(\d+)""".toRegex()
val (x1, y1, x2, y2) = regex.find(this)!!
.destructured
.toList()
.map(String::toInt)
return Line(x1, y1, x2, y2)
}
private fun part1(lines: List<Line>) =
lines.asSequence()
.flatMap { (x1, y1, x2, y2) ->
if (y1 == y2) {
(min(x1, x2)..max(x1, x2)).asSequence().map { x -> Point(x, y1) }
} else if (x1 == x2) {
(min(y1, y2)..max(y1, y2)).asSequence().map { y -> Point(x1, y) }
} else {
sequenceOf()
}
}
.groupingBy { it }
.eachCount()
.count { (_, frequency) -> frequency >= 2 }
private fun part2(lines: List<Line>) =
lines.asSequence()
.flatMap { (x1, y1, x2, y2) ->
if (y1 == y2) {
(min(x1, x2)..max(x1, x2)).asSequence().map { x -> Point(x, y1) }
} else if (x1 == x2) {
(min(y1, y2)..max(y1, y2)).asSequence().map { y -> Point(x1, y) }
} else {
val xd = if (x2 > x1) 1 else -1
val yd = if (y2 > y1) 1 else -1
(0..(max(x1, x2) - min(x1, x2))).asSequence()
.map { delta -> Point(x1 + delta * xd, y1 + delta * yd) }
}
}
.groupingBy { it }
.eachCount()
.count { (_, frequency) -> frequency >= 2 } | [
{
"class_path": "daniilsjb__advent-of-code-2021__bcdd709/day05/Day05Kt$part1$$inlined$groupingBy$1.class",
"javap": "Compiled from \"_Sequences.kt\"\npublic final class day05.Day05Kt$part1$$inlined$groupingBy$1 implements kotlin.collections.Grouping<day05.Point, day05.Point> {\n final kotlin.sequences.Sequ... |
daniilsjb__advent-of-code-2021__bcdd709/src/main/kotlin/day20/Day20.kt | package day20
import java.io.File
fun main() {
val data = parse("src/main/kotlin/day20/Day20.txt")
val answer1 = part1(data)
val answer2 = part2(data)
println("🎄 Day 20 🎄")
println()
println("[Part 1]")
println("Answer: $answer1")
println()
println("[Part 2]")
println("Answer: $answer2")
}
private fun parse(path: String): Enhance {
val (algorithm, bits) = File(path)
.readText()
.trim()
.split("""(\n\n)|(\r\n\r\n)""".toRegex())
return Enhance(bits.toImage(), algorithm)
}
private fun String.toImage(): Image =
this.lines()
.let { lines -> lines.joinToString(separator = "") to lines.size }
.let { (bitmap, size) -> Image(bitmap, size) }
private data class Enhance(
val image: Image,
val algorithm: String,
)
private data class Image(
val bitmap: String,
val size: Int,
val fill: Char = '.',
)
private fun <T> Iterable<T>.cross(other: Iterable<T>): List<Pair<T, T>> =
this.flatMap { a -> other.map { b -> a to b } }
private operator fun Image.get(x: Int, y: Int): Char =
if (x in 0 until size && y in 0 until size) {
bitmap[y * size + x]
} else {
fill
}
private fun Image.adjacent(x: Int, y: Int): List<Char> =
(-1..1).cross(-1..1)
.map { (dy, dx) -> this[x + dx, y + dy] }
private fun Image.indexAt(x: Int, y: Int): Int =
this.adjacent(x, y)
.fold(0) { acc, c -> acc shl 1 or if (c == '#') 1 else 0 }
private fun Enhance.step(): Enhance {
// After each iteration, the image expands one unit in each direction,
// increasing the length of its sides by 2 in total.
val size = image.size + 2
val side = -1 until image.size + 1
val bitmap = (side).cross(side)
.map { (y, x) -> image.indexAt(x, y) }
.map { index -> algorithm[index] }
.joinToString(separator = "")
val fill = if (image.fill == '.') {
algorithm.first()
} else {
algorithm.last()
}
return this.copy(image = Image(bitmap, size, fill))
}
private fun Enhance.perform(iterations: Int): Image =
generateSequence(this) { p -> p.step() }
.elementAt(iterations).image
private fun Enhance.countAfter(iterations: Int): Int =
perform(iterations)
.bitmap.count { pixel -> pixel == '#' }
private fun part1(enhance: Enhance): Int =
enhance.countAfter(iterations = 2)
private fun part2(enhance: Enhance): Int =
enhance.countAfter(iterations = 50)
| [
{
"class_path": "daniilsjb__advent-of-code-2021__bcdd709/day20/Day20Kt.class",
"javap": "Compiled from \"Day20.kt\"\npublic final class day20.Day20Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String src/main/kotlin/day20/Day20.txt\n 2: invokestati... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.