path stringlengths 5 169 | owner stringlengths 2 34 | repo_id int64 1.49M 755M | is_fork bool 2 classes | languages_distribution stringlengths 16 1.68k ⌀ | content stringlengths 446 72k | issues float64 0 1.84k | main_language stringclasses 37 values | forks int64 0 5.77k | stars int64 0 46.8k | commit_sha stringlengths 40 40 | size int64 446 72.6k | name stringlengths 2 64 | license stringclasses 15 values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/main/kotlin/cloud/dqn/leetcode/sudoku2/Board.kt | aviuswen | 112,305,062 | false | null | package cloud.dqn.leetcode.sudoku2
class Board {
val grids: Array<Array<DigitValue>>
/**
* By default create an empty board
*/
private constructor() {
grids = Array(
size = BOARD_SIZE,
init = { DigitValue.rowFactory(BOARD_SIZE) }
)
}
constructor(leetcodeBoard: Array<CharArray>): this() {
leetcodeBoard.forEachIndexed { rowIndex, row ->
row.forEachIndexed { colIndex, char ->
CHAR_TO_VALID_INT[char]?.let { num ->
grids[rowIndex][colIndex].setSolved(num)
}
}
}
reduceAllPossibleFromSolved()
}
constructor(board: Board) {
grids = Array(
size = BOARD_SIZE,
init = { index ->
DigitValue.rowFactory(board.grids[index])
}
)
reduceAllPossibleFromSolved()
}
fun allDone(): Boolean {
var done = true
BOARD_INDEX_RANGE.forEach { row ->
BOARD_INDEX_RANGE.forEach { col ->
if (grids[row][col].isNotSolved()) {
done = false
}
}
}
return done
}
/********************************************************
* SOLVERS
********************************************************/
fun solve(targetCopy: Array<CharArray>): Boolean {
var solvedOne = false
do {
solvedOne = solveAll()
} while(solvedOne)
// copy over to targetCopy
BOARD_INDEX_RANGE.forEach { row ->
BOARD_INDEX_RANGE.forEach { col ->
val num = grids[row][col].getSolved() ?: -1
targetCopy[row][col] = INT_TO_CHAR[num] ?: DigitValue.WILDCARD_CHAR
}
}
return allDone() && (findInvalid() == null)
}
/**
* Iterates through all values once and tries to solve it
* @return true if one value was solved
*/
private fun solveAll(): Boolean {
var solvedOne = false
BOARD_INDEX_RANGE.forEach { row ->
BOARD_INDEX_RANGE.forEach { col ->
val foundOne = solver_boxAndLine(row, col)
if (foundOne) {
findInvalid()?.let {
// println("invalid")
}
}
solvedOne = solvedOne || foundOne
}
}
return solvedOne
}
/**
* for that location, and for each possibility:
* if it cannot be anywhere else in a 3x3 box ||
* it cannot be in any other row or column then
* that location can only be that value from the possibility
* @return true if solved
*/
private fun solver_boxAndLine(row: Int, col: Int): Boolean {
val digitValue = grids[row][col]
if (digitValue.isNotSolved()) {
collectAllPossibles(row, col).forEach { possibleSet ->
digitValue.forEach {
if (!possibleSet.contains(it)) {
digitValue.setSolved(it)
reduceAllPossibleFromSolved()
return true
}
}
}
}
return false
}
/**
* Iterates through all non solved cells and tries
* a possible value for a given cell and sees if it is
* solvable.
*/
fun guessOneAndSeeIfItWorks(targetCopy: Array<CharArray>): Board? {
BOARD_INDEX_RANGE.forEach { row ->
BOARD_INDEX_RANGE.forEach { col ->
val digitValue = grids[row][col]
if (digitValue.isNotSolved()) {
digitValue.forEach {
val testBoard = Board(this)
testBoard.grids[row][col].setSolved(it)
val solvable = testBoard.solve(targetCopy)
if (solvable) {
return testBoard
}
}
}
}
}
return null
}
/********************************************************
* REDUCTION OF POSSIBLES BASED UPON SOLVED ONLY
********************************************************/
private fun reduceAllPossibleFromSolved() {
var newSolved = false
BOARD_INDEX_RANGE.forEach { rowIndex ->
BOARD_INDEX_RANGE.forEach { colIndex ->
val digitValue = grids[rowIndex][colIndex]
if (digitValue.isNotSolved()) {
digitValue.removeAllPossible(collectAllSolved(rowIndex, colIndex))
// you just solved something, you need to update the ones
// you just updated
newSolved = newSolved || digitValue.isSolved()
}
}
}
if (newSolved) {
reduceAllPossibleFromSolved()
}
}
private fun collectAllSolved(row: Int, col: Int): DigitSet {
val solutions = DigitSet.emptyDigitSet()
// collect solved for containing 3x3 box
val rowOrigin = (row / 3) * 3
val colOrigin = (col / 3) * 3
THREE_TIMES.forEach { rowOffset ->
THREE_TIMES.forEach { colOffset ->
val digitValue = grids[rowOrigin + rowOffset][colOrigin + colOffset]
digitValue.getSolved()?.let { solutions.add(it) }
}
}
BOARD_INDEX_RANGE.forEach {
// collect solved by Column
grids[it][col].getSolved()?.let {
solutions.add(it)
}
// collect solved by Row
grids[row][it].getSolved()?.let {
solutions.add(it)
}
}
return solutions
}
/********************************************************
* POSSIBLES COLLECTORS
********************************************************/
private fun collectAllPossibles(rowExclude: Int, colExclude: Int): Array<DigitSet> {
val possibles = Array(3, {DigitSet.emptyDigitSet()})
// collect possibles from contain 3x3 box
val rowOrigin = (rowExclude / 3) * 3
val colOrigin = (colExclude / 3) * 3
THREE_TIMES.forEach { rowOffset ->
THREE_TIMES.forEach { colOffset ->
val rowActual = rowOrigin + rowOffset
val colActual = colOrigin + colOffset
if (rowActual != rowExclude || colActual != colExclude) {
val digitValue = grids[rowActual][colActual]
if (digitValue.isNotSolved()) {
possibles[0].addAll(digitValue)
}
}
}
}
BOARD_INDEX_RANGE.forEach {
// collect possibles from column
if (it != rowExclude) {
val digitValue = grids[it][colExclude]
if (digitValue.isNotSolved()) {
possibles[1].addAll(digitValue)
}
}
// collect possibles from row
if (it != colExclude) {
val digitValue = grids[rowExclude][it]
if (digitValue.isNotSolved()) {
possibles[2].addAll(digitValue)
}
}
}
return possibles
}
/********************************************************
* FIND INVALIDATIONS
********************************************************/
fun findInvalid(): Pair<Int, Int>? {
BOARD_INDEX_RANGE.forEach { index ->
(findInvalidPairByCol(index) ?: findInvalidPairByRow(index))?.let {
return it
}
}
return findInvalidBy3x3Box() ?: findByEmptyPossibles()
}
private fun findInvalidBy3x3Box(): Pair<Int, Int>? {
THREE_TIMES.forEach { rowFactor -> THREE_TIMES.forEach { colFactor ->
val allValues = DigitSet.emptyDigitSet()
THREE_TIMES.forEach{ rowOffSet -> THREE_TIMES.forEach { colOffset ->
val rowActual = rowFactor * 3 + rowOffSet
val colActual = colFactor * 3 + colOffset
val digitValue = grids[rowActual][colActual]
digitValue.getSolved()?.let {
if (allValues.contains(it)) {
return (rowActual to colActual)
} else {
allValues.add(it)
}
}
} }
} }
return null
}
private fun findInvalidPairByCol(col: Int): Pair<Int, Int>? {
val allValues = DigitSet.emptyDigitSet()
BOARD_INDEX_RANGE.forEach { row ->
grids[row][col].getSolved()?.let {
if (allValues.contains(it)) {
return (row to col)
} else {
allValues.add(it)
}
}
}
return null
}
private fun findInvalidPairByRow(row: Int): Pair<Int, Int>? {
val allValues = DigitSet.emptyDigitSet()
val workingRow = grids[row]
workingRow.forEachIndexed { col, value ->
value.getSolved()?.let {
if (allValues.contains(it)) {
return (row to col)
} else {
allValues.add(it)
}
}
}
return null
}
private fun findByEmptyPossibles(): Pair<Int, Int>? {
BOARD_INDEX_RANGE.forEach { row ->
BOARD_INDEX_RANGE.forEach { col ->
val digitValue = grids[row][col]
if (digitValue.isNotValid()) {
return (row to col)
}
}
}
return null
}
/********************************************************
* COMPANION OBJECTS
********************************************************/
companion object {
val BOARD_SIZE = 9
private val CHAR_TO_VALID_INT = hashMapOf(
'1' to 1, '2' to 2, '3' to 3,
'4' to 4, '5' to 5, '6' to 6,
'7' to 7, '8' to 8, '9' to 9
)
private val INT_TO_CHAR = hashMapOf(
1 to '1', 2 to '2', 3 to '3',
4 to '4', 5 to '5', 6 to '6',
7 to '7', 8 to '8', 9 to '9'
)
private val DEFAULT_STRING_BUILDER_CAPACITY = 256
private val THIRD_TIME = 2
private val THREE_TIMES = 0..THIRD_TIME
val BOARD_INDEX_RANGE = 0..(BOARD_SIZE - 1)
private val HORIZONTAL_DIVIDER = "---------------------\n"
}
/********************************************************
* TO STRING
********************************************************/
override fun toString(): String {
val s = StringBuilder(DEFAULT_STRING_BUILDER_CAPACITY)
BOARD_INDEX_RANGE.forEach {
appendRow(s, it)
if (it == 2 || it == 5) {
s.append(HORIZONTAL_DIVIDER)
}
}
return s.toString()
}
private fun appendRow(s: StringBuilder, startRow: Int) {
val row: Array<DigitValue> = grids[startRow]
THREE_TIMES.forEach {
append3GridValues(s, row, it * 3)
if (it != THIRD_TIME) {
s.append(" | ")
}
}
s.append("\n")
}
private fun append3GridValues(s: StringBuilder, row: Array<DigitValue>, startCol: Int) {
s.append("${row[startCol]} ${row[startCol + 1]} ${row[startCol + 2]}")
}
/********************************************************
*
*
* NESTED SUB CLASSES
*
*
********************************************************/
class DigitSet: Iterable<Int> {
private var internalSet: Int
private var size: Int
constructor(setFull: Boolean = true) {
if (setFull) {
size = MAX_SIZE
internalSet = NINE_ONES
} else {
size = 0
internalSet = EMPTY_SET
}
}
constructor(digitSet: DigitSet) {
this.internalSet = digitSet.internalSet
this.size = digitSet.size
}
fun getSize() = size
fun isEmpty() = size == 0
fun getFirst(): Int {
return getRandom() ?: -1
}
fun getRandom(): Int? {
this.forEach { return it }
return null
}
fun add(value: Int): Boolean {
var valueWasMissing = false
if (validDigit(value)) {
val internalValue = convertToInternal(value)
valueWasMissing = !containsInternal(internalValue)
if (valueWasMissing) {
size++
}
internalSet = internalSet or internalValue
}
return valueWasMissing
}
fun addAll(iterable: Iterable<Int>) = iterable.forEach { add(it) }
fun remove(value: Int): Boolean {
var setChanged = false
if (validDigit(value)) {
val internalValue = convertToInternal(value)
setChanged = containsInternal(internalValue)
if (setChanged) {
size--
}
internalSet = internalSet and (internalValue.inv())
}
return setChanged
}
fun removeAll(iterable: Iterable<Int>) = iterable.forEach { remove(it) }
fun clear() {
size = 0
internalSet = EMPTY_SET
}
fun contains(value: Int): Boolean = containsInternal(convertToInternal(value))
private fun containsInternal(internalValue: Int): Boolean {
return (internalValue and internalSet) > 0
}
private fun convertToInternal(value: Int): Int = (1 shl (value - 1))
override fun iterator(): Iterator<Int> {
return DigitIterator(internalSet)
}
private class DigitIterator: Iterator<Int> {
val set: Int
var nextValue: Int
constructor(set: Int) {
this.set = set
nextValue = 1
walkNextValueToExisting()
}
private fun walkNextValueToExisting() {
while (nextValue <= 9) {
if (1.shl(nextValue - 1).and(set) > 0) {
break
} else {
nextValue++
}
}
}
override fun hasNext(): Boolean = (nextValue <= MAX_SIZE)
override fun next(): Int {
val element = nextValue++
walkNextValueToExisting()
return element
}
}
companion object {
private val ALL_ONES: Int = (-1) ushr 1
private val NINE_ONES: Int = 511 //(Math.pow(2.0, 9.0) - 1).toInt()
private val EMPTY_SET: Int = 0
private val MAX_SIZE = 9
private fun validDigit(digit: Int): Boolean {
return digit >= 1 && digit <= MAX_SIZE
}
fun emptyDigitSet(): DigitSet {
return DigitSet(setFull = false)
}
}
}
class DigitValue: Iterable<Int> {
private var solved: Int
private val possible: DigitSet
constructor() {
solved = UNSOLVED_VALUE
possible = DigitSet()
}
constructor(digitValue: DigitValue) {
solved = digitValue.solved
possible = DigitSet(digitValue.possible)
}
fun isNotValid(): Boolean = (possible.isEmpty() && isNotSolved())
fun setSolved(num: Int) { solved = num }
fun getSolved(): Int? = if (isSolved()) solved else null
fun isSolved(): Boolean = (solved != UNSOLVED_VALUE)
fun isNotSolved(): Boolean = !isSolved()
fun removeAllPossible(iterable: Iterable<Int>) {
possible.removeAll(iterable)
if (possible.getSize() == 1 && isNotSolved()) {
solved = possible.getFirst()
}
}
override fun iterator(): Iterator<Int> {
return possible.iterator()
}
override fun toString(): String = getSolved()?.toString() ?: WILDCARD_STR
companion object {
val UNSOLVED_VALUE = 0
val WILDCARD_CHAR = '.'
private val WILDCARD_STR = WILDCARD_CHAR.toString()
fun rowFactory(columnCount: Int): Array<DigitValue> {
return Array(
size = columnCount,
init = { DigitValue() }
)
}
fun rowFactory(values: Array<DigitValue>): Array<DigitValue> {
return Array(
size = values.size,
init = { DigitValue(values[it]) }
)
}
}
}
} | 0 | Kotlin | 0 | 0 | 23458b98104fa5d32efe811c3d2d4c1578b67f4b | 17,161 | cloud-dqn-leetcode | No Limit Public License |
src/main/kotlin/codes/jakob/aoc/shared/UndirectedGraph.kt | The-Self-Taught-Software-Engineer | 433,875,929 | false | {"Kotlin": 56277} | package codes.jakob.aoc.shared
import java.util.*
class UndirectedGraph<T>(input: List<Pair<T, T>>) {
private val edges: Set<UndirectedEdge<T>> = buildEdges(input)
private val adjacentVertices: Map<Vertex<T>, Set<Vertex<T>>> = buildAdjacentVertices(edges)
val vertices: Set<Vertex<T>> = edges.flatMap { setOf(it.a, it.b) }.toSet()
fun findBestPath(
from: Vertex<T>,
to: Vertex<T>,
heuristic: (T) -> Long,
cost: (T, T) -> Long,
): List<Vertex<T>> {
require(from in vertices && to in vertices) { "The given start and end points are unknown" }
// For node n, gScores[n] is the cost of the cheapest path from start to n currently known.
val gScores: MutableMap<Vertex<T>, Long> =
mutableMapOf<Vertex<T>, Long>().withDefault { Long.MAX_VALUE }.also { it[from] = 0L }
// For node n, fScores[n] == gScores[n] + heuristic(n). fScores[n] represents our current best guess as to
// how short a path from start to finish can be if it goes through n.
val fScores: MutableMap<Vertex<T>, Long> =
mutableMapOf<Vertex<T>, Long>().withDefault { Long.MAX_VALUE }.also { it[from] = heuristic(from.value) }
// The priority queue of discovered nodes that may need to be (re-)expanded.
val comparator = Comparator { o1: Vertex<T>, o2: Vertex<T> ->
fScores.getValue(o1).compareTo(fScores.getValue(o2))
}
val open: PriorityQueue<Vertex<T>> = PriorityQueue(comparator).also { it.add(from) }
// For node n, cameFrom[n] is the node immediately preceding it on the cheapest path from start
// to n currently known.
val cameFrom: MutableMap<Vertex<T>, Vertex<T>> = mutableMapOf()
while (open.isNotEmpty()) {
val current: Vertex<T> = open.remove()
if (current == to) return reconstructPath(current, cameFrom)
for (adjacent: Vertex<T> in getAdjacent(current)) {
// gScore is the distance from start to the adjacent through current
val gScore: Long = gScores.getValue(current) + cost(current.value, adjacent.value)
if (gScore < gScores.getValue(adjacent)) {
cameFrom[adjacent] = current
gScores[adjacent] = gScore
fScores[adjacent] = gScore + heuristic(adjacent.value)
if (adjacent !in open) open.add(adjacent)
}
}
}
error("There is no path between $from and $to")
}
private fun reconstructPath(last: Vertex<T>, cameFrom: Map<Vertex<T>, Vertex<T>>): List<Vertex<T>> {
val path: MutableList<Vertex<T>> = mutableListOf(last)
var current: Vertex<T> = last
while (current in cameFrom.keys) {
current = cameFrom[current]!!
path.add(current)
}
return path.reversed()
}
fun findAllPaths(
from: Vertex<T>,
to: Vertex<T>,
canVisit: (Vertex<T>, Collection<Vertex<T>>) -> Boolean,
): Set<List<Vertex<T>>> {
require(from in vertices && to in vertices) { "The given start and end points are unknown" }
val allPaths: MutableSet<List<Vertex<T>>> = mutableSetOf()
val visited: MutableList<Vertex<T>> = mutableListOf<Vertex<T>>().also { it.add(from) }
findAllPaths(from, to, visited, allPaths, canVisit)
return allPaths
}
private fun findAllPaths(
from: Vertex<T>,
to: Vertex<T>,
visited: MutableList<Vertex<T>>,
allPaths: MutableSet<List<Vertex<T>>>,
canVisit: (Vertex<T>, Collection<Vertex<T>>) -> Boolean,
) {
val visitedFiltered: Collection<Vertex<T>> = visited.filterNot { canVisit(it, visited) }
val vertices: Collection<Vertex<T>> = getAdjacent(visited.last()).filterNot { it in visitedFiltered }
if (to in vertices) {
visited.add(to)
allPaths.add(visited.toList())
visited.removeLast()
}
for (current: Vertex<T> in vertices) {
if (current == to) continue
visited.add(current)
findAllPaths(from, to, visited, allPaths, canVisit)
visited.removeLast()
}
}
private fun getAdjacent(vertex: Vertex<T>): Set<Vertex<T>> {
return adjacentVertices[vertex]!!
}
private fun buildEdges(input: List<Pair<T, T>>): Set<UndirectedEdge<T>> {
return input.map { (from: T, to: T) -> UndirectedEdge(Vertex(from), Vertex(to)) }.toSet()
}
private fun buildAdjacentVertices(edges: Set<UndirectedEdge<T>>): Map<Vertex<T>, Set<Vertex<T>>> {
val adjacentVertices: MutableMap<Vertex<T>, MutableSet<Vertex<T>>> = mutableMapOf()
for (edge in edges) {
adjacentVertices.putIfAbsent(edge.a, mutableSetOf())
adjacentVertices.getValue(edge.a).add(edge.b)
adjacentVertices.putIfAbsent(edge.b, mutableSetOf())
adjacentVertices.getValue(edge.b).add(edge.a)
}
return adjacentVertices
}
data class Vertex<T>(
val value: T
)
data class UndirectedEdge<T>(
val a: Vertex<T>,
val b: Vertex<T>,
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as UndirectedEdge<*>
if (a != other.a) return false
if (b != other.b) return false
if (a != other.b) return false
if (b != other.a) return false
return true
}
override fun hashCode(): Int {
return 31 * (a.hashCode() + b.hashCode())
}
}
}
| 0 | Kotlin | 0 | 6 | d4cfb3479bf47192b6ddb9a76b0fe8aa10c0e46c | 5,751 | advent-of-code-2021 | MIT License |
src/main/kotlin/Puzzle21.kt | namyxc | 317,466,668 | false | null | object Puzzle21 {
@JvmStatic
fun main(args: Array<String>) {
val input = Puzzle21::class.java.getResource("puzzle21.txt").readText()
val allergicData = AllergicData(input)
println(allergicData.countNonAllergicIngredients())
println(allergicData.listIngredientsByAllergens())
}
class AllergicData(input: String){
private val allergenCanBeInFoods = mutableMapOf<String, Set<String>>()
private val allIngredients = mutableListOf<String>()
init {
input.split("\n").forEach { line ->
val ingredientsAndAllergens = line
.replace("(", "")
.replace(")", "")
.replace(",", "")
.split(" contains ")
val ingredients = ingredientsAndAllergens.first().split(" ")
allIngredients.addAll(ingredients)
val ingredientsSet = ingredients.toSet()
val allergens = ingredientsAndAllergens.last().split(" ")
allergens.forEach { allergen ->
if (allergenCanBeInFoods.containsKey(allergen)){
allergenCanBeInFoods[allergen] = allergenCanBeInFoods[allergen]!!.intersect(ingredientsSet)
}else{
allergenCanBeInFoods[allergen] = ingredientsSet
}
}
}
while (allergenCanBeInFoods.any { it.value.size > 1 }){
val knownAllergens = allergenCanBeInFoods.filter { it.value.size == 1 }
val unknownAllergenKeys = allergenCanBeInFoods.filter { allergenWithFoodList ->
allergenWithFoodList.value.size > 1
}.keys
unknownAllergenKeys.forEach { unknownAllergen ->
knownAllergens.forEach { knownAllergen->
allergenCanBeInFoods[unknownAllergen] = allergenCanBeInFoods[unknownAllergen]!!.minus(knownAllergen.value.first())
}
}
}
}
fun countNonAllergicIngredients() = allIngredients.count { ingredient -> allergenCanBeInFoods.none { allergen -> allergen.value.contains(ingredient) } }
fun listIngredientsByAllergens() = allergenCanBeInFoods.toList().sortedBy { (key, _) -> key }
.joinToString(",") { it.second.first() }
}
} | 0 | Kotlin | 0 | 0 | 60fa6991ac204de6a756456406e1f87c3784f0af | 2,402 | adventOfCode2020 | MIT License |
src/main/kotlin/aoc23/Day18.kt | tom-power | 573,330,992 | false | {"Kotlin": 254717, "Shell": 1026} | package aoc23
import aoc23.Day18Domain.DigPlan
import aoc23.Day18Domain.Lagoon
import aoc23.Day18Parser.toLagoon
import common.Monitoring
import common.Space2D
import common.Year23
import kotlin.math.absoluteValue
object Day18 : Year23 {
fun List<String>.part1(): Long =
toLagoon(planFromColours = false)
.calculateArea()
fun List<String>.part2(): Long =
toLagoon(planFromColours = true)
.calculateArea()
}
object Day18Domain {
data class Lagoon(
val digPlans: List<DigPlan>,
val start: PointOfLong = PointOfLong(x = 0, y = 0),
) {
private val trenchLength: Long = digPlans.sumOf { it.distance }
private val trenchVertices: Set<PointOfLong> =
digPlans.fold(setOf(start)) { acc, digPlan ->
acc + acc.last().move(digPlan.direction, digPlan.distance)
}
fun calculateArea(): Long {
val boundaryCount: Long = trenchLength
val area: Long = areaFrom(trenchVertices)
val interiorCount: Long = interiorCountFrom(area, boundaryCount)
return (boundaryCount + interiorCount)
}
// https://en.wikipedia.org/wiki/Pick%27s_theorem
private fun interiorCountFrom(area: Long, boundary: Long): Long = area - (boundary / 2L) + 1L
// https://en.wikipedia.org/wiki/Shoelace_formula
private fun areaFrom(vertices: Set<PointOfLong>): Long =
(vertices
.zipWithNext { a, b ->
(a.x * b.y) - (a.y * b.x)
}.sum() / 2).absoluteValue
}
data class DigPlan(
val direction: Space2D.Direction,
val distance: Long,
)
data class PointOfLong(
val x: Long, val y: Long
) {
fun move(direction: Space2D.Direction, by: Long = 1): PointOfLong =
when (direction) {
Space2D.Direction.North -> copy(y = y + by)
Space2D.Direction.East -> copy(x = x + by)
Space2D.Direction.South -> copy(y = y - by)
Space2D.Direction.West -> copy(x = x - by)
}
}
}
object Day18Parser {
fun List<String>.toLagoon(planFromColours: Boolean = false): Lagoon =
Lagoon(
digPlans = map {
it.split(" ").take(3).let { (direction, distance, colour) ->
when {
planFromColours -> {
val instruction =
colour
.replace("(", "")
.replace(")", "")
DigPlan(
direction = instruction.toDirectionChar().toDirection(),
distance = instruction.toDistance(),
)
}
else -> {
DigPlan(
direction = direction.toDirection(),
distance = distance.toLong(),
)
}
}
}
},
)
private fun String.toDirectionChar(): String =
when (last().digitToInt()) {
0 -> "R"
1 -> "D"
2 -> "L"
3 -> "U"
else -> error("bad")
}
@OptIn(ExperimentalStdlibApi::class)
private fun String.toDistance(): Long = drop(1).take(5).hexToLong()
private fun String.toDirection(): Space2D.Direction =
when (this) {
"U" -> Space2D.Direction.North
"D" -> Space2D.Direction.South
"R" -> Space2D.Direction.East
"L" -> Space2D.Direction.West
else -> error("Unknown direction: $this")
}
}
| 0 | Kotlin | 0 | 0 | baccc7ff572540fc7d5551eaa59d6a1466a08f56 | 3,847 | aoc | Apache License 2.0 |
src/leetcode/juneChallenge2020/weektwo/LargestDivisibleSubset.kt | adnaan1703 | 268,060,522 | false | null | package leetcode.juneChallenge2020.weektwo
import utils.print
fun main() {
largestDivisibleSubset(intArrayOf()).print()
largestDivisibleSubset(intArrayOf(1, 2, 3)).print()
largestDivisibleSubset(intArrayOf(1, 2, 4, 8)).print()
}
fun largestDivisibleSubset(nums: IntArray): List<Int> {
if (nums.isEmpty())
return listOf()
val dp = Array(nums.size) { 0 to 0 }
var maxPair = -1 to -1
nums.sort()
nums.forEachIndexed { index, it ->
var maxx = 0 to -1
for (i in 0 until index) {
if (it % nums[i] == 0 && dp[i] > maxx)
maxx = dp[i].first to i
}
dp[index] = maxx.first + 1 to maxx.second
if (dp[index] > maxPair) maxPair = dp[index].first to index
}
val ans = mutableListOf<Int>()
var index = maxPair.second
while (index != -1) {
ans.add(nums[index])
index = dp[index].second
}
return ans
}
private operator fun Pair<Int, Int>.compareTo(arg: Pair<Int, Int>): Int {
return this.first - arg.first
}
| 0 | Kotlin | 0 | 0 | e81915db469551342e78e4b3f431859157471229 | 1,048 | KotlinCodes | The Unlicense |
src/main/kotlin/org/agoranomic/assessor/lib/voting_strength/VotingStrengthModification.kt | AgoraNomic | 98,589,628 | false | {"Kotlin": 1516634, "HTML": 3937} | package org.agoranomic.assessor.lib.voting_strength
import kotlinx.collections.immutable.ImmutableMap
import kotlinx.collections.immutable.toImmutableMap
data class VotingStrengthModificationDescription(
val readable: String,
val kind: String,
val parameters: ImmutableMap<String, String>
) {
companion object {
fun empty() = VotingStrengthModificationDescription(
readable = "No change.",
kind = "unchanged",
parameters = emptyMap()
)
}
constructor(
readable: String,
kind: String,
parameters: Map<String, String>
) : this(
readable,
kind,
parameters.toImmutableMap()
)
}
interface VotingStrengthModification {
val description: VotingStrengthModificationDescription
fun transform(old: VotingStrength): VotingStrength
}
data class AdditiveVotingStrengthModification(
private val addend: VotingStrengthDifference,
override val description: VotingStrengthModificationDescription
) : VotingStrengthModification {
companion object {
fun defaultDescriptionFor(addend: VotingStrengthDifference): VotingStrengthModificationDescription {
return VotingStrengthModificationDescription(
readable = "Voting strength increased by $addend",
kind = "addition",
parameters = mapOf(
"amount" to addend.toString()
)
)
}
}
override fun transform(old: VotingStrength): VotingStrength {
return old + addend
}
}
data class ClampVotingStrengthModification(
private val minValue: VotingStrength?,
private val maxValue: VotingStrength?
) : VotingStrengthModification {
init {
if (minValue != null && maxValue != null) require(minValue <= maxValue)
}
override val description: VotingStrengthModificationDescription
get() = createDescription()
private fun createDescription(): VotingStrengthModificationDescription {
if (minValue == null && maxValue == null) return VotingStrengthModificationDescription.empty()
val readable = when {
minValue != null && maxValue != null -> "Clamped between $minValue and $maxValue."
minValue != null -> "Capped at minimum of $minValue."
maxValue != null -> "Capped at maximum of $maxValue."
else -> throw IllegalStateException()
}
return VotingStrengthModificationDescription(
readable = readable,
kind = "clamp",
parameters = mapOf(
"min" to (minValue?.toString() ?: "none"),
"max" to (maxValue?.toString() ?: "none")
)
)
}
override fun transform(old: VotingStrength): VotingStrength {
if (minValue != null && old < minValue) return minValue
if (maxValue != null && old > maxValue) return maxValue
return old
}
}
| 0 | Kotlin | 0 | 1 | a27c3b7d6fcba013983bf103854c6a60c800077c | 2,973 | assessor | MIT License |
src/main/kotlin/org/kotrix/rational/Rational.kt | JarnaChao09 | 285,169,397 | false | {"Kotlin": 446442, "Jupyter Notebook": 26378} | package org.kotrix.rational
import kotlin.math.absoluteValue
import kotlin.math.sign
sealed interface Rational {
val numerator: UInt
val denominator: UInt
val sign: Sign
}
fun Rational(numerator: Int, denominator: Int = 1, sign: Sign? = null): Rational {
val numeratorAbsolute = numerator.absoluteValue
val denominatorAbsolute = denominator.absoluteValue
val determinedSign: Sign = sign ?: when (numerator.sign * denominator.sign) {
1 -> Sign.Positive
-1 -> Sign.Negative
else -> { // must be 0
when {
numerator.sign != 0 -> {
when (numerator.sign) {
1 -> Sign.Positive
-1 -> Sign.Negative
else -> throw Exception("Unreachable")
}
}
denominator.sign != 0 -> {
when (denominator.sign) {
1 -> Sign.Positive
-1 -> Sign.Negative
else -> throw Exception("Unreachable")
}
}
numerator.sign == denominator.sign -> Sign.Positive // number is NaN just return dummy sign
else -> throw Exception("Cannot determine sign of ($numerator / $denominator)")
}
}
}
return when {
numeratorAbsolute == 0 -> {
if (denominatorAbsolute != 0) {
when (determinedSign) {
Sign.Positive -> Zero.Positive
Sign.Negative -> Zero.Negative
}
} else {
NaN
}
}
numeratorAbsolute == 1 && denominatorAbsolute == 0 -> {
when (determinedSign) {
Sign.Positive -> Infinity.Positive
Sign.Negative -> Infinity.Negative
}
}
numeratorAbsolute == denominatorAbsolute -> {
when (determinedSign) {
Sign.Positive -> One.Positive
Sign.Negative -> One.Negative
}
}
else -> {
createRational(
numeratorAbsolute,
denominatorAbsolute,
determinedSign
)
}
}
}
fun Rational(unsignedNum: UInt, unsignedDen: UInt, sign: Sign): Rational {
return when {
unsignedNum == 0U -> {
if (unsignedDen != 0U) {
when (sign) {
Sign.Positive -> Zero.Positive
Sign.Negative -> Zero.Negative
}
} else {
NaN
}
}
unsignedNum == 1U && unsignedDen == 0U -> {
when (sign) {
Sign.Positive -> Infinity.Positive
Sign.Negative -> Infinity.Negative
}
}
unsignedNum == unsignedDen -> {
when (sign) {
Sign.Positive -> One.Positive
Sign.Negative -> One.Negative
}
}
else -> {
// TODO find way to make createRational work with UInt
createRational(
unsignedNum.toInt(),
unsignedDen.toInt(),
sign
)
}
}
}
fun Rational(value: String): Rational {
return parseString(value.replace(" ", "")).let { (n, d, s) ->
Rational(n, d, s)
}
}
fun <T : Number> Rational(number: T): Rational {
return parseNumber(number).let { (n, d, s) ->
Rational(n, d, s)
}
}
private fun createRational(numAbs: Int, denAbs: Int, sign: Sign): Rational =
simplify(numAbs, denAbs).let { (n, d) ->
RationalImpl(n.toUInt(), d.toUInt(), sign)
}
private fun parseNumber(num: Number) = parseString(num.toString())
private fun parseString(str: String): Triple<Int, Int, Sign> {
val sign = when {
str.startsWith("+") -> Sign.Positive
str.startsWith("-") -> Sign.Negative
else -> Sign.Positive
}
if ("." !in str) {
return Triple(str.toInt(), 1, sign)
}
val numStr = str.replace(".", "")
val numOfDecimalPlaces = str.substringAfter(".").length
return Triple(numStr.toInt(), 10.pow(numOfDecimalPlaces), sign)
}
private fun simplify(num: Int, den: Int): Pair<Int, Int> {
val numFactors = num.trialDivision()
val denFactors = den.trialDivision()
val newFactors = mutableMapOf<Int, Int>()
for (p in numFactors.keys union denFactors.keys) {
val n: Int = numFactors.getOrDefault(p, 0)
val d: Int = denFactors.getOrDefault(p, 0)
val new = n - d
newFactors[p] = new
}
var newNum = 1
var newDen = 1
for (i in newFactors.entries) {
when {
i.value == 0 -> {
continue
}
i.value > 0 -> {
newNum *= i.key.pow(i.value)
}
i.value < 0 -> {
newDen *= i.key.pow(-i.value)
}
}
}
return newNum to newDen
} | 0 | Kotlin | 1 | 5 | c5bb19457142ce1f3260e8fed5041a4d0c77fb14 | 5,060 | Kotrix | MIT License |
year2017/src/main/kotlin/net/olegg/aoc/year2017/day11/Day11.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2017.day11
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.utils.Vector2D
import net.olegg.aoc.year2017.DayOf2017
import kotlin.math.abs
/**
* See [Year 2017, Day 11](https://adventofcode.com/2017/day/11)
*/
object Day11 : DayOf2017(11) {
override fun first(): Any? {
return data
.split(",")
.fold(Vector2D()) { acc, value ->
acc + when (value) {
"nw" -> Vector2D(-1, 0)
"n" -> Vector2D(0, 1)
"ne" -> Vector2D(1, 1)
"sw" -> Vector2D(-1, -1)
"s" -> Vector2D(0, -1)
"se" -> Vector2D(1, 0)
else -> Vector2D()
}
}
.let {
maxOf(abs(it.x), abs(it.y), abs(it.x - it.y))
}
}
override fun second(): Any? {
return data
.split(",")
.fold(Vector2D() to 0) { (pos, speed), value ->
val next = pos + when (value) {
"nw" -> Vector2D(-1, 0)
"n" -> Vector2D(0, 1)
"ne" -> Vector2D(1, 1)
"sw" -> Vector2D(-1, -1)
"s" -> Vector2D(0, -1)
"se" -> Vector2D(1, 0)
else -> Vector2D()
}
val dist = maxOf(speed, abs(next.x), abs(next.y), abs(next.x - next.y))
return@fold next to dist
}
.second
}
}
fun main() = SomeDay.mainify(Day11)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 1,319 | adventofcode | MIT License |
src/main/kotlin/Day08.kt | N-Silbernagel | 573,145,327 | false | {"Kotlin": 118156} | fun main() {
val input = readFileAsList("Day08")
println(Day08.part1(input))
println(Day08.part2(input))
}
object Day08 {
fun part1(input: List<String>): Int {
var visibleItems = 0
for ((rowIndex, row) in input.withIndex()) {
for ((itemIndex, tree) in row.withIndex()) {
val isVisible = checkVisibility(itemIndex, rowIndex, input, row, tree.digitToInt())
if (isVisible) {
visibleItems++
}
}
}
return visibleItems
}
fun part2(input: List<String>): Int {
var bestScenicScore = 0
for ((rowIndex, row) in input.withIndex()) {
for ((treeIndex, tree) in row.withIndex()) {
val itemIsOnEdge = treeIndex == 0 || rowIndex == 0 || rowIndex == input.size - 1 || treeIndex == row.length - 1
if (itemIsOnEdge) {
// 0 scenic score because of multiplication -> not gonna be the biggest
continue
}
val scenicScore = calculateScenicScore(treeIndex, row, tree.digitToInt(), rowIndex, input)
if (scenicScore > bestScenicScore) {
bestScenicScore = scenicScore
}
}
}
return bestScenicScore
}
private fun checkVisibility(
itemIndex: Int,
rowIndex: Int,
input: List<String>,
row: String,
item: Int
): Boolean {
val itemIsOnEdge = itemIndex == 0 || rowIndex == 0 || rowIndex == input.size - 1 || itemIndex == row.length - 1
if (itemIsOnEdge) {
return true
}
var visibleFromRight = true
var visibleFromLeft = true
for ((otherRowItemIndex, otherRowItem) in row.withIndex()) {
if (otherRowItem.digitToInt() < item) continue
if (otherRowItemIndex < itemIndex) {
visibleFromLeft = false
}
if (otherRowItemIndex > itemIndex) {
visibleFromRight = false
}
if (!visibleFromLeft && !visibleFromRight) {
break
}
}
var visibleFromTop = true
var visibleFromBottom = true
for ((otherColItemIndex, innerRow) in input.withIndex()) {
val otherColItem = innerRow[itemIndex]
if (otherColItem.digitToInt() < item) continue
if (otherColItemIndex < rowIndex) {
visibleFromTop = false
}
if (otherColItemIndex > rowIndex) {
visibleFromBottom = false
}
if (!visibleFromTop && !visibleFromBottom) {
break
}
}
return visibleFromTop || visibleFromRight || visibleFromBottom || visibleFromLeft
}
private fun calculateScenicScore(
treeIndex: Int,
row: String,
tree: Int,
rowIndex: Int,
input: List<String>
): Int {
var scenicScoreLeft = 0
for (otherRowItemIndex in (treeIndex - 1) downTo 0) {
val otherRowItem = row[otherRowItemIndex]
scenicScoreLeft++
if (otherRowItem.digitToInt() >= tree) {
break
}
}
var scenicScoreRight = 0
for (otherRowItemIndex in (treeIndex + 1) until row.length) {
val otherRowItem = row[otherRowItemIndex]
scenicScoreRight++
if (otherRowItem.digitToInt() >= tree) {
break
}
}
var scenicScoreTop = 0
for (otherColItemIndex in (rowIndex - 1) downTo 0) {
val otherColItem = input[otherColItemIndex][treeIndex]
scenicScoreTop++
if (otherColItem.digitToInt() >= tree) {
break
}
}
var scenicScoreBottom = 0
for (otherColItemIndex in (rowIndex + 1) until input.size) {
val otherColItem = input[otherColItemIndex][treeIndex]
scenicScoreBottom++
if (otherColItem.digitToInt() >= tree) {
break
}
}
return scenicScoreTop * scenicScoreRight * scenicScoreBottom * scenicScoreLeft
}
}
| 0 | Kotlin | 0 | 0 | b0d61ba950a4278a69ac1751d33bdc1263233d81 | 4,285 | advent-of-code-2022 | Apache License 2.0 |
src/day10/Day10.kt | PoisonedYouth | 571,927,632 | false | {"Kotlin": 27144} | package day10
import readInput
fun main() {
fun part1(input: List<String>): Int {
val steps = listOf(20, 60, 100, 140, 180, 220)
var x = 1
var cycle = 1
var sum = 0
fun processInstruction() {
if (cycle in steps) {
sum += cycle * x
}
cycle++
}
input.forEach { line ->
processInstruction()
if (line.startsWith("addx")) {
processInstruction()
x += line.substringAfter(" ").toInt()
}
}
return sum
}
fun part2(input: List<String>) {
val lines = listOf(40, 80, 120, 160, 200, 240)
var x = 1
var cycle = 1
fun processInstruction() {
val sprite = (cycle - 1) % 40
if (sprite in (x - 1..x + 1)) {
print("#")
} else {
print(".")
}
if (cycle in lines) {
println()
}
cycle++
}
input.forEach { line ->
processInstruction()
if (line.startsWith("addx")) {
processInstruction()
x += line.substringAfter(" ").toInt()
}
}
}
val input = readInput("day10/Day10")
println(part1(input))
part2(input)
}
| 0 | Kotlin | 1 | 0 | dbcb627e693339170ba344847b610f32429f93d1 | 1,366 | advent-of-code-kotlin-2022 | Apache License 2.0 |
kotlin/src/main/kotlin/AoC_Day25.kt | sviams | 115,921,582 | false | null | object AoC_Day25 {
// Yet another concession to mutability...first effort with immutable tape took 27s :(
data class CpuState(val tape: MutableMap<Int, Int>, val nextOp: Char, val cursor: Int, val pc: Long, val stopCond: Long)
fun parseInput(input: List<String>) : Pair<CpuState, Map<Char, (CpuState) -> CpuState>> {
val startOp = input.first().split(" ")[3].toCharArray().first()
val stopCond = input.get(1).split(" ")[5].toLong()
val opInput = input.drop(3).chunked(10).associate { it.first().split(" ")[2].toCharArray().first() to parseOp(it.drop(1)) }
return Pair(CpuState(HashMap(5000), startOp, 0, 0, stopCond), opInput)
}
fun parseSetValue(line: String) : Int = line.trimStart().split(" ")[4].toCharArray().first().toString().toInt()
fun parseDirectionValue(line: String) : Int = if (line.trimStart().split(" ")[6].contains("left")) -1 else 1
fun parseNextStateValue(line: String) : Char = line.trimStart().split(" ")[4].toCharArray().first()
fun parseOp(input: List<String>) : (CpuState) -> CpuState {
val setIfZero = parseSetValue(input[1])
val dirIfZero = parseDirectionValue(input[2])
val nextIfZero = parseNextStateValue(input[3])
val setIfOne = parseSetValue(input[5])
val dirIfOne = parseDirectionValue(input[6])
val nextIfOne = parseNextStateValue(input[7])
return { s ->
if (s.tape[s.cursor] == 1) {
s.tape[s.cursor] = setIfOne
CpuState(s.tape, nextIfOne, s.cursor + dirIfOne, s.pc + 1, s.stopCond)
} else {
s.tape[s.cursor] = setIfZero
CpuState(s.tape, nextIfZero, s.cursor + dirIfZero, s.pc + 1, s.stopCond)
}
}
}
fun solvePt1(input: List<String>) : Int {
val parsed = parseInput(input)
val startState = parsed.first
val ops : Map<Char, (CpuState) -> CpuState> = parsed.second
val endState = generateSequence(startState) {
ops[it.nextOp]!!(it)
}.takeWhile { it.pc < it.stopCond }.last()
return endState.tape.values.sum()
}
} | 0 | Kotlin | 0 | 0 | 19a665bb469279b1e7138032a183937993021e36 | 2,152 | aoc17 | MIT License |
advent-of-code-2018/src/test/java/aoc/Advent18.kt | yuriykulikov | 159,951,728 | false | {"Kotlin": 1666784, "Rust": 33275} | package aoc
import org.assertj.core.api.Assertions.assertThat
import org.junit.Ignore
import org.junit.Test
class Advent18 {
data class Acre(val x: Int, val y: Int, val content: Char) {
val pos = x to y
}
@Test
fun `it is a wood`() {
assertThat(fieldAfter(testInput, 10)).isEqualTo(1147)
}
@Test
fun `it is real wood`() {
assertThat(fieldAfter(realInput, 10)).isEqualTo(584714)
}
@Test
fun `it is real wood 2 small`() {
assertThat(fieldAfter2(realInput, 1000)).isEqualTo(fieldAfter(realInput, 1000))
}
@Test
fun `it is real wood 2 small 2`() {
assertThat(fieldAfter2(realInput, 2000)).isEqualTo(fieldAfter(realInput, 2000))
}
@Ignore("Wrong")
@Test
fun `it is real wood 2`() {
assertThat(fieldAfter2(realInput, 1000000000)).isEqualTo(584714)
}
private fun fieldAfter(input: String, iterations: Int): Int {
val acres = input.lines()
.mapIndexed { y, line ->
line.toCharArray()
.mapIndexed { x, char -> Acre(x, y, char) }
}
.flatten()
// dump(acres)
val lastState = generateSequence(acres) { prev ->
val map: Map<Pair<Int, Int>, Acre> = prev.associateBy { it.pos }
prev.map { acre ->
val neighbours = (acre.x - 1..acre.x + 1)
.flatMap { x -> (acre.y - 1..acre.y + 1).map { y -> x to y } }
.minus(acre.x to acre.y)
.mapNotNull { pos -> map[pos] }
.map { it.content }
// .apply { println(this) }
when {
// An open acre will become filled with trees if three or more adjacent acres contained trees. Otherwise, nothing happens.
acre.content == '.' && neighbours.count { it == '|' } >= 3 -> acre.copy(content = '|')
acre.content == '.' -> acre
// An acre filled with trees will become a lumberyard if three or more adjacent acres were lumberyards. Otherwise, nothing happens.
acre.content == '|' && neighbours.count { it == '#' } >= 3 -> acre.copy(content = '#')
acre.content == '|' -> acre
// An acre containing a lumberyard will remain a lumberyard if it was adjacent to at least one other lumberyard and at least one acre containing trees. Otherwise, it becomes open.
acre.content == '#' && neighbours.count { it == '#' } >= 1 && neighbours.count { it == '|' } >= 1 -> acre.copy(
content = '#'
)
else -> acre.copy(content = '.')
}
}
}
// .onEach { dump(it) }
.take(iterations + 1)
// .onEach { dump(it) }
// .mapIndexed { index, lastState -> index to lastState }
// .onEach { (index, lastState) -> println("$index: ${lastState.count { it.content == '|' } * lastState.count { it.content == '#' }}") }
// .map { it.second }
.last()
// dump(lastState)
return lastState.count { it.content == '|' } * lastState.count { it.content == '#' }
}
private fun fieldAfter2(input: String, iterations: Int): Int {
val base = (iterations - 466).rem(28)
return when (base) {
0 -> 169472
1 -> 163068
2 -> 161160
3 -> 158921
4 -> 155439
5 -> 158004
6 -> 159120
7 -> 158992
8 -> 160966
9 -> 164395
10 -> 165300
11 -> 171152
12 -> 175712
13 -> 182246
14 -> 185978
15 -> 192831
16 -> 192878
17 -> 197136
18 -> 192075
19 -> 191880
20 -> 190968
21 -> 192807
22 -> 190656
23 -> 190176
24 -> 187265
25 -> 184960
26 -> 179088
27 -> 177498
else -> throw RuntimeException()
}
}
private fun dump(acres: List<Acre>) {
println()
acres.groupBy { it.y }
.toSortedMap().values.forEach { acres -> println(acres.joinToString("") { "${it.content}" }) }
}
val testInput = """
.#.#...|#.
.....#|##|
.|..|...#.
..|#.....#
#.#|||#|#|
...#.||...
.|....|...
||...#|.#|
|.||||..|.
...#.|..|.
""".trimIndent()
val realInput = """
#.##...#....|...#..|...#|...#....|.....|..##.|.|.#
||#...##|.|.##....|..#.#......#.#..#......|..#.|.#
|......#.##....||..#..||..|.....|..##....|.#.|..|#
.|...#||..||#|#.....|#...|.||.||#...#..|.##.......
...#.|.||.|.....|..##.#|....|#...|#.#|.#|...#.....
##.#....|..|.|....#.#|..##..#.......|.|.||#.......
....|..#|...|...|#..#...#....#.........#....#.|..|
....##...|..........|.|##|##..||..|..#..#|..|.....
........|..#.......|.#|............##.||.##.#..||#
.|...|##..#.|..|..|.#|.#.|#...|......#.....#...##|
............#.|.|||....|...#.#..#|.#...|.#....#|..
.....#....##....|#..##..|......|#.........|..##..|
#|.#||...|#...#|#|......#|#.|.#|#.|#...|.....#|.||
..|..#..|.#||.#.#.......#..#.#...|.#...|.|.|..|..#
.#|....#..#.|........#.....#.|....|#|#........#.|.
###|....##|#|||#.||.....#....#.#....|.#...|#..|#..
...#.##..#....|...||.#.|#.....||##|#.....|#|...|..
#..|.|.|#......|.#....#||...#.|.|..|#...|#|.|#|...
....###..|||#..##....||..|.|.#|#.....#||.......|..
|....#...#.||.|...#.#|...##.##....||.|.|##.#.#|...
#..#...#...|##....#.#|....|.#|#.|.....|##|||...#.|
..||.|.#...#.#|#...#..||.|#.|.|.|.###.....|....#..
.#|..|###.#....#.......#|.#|..#.|.||.|.||..##...#|
|..|....|#.........#|.|.....|.#...|.#|.||..|.|||.|
#...........|##|..#..##.......|||..#.....#.|#..##.
.#.#..|....|.|||###..#........|..#..|..##|...|#...
#.#..|||||....#.#..#...##....#....##.#|......##.#.
|.|#|.....|......#.....#........|.||....##|.#...|.
#....#.....#.#.|#......|#.|........|#|..#.|##.|.#.
.#|##..|.||..#|....#.|..#|#.#...###|...#.#....#...
#...#....||..#.|...||..#....|.|......|||....#.....
.#|....#|...#.#....|...|#|#.##...|.|.#||||..|.##.#
....#..#....|.|.#....|..|||#....#...|.#....#.|#.|.
.#..###|..|#.....#....|.|.|||.|.|#||#.#..|.##|...#
##.#...#|.....||.#..|.|...||.....|||.||#......|#..
||#|.|...||......#...#.|#..|..#.......##..##.#...#
...##.|#....#||.|.#.|#..........#...#.......#....|
..#...#...|#..|||..#||||....#..|.#..#.#..||.##|.||
#..|...|##||.||..|#.|.#....|.......|..#....|.#|...
...|.#####.##|####..#.|..#....#...|#.#.#|......||.
###......|.|..|#.|#....|.......|##.|#|...|.......|
##|....|#..|...#..|.||......#|.....##|...|...|..#|
..#.|.#.||...###..##.##..|....|..|....#..#...####.
.|##.#..|..|...##......#...##||........|.|....#||.
##.|#....|...|..|#.....|....|.|....|.|.|..|..#.#..
..|.|.#|.|....||#.|#...............##..|...#.....#
.#...#.......#.......#.##...#.|.|..####.||#....#||
.||#...##.#|.||..##.|....|||##...|#.|...#.#|.#....
.#|.||#..#.|#.......||.||#...........#....|###....
#|....#......##.#....|.....|##.#|.....|.#..|.....#
""".trimIndent()
} | 0 | Kotlin | 0 | 1 | f5efe2f0b6b09b0e41045dc7fda3a7565cb21db3 | 7,132 | advent-of-code | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/Dota2Senate.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import java.util.LinkedList
import java.util.Queue
private const val RADIANT = "Radiant"
private const val DIRE = "Dire"
/**
* 649. Dota2 Senate
* @see <a href="https://leetcode.com/problems/dota2-senate/">Source</a>
*/
fun interface Dota2Senate {
fun predictPartyVictory(senate: String): String
}
class Dota2SenateGreedy : Dota2Senate {
override fun predictPartyVictory(senate: String): String {
// Convert to StringBuilder for easy deletion
val senateArray = StringBuilder(senate)
// Count of Each Type of Senator to check for Winner
var rCount = 0
var dCount = 0
for (element in senateArray) {
if (element == 'R') {
rCount++
} else {
dCount++
}
}
// Turn of Senator at this index
var turn = 0
// While No Winner
while (rCount > 0 && dCount > 0) {
// Ban the next opponent, starting at one index ahead
// Taking MOD to loop around.
// If index of banned senator is before current index,
// then we need to decrement turn by 1, as we have removed
// a senator from list
if (senateArray[turn] == 'R') {
val bannedSenatorBefore = ban(senateArray, 'D', (turn + 1) % senateArray.length)
if (bannedSenatorBefore) {
turn--
}
dCount--
} else {
val bannedSenatorBefore = ban(senateArray, 'R', (turn + 1) % senateArray.length)
if (bannedSenatorBefore) {
turn--
}
rCount--
}
// Increment Turn
turn = (turn + 1) % senateArray.length
}
// Return Winner
return if (rCount > 0) {
RADIANT
} else {
DIRE
}
}
// Ban the candidate "toBan", immediate next to "startAt"
// If have to loop around, then it means next turn will be of
// senator at same index. Returns loop around boolean
private fun ban(senateArray: StringBuilder, toBan: Char, startAt: Int): Boolean {
var loopAround = false
var pointer = startAt
while (true) {
if (pointer == 0) {
loopAround = true
}
if (senateArray[pointer] == toBan) {
senateArray.deleteCharAt(pointer)
break
}
pointer = (pointer + 1) % senateArray.length
}
return loopAround
}
}
class Dota2SenateBooleanArray : Dota2Senate {
override fun predictPartyVictory(senate: String): String {
// To mark Banned Senators
val banned = BooleanArray(senate.length)
// Count of Each Type of Senator who are not-banned
var rCount = 0
var dCount = 0
for (element in senate) {
if (element == 'R') {
rCount++
} else {
dCount++
}
}
// Turn of Senator at this Index
var turn = 0
// While both parties have at least one senator
while (rCount > 0 && dCount > 0) {
if (!banned[turn]) {
if (senate[turn] == 'R') {
ban(senate, banned, 'D', (turn + 1) % senate.length)
dCount--
} else {
ban(senate, banned, 'R', (turn + 1) % senate.length)
rCount--
}
}
turn = (turn + 1) % senate.length
}
return if (dCount == 0) RADIANT else DIRE
}
// Ban the candidate "toBan", immediate next to "startAt"
private fun ban(senate: String, banned: BooleanArray, toBan: Char, startAt: Int) {
// Find the next eligible candidate to ban
var pointer = startAt
while (true) {
if (senate[pointer] == toBan && !banned[pointer]) {
banned[pointer] = true
break
}
pointer = (pointer + 1) % senate.length
}
}
}
class Dota2SenateTwoQueues : Dota2Senate {
override fun predictPartyVictory(senate: String): String {
// Number of Senator
val n: Int = senate.length
// Queues with Senator's Index.
// Index will be used to find the next turn of Senator
val rQueue: Queue<Int> = LinkedList()
val dQueue: Queue<Int> = LinkedList()
// Populate the Queues
for (i in 0 until n) {
if (senate[i] == 'R') {
rQueue.add(i)
} else {
dQueue.add(i)
}
}
// While both parties have at least one Senator
while (rQueue.isNotEmpty() && dQueue.isNotEmpty()) {
// Pop the Next-Turn Senate from both Q.
val rTurn: Int = rQueue.poll()
val dTurn: Int = dQueue.poll()
// ONE having a larger index will be banned by a lower index
// will again get Turn, so EN-Queue again
// But ensure its turn comes in the next round only
if (dTurn < rTurn) {
dQueue.add(dTurn + n)
} else {
rQueue.add(rTurn + n)
}
}
// One's which Empty is not winner
return if (rQueue.isEmpty()) DIRE else RADIANT
}
}
class Dota2SenateSingleQueue : Dota2Senate {
override fun predictPartyVictory(senate: String): String {
// Number of Senators of each party
var rCount = 0
var dCount = 0
// Floating Ban Count
var dFloatingBan = 0
var rFloatingBan = 0
// Queue of Senators
val q: Queue<Char> = LinkedList()
for (c in senate.toCharArray()) {
q.add(c)
if (c == 'R') rCount++ else dCount++
}
// While any party has eligible Senators
while (rCount > 0 && dCount > 0) {
// Pop the senator with turn
val curr = q.poll()
// If eligible, float the ban on the other party, enqueue again.
// If not, decrement the floating ban and count of the party.
if (curr == 'D') {
if (dFloatingBan > 0) {
dFloatingBan--
dCount--
} else {
rFloatingBan++
q.add('D')
}
} else {
if (rFloatingBan > 0) {
rFloatingBan--
rCount--
} else {
dFloatingBan++
q.add('R')
}
}
}
// Return the party with eligible Senators
return if (rCount > 0) RADIANT else DIRE
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 7,472 | kotlab | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/IsMatch.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2020 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
/**
* Wildcard Matching
*/
fun Pair<String, String>.isMatch(): Boolean {
val m = first.length
val n = second.length
val ws = first.toCharArray()
val wp = second.toCharArray()
val dp = Array(m + 1) { BooleanArray(n + 1) }
dp[0][0] = true
for (j in 1..n) {
dp[0][j] = dp[0][j - 1] && wp[j - 1] == '*'
}
for (i in 1..m) {
dp[i][0] = false
}
for (i in 1..m) {
for (j in 1..n) {
if (wp[j - 1] == '?' || ws[i - 1] == wp[j - 1]) {
dp[i][j] = dp[i - 1][j - 1]
} else if (wp[j - 1] == '*') {
dp[i][j] = dp[i - 1][j] || dp[i][j - 1]
}
}
}
return dp[m][n]
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,343 | kotlab | Apache License 2.0 |
src/main/kotlin/Day07.kt | N-Silbernagel | 573,145,327 | false | {"Kotlin": 118156} | fun main() {
val input = readFileAsList("Day07")
println(Day07.part1(input))
println(Day07.part2(input))
}
object Day07 {
fun part1(input: List<String>): Int {
val rootDir = buildFileSystem(input)
val dirSizeMap = mutableMapOf<Dir, Int>()
calculateSize(rootDir, dirSizeMap)
var totalSize = 0
for (size in dirSizeMap.values) {
if (size <= 100000) {
totalSize += size
}
}
return totalSize
}
fun part2(input: List<String>): Int {
val rootDir = buildFileSystem(input)
val dirSizeMap = mutableMapOf<Dir, Int>()
calculateSize(rootDir, dirSizeMap)
val totalSpace = 70000000
val neededSpace = 30000000
val rootDirSize = dirSizeMap.getOrDefault(rootDir, totalSpace)
val freeSpace = totalSpace - rootDirSize
val spaceLeft = neededSpace - freeSpace
var bestDirSize = rootDirSize
for (size in dirSizeMap.values) {
if (size in spaceLeft until bestDirSize) {
bestDirSize = size
}
}
return bestDirSize
}
private fun calculateSize(dir: Dir, dirSizeMap: MutableMap<Dir, Int>): Int {
var size = 0
for (content in dir.content) {
if (content is File) {
size += content.fileSize
} else if (content is Dir) {
size += calculateSize(content, dirSizeMap)
}
}
dirSizeMap[dir] = size
return size
}
private fun buildFileSystem(input: List<String>): Dir {
val commands = parseCommands(input)
val rootDir = Dir("/", null)
applyCommands(commands, rootDir)
return rootDir
}
private fun applyCommands(
commands: MutableList<Command>,
rootDir: Dir,
) {
val dirs = HashMap<String, Dir>()
var currentDir = rootDir
for (command in commands) {
if (command.name == "cd") {
currentDir = applyCdCommand(command, currentDir, rootDir, dirs)
} else if (command.name == "ls") {
applyLsCommand(command, currentDir, dirs)
}
}
}
private fun applyLsCommand(
command: Command,
currentDir: Dir,
dirs: HashMap<String, Dir>
) {
val fileRegex = "(\\d+) (.+)".toRegex()
val dirRegex = "dir (.+)".toRegex()
for (output in command.output) {
val fileRegexMatches = fileRegex.find(output)
val dirRegexMatches = dirRegex.find(output)
if (fileRegexMatches != null) {
addFileToDir(fileRegexMatches, currentDir)
} else if (dirRegexMatches != null) {
addDirToDir(dirRegexMatches, currentDir, dirs)
}
}
}
private fun addDirToDir(
dirRegexMatches: MatchResult,
currentDir: Dir,
dirs: HashMap<String, Dir>
) {
val dirName = dirRegexMatches.groupValues[1]
val path = "${currentDir.path}/${dirName}"
.replace("//", "/")
val dir = dirs.getOrPut(path) {
Dir(path, currentDir)
}
currentDir.content.add(dir)
}
private fun addFileToDir(fileRegexMatches: MatchResult, currentDir: Dir) {
val fileSize = fileRegexMatches.groupValues[1].toInt()
val fileName = fileRegexMatches.groupValues[2]
val file = File(fileName, currentDir, fileSize)
currentDir.content
.add(file)
}
private fun applyCdCommand(
command: Command,
currentDir: Dir,
rootDir: Dir,
dirs: HashMap<String, Dir>
): Dir {
if (command.argument == null) {
throw RuntimeException()
}
if (command.argument == "..") {
return currentDir.parent ?: rootDir
}
if (command.argument == "/") {
return rootDir
}
val path = "${currentDir.path}/${command.argument}"
.replace("//", "/")
val newDir = Dir(
"${currentDir.path}/${command.argument}",
currentDir
)
return dirs.getOrPut(path) { newDir }
}
private fun parseCommands(input: List<String>): MutableList<Command> {
val commands = mutableListOf<Command>()
val commandRegex = "\\\$ (\\w+)(?: (.+))?".toRegex()
for (line in input) {
val regexResult = commandRegex.find(line)
if (regexResult != null) {
val command = regexResult.groupValues[1]
val argument = regexResult.groupValues[2]
commands.add(Command(command, argument))
} else {
commands.last()
.output
.add(line)
}
}
return commands
}
interface FileSystemEntity
data class File(val name: String, val dir: Dir, val fileSize: Int) : FileSystemEntity
data class Dir(
val path: String,
val parent: Dir?,
val content: MutableList<FileSystemEntity> = mutableListOf()
) : FileSystemEntity {
override fun hashCode(): Int {
return path.hashCode()
}
override fun toString(): String {
return path
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Dir
if (path != other.path) return false
return true
}
}
data class Command(val name: String, val argument: String?, val output: MutableList<String> = mutableListOf())
}
| 0 | Kotlin | 0 | 0 | b0d61ba950a4278a69ac1751d33bdc1263233d81 | 5,745 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/days/Day9.kt | vovarova | 572,952,098 | false | {"Kotlin": 103799} | package days
class Day9 : Day(9) {
class Move(val command: Char, val times: Int)
val moves: List<Move> = inputList.map { it.split(" ").let { Move(it[0][0], it[1].toInt()) } }
data class KnotPosition(val row: Int = 0, val column: Int = 0) {
fun up(): KnotPosition = KnotPosition(row + 1, column)
fun down(): KnotPosition = KnotPosition(row - 1, column)
fun left(): KnotPosition = KnotPosition(row, column - 1)
fun right(): KnotPosition = KnotPosition(row, column + 1)
fun diagonalSiblings(): List<KnotPosition> {
return listOf(up().left(), up().right(), down().left(), down().right())
}
fun straightSiblings(): List<KnotPosition> {
return listOf(up(), right(), down(), left())
}
fun singleStep(command: Char): KnotPosition {
return when (command) {
'U' -> up()
'R' -> right()
'L' -> left()
'D' -> down()
else -> up()
}
}
fun isSibling(other: KnotPosition): Boolean {
return (listOf(this) + straightSiblings() + diagonalSiblings()).any { it.equals(other) }
}
fun follow(other: KnotPosition): KnotPosition {
if (!isSibling(other)) {
if (row == other.row || column == other.column) {
return straightSiblings().first { it.isSibling(other) }
}
return diagonalSiblings().first { it.isSibling(other) }
}
return this
}
}
override fun partOne(): Any {
var headKnotPosition = KnotPosition()
var tailKnotPosition = KnotPosition()
val positions = mutableSetOf<KnotPosition>()
positions.add(tailKnotPosition)
for (move in moves) {
for (iter in 1..move.times) {
headKnotPosition = headKnotPosition.singleStep(move.command)
tailKnotPosition = tailKnotPosition.follow(headKnotPosition)
positions.add(tailKnotPosition)
}
}
return positions.size
}
override fun partTwo(): Any {
val knots = Array(10) {
KnotPosition()
}
val positions = mutableSetOf<KnotPosition>()
positions.add(knots.last())
for (move in moves) {
for (iter in 1..move.times) {
knots[0] = knots[0].singleStep(move.command)
for (knotIndex in 1 until knots.size) {
knots[knotIndex] = knots[knotIndex].follow(knots[knotIndex - 1])
}
positions.add(knots.last())
}
}
return positions.size
}
} | 0 | Kotlin | 0 | 0 | e34e353c7733549146653341e4b1a5e9195fece6 | 2,740 | adventofcode_2022 | Creative Commons Zero v1.0 Universal |
leetcode/src/tree/Q102.kt | zhangweizhe | 387,808,774 | false | null | package tree
import linkedlist.TreeNode
import java.util.*
import kotlin.collections.ArrayList
fun main() {
// 102. 二叉树的层序遍历
// https://leetcode-cn.com/problems/binary-tree-level-order-traversal/
val root = TreeNode(3)
root.left = TreeNode(9)
root.right = TreeNode(20)
root.right?.right = TreeNode(7)
root.right?.left = TreeNode(15)
println(levelOrder(root))
println(levelOrder1(root))
}
fun levelOrder(root: TreeNode?): List<List<Int>> {
val ret = ArrayList<ArrayList<Int>>()
helper(ret, root, 0)
return ret
}
private fun helper(ret:ArrayList<ArrayList<Int>>, root: TreeNode?, level:Int) {
if (root == null) {
return
}
if (level >= ret.size) {
ret.add(ArrayList())
}
val curLevel = ret[level]
curLevel.add(root.`val`)
helper(ret, root.left, level + 1)
helper(ret, root.right, level + 1)
}
private fun levelOrder1(root: TreeNode?): List<List<Int>> {
val ret = ArrayList<ArrayList<Int>>()
if (root == null) {
return ret
}
val queue = LinkedList<TreeNode>()
queue.add(root)
while (queue.isNotEmpty()) {
// 遍历每一层之前,先每一层节点的数量
val n = queue.size
val list = ArrayList<Int>()
// 再一个循环中,遍历完当前层的节点,并把当前层的节点的子节点加入队列
for (i in 0 until n) {
val poll = queue.poll()
list.add(poll.`val`)
if (poll.left != null) {
queue.add(poll.left!!)
}
if (poll.right != null) {
queue.add(poll.right!!)
}
}
ret.add(list)
}
return ret
} | 0 | Kotlin | 0 | 0 | 1d213b6162dd8b065d6ca06ac961c7873c65bcdc | 1,732 | kotlin-study | MIT License |
algorithms/src/main/kotlin/io/nullables/api/playground/algorithms/SierpinskiTriangle.kt | AlexRogalskiy | 331,076,596 | false | null | /*
* Copyright (C) 2021. <NAME>. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.nullables.api.playground.algorithms
class SierpinskiTriangle {
/**
* @param d base of the triangle (i.e. the smallest dimension)
* @param n fractalization depth (must be less than log2(d))
* @throws IllegalArgumentException if n > log2(d)
*/
fun makeTriangles(base: Int, n: Int): Array<BooleanArray> {
if (n > log2(base)) throw IllegalArgumentException(
"fractalization depth must be less than log2(base): " +
"$n > ${log2(base).toInt()}"
)
val arr = Array(base, { BooleanArray(base * 2 - 1) })
drawTriangles(n, arr, 0, 0, base - 1, base * 2 - 2)
return arr
}
fun drawTriangles(
n: Int,
arr: Array<BooleanArray>,
top: Int,
left: Int,
bottom: Int,
right: Int
) {
if (n > 0) {
val width = right - left
val height = bottom - top
drawTriangles(
n - 1, arr,
top,
left + width / 4 + 1,
top + height / 2,
right - width / 4 - 1
)
drawTriangles(
n - 1, arr,
top + 1 + height / 2,
left,
bottom,
left + width / 2 - 1
)
drawTriangles(
n - 1, arr,
top + 1 + height / 2,
left + width / 2 + 1,
bottom,
right
)
} else {
drawTriangles(arr, top, left, bottom, right)
}
}
fun drawTriangles(arr: Array<BooleanArray>, top: Int, left: Int, bottom: Int, right: Int) {
val height = bottom - top
val width = right - left
for (i in 0..height) {
for (j in (height - i)..width / 2) {
arr[top + i][left + j] = true
}
for (j in (width / 2..width / 2 + i)) {
arr[top + i][left + j] = true
}
}
}
}
fun main(args: Array<String>) {
SierpinskiTriangle()
.makeTriangles(128, 7)
.map { array ->
array.map { if (it) 'x' else ' ' }.joinToString(separator = "")
}
.forEach { println(it) }
}
| 13 | Kotlin | 2 | 2 | d7173ec1d9ef227308d926e71335b530c43c92a8 | 2,896 | gradle-kotlin-sample | Apache License 2.0 |
src/Day06.kt | cypressious | 572,898,685 | false | {"Kotlin": 77610} | fun main() {
fun compute(line: String, size: Int): Int {
var substring = line.take(size)
var index = size
while (true) {
if (substring.toCharArray().distinct().size == size) {
return index
}
substring = substring.substring(1) + line[index]
index++
}
}
fun part1(input: List<String>) = compute(input.single(), 4)
fun part2(input: List<String>) = compute(input.single(), 14)
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day06_test")
check(part1(testInput) == 7)
check(part2(testInput) == 19)
val input = readInput("Day06")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 7b4c3ee33efdb5850cca24f1baa7e7df887b019a | 764 | AdventOfCode2022 | Apache License 2.0 |
src/kotlin/sort/mergesort/MergeSort.kts | carloseduardosx | 67,647,496 | false | {"Kotlin": 4884} | val defaultArray = intArrayOf(10, 5, 8, 3, 1, 7, 6, 4, 2, 0, 9)
fun mergeSort(unsortedArray: IntArray) {
splitAndMerge(unsortedArray, 0, unsortedArray.size, IntArray(unsortedArray.size))
unsortedArray.forEach { println(it) }
}
fun splitAndMerge(unsortedArray: IntArray, first: Int, last: Int, sortedArray: IntArray) {
if (last - first < 2) return
val middle = (last + first) / 2
splitAndMerge(unsortedArray, first, middle, sortedArray)
splitAndMerge(unsortedArray, middle, last, sortedArray)
merge(unsortedArray, first, middle, last, sortedArray)
copyArray(unsortedArray, first, last, sortedArray)
}
fun merge(unsortedArray: IntArray, first: Int, middle: Int, last: Int, sortedArray: IntArray) {
var i = first
var j = middle
for (k in first..last - 1) {
if (i < middle && (j >= last || unsortedArray[i] <= unsortedArray[j])) {
sortedArray[k] = unsortedArray[i]
i += 1
} else {
sortedArray[k] = unsortedArray[j]
j += 1
}
}
}
fun copyArray(unsortedArray: IntArray, first: Int, last: Int, sortedArray: IntArray) {
for (i in first..last - 1) {
unsortedArray[i] = sortedArray[i]
}
}
if (args.size != 0) {
val array = IntArray(args.size)
for (i in 0..args.size - 1) {
array[i] = args[i].toInt()
}
mergeSort(array)
} else {
mergeSort(defaultArray)
} | 0 | Kotlin | 0 | 0 | 9e1ca2ebd3a6936cd95e8a9a576d627316ddc701 | 1,425 | Algorithms | MIT License |
year2016/src/main/kotlin/net/olegg/aoc/year2016/day18/Day18.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2016.day18
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.year2016.DayOf2016
/**
* See [Year 2016, Day 18](https://adventofcode.com/2016/day/18)
*/
object Day18 : DayOf2016(18) {
private val PATTERNS = listOf(
"\\^\\^\\.".toRegex(),
"\\.\\^\\^".toRegex(),
"\\^\\.\\.".toRegex(),
"\\.\\.\\^".toRegex(),
)
override fun first(): Any? {
return solve(40)
}
override fun second(): Any? {
return solve(400000)
}
private fun solve(rows: Int): Int {
return (1..<rows).fold(".$data." to data.count { it == '.' }) { acc, _ ->
val traps = PATTERNS.flatMap { pattern -> pattern.findAll(acc.first).map { it.range.first + 1 }.toList() }
val row = acc.first.indices.map { if (traps.contains(it)) '^' else '.' }.joinToString(separator = "")
return@fold row to acc.second + row.count { it == '.' } - 2
}.second
}
}
fun main() = SomeDay.mainify(Day18)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 944 | adventofcode | MIT License |
src/main/kotlin/oct_challenge2021/IslandPerimeter.kt | yvelianyk | 405,919,452 | false | {"Kotlin": 147854, "Java": 610} | package oct_challenge2021
fun main() {
val grid = arrayOf(
intArrayOf(0, 1, 0, 0),
intArrayOf(1, 1, 1, 0),
intArrayOf(0, 1, 0, 0),
intArrayOf(1, 1, 0, 0),
)
val result = Solution().islandPerimeter(grid)
assert(result == 16)
println(result)
}
class Solution {
private lateinit var grid: Array<IntArray>
private lateinit var visited: Array<IntArray>
private val dirs = arrayOf(intArrayOf(1, 0), intArrayOf(-1, 0), intArrayOf(0, 1), intArrayOf(0, -1))
private var result: Int = 0
fun islandPerimeter(grid: Array<IntArray>): Int {
this.grid = grid
this.visited = Array(grid.size) { IntArray(grid[0].size) { 0 } }
for (i in grid.indices) {
for (j in grid[0].indices) {
if (grid[i][j] == 1 && visited[i][j] == 0) {
traverse(i, j)
return result
}
}
}
return result
}
private fun traverse(i: Int, j: Int) {
val m = grid.size
val n = grid[0].size
visited[i][j] = 1
for (dir in dirs) {
val newI = i + dir[0]
val newJ = j + dir[1]
val canTraverse = newI in 0 until m && newJ in 0 until n && grid[newI][newJ] == 1
when {
canTraverse -> {
if (visited[newI][newJ] == 0) traverse(newI, newJ)
}
else -> {
result++
}
}
}
}
} | 0 | Kotlin | 0 | 0 | 780d6597d0f29154b3c2fb7850a8b1b8c7ee4bcd | 1,536 | leetcode-kotlin | MIT License |
jvm_sandbox/projects/advent_of_code/src/main/kotlin/year2018/Day4.kt | jduan | 166,515,850 | false | {"Rust": 876461, "Kotlin": 257167, "Java": 139101, "Python": 114308, "Vim Script": 100117, "Shell": 96665, "C": 67784, "Starlark": 23497, "JavaScript": 20939, "HTML": 12920, "Ruby": 5087, "Thrift": 4518, "Nix": 2919, "HCL": 1069, "Lua": 926, "CSS": 826, "Assembly": 761, "Makefile": 591, "Haskell": 585, "Dockerfile": 501, "Scala": 322, "Smalltalk": 270, "CMake": 252, "Smarty": 97, "Clojure": 91} | package year2018.day4
import java.io.File
data class Sleep(
// The minute the sleep starts
val start: Int,
// The minute the sleep ends
val end: Int
) {
fun minutes() = end - start
}
data class GuardSleep(
val guardId: Int
) {
private val sleeps = mutableListOf<Sleep>()
fun addSleep(sleep: Sleep): GuardSleep {
sleeps.add(sleep)
return this
}
fun totalSleepMinutes() =
sleeps.fold(0) { acc, sleep -> acc + sleep.minutes()}
// Return the most slept minute and how many times
fun sleepMostMinute(): Pair<Int, Int> {
val minuteCount = mutableMapOf<Int, Int>()
sleeps.forEach {sleep ->
for (minute in sleep.start until sleep.end) {
val count = minuteCount.getOrDefault(minute, 0)
minuteCount[minute] = count + 1
}
}
val maxCount = minuteCount.values.max()
val counts = minuteCount.filter { entry -> entry.value == maxCount }
return counts.keys.first() to maxCount!!
}
override fun toString(): String {
return "GuardSleep(guardId=${guardId}, sleeps=${sleeps}"
}
}
sealed class Event(open val hour: Int, open val minute: Int)
data class ShiftStarts(
val guardId: Int,
override val hour: Int,
override val minute: Int
) : Event(hour, minute)
data class FallAsleep(
override val hour: Int,
override val minute: Int
) : Event(hour, minute)
data class WakesUp(
override val hour: Int,
override val minute: Int
) : Event(hour, minute)
fun parseLine(line: String): Event {
val shiftStartsRegex = """\[\d{4}-\d{2}-\d{2} (\d{2}):(\d{2})\] Guard #(\d+) begins shift""".toRegex()
val fallAsleepRegex = """\[\d{4}-\d{2}-\d{2} (\d{2}):(\d{2})\] falls asleep""".toRegex()
val wakesUpRegex = """\[\d{4}-\d{2}-\d{2} (\d{2}):(\d{2})\] wakes up""".toRegex()
return when {
shiftStartsRegex.matches(line) -> {
val (_, hour, minute, guardId) = shiftStartsRegex.find(line)!!.groupValues
ShiftStarts(guardId.toInt(), hour.toInt(), minute.toInt())
}
fallAsleepRegex.matches(line) -> {
val (_, hour, minute) = fallAsleepRegex.find(line)!!.groupValues
FallAsleep(hour.toInt(), minute.toInt())
}
wakesUpRegex.matches(line) -> {
val (_, hour, minute) = wakesUpRegex.find(line)!!.groupValues
WakesUp(hour.toInt(), minute.toInt())
}
else -> throw Exception("Unexpected line: $line")
}
}
fun parseFile(path: String): Map<Int, GuardSleep> {
val lines = File(path).readLines().sorted()
val guardToSleep = mutableMapOf<Int, GuardSleep>()
var guardId: Int = 0
var sleepStart: Int = 0
lines.forEach { line ->
val event = parseLine(line)
when(event) {
is ShiftStarts -> {
guardId = event.guardId
}
is FallAsleep -> {
sleepStart = event.minute
}
is WakesUp -> {
val sleepEnd = event.minute
val guardSleep = guardToSleep[guardId]
if (guardSleep == null) {
val gs = GuardSleep(guardId)
gs.addSleep(Sleep(sleepStart, sleepEnd))
guardToSleep[guardId] = gs
} else {
guardSleep.addSleep(Sleep(sleepStart, sleepEnd))
}
}
}
}
return guardToSleep
}
// Find the guard that spent the most minutes asleep.
// Find the minute the guard that was asleep the most.
| 58 | Rust | 1 | 0 | d5143e89ce25d761eac67e9c357620231cab303e | 3,294 | cosmos | MIT License |
kotlin/src/com/daily/algothrim/leetcode/RemoveDuplicates.kt | idisfkj | 291,855,545 | false | null | package com.daily.algothrim.leetcode
/**
* 80. 删除有序数组中的重复项 II
*
* 给你一个有序数组 nums ,请你 原地 删除重复出现的元素,使每个元素 最多出现两次 ,返回删除后数组的新长度。
* 不要使用额外的数组空间,你必须在 原地 修改输入数组 并在使用 O(1) 额外空间的条件下完成。
*/
class RemoveDuplicates {
companion object {
@JvmStatic
fun main(args: Array<String>) {
println(
RemoveDuplicates().removeDuplicates(
intArrayOf(
1, 1, 1, 2, 2, 3
)
)
)
println(
RemoveDuplicates().removeDuplicates(
intArrayOf(
0, 0, 1, 1, 1, 2, 3, 3
)
)
)
println(
RemoveDuplicates().removeDuplicates2(
intArrayOf(
1, 1, 1, 2, 2, 3
)
)
)
println(
RemoveDuplicates().removeDuplicates2(
intArrayOf(
0, 0, 1, 1, 1, 2, 3, 3
)
)
)
}
}
// 输入:nums = [1,1,1,2,2,3]
// 输出:5, nums = [1,1,2,2,3]
fun removeDuplicates(nums: IntArray): Int {
val size = nums.size
if (size <= 2) return size
var slow = 0
var fast = 1
var index = 1
var moreDouble = false
while (fast < size) {
if (nums[slow] == nums[fast] && !moreDouble) {
moreDouble = true
nums[index] = nums[fast]
index++
} else if (nums[slow] != nums[fast]) {
moreDouble = false
nums[index] = nums[fast]
index++
}
fast++
slow++
}
return index
}
fun removeDuplicates2(nums: IntArray): Int {
val size = nums.size
if (size <= 2) return size
var slow = 2
var fast = 2
while (fast < size) {
if (nums[slow - 2] != nums[fast]) {
nums[slow] = nums[fast]
slow++
}
fast++
}
return slow
}
} | 0 | Kotlin | 9 | 59 | 9de2b21d3bcd41cd03f0f7dd19136db93824a0fa | 2,401 | daily_algorithm | Apache License 2.0 |
src/day17/Rocks.kt | g0dzill3r | 576,012,003 | false | {"Kotlin": 172121} | package day17
data class Point (val x: Int, val y: Int) {
fun add (point: Point): Point = add (point.x, point.y)
fun add (dx: Int, dy: Int): Point = Point (x + dx, y + dy)
}
data class Rock (val raw: String) {
val points: List<Point> = parseRock (raw)
val width: Int = points.fold (0) { acc, p -> Math.max (acc, p.x + 1) }
val height: Int = points.fold (0) { acc, p -> Math.max (acc, Math.abs (p.y) + 1) }
companion object {
fun parseRock (raw: String): List<Point> {
val list = mutableListOf<Point> ()
raw.split ("\n").forEachIndexed { y, row ->
row.forEachIndexed { x, c ->
if (c == '#') {
list.add(Point(x, -y))
}
}
}
return list
}
}
}
object Rocks {
val rocks = parseRocks ()
val iterator: TrackableIterator<Rock>
get () {
return object : TrackableIterator<Rock> {
override var current = 0
override val size = rocks.size
override fun hasNext(): Boolean = true
override fun next(): Rock {
val next = current ++
current %= rocks.size
return rocks[next]
}
}
}
private fun parseRocks (): List<Rock> {
val list = mutableListOf<Rock> ()
ROCKS.trim ().split ("\n\n").forEach {
list.add (Rock (it))
}
return list
}
}
fun main (args: Array<String>) {
val iter = Rocks.iterator
repeat (10) {
iter.next ().let {
println ("\n${it}\n${it.width} x ${it.height}")
it.points.forEach {
println (it)
}
}
}
}
private val ROCKS = """
####
.#.
###
.#.
..#
..#
###
#
#
#
#
##
##
"""
// EOF | 0 | Kotlin | 0 | 0 | 6ec11a5120e4eb180ab6aff3463a2563400cc0c3 | 1,890 | advent_of_code_2022 | Apache License 2.0 |
src/test/kotlin/com/igorwojda/integer/addupto/Solution.kt | igorwojda | 159,511,104 | false | {"Kotlin": 254856} | package com.igorwojda.integer.addupto
// Kotlin idiomatic solution
private object Solution1 {
private fun addUpTo(n: Int): Int {
return (1..n).sum()
}
}
// Kotlin idiomatic solution
private object Solution2 {
private fun addUpTo(n: Int): Int {
return (0..n).fold(0) { accumulated, current -> accumulated + current }
}
}
// Recursive solution
private object Solution3 {
private fun addUpTo(n: Int): Int {
if (n == 1) {
return 1
}
return n + addUpTo(n - 1)
}
}
// Time Complexity: O(1)
// Mathematical formula
private object Solution4 {
private fun addUpTo(n: Int): Int {
return n * (n + 1) / 2
}
}
// Time Complexity: O(n)
// Iterative solution
private object Solution5 {
private fun addUpTo(n: Int): Int {
var total = 0
(0..n).forEach { total += it }
return total
}
}
// Iterative solution
private object Solution6 {
private fun addUpTo(n: Int): Int {
var total = 0
repeat(n + 1) { total += it }
return total
}
}
| 9 | Kotlin | 225 | 895 | b09b738846e9f30ad2e9716e4e1401e2724aeaec | 1,078 | kotlin-coding-challenges | MIT License |
src/main/kotlin/me/dkim19375/adventofcode2022/day/Day2.kt | dkim19375 | 573,172,567 | false | {"Kotlin": 13147} | package me.dkim19375.adventofcode2022.day
import me.dkim19375.adventofcode2022.AdventOfCodeDay
object Day2 : AdventOfCodeDay() {
@JvmStatic
fun main(args: Array<String>) = solve()
override val day: Int = 2
private val rpsChoices = mapOf(
"A" to 1,
"B" to 2,
"C" to 3,
"X" to 1,
"Y" to 2,
"Z" to 3,
)
override fun solve() {
val input = getInputString().lines().map {
it.split(' ').let { list ->
(rpsChoices[list[0]] ?: 0) to (rpsChoices[list[1]] ?: 0)
}
}
val part1Score = input.sumOf { (opponent, player) ->
calculateScore(opponent, player)
}
val part2Score = input.sumOf { (opponent, action) ->
val player = when (action) {
1 -> if (opponent == 1) 3 else opponent - 1
2 -> opponent
else -> if (opponent == 3) 1 else opponent + 1
}
calculateScore(opponent, player)
}
println(
"""
Part 1: $part1Score
Part 2: $part2Score
""".trimIndent()
)
}
private fun calculateScore(opponent: Int, player: Int): Int = when {
opponent == player -> 3
((opponent + 1) == player) || ((opponent - 2) == player) -> 6
else -> 0
} + player
} | 1 | Kotlin | 0 | 0 | f77c4acec08a4eca92e6d68fe2a5302380688fe6 | 1,389 | AdventOfCode2022 | The Unlicense |
src/main/kotlin/io/github/pshegger/aoc/y2015/Y2015D15.kt | PsHegger | 325,498,299 | false | null | package io.github.pshegger.aoc.y2015
import io.github.pshegger.aoc.common.BaseSolver
import io.github.pshegger.aoc.common.extractAll
import io.github.pshegger.aoc.common.generateSplits
import io.github.pshegger.aoc.common.toExtractor
import kotlin.math.max
class Y2015D15 : BaseSolver() {
override val year = 2015
override val day = 15
private val extractor = "%s: capacity %d, durability %d, flavor %d, texture %d, calories %d".toExtractor()
private val ingredients by lazy { parseInput() }
private val ratios by lazy { generateSplits(ingredients.size, INGREDIENT_COUNT) }
private val rationedProperties by lazy { ratios.map { ingredients.calculateProperties(it) } }
override fun part1(): Int = rationedProperties.maxOf { it.score }
override fun part2(): Int = rationedProperties
.filter { it.calories == TARGET_CALORIES }
.maxOf { it.score }
private fun List<Ingredient>.calculateProperties(ratio: List<Int>): Properties = Properties(
capacity = max(
ratio.mapIndexed { i, r -> r * get(i).properties.capacity }.sum(),
0
),
durability = max(
ratio.mapIndexed { i, r -> r * get(i).properties.durability }.sum(),
0
),
flavor = max(
ratio.mapIndexed { i, r -> r * get(i).properties.flavor }.sum(),
0
),
texture = max(
ratio.mapIndexed { i, r -> r * get(i).properties.texture }.sum(),
0
),
calories = max(
ratio.mapIndexed { i, r -> r * get(i).properties.calories }.sum(),
0
),
)
private fun parseInput() = readInput {
readLines().extractAll(extractor) {
Ingredient(
it[0],
Properties(
it[1].toInt(),
it[2].toInt(),
it[3].toInt(),
it[4].toInt(),
it[5].toInt(),
)
)
}
}
private data class Ingredient(
val name: String,
val properties: Properties
)
private data class Properties(
val capacity: Int,
val durability: Int,
val flavor: Int,
val texture: Int,
val calories: Int
) {
val score: Int get() = capacity * durability * flavor * texture
}
companion object {
private const val INGREDIENT_COUNT = 100
private const val TARGET_CALORIES = 500
}
} | 0 | Kotlin | 0 | 0 | 346a8994246775023686c10f3bde90642d681474 | 2,513 | advent-of-code | MIT License |
src/8ExponentialTimeAlgorithms/ColoringGraphs.kt | bejohi | 136,087,641 | false | {"Java": 63408, "Kotlin": 5933, "C++": 5711, "Python": 3670} | import java.util.*
import kotlin.system.exitProcess
// Solution for https://open.kattis.com/problems/coloring
// With help from https://github.com/amartop
fun main(args: Array<String>){
val input = Scanner(System.`in`)
val vertices = input.nextLine().toInt()
val adjMatrix = Array(vertices,{IntArray(vertices)})
var coloredArr = IntArray(vertices, { x -> 1})
for(vert in 0 until vertices){
val line = input.nextLine()
val numberList = line.split(" ").map { x -> x.toInt() }
for(number in numberList){
adjMatrix[vert][number] = 1
adjMatrix[number][vert] = 1
}
}
for(i in 1..vertices+1){
recursiveSolve(i,adjMatrix,0,coloredArr)
}
}
fun recursiveSolve(numberOfColors: Int, adjMatrix: Array<IntArray>, currentVertex: Int, vertColored: IntArray){
// 1. Verify valid color.
val colorOk = colorOk(adjMatrix,currentVertex,vertColored)
if(!colorOk){
return
}
if(currentVertex == adjMatrix.size-1){
println(numberOfColors+1)
exitProcess(0)
}
for(i in 1..numberOfColors+1) {
vertColored[currentVertex+1] = i // new color
recursiveSolve(numberOfColors,adjMatrix,currentVertex+1,vertColored)
}
}
fun colorOk(adjMatrix: Array<IntArray>, currentVertex: Int, vertColored: IntArray): Boolean {
for(i in 0..currentVertex-1){
if(adjMatrix[i][currentVertex] != 0 && vertColored[i] == vertColored[currentVertex]){
return false;
}
}
/*for(i in 0 until adjMatrix.size){
if(i == currentVertex){
continue
}
if(adjMatrix[currentVertex][i] != 0){ // Has neighbour?
if(vertColored[i] == vertColored[currentVertex]){ // Same color?
return false
}
}
}*/
return true
}
fun ClosedRange<Int>.random() = Random().nextInt(endInclusive - start) + start | 0 | Java | 0 | 0 | 7e346636786215dee4c681b80bc694c8e016e762 | 1,931 | UiB_INF237 | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/FindModeInBinarySearchTree.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2020 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import java.util.LinkedList
import java.util.Queue
import java.util.Stack
import kotlin.math.max
/**
* 501. Find Mode in Binary Search Tree
* @see <a href="https://leetcode.com/problems/find-mode-in-binary-search-tree">Source</a>
*/
fun interface FindModeInBinarySearchTree {
operator fun invoke(root: TreeNode?): IntArray
}
sealed interface FindModeInBinarySearchTreeStrategy {
/**
* Approach 1: Count Frequency With Hash Map (DFS)
*/
data object DFS : FindModeInBinarySearchTree, FindModeInBinarySearchTreeStrategy {
override fun invoke(root: TreeNode?): IntArray {
val counter: MutableMap<Int, Int> = HashMap()
var maxFreq = 0
fun dfs(node: TreeNode?, counter: MutableMap<Int, Int>) {
if (node == null) {
return
}
counter[node.value] = counter.getOrDefault(node.value, 0) + 1
dfs(node.left, counter)
dfs(node.right, counter)
}
dfs(root, counter)
for (key in counter.keys) {
maxFreq = max(maxFreq.toDouble(), counter[key]!!.toDouble()).toInt()
}
val ans: MutableList<Int?> = ArrayList()
for (key in counter.keys) {
if (counter[key] == maxFreq) {
ans.add(key)
}
}
val result = IntArray(ans.size)
for (i in ans.indices) {
result[i] = ans[i]!!
}
return result
}
}
/**
* Approach 2: Iterative DFS
*/
data object IterativeDFS : FindModeInBinarySearchTree, FindModeInBinarySearchTreeStrategy {
override fun invoke(root: TreeNode?): IntArray {
val counter: MutableMap<Int, Int> = HashMap()
val stack: Stack<TreeNode> = Stack()
stack.push(root)
while (!stack.empty()) {
val node: TreeNode = stack.pop()
counter[node.value] = counter.getOrDefault(node.value, 0) + 1
if (node.left != null) {
stack.push(node.left)
}
if (node.right != null) {
stack.push(node.right)
}
}
var maxFreq = 0
for (key in counter.keys) {
maxFreq = max(maxFreq.toDouble(), counter[key]!!.toDouble()).toInt()
}
val ans: MutableList<Int?> = ArrayList()
for (key in counter.keys) {
if (counter[key] == maxFreq) {
ans.add(key)
}
}
val result = IntArray(ans.size)
for (i in ans.indices) {
result[i] = ans[i]!!
}
return result
}
}
/**
* Approach 3: Breadth First Search (BFS)
*/
data object BFS : FindModeInBinarySearchTree, FindModeInBinarySearchTreeStrategy {
override fun invoke(root: TreeNode?): IntArray {
val counter: MutableMap<Int?, Int?> = HashMap()
val queue: Queue<TreeNode?> = LinkedList()
queue.add(root)
while (queue.isNotEmpty()) {
val node: TreeNode? = queue.remove()
counter[node?.value] = counter.getOrDefault(node?.value, 0)!! + 1
if (node?.left != null) {
queue.add(node.left)
}
if (node?.right != null) {
queue.add(node.right)
}
}
var maxFreq = 0
for (key in counter.keys) {
maxFreq = max(maxFreq.toDouble(), counter[key]!!.toDouble()).toInt()
}
val ans: MutableList<Int?> = ArrayList()
for (key in counter.keys) {
if (counter[key] == maxFreq) {
ans.add(key)
}
}
val result = IntArray(ans.size)
for (i in ans.indices) {
result[i] = ans[i]!!
}
return result
}
}
/**
* Approach 4: No Hash-Map
*/
data object DFSList : FindModeInBinarySearchTree, FindModeInBinarySearchTreeStrategy {
override fun invoke(root: TreeNode?): IntArray {
val values: MutableList<Int> = ArrayList()
var maxStreak = 0
var currStreak = 0
var currNum = 0
var ans: MutableList<Int?> = ArrayList()
fun dfs(node: TreeNode?, values: MutableList<Int>) {
if (node == null) {
return
}
// Inorder traversal visits nodes in sorted order
dfs(node.left, values)
values.add(node.value)
dfs(node.right, values)
}
dfs(root, values)
for (num in values) {
if (num == currNum) {
currStreak++
} else {
currStreak = 1
currNum = num
}
if (currStreak > maxStreak) {
ans = ArrayList()
maxStreak = currStreak
}
if (currStreak == maxStreak) {
ans.add(num)
}
}
val result = IntArray(ans.size)
for (i in ans.indices) {
result[i] = ans[i]!!
}
return result
}
}
/**
* Approach 5: No "Values" Array
*/
data object DFSArray : FindModeInBinarySearchTree, FindModeInBinarySearchTreeStrategy {
override fun invoke(root: TreeNode?): IntArray {
val ans = mutableListOf<Int>()
var maxStreak = 0
var currentStreak = 0
var currentNum = 0
fun dfs(node: TreeNode?) {
if (node == null) {
return
}
dfs(node.left)
val num = node.value
if (num == currentNum) {
currentStreak++
} else {
currentStreak = 1
currentNum = num
}
if (currentStreak > maxStreak) {
ans.clear()
maxStreak = currentStreak
}
if (currentStreak == maxStreak) {
ans.add(num)
}
dfs(node.right)
}
dfs(root)
return ans.toIntArray()
}
}
/**
* Approach 6: True Constant Space: Morris Traversal
*/
data object MorrisTraversal : FindModeInBinarySearchTree, FindModeInBinarySearchTreeStrategy {
override fun invoke(root: TreeNode?): IntArray {
var maxStreak = 0
var currStreak = 0
var currNum = 0
val ans = mutableListOf<Int>()
var curr = root
while (curr != null) {
if (curr.left != null) {
// Find the friend
var friend = curr.left
while (friend?.right != null) {
friend = friend.right
}
friend?.right = curr
// Delete the edge after using it
val left = curr.left
curr.left = null
curr = left
} else {
// Handle the current node
val num = curr.value
if (num == currNum) {
currStreak++
} else {
currStreak = 1
currNum = num
}
if (currStreak > maxStreak) {
ans.clear()
maxStreak = currStreak
}
if (currStreak == maxStreak) {
ans.add(num)
}
curr = curr.right
}
}
return ans.toIntArray()
}
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 8,891 | kotlab | Apache License 2.0 |
src/main/kotlin/adventofcode/year2015/Day18LikeAGifForYourYard.kt | pfolta | 573,956,675 | false | {"Kotlin": 199554, "Dockerfile": 227} | package adventofcode.year2015
import adventofcode.Puzzle
import adventofcode.PuzzleInput
import adventofcode.common.Tuple.plus
import adventofcode.common.cartesianProduct
class Day18LikeAGifForYourYard(customInput: PuzzleInput? = null) : Puzzle(customInput) {
override val name = "Like a GIF For Your Yard"
private val initialConfiguration by lazy {
input
.lines()
.flatMapIndexed { y, row -> row.mapIndexed { x, state -> Pair(x, y) to (state == TURNED_ON) } }
.toMap()
}
override fun partOne() = initialConfiguration.animate()
.drop(1)
.take(STEP_COUNT)
.last()
.count { (_, turnedOn) -> turnedOn }
override fun partTwo() = initialConfiguration.animate(setOf(Pair(0, 0), Pair(99, 0), Pair(0, 99), Pair(99, 99)))
.drop(1)
.take(STEP_COUNT)
.last()
.count { (_, turnedOn) -> turnedOn }
companion object {
private const val TURNED_ON = '#'
private const val GRID_HEIGHT = 100
private const val GRID_WIDTH = 100
private const val STEP_COUNT = 100
fun Map<Pair<Int, Int>, Boolean>.animate(stuckLights: Set<Pair<Int, Int>> = emptySet()) = generateSequence(this) { previous ->
previous + previous.minus(stuckLights).mapNotNull { (light, turnedOn) ->
val turnedOnNeighbors = light.neighbors().count { previous[it]!! }
if (turnedOn && listOf(2, 3).none { turnedOnNeighbors == it }) {
light to false
} else if (!turnedOn && turnedOnNeighbors == 3) {
light to true
} else {
null
}
}
}
private fun Pair<Int, Int>.neighbors() = listOf((-1..1).toList(), (-1..1).toList())
.cartesianProduct()
.map { this + (it.first() to it.last()) }
.minus(this)
.filter { it.first >= 0 && it.second >= 0 && it.first < GRID_WIDTH && it.second < GRID_HEIGHT }
}
}
| 0 | Kotlin | 0 | 0 | 72492c6a7d0c939b2388e13ffdcbf12b5a1cb838 | 2,049 | AdventOfCode | MIT License |
src/day5/Solution.kt | Zlate87 | 572,858,682 | false | {"Kotlin": 12960} | package day5
import java.io.File
fun main() {
fun toStacks(input: List<String>): ArrayList<ArrayDeque<Char>> {
val matrix = ArrayList(input.map { it.toCharArray() })
val numberOfRows = (matrix[0].size + 2) / 4
val header = matrix.removeAt(0)
println(header)
matrix.forEach {
println(it)
}
println("")
val stacks = ArrayList<ArrayDeque<Char>>()
repeat((1..numberOfRows).count()) {
stacks.add(ArrayDeque())
}
matrix.forEachIndexed { columIndex, row ->
row.forEachIndexed { rowIndex, value ->
if (header.size > rowIndex && header[rowIndex] != ' ' && value != ' ') {
println("$columIndex XXX $rowIndex XXX ${header[rowIndex].digitToInt()} XXX $value ")
stacks[header[rowIndex].digitToInt() - 1].add(value)
}
}
}
return stacks
}
fun toPairInputs(input: String): Pair<List<String>, List<String>> {
val split = input
.split("\n\n")
.map { it.split("\n") }
return Pair(split[0], split[1])
}
fun ArrayList<ArrayDeque<Char>>.move(krainInput: List<String>) {
krainInput.forEach {
println(it)
}
val instructionsTriple = krainInput.map {
val instructions = it.split(" ")
Triple(instructions[1].toInt(), instructions[3].toInt(), instructions[5].toInt())
}
println("XXXXXXX")
instructionsTriple.forEach { instruction ->
println(instruction)
for (i in 0..instruction.first - 1) {
this.forEach {
it.forEach {
print(it)
}
println()
}
println()
this[instruction.third - 1]
.add(
this[instruction.second - 1]
.removeLastOrNull()!!
)
}
}
}
fun ArrayList<ArrayDeque<Char>>.move2(krainInput: List<String>) {
krainInput.forEach {
println(it)
}
val instructionsTriple = krainInput.map {
val instructions = it.split(" ")
Triple(instructions[1].toInt(), instructions[3].toInt(), instructions[5].toInt())
}
println("XXXXXXX")
instructionsTriple.forEach { instruction ->
println(instruction)
val movingLoad = ArrayList<Char>()
for (i in 0..instruction.first - 1) {
this.forEach {
it.forEach {
print(it)
}
println()
}
println()
movingLoad
.add(
this[instruction.second - 1]
.removeLastOrNull()!!
)
}
this[instruction.third - 1].addAll(movingLoad.reversed())
}
}
fun part1(input: String): String {
val inputPair = toPairInputs(input)
val stacks: ArrayList<ArrayDeque<Char>> = toStacks(inputPair.first.reversed())
println()
stacks.forEach {
it.forEach {
print(it)
}
println()
}
stacks.move(inputPair.second)
var topElements = ""
stacks.forEach {
topElements += it.last()
}
return topElements
}
fun part2(input: String): String {
val inputPair = toPairInputs(input)
val stacks: ArrayList<ArrayDeque<Char>> = toStacks(inputPair.first.reversed())
println()
stacks.forEach {
it.forEach {
print(it)
}
println()
}
stacks.move2(inputPair.second)
var topElements = ""
stacks.forEach {
topElements += it.last()
}
return topElements
}
// test if implementation meets criteria from the description, like:
val testInput = File("src/day5/Input_test.txt").readText()
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = File("src/day5/Input.txt").readText()
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 57acf4ede18b72df129ea932258ad2d0e2f1b6c3 | 4,393 | advent-of-code-2022 | Apache License 2.0 |
src/Day01.kt | AmandaLi0 | 574,592,026 | false | {"Kotlin": 5338} | fun main() {
// // test if implementation meets criteria from the description, like:
// val testInput = readInput("Day01_test")
// println(part1(testInput))
// //println(part2(input))
//748958
val input = readInput("Day01")
println(cals3Elves(input))
//println(part2(input))
}
fun countCalsPerElf(input: List<String>): Int {
var maxCount = 0
var current = 0
for(num in input){
if(num != ""){
current += num.toInt()
}
else{
if(current > maxCount){
maxCount = current
}
current = 0
}
}
if(current > maxCount){
maxCount = current
}
return maxCount
}
fun cals3Elves(input: List<String>): Int {
val arrayList = ArrayList<Int>()
var current = 0
for(num in input){
if(num != ""){
current += num.toInt()
}
else{
arrayList.add(current)
current = 0
}
}
val sorted = arrayList.map{it}.sortedDescending()
return sorted.take(3).sum()
}
| 0 | Kotlin | 0 | 0 | 5ce0072f3095408688a7812bc3267834f2ee8cee | 1,217 | AdventOfCode | Apache License 2.0 |
src/main/kotlin/com/deflatedpickle/marvin/Version.kt | DeflatedPickle | 282,412,324 | false | null | /* Copyright (c) 2020 DeflatedPickle under the MIT license */
package com.deflatedpickle.marvin
class Version(
val major: Int,
val minor: Int,
val patch: Int = 0
) : Comparable<Version> {
constructor(
major: String,
minor: String,
patch: String = "0"
) : this(
major.toInt(),
minor.toInt(),
patch.toInt()
)
companion object {
val ZERO = Version(0, 0, 0)
fun fromString(version: String): Version {
val split = version.split(".")
return Version(
split[0].toInt(),
split[1].toInt(),
if (split.lastIndex == 2) split[2].toInt() else 0
)
}
}
override fun toString(): String = "$major.$minor.$patch"
override fun equals(other: Any?): Boolean =
if (other is Version) {
this.major == other.major &&
this.minor == other.minor &&
this.patch == other.patch
} else {
false
}
override operator fun compareTo(other: Version): Int {
var cmp: Int = major - other.major
if (cmp == 0) {
cmp = minor - other.minor
if (cmp == 0) {
cmp = patch - other.patch
}
}
return cmp
}
operator fun rangeTo(that: Version): VersionProgression = VersionProgression(this, that)
operator fun plus(i: Int): Version =
when {
this.patch + i < 100 -> {
Version(this.major, this.minor, this.patch + i)
}
this.minor + i < 100 -> {
Version(this.major, this.major + i, this.patch)
}
else -> {
Version(this.major + i, this.minor, this.patch)
}
}
override fun hashCode(): Int {
var result = major
result = 31 * result + minor
result = 31 * result + patch
return result
}
}
class VersionIterator(
private val start: Version,
private val endInclusive: Version
) : Iterator<Version> {
private var current = this.start
override fun hasNext(): Boolean = this.current <= this.endInclusive
override fun next(): Version {
val next = this.current
current = next + 1
return next
}
}
class VersionProgression(
override val start: Version,
override val endInclusive: Version
) : Iterable<Version>, ClosedRange<Version> {
override fun toString(): String = "$start - $endInclusive"
override fun iterator(): Iterator<Version> = VersionIterator(start, endInclusive)
}
/**
* Construct a [Version] from a string patterned as *.*.*
*/
@Throws(StringIndexOutOfBoundsException::class)
fun String.toVersion(): Version =
if (this.count { it == '.' } in listOf(1, 2)) {
val split = this.split('.')
var index = -1
Version(
major = split[++index],
minor = split[++index],
patch = split.getOrNull(++index) ?: "0"
)
} else throw StringIndexOutOfBoundsException()
fun v(version: String) = version.toVersion()
| 2 | Kotlin | 0 | 0 | 83514a67d51f843422e7fb424d480e46490f87f5 | 3,150 | marvin | MIT License |
day08/src/main/kotlin/ver_a_and_b.kt | jabbalaci | 115,397,721 | false | null | import java.io.File
object Registers {
private val map = mutableMapOf<String, Int>()
private var maxValue = 0
fun get(name: String): Int {
if (map.containsKey(name) == false) {
map[name] = 0
}
return map[name]!!
}
fun inc(name: String, num: Int) {
if (map.containsKey(name) == false) {
map[name] = 0
}
val newValue = map[name]!! + num
map[name] = newValue
//
if (newValue > this.maxValue) {
this.maxValue = newValue
}
}
fun dec(name: String, num: Int) {
inc(name, -1 * num)
}
fun getMap(): Map<String, Int> {
return this.map
}
fun getMaxValue() =
this.maxValue
}
fun main(args: Array<String>) {
// val fname = "example.txt"
val fname = "input.txt"
File(fname).forEachLine { line ->
val parts = line.split(Regex("\\s+"))
// println(parts)
if (isTrue(parts[4], parts[5], parts[6])) {
val register = parts[0]
val num = parts[2].toInt()
when(parts[1]) {
"inc" -> Registers.inc(register, num)
"dec" -> Registers.dec(register, num)
}
}
}
// for ((k ,v) in Registers.getMap().entries) {
// println("%s: %d".format(k, v))
// }
println("Highest value (Part A): %d".format(Registers.getMap().values.max()))
println("Highest value ever (Part B): %d".format(Registers.getMaxValue()))
}
fun isTrue(register: String, operator: String, value: String): Boolean {
val registerValue = Registers.get(register)
val num = value.toInt()
return when(operator) {
"==" -> registerValue == num
"!=" -> registerValue != num
"<" -> registerValue < num
"<=" -> registerValue <= num
">" -> registerValue > num
">=" -> registerValue >= num
else -> false // shouldn't ever arrive here
}
}
| 0 | Kotlin | 0 | 0 | bce7c57fbedb78d61390366539cd3ba32b7726da | 1,982 | aoc2017 | MIT License |
src/coursera/QuickSort.kt | fpr0001 | 191,991,724 | false | null | package coursera
// Count the comparisons made by each recursive call
var count = 0
fun main() {
val intArray = getIntArrayFromFile("QuickSort.txt")
count = 0
intArray.quickSort()
intArray.map { print("$it, ") }
println("\nTotal count: $count")
}
fun IntArray.quickSort(intRange: IntRange = 0 until size) {
if (intRange.last - intRange.first == 0) { //array is sorted
return
}
count += intRange.last - intRange.first
val pivotIndex = getPivotIndex(intRange)
val intRanges = partitionArray(pivotIndex, intRange)
quickSort(intRanges.first)
quickSort(intRanges.second)
}
/**
* @return index leftmost and rightmost index of
*/
fun IntArray.partitionArray(pi: Int, intRange: IntRange): Pair<IntRange, IntRange> {
val pivot = get(pi)
var pivotIndex = pi
if (pi != intRange.first) {
swap(intRange.first, pi)
pivotIndex = intRange.first
}
var i = pivotIndex + 1 //divides what's greater than pivot
for (j: Int in intRange) {
val auxJ = get(j)
if (auxJ < pivot) {
swap(i, j)
i++
}
}
swap(pivotIndex, i - 1)
val intRage1: IntRange
intRage1 = if (intRange.first == i - 1) { //pivot is in the first place
IntRange(0, 0)
} else {
IntRange(intRange.first, i - 2)
}
val intRange2 = if (i > intRange.last) {
IntRange(intRange.last, intRange.last)
} else {
IntRange(i, intRange.last)
}
return Pair(intRage1, intRange2)
}
fun IntArray.swap(firstIndex: Int, lastIndex: Int) {
if (firstIndex == lastIndex) return
val firstInt = get(firstIndex)
set(firstIndex, get(lastIndex))
set(lastIndex, firstInt)
}
/**
* Chooses pivot and return its index. You can also use just intRange.first or intRange.last as other
* ways of choosing the pivot
*/
fun IntArray.getPivotIndex(intRange: IntRange): Int {
val first = get(intRange.first)
val size = intRange.last - intRange.first + 1
val secondIndex: Int = if (size.rem(2) != 0) {//is odd
(size / 2)
} else {
(size / 2) - 1
} + intRange.first
val second = get(secondIndex)
val third = get(intRange.last)
val response = when {
first < second && second < third -> secondIndex
third < second && second < first -> secondIndex
second < first && first < third -> intRange.first
third < first && first < second -> intRange.first
second < third && third < first -> intRange.last
first < third && third < second -> intRange.last
else -> intRange.first
}
return response
} | 0 | Kotlin | 0 | 0 | 8878ef2a08303ea39a414e1ef2e9b499ea597d1c | 2,651 | Exercises | MIT License |
src/main/kotlin/boti996/dsl/proba/models/Bonus.kt | boti996 | 215,871,891 | false | {"HTML": 512127, "Kotlin": 53046, "CSS": 2148} | package boti996.dsl.proba.models
/**
* this defines bonus-effect ID-s
*/
enum class BonusEffect(val literal: String) {
REGENERATION("regeneration"),
STRENGTH("strength"),
DEFENSE("defense")
}
/**
* bonus type: this defines a set of [BonusEffect]-s
*/
enum class BonusType {
ANOXIA {
override fun _getBonus(): Map<BonusEffect, Float> = mutableMapOf(
BonusEffect.REGENERATION to 2.0f,
BonusEffect.STRENGTH to 4.0f
)
},
EXTRA_STRENGTH {
override fun _getBonus(): Map<BonusEffect, Float> = mutableMapOf(
BonusEffect.STRENGTH to 6.0f
)
},
EXTRA_DEFENSE {
override fun _getBonus(): Map<BonusEffect, Float> = mutableMapOf(
BonusEffect.DEFENSE to 2.0f
)
},
EXTRA_HEAL {
override fun _getBonus(): Map<BonusEffect, Float> = mutableMapOf(
BonusEffect.REGENERATION to 1.5f
)
};
protected abstract fun _getBonus(): Map<BonusEffect, Float>
/**
* return a set of [BonusEffect]-s
* @param multiplier optional, multiplies [BonusEffect]-s
*/
fun getBonus(multiplier: Float = 1.0f): Map<BonusEffect, Float> {
val map = _getBonus() as MutableMap
map.keys.forEach { key -> map[key] = map[key]!!.times(multiplier) }
return map
}
}
/**
* [Bonus] can be set on object to take effect
*/
interface BonusAcceptor {
fun setBonus(bonus: Bonus)
}
/**
* wrapper for [BonusType] with a multiplier parameter
* @param multiplier multiplies [BonusEffect]-s
*/
data class Bonus(val bonus: BonusType, var multiplier: Float = 1.0f) {
fun getBonus(): Map<BonusEffect, Float> = bonus.getBonus(multiplier)
override fun equals(other: Any?): Boolean {
return other is Bonus &&
bonus == other.bonus &&
multiplier == other.multiplier
}
override fun hashCode(): Int {
var result = bonus.hashCode()
result = 31 * result + multiplier.hashCode()
return result
}
}
/**
* object has accessible [Bonus]-s
*/
interface BonusProvider<T : Enum<T>> {
fun getBonuses(modifierType: T? = null): List<Bonus>
}
| 0 | HTML | 0 | 0 | dd0ac203b64c7d2857037b81d4432f4b04c347f0 | 2,186 | fish_dsl | MIT License |
src/main/kotlin/gameover/fwk/math/MathUtils.kt | gameover-fwk | 38,446,869 | false | {"Kotlin": 114318} | package gameover.fwk.math
import com.badlogic.gdx.math.GridPoint2
import com.badlogic.gdx.math.MathUtils
import com.badlogic.gdx.math.Rectangle
import com.badlogic.gdx.math.Vector2
import gameover.fwk.pool.Vector2Pool
object MathUtils {
/**
* Compute the distance for a list of points.
* For example, if we give three points a, b and c, it
* will compute two distances: from a to b and from b to c
* @param pathPoints the path point
* @return a list of distances
*/
fun distance(pathPoints: List<GridPoint2>?) : List<Double>?
= if (pathPoints != null) pathPoints.mapIndexed { i, p -> if (i == 0) 0.0 else distance(p, pathPoints[i - 1]) } else null
fun floorAsInt(x: Float): Int {
return MathUtils.floor(x)
}
fun floor(x: Float): Float {
return floorAsInt(x).toFloat()
}
/**
* Compute the sum of all distances for a list of points.
* For example, if we give three points a, b and c, it
* will compute two distances: from a to b and from b to c, then it will sum this two distances
* @param pathPoints the path point
* @return a distance
*/
fun distanceSum(pathPoints: List<GridPoint2>?) : Double = distance(pathPoints)?.reduceRight { v, acc -> v + acc } ?: 0.0
fun distance(a: GridPoint2, b: GridPoint2) : Double = Math.sqrt(Math.pow((b.x - a.x).toDouble(), 2.0) + Math.pow((b.y - a.y).toDouble(), 2.0))
fun computeAngle(x1: Float, y1: Float, x2: Float, y2: Float): Float = computeAngle(x2 - x1, y2 - y1)
fun computeAngle(dx: Float, dy: Float): Float {
val dv: Vector2 = Vector2Pool.obtain(dx, dy)
try {
return dv.angle()
} finally {
Vector2Pool.free(dv)
}
}
/**
* Find directions to reach a point from a point.
*/
fun directions(x: Float, y: Float, tx: Float, ty: Float) : Directions {
val diffX = Math.signum(tx - x)
val diffY = Math.signum(ty - y)
return Directions(diffY > 0f, diffY < 0f, diffX < 0f, diffX > 0f)
}
/**
* Return all edges
*/
fun edges(area: Rectangle) : List<Pair<Float, Float>> =
listOf(Pair(area.x, area.y), Pair(area.x + area.width, area.y), Pair(area.x, area.y + area.height), Pair(area.x + area.width, area.y + area.height))
/**
* Return all edges sorted from the closest to farest
*/
fun nearestEdges(x: Float, y: Float, area: Rectangle) : List<Pair<Float, Float>> {
return edges(area).sortedBy {
(tx, ty) -> Math.pow((tx - x).toDouble(), 2.0) + Math.pow((ty - y).toDouble(), 2.0)
}
}
}
data class Directions(val top: Boolean, val bottom: Boolean, val left: Boolean, val right: Boolean)
| 0 | Kotlin | 0 | 7 | 7a87e1eba73e4a16a2a3dd58f5818c49d9460996 | 2,742 | gameover-fwk | MIT License |
utils/utils-kotlin/src/main/kotlin/de/havox_design/aoc/utils/kotlin/model/coordinates/Coordinate.kt | Gentleman1983 | 737,309,232 | false | {"Kotlin": 746488, "Java": 441473, "Scala": 33415, "Groovy": 5725, "Python": 3319} | package de.havox_design.aoc.utils.kotlin.model.coordinates
import kotlin.math.abs
data class Coordinate(val x: Int, val y: Int) : Comparable<Coordinate> {
override fun compareTo(other: Coordinate): Int =
when (val result = y.compareTo(other.y)) {
0 -> x.compareTo(other.x)
else -> result
}
operator fun minus(other: Coordinate): Coordinate =
Coordinate(x - other.x, y - other.y)
operator fun plus(other: Coordinate): Coordinate =
Coordinate(x + other.x, y + other.y)
operator fun plus(i: Number): Coordinate =
plus(Coordinate(i.toInt(), i.toInt()))
operator fun times(i: Number): Coordinate =
this * Coordinate(i.toInt(), i.toInt())
operator fun times(other: Coordinate): Coordinate =
Coordinate(x * other.x, y * other.y)
operator fun div(other: Coordinate): Coordinate =
Coordinate(x / other.x, y / other.y)
}
fun manhattanDistance(a: Coordinate, b: Coordinate) =
abs(a.x - b.x) + abs(a.y - b.y)
val origin = Coordinate(0, 0)
fun <V> Map<Coordinate, V>.yRange() =
keys.minByOrNull { it.y }!!.y to keys.maxByOrNull { it.y }!!.y
fun <V> Map<Coordinate, V>.xRange() =
keys.minByOrNull { it.x }!!.x to keys.maxByOrNull { it.x }!!.x
fun adjacentCoordinates(origin: Coordinate) = sequenceOf(
Coordinate(origin.x + 1, origin.y),
Coordinate(origin.x - 1, origin.y),
Coordinate(origin.x, origin.y + 1),
Coordinate(origin.x, origin.y - 1)
)
| 4 | Kotlin | 0 | 1 | 35ce3f13415f6bb515bd510a1f540ebd0c3afb04 | 1,490 | advent-of-code | Apache License 2.0 |
Coding Challenges/Advent of Code/2021/Day 10/part2.kt | Alphabeater | 435,048,407 | false | {"Kotlin": 69566, "Python": 5974} | import java.io.File
import java.util.Scanner
val list = listOf('(', '[', '{', '<')
val lineScores = mutableListOf<Long>()
val scoreDict = mapOf('(' to 1, '[' to 2, '{' to 3, '<' to 4) //scores for each character.
fun analyzeLine(l: String) { //if it's a corrupted line, skip. If it's an incomplete line, it's evaluated by getScore().
var line = l
outerLoop@ while(true) {
innerLoop@ for (i in line.indices) {
if (i < line.length - 1)
when (line[i]) {
'(' -> {
if (line[i + 1] == ')') {
line = line.removeRange(i..i + 1)
break@innerLoop
} else {
if (line[i + 1] !in list) break@outerLoop
}
}
'[' -> {
if (line[i + 1] == ']') {
line = line.removeRange(i..i + 1)
break@innerLoop
} else {
if (line[i + 1] !in list) break@outerLoop
}
}
'{' -> {
if (line[i + 1] == '}') {
line = line.removeRange(i..i + 1)
break@innerLoop
} else {
if (line[i + 1] !in list) break@outerLoop
}
}
'<' -> {
if (line[i + 1] == '>') {
line = line.removeRange(i..i + 1)
break@innerLoop
} else {
if (line[i + 1] !in list) break@outerLoop
}
}
else -> break@innerLoop
}
else {
getScore(line)
break@outerLoop
}
}
}
}
fun getScore(line: String) { //reverse the incomplete line and loop it, using the formula provided.
var score = 0L
for (char in line.reversed()) {
score *= 5
score += scoreDict[char]!!
}
lineScores.add(score)
}
fun main() {
val file = File("src/input.txt")
val scanner = Scanner(file)
while (scanner.hasNextLine()) {
val line = scanner.nextLine()!!
analyzeLine(line)
}
println(lineScores.sorted()[lineScores.size/2]) //sort the values and display the one in the middle.
}
| 0 | Kotlin | 0 | 0 | 05c8d4614e025ed2f26fef2e5b1581630201adf0 | 2,564 | Archive | MIT License |
src/aoc2022/Day14.kt | anitakar | 576,901,981 | false | {"Kotlin": 124382} | package aoc2022
import println
import readInput
fun main() {
fun print(grid: Array<CharArray>) {
for (i in grid.indices) {
for (j in grid[0].indices) {
print(grid[i][j])
}
println()
}
}
fun part1(input: List<String>): Int {
var minx = 500
var maxx = 500
var miny = 0
var maxy = 0
for (line in input) {
val coords = line.split(" -> ")
for (coord in coords) {
val (x, y) = coord.split(",")
minx = Math.min(minx, x.toInt())
maxx = Math.max(maxx, x.toInt())
miny = Math.min(miny, y.toInt())
maxy = Math.max(maxy, y.toInt())
}
}
val grid = Array<CharArray>(maxy - miny + 1) { CharArray(maxx - minx + 3) }
for (i in grid.indices) {
for (j in grid[0].indices) {
grid[i][j] = '.'
}
}
grid[0][500 - minx + 1] = '+'
for (line in input) {
val coords = line.split(" -> ")
val (prevXs, prevYs) = coords[0].split(",")
var prevX = prevXs.toInt() - minx + 1
var prevY = prevYs.toInt() - miny
for (i in 1 until coords.size) {
val (xs, ys) = coords[i].split(",")
val x = xs.toInt() - minx + 1
val y = ys.toInt() - miny
if (prevX == x) {
for (ny in Math.min(y, prevY)..Math.max(y, prevY)) {
grid[ny][x] = '#'
}
}
if (prevY == y) {
for (nx in Math.min(x, prevX)..Math.max(x, prevX)) {
grid[y][nx] = '#'
}
}
prevX = x
prevY = y
}
}
var grain = 1
while (true) {
var droplety = 0
var dropletx = 500 - minx + 1
var moved = true
do {
if (grid[droplety + 1][dropletx] == '.') {
droplety += 1
} else if (grid[droplety + 1][dropletx - 1] == '.') {
droplety += 1
dropletx -= 1
} else if (grid[droplety + 1][dropletx + 1] == '.') {
droplety += 1
dropletx += 1
} else {
moved = false
grid[droplety][dropletx] = 'o'
}
if (droplety == maxy) return grain - 1
} while (moved)
grain += 1
}
return grain
}
fun part2(input: List<String>): Int {
var minx = 500
var maxx = 500
var miny = 0
var maxy = 0
for (line in input) {
val coords = line.split(" -> ")
for (coord in coords) {
val (x, y) = coord.split(",")
minx = Math.min(minx, x.toInt())
maxx = Math.max(maxx, x.toInt())
miny = Math.min(miny, y.toInt())
maxy = Math.max(maxy, y.toInt())
}
}
val grid = Array<CharArray>(maxy - miny + 3) { CharArray(maxx - minx + 3 + 400) }
for (i in grid.indices) {
for (j in grid[0].indices) {
grid[i][j] = '.'
}
}
for (j in grid[0].indices) {
grid[maxy + 2][j] = '#'
}
grid[0][500 - minx + 1 + 200] = '+'
for (line in input) {
val coords = line.split(" -> ")
val (prevXs, prevYs) = coords[0].split(",")
var prevX = prevXs.toInt() - minx + 1 + 200
var prevY = prevYs.toInt() - miny
for (i in 1 until coords.size) {
val (xs, ys) = coords[i].split(",")
val x = xs.toInt() - minx + 1 + 200
val y = ys.toInt() - miny
if (prevX == x) {
for (ny in Math.min(y, prevY)..Math.max(y, prevY)) {
grid[ny][x] = '#'
}
}
if (prevY == y) {
for (nx in Math.min(x, prevX)..Math.max(x, prevX)) {
grid[y][nx] = '#'
}
}
prevX = x
prevY = y
}
}
var grain = 1
while (true) {
var droplety = 0
var dropletx = 500 - minx + 1 + 200
var moved = true
do {
if (grid[droplety + 1][dropletx] == '.') {
droplety += 1
} else if (grid[droplety + 1][dropletx - 1] == '.') {
droplety += 1
dropletx -= 1
} else if (grid[droplety + 1][dropletx + 1] == '.') {
droplety += 1
dropletx += 1
} else {
moved = false
grid[droplety][dropletx] = 'o'
if (droplety == 0) {
return grain
}
}
} while (moved)
grain += 1
}
return grain
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day14_test")
check(part1(testInput) == 24)
check(part2(testInput) == 93)
val input = readInput("Day14")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 1 | 50998a75d9582d4f5a77b829a9e5d4b88f4f2fcf | 5,558 | advent-of-code-kotlin | Apache License 2.0 |
src/main/kotlin/days/Day11.kt | wmichaelshirk | 315,495,224 | false | null | package days
class Day11 : Day(11) {
private val width = inputString.indexOf('\n') + 1
override fun partOne(): Int {
val surroundingIndices = listOf(
-width - 1, -width , -width + 1,
-1, 1, width - 1, width , width + 1
)
var prev = listOf<Char>()
var cur = inputString.toList()
while (prev != cur) {
prev = cur
cur = prev.mapIndexed { index, s ->
// 1) If a seat is empty (L) and there are no occupied seats adjacent to it,
// the seat becomes occupied.
// 2) If a seat is occupied (#) and four or more seats adjacent to it are also occupied, the seat becomes empty.
// 3) Otherwise, the seat's state does not change.
val surrounding = surroundingIndices
.map { prev.getOrNull(index + it) }
.count { it == '#' }
if (s == 'L' && surrounding == 0) '#'
else if (s == '#' && surrounding >= 4) 'L'
else s
}
}
return cur.count { it == '#' }
}
override fun partTwo(): Int {
val surroundingIndices = listOf(
-1 to -1,
0 to -1,
1 to -1,
-1 to 0,
1 to 0,
-1 to 1,
0 to 1,
1 to 1
)
var prev = listOf<Char>()
var cur = inputString.toList()
while (prev != cur) {
prev = cur
cur = prev.mapIndexed { index, s ->
// 1) If a seat is empty (L) and there are no occupied seats adjacent to it,
// the seat becomes occupied.
// 2) If a seat is occupied (#) and four or more seats adjacent to it are also occupied, the seat becomes empty.
// 3) Otherwise, the seat's state does not change.
val surrounding = surroundingIndices
.map {
val (xd, yd) = it
var loc = index
var first: Char? = '.'
while (first == '.') {
loc += (xd + yd * width)
first = prev.getOrNull(loc)
}
first
}
.count { it == '#' }
if (s == 'L' && surrounding == 0) '#'
else if (s == '#' && surrounding >= 5) 'L'
else s
}
}
return cur.count { it == '#' }
}
}
| 0 | Kotlin | 0 | 0 | b36e5236f81e5368f9f6dbed09a9e4a8d3da8e30 | 2,590 | 2020-Advent-of-Code | Creative Commons Zero v1.0 Universal |
src/y2015/Day11.kt | gaetjen | 572,857,330 | false | {"Kotlin": 325874, "Mermaid": 571} | package y2015
object Day11 {
fun next(str: String): String {
val chars = str.toCharArray().toMutableList()
var idx = str.length - 1
while (idx >= 0) {
chars[idx] = chars[idx] + 1
if (chars[idx] > 'z') {
chars[idx] = 'a'
idx--
} else {
break
}
}
return chars.joinToString(separator = "") { it.toString() }
}
fun isSecure(password: String) : Boolean {
if (password.contains(Regex("[iol]"))) {
return false
}
if (!password.contains(Regex(
"abc|bcd|cde|def|efg|fgh|pqr|qrs|rst|stu|tuv|uvw<PASSWORD>"
))) {
return false
}
return password.windowed(2, 1).filter { it[0] == it[1] }.toSet().size >= 2
}
fun part1(input: String): String {
var result = input
while (true) {
result = next(result)
if (isSecure(result)) {
break
}
}
return result
}
fun part2(input: String): String {
return part1(part1(input))
}
}
fun main() {
println((-1).mod(3))
println(Day11.next("zzz"))
println("ghjaabcc is secure: ${Day11.isSecure("ghjaabcc")}")
val testInput = "abcdefgh"
println("------Tests------")
println(Day11.part1(testInput))
println(Day11.part1("ghijklmn"))
println(Day11.part2(testInput))
println("------Real------")
val input = "hxbxwxba"
println(Day11.part1(input))
println(Day11.part2(input))
}
| 0 | Kotlin | 0 | 0 | d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a | 1,586 | advent-of-code | Apache License 2.0 |
src/com/freaklius/kotlin/algorithms/sort/Util.kt | vania-pooh | 8,736,623 | false | null | package com.freaklius.kotlin.algorithms.sort
import java.util.Random
/**
* Contains a set of utility methods like printing array contents and so on
*/
/**
* Prints contents of an array
* @param arr an array to be converted to string
*/
fun <T> arrayToString(arr: Array<T> ) : String{
var str = "Array("
var isFirst = true
for (element in arr){
if (!isFirst){
str += ", "
}
str += element
if (isFirst){
isFirst = false
}
}
str += ")"
return str
}
/**
* Returns a shuffled version of the input array
* @param arr an array to shuffle
*/
fun shuffleArray(arr: Array<Long>) : Array<Long>{
val rg = Random()
for (i in 0..arr.size - 1) {
val randomPosition = rg.nextInt(arr.size)
swap(arr, i, randomPosition)
}
return arr
}
/**
* Swaps i-th and j-th elemens of the array
* @param arr
* @param i
* @param j
*/
fun swap(arr: Array<Long>, i: Int, j: Int) : Array<Long>{
val tmp : Long = arr[i]
arr[i] = arr[j]
arr[j] = tmp
return arr
}
/**
* Creates random array or Long of given length and max value
* @param length length of an array to be generated
* @param maxValue
*/
fun randomNumericArray(length: Int, maxValue : Int = 10) : Array<Long>{
return Array<Long>(length, {i -> Math.round(maxValue * Math.random())})
}
/**
* Returns whether given array is sorted in ascending order
* @param arr array to be checked
*/
fun isSortedAsc(arr: Array<Long>) : Boolean{
for (i in 0..arr.size - 2){
if (arr[i] > arr[i + 1]){
return false
}
}
return true
}
/**
* Returns maximum value of an array (a linear complexity operation).
*/
fun maximum(arr: Array<Long>) : Int{
var max = 0
for (value in arr){
if (value > max){
max = value.toInt()
}
}
return max
} | 1 | Kotlin | 14 | 51 | 8c5e7b52d2831322d578af895cd4e80fbe471950 | 1,891 | kotlin-algorithms | MIT License |
src/main/kotlin/g0201_0300/s0289_game_of_life/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g0201_0300.s0289_game_of_life
// #Medium #Top_Interview_Questions #Array #Matrix #Simulation
// #2022_11_04_Time_174_ms_(96.97%)_Space_34.2_MB_(93.94%)
class Solution {
companion object {
var dim: Array<IntArray> = arrayOf(
intArrayOf(1, 0), intArrayOf(0, 1), intArrayOf(-1, 0), intArrayOf(0, -1),
intArrayOf(1, 1), intArrayOf(1, -1), intArrayOf(-1, 1), intArrayOf(-1, -1)
)
}
fun gameOfLife(board: Array<IntArray>) {
for (i in board.indices) {
for (j in board[0].indices) {
val com = compute(board, i, j)
if (board[i][j] == 0) {
if (com == 3) {
board[i][j] = -1
}
} else if (board[i][j] == 1 && (com < 2 || com > 3)) {
board[i][j] = 2
}
}
}
update(board)
}
private fun update(board: Array<IntArray>) {
for (i in board.indices) {
for (j in board[0].indices) {
if (board[i][j] == -1) {
board[i][j] = 1
} else if (board[i][j] == 2) {
board[i][j] = 0
}
}
}
}
private fun compute(board: Array<IntArray>, r: Int, c: Int): Int {
var ret: Int = 0
for (arr in dim) {
val row = arr[0] + r
val col = arr[1] + c
if (row >= 0 && row < board.size && col >= 0 && col < board[0].size &&
(board[row][col] == 1 || board[row][col] == 2)
) {
ret++
}
}
return ret
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,682 | LeetCode-in-Kotlin | MIT License |
src/Day01.kt | Ajimi | 572,961,710 | false | {"Kotlin": 11228} | fun main() {
fun part1(input: List<String>): Int {
return input.caloriesSum().max()
}
fun part2(input: List<String>): Int {
return input.caloriesSum().sortedDescending().subList(0, 3).sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
fun List<String>.caloriesSum(): MutableList<Int> {
val caloriesSumsByElf = mutableListOf<Int>()
var caloriesCount = 0
forEach { line ->
if (line.isEmpty()) {
caloriesSumsByElf.add(caloriesCount)
caloriesCount = 0
} else {
caloriesCount += line.toInt()
}
}
return caloriesSumsByElf
}
| 0 | Kotlin | 0 | 0 | 8c2211694111ee622ebb48f52f36547fe247be42 | 836 | adventofcode-2022 | Apache License 2.0 |
src/Day07.kt | kprow | 573,685,824 | false | {"Kotlin": 23005} | fun main() {
fun part1(input: List<String>): Int {
var files = mutableListOf<File>()
var dirs = mutableListOf<Directory>()
for ((index, ls) in input.withIndex()) {
val lsResult = ls.split(" ")
if (lsResult[0].toIntOrNull() != null) {
files += File(lsResult[1], lsResult[0].toInt(), index)
}
if (lsResult[1] == "cd" && lsResult[2] != "..") {
dirs += Directory(lsResult[2], index)
}
}
var directoryContents = mutableMapOf<String, MutableList<File>>()
files.forEach {
print(it.size)
val dir = it.findDirectory(input)
println(" " + it.name + " " + dir)
val dirFiles = if (directoryContents[dir] == null) {
directoryContents[dir] = arrayListOf(it)
} else {
directoryContents[dir]!! += it
}
}
// check(directoryContents["a"]!!.size == 3)
// check(directoryContents["e"]!!.size == 1)
// check(directoryContents["d"]!!.size == 4)
// check(dirs.size == 4)
dirs.forEach { it.findChild(input) }
val dirsMap = dirs.associateBy(keySelector = {it.name}, valueTransform = {it})
var dirSize = mutableMapOf<String, Int>()
for (dir in dirs) {
val size = dir.findDirSize(dirsMap, directoryContents)
dirSize[dir.name] = size
}
// val eSize = dirs[2].findDirSize(dirsMap, directoryContents)
// check(eSize == 584)
// val aSize = dirs[1].findDirSize(dirsMap, directoryContents)
// check(aSize == 94853)
var sumOfDirSizeUnderTenK = 0
for ((dirName, size) in dirSize) {
if (size < 100000) {
sumOfDirSizeUnderTenK += size
}
}
return sumOfDirSizeUnderTenK
}
fun part2(input: List<String>): Int {
var files = mutableListOf<File>()
var dirs = mutableListOf<Directory>()
for ((index, ls) in input.withIndex()) {
val lsResult = ls.split(" ")
if (lsResult[0].toIntOrNull() != null) {
files += File(lsResult[1], lsResult[0].toInt(), index)
}
if (lsResult[1] == "cd" && lsResult[2] != "..") {
dirs += Directory(lsResult[2], index)
}
}
var directoryContents = mutableMapOf<String, MutableList<File>>()
files.forEach {
print(it.size)
val dir = it.findDirectory(input)
println(" " + it.name + " " + dir)
val dirFiles = if (directoryContents[dir] == null) {
directoryContents[dir] = arrayListOf(it)
} else {
directoryContents[dir]!! += it
}
}
// check(directoryContents["a"]!!.size == 3)
// check(directoryContents["e"]!!.size == 1)
// check(directoryContents["d"]!!.size == 4)
// check(dirs.size == 4)
dirs.forEach { it.findChild(input) }
val dirsMap = dirs.associateBy(keySelector = {it.name}, valueTransform = {it})
var dirSize = mutableMapOf<String, Int>()
for (dir in dirs) {
val size = dir.findDirSize(dirsMap, directoryContents)
dirSize[dir.name] = size
}
val dirSizeDelete = 30000000 - (70000000 - dirSize["/"]!!)
var currentDelete = 70000000
for ((dirName, size) in dirSize) {
if (size > dirSizeDelete && size <= currentDelete) {
currentDelete = size
}
}
return currentDelete
}
val testInput = readInput("Day07_test")
check(part1(testInput) == 95437)
val input = readInput("Day07")
// println(part1(input))
println(part2(input))
}
class Directory(val name: String, val inputIndex: Int) {
var children = mutableListOf<String>()
fun findChild(input: List<String>) {
for (n in inputIndex + 1..input.size - 1) {
val endDirContentsFind = "$ cd "
if (input[n].startsWith(endDirContentsFind)) {
return
} else {
val dirFind = "dir "
if (input[n].startsWith(dirFind)) {
children += input[n].split(dirFind)[1]
}
}
}
}
fun findDirSize(map: Map<String, Directory>, dirContents: Map<String, List<File>>): Int {
if (map[name]!!.children.isEmpty()) {
return dirContents[name]!!.sumOf { it.size }
} else {
val childDirs = map[name]!!.children.map { map[it]!! }
val sizOfCurrent = dirContents[name]?.let { it.sumOf { it.size } } ?: run { 0 }
return childDirs.sumOf { it.findDirSize(map, dirContents) } + sizOfCurrent
}
}
}
class File(val name: String, val size: Int, val inputIndex: Int) {
fun findDirectory(input: List<String>): String {
for (n in inputIndex downTo 0) {
val findDirString = "$ cd "
if (input[n].startsWith(findDirString)) {
val cdCommand = input[n].split(findDirString)
return cdCommand[1]
}
}
return ""
}
} | 0 | Kotlin | 0 | 0 | 9a1f48d2a49aeac71fa948656ae8c0a32862334c | 5,232 | AdventOfCode2022 | Apache License 2.0 |
src/problems/day10/part1/part1.kt | klnusbaum | 733,782,662 | false | {"Kotlin": 43060} | package problems.day10.part1
import java.io.File
private const val testFile1 = "input/day10/test1.txt"
private const val inputFile = "input/day10/input.txt"
fun main() {
val farthestTileDistance = File(inputFile).bufferedReader().useLines { farthestTileDistance(it) }
println("The tile farthest from start is $farthestTileDistance tiles away")
}
fun farthestTileDistance(it: Sequence<String>): Int {
val board = it.fold(BoardBuilder()) { builder, line -> builder.nextLine(line) }.build()
// println("Board: ${board.tiles}")
// println("start: ${board.startRow} ${board.startCol}")
val totalDistance = board.totalPipeDistance()
return totalDistance / 2
}
private class BoardBuilder {
private val tiles = mutableMapOf<Location, Tile>()
private var start: Location? = null
private var rowIndex = 0
fun nextLine(line: String): BoardBuilder {
line.forEachIndexed { colIndex, c ->
val tile = c.toTile()
val location = Location(rowIndex, colIndex)
if (tile is Tile.Start) {
start = location
}
tiles[location] = tile
}
rowIndex++
return this
}
fun build() = Board(
tiles,
start ?: throw IllegalArgumentException("No location found for start"),
)
}
private class Board(val tiles: Map<Location, Tile>, val start: Location) {
fun totalPipeDistance(): Int {
var previousLocation = start
var (currentLocation, currentTile) = nextFromStart()
var distance = 1
while (currentLocation != start) {
val (nextLocation, nextTile) = nextTile(previousLocation, currentLocation, currentTile)
previousLocation = currentLocation
currentLocation = nextLocation
currentTile = nextTile
distance++
}
return distance
}
private fun nextFromStart(): Pair<Location, Tile> {
val northernLocation = start.toNorth()
val northernTile = tiles[northernLocation]
if (northernTile?.opensOn(Direction.SOUTH) == true) {
return Pair(northernLocation, northernTile)
}
val southernLocation = start.toSouth()
val southernTile = tiles[southernLocation]
if (southernTile?.opensOn(Direction.NORTH) == true) {
return Pair(southernLocation, southernTile)
}
val westernLocation = start.toWest()
val westernTile = tiles[westernLocation]
if (westernTile?.opensOn(Direction.EAST) == true) {
return Pair(westernLocation, westernTile)
}
val easternLocation = start.toEast()
val easternTile = tiles[easternLocation]
if (easternTile?.opensOn(Direction.WEST) == true) {
return Pair(easternLocation, easternTile)
}
throw IllegalArgumentException("No tile accessible from start")
}
private fun nextTile(
previousLocation: Location,
currentLocation: Location,
currentTile: Tile
): Pair<Location, Tile> {
if (currentTile.opensOn(Direction.NORTH)) {
val northernLocation = currentLocation.toNorth()
val northernTile = tiles[northernLocation]
if (northernTile?.opensOn(Direction.SOUTH) == true && northernLocation != previousLocation) {
return Pair(northernLocation, northernTile)
}
}
if (currentTile.opensOn(Direction.SOUTH)) {
val southernLocation = currentLocation.toSouth()
val southernTile = tiles[southernLocation]
if (southernTile?.opensOn(Direction.NORTH) == true && southernLocation != previousLocation) {
return Pair(southernLocation, southernTile)
}
}
if (currentTile.opensOn(Direction.WEST)) {
val westernLocation = currentLocation.toWest()
val westernTile = tiles[westernLocation]
if (westernTile?.opensOn(Direction.EAST) == true && westernLocation != previousLocation) {
return Pair(westernLocation, westernTile)
}
}
if (currentTile.opensOn(Direction.EAST)) {
val easternLocation = currentLocation.toEast()
val easternTile = tiles[easternLocation]
if (easternTile?.opensOn(Direction.WEST) == true && easternLocation != previousLocation) {
return Pair(easternLocation, easternTile)
}
}
throw IllegalArgumentException("No next tile from $currentLocation")
}
}
private data class Location(val row: Int, val col: Int) {
fun toNorth(): Location = Location(row - 1, col)
fun toSouth(): Location = Location(row + 1, col)
fun toWest(): Location = Location(row, col - 1)
fun toEast(): Location = Location(row, col + 1)
}
private sealed class Tile {
data class Pipe(val first: Direction, val second: Direction) : Tile()
data object Ground : Tile()
data object Start : Tile()
fun opensOn(direction: Direction) = when (this) {
is Pipe -> this.first == direction || this.second == direction
is Start -> true
else -> false
}
}
private fun Char.toTile(): Tile = when (this) {
'|' -> Tile.Pipe(Direction.NORTH, Direction.SOUTH)
'-' -> Tile.Pipe(Direction.EAST, Direction.WEST)
'L' -> Tile.Pipe(Direction.NORTH, Direction.EAST)
'J' -> Tile.Pipe(Direction.NORTH, Direction.WEST)
'7' -> Tile.Pipe(Direction.SOUTH, Direction.WEST)
'F' -> Tile.Pipe(Direction.SOUTH, Direction.EAST)
'S' -> Tile.Start
else -> Tile.Ground
}
private enum class Direction {
NORTH,
SOUTH,
EAST,
WEST,
} | 0 | Kotlin | 0 | 0 | d30db2441acfc5b12b52b4d56f6dee9247a6f3ed | 5,689 | aoc2023 | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/ShortestWordDistance2.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import kotlin.math.abs
import kotlin.math.min
class ShortestWordDistance2(words: Array<String>) {
private val locations: MutableMap<String, MutableList<Int>> = HashMap()
init {
// Prepare a mapping from a word to all it's locations (indices).
for (i in words.indices) {
val loc = locations.getOrDefault(words[i], ArrayList())
loc.add(i)
locations[words[i]] = loc
}
}
fun shortest(word1: String, word2: String): Int {
val loc1: MutableList<Int> = locations[word1] ?: ArrayList()
val loc2: MutableList<Int> = locations[word2] ?: ArrayList()
// Location lists for both the words
// the indices will be in SORTED order by default
var l1 = 0
var l2 = 0
var minDiff = Int.MAX_VALUE
while (l1 < loc1.size && l2 < loc2.size) {
minDiff = min(minDiff, abs(loc1[l1] - loc2[l2]))
if (loc1[l1] < loc2[l2]) {
l1++
} else {
l2++
}
}
return minDiff
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,724 | kotlab | Apache License 2.0 |
Bootcamp_00/src/exercise4/src/main/kotlin/Exercise3.kt | Hasuk1 | 740,111,124 | false | {"Kotlin": 120039} | enum class Mode {
CELSIUS, KELVIN, FAHRENHEIT
}
fun readOutputMode(): Mode {
while (true) {
try {
print("Output mode: ")
val input = readLine()
?: throw IllegalArgumentException("The output format is not correct. Standard format - Celsius is set")
return when (input.uppercase()) {
"CELSIUS" -> Mode.CELSIUS
"KELVIN" -> Mode.KELVIN
"FAHRENHEIT" -> Mode.FAHRENHEIT
else -> {
println("The output format is not correct. Standard format - Celsius is set")
return Mode.CELSIUS
}
}
} catch (e: IllegalArgumentException) {
println(e.message)
return Mode.CELSIUS
}
}
}
enum class Season {
SUMMER, WINTER
}
fun readSeason(): Season {
while (true) {
println("Enter a season - (W)inter or (S)ummer: ")
val input = readLine()?.uppercase()
if (input == "W" || input == "WINTER") {
return Season.WINTER
} else if (input == "S" || input == "SUMMER") {
return Season.SUMMER
} else {
println("Incorrect input. Please enter either 'W' for Winter or 'S' for Summer.")
}
}
}
fun readTemperature(): Float {
while (true) {
try {
println("Enter a temperature in Celsius (˚C): ")
val input = readLine()?.toFloatOrNull()
if (input != null && input >= -50 && input <= 50) {
return input
} else {
println("Incorrect input. Please enter a valid temperature.")
}
} catch (e: NumberFormatException) {
println("Failed to parse the temperature. Please try again.")
}
}
}
fun getModeSymbol(outputMode: Mode): String {
return when (outputMode) {
Mode.CELSIUS -> "˚C"
Mode.FAHRENHEIT -> "°F"
Mode.KELVIN -> "K"
}
}
fun getComfortableTemperatureRange(seasonInput: Season, outputMode: Mode): ClosedRange<Float> {
return when (outputMode) {
Mode.CELSIUS -> when (seasonInput) {
Season.SUMMER -> 22f..25f
Season.WINTER -> 20f..22f
}
Mode.KELVIN -> when (seasonInput) {
Season.SUMMER -> 295.15f..298.15f
Season.WINTER -> 293.15f..295.15f
}
Mode.FAHRENHEIT -> when (seasonInput) {
Season.SUMMER -> 71.6f..77f
Season.WINTER -> 68f..71.6f
}
}
}
fun setTemperatureAsMod(outputMode: Mode, temperatureInput: Float): Float {
return when (outputMode) {
Mode.CELSIUS -> temperatureInput
Mode.FAHRENHEIT -> (temperatureInput * 9 / 5) + 32
Mode.KELVIN -> (temperatureInput + 273.15f)
}
}
| 0 | Kotlin | 0 | 1 | 1dc4de50dd3cd875e3fe76e3da4a58aa04bb87c7 | 2,483 | Kotlin_bootcamp | MIT License |
src/main/kotlin/nl/meine/aoc/_2023/Day7.kt | mtoonen | 158,697,380 | false | {"Kotlin": 201978, "Java": 138385} | package nl.meine.aoc._2023
class Day7 {
fun one(input: String): Int {
val lines = createHands(input)
val h = orderHands(lines)
h.forEach { println(it) }
return h.mapIndexed { rank, hand -> (rank + 1) * hand.bid }
.sum()
}
fun createHands(input: String): MutableList<Hand> {
return input.split("\n")
.map { it.split(" ") }
.map { Hand(it[0].chunked(1).map { c -> Card.getCard(c) }.toList(), it[1].toInt()) }
.map { processJokers(it) }
.toMutableList()
}
fun orderHands(hand: MutableList<Hand>): MutableList<Hand> {
hand.sort()
hand.reversed()
return hand
}
fun processJokers(hand: Hand): Hand {
val initial = hand.hand.filter { it.name != "J" }.groupingBy { it }.eachCount().toMutableMap()
if (initial.isEmpty()) {
initial[Card.A] = 0
}
val a = initial.maxBy { it.value }.key
initial[a] = initial[a]!! + hand.hand.count { it.name == "J" }
hand.counts = initial
return hand
}
fun two(input: String): Int {
val lines = createHands(input)
val h = orderHands(lines)
h.forEach { println(it) }
return h.mapIndexed { rank, hand -> (rank + 1) * hand.bid }
.sum()
}
}
// two: 250665479
// 250665248
fun main() {
val inputReal =
"""9A35J 469
75T32 237
6T8JQ 427
3366A 814
K2AK9 982
J8KTT 9
94936 970
Q8AK9 15
3QQ32 940
65555 484
8K88K 674
Q67T5 788
77575 476
KAKAA 785
AA3AA 240
44767 423
Q923A 300
KK444 650
QQQ6Q 313
5JA22 167
7A264 837
TTKTT 646
K62JJ 682
34A63 532
7J554 393
Q86T6 745
9963K 718
92K85 97
3KKJ3 604
98Q26 257
7AJ6Q 132
K48T5 125
554J4 408
T6333 178
5757J 479
8J222 488
KKJ6A 460
95T38 944
23J22 796
AK333 69
25AK9 978
77779 123
K9T83 56
46A39 730
655J5 77
A2T2A 78
J8Q75 847
QA82A 700
TTT67 443
KT9A5 343
6969T 582
A7779 703
3QA93 597
6JT6T 558
28888 290
26TT2 147
T9356 587
6T542 482
3J733 140
TQT72 534
3K3K3 208
5JA6J 833
64646 277
86K68 795
24455 997
3633K 504
K3K36 790
22KK2 731
AA8AA 991
A6666 312
38395 712
46J44 229
52529 268
49AA9 573
J7J94 258
87TKA 947
J2999 555
T9KJK 194
7KK3K 146
T255T 875
9QAT4 475
759A2 169
22322 510
27T69 299
644K6 4
44J84 227
6A722 806
775KJ 25
37425 679
7TA8T 226
3Q6TK 391
8T3J4 196
67534 339
5QQ55 565
J33A3 305
8A8AJ 732
2QQJ5 523
AAAJA 618
97733 858
2A6Q2 433
J8QT3 390
3333J 910
K2AK2 884
AQTTQ 810
55666 855
7Q7QJ 743
K8KK3 489
4AKKJ 619
QQKQQ 373
QJ59A 688
2687J 622
7Q77J 512
578A3 120
T2662 737
JKJK7 807
44T94 223
454Q5 607
75J58 551
A686J 763
TAT4T 108
75356 591
96989 977
K7KTK 775
5252Q 318
77A5A 599
22K87 359
JJQQQ 930
8TKT8 436
A9QQ8 374
4T2JA 30
777AJ 463
8J888 87
42K8Q 657
J5JJ5 713
AKQJ3 45
T59K4 765
22A77 266
K8KK8 219
6T666 349
72T7T 92
3JQJQ 964
AA2J9 672
66997 803
5A8A2 467
KKKQ7 98
67Q5J 669
J57A6 503
98347 331
6J668 279
9K7KK 319
84848 337
33353 974
A333T 576
66636 461
6AAA2 281
Q52QQ 691
7876A 892
533T8 966
5A9Q7 533
A6AAQ 21
688Q6 100
K8483 764
62865 453
39323 189
TTJJT 498
5J437 306
55A7A 876
9A366 562
8J479 249
65544 640
83T88 325
AK45A 321
39QQ3 849
83838 749
43394 602
33722 843
T5KTJ 428
JJKK9 549
33737 27
4KKK4 638
KK398 246
J6828 372
99229 23
2963K 577
3ATJJ 862
6488T 912
48554 903
3A353 627
86923 768
79A98 540
77TTT 965
TK2T7 188
2A644 687
QT943 253
K2QJT 887
J5KK5 915
9Q2JA 980
J237J 28
A46Q2 264
7T2TT 621
A4T8J 57
Q5QT5 217
K9AK7 248
TAJTT 973
82822 919
858AA 265
5555J 800
552J2 908
Q5248 272
A5KK5 529
K8J9T 85
888TT 477
665Q5 823
Q42AT 449
4843A 83
Q5476 885
Q52T2 409
6A2TJ 580
92A99 483
Q9Q6Q 734
36662 134
88899 401
KQQQ9 389
JQ259 658
57895 639
KQ654 852
94273 612
77KT7 987
3Q4AQ 364
6KQK6 651
4AQ23 163
34TTT 107
T98T2 870
J78Q9 756
3K3J3 404
J993J 328
Q8JQA 678
96759 326
2J22J 383
2T222 236
76666 772
QQ5QJ 225
A47AA 505
967TJ 924
Q3TJ4 63
2KK29 879
44Q4Q 685
TTQ9T 659
7244J 414
T22TJ 269
55552 3
J78TK 474
3J3J3 559
8QJ42 382
28T86 740
TKTT8 381
22J44 579
J8668 242
88TT6 709
KKKJ9 192
478K2 501
3Q66J 22
K9KAJ 774
K3333 113
4TJT4 945
Q55KK 609
Q7272 955
6AKAA 490
964T5 971
36Q3Q 51
3T9AT 969
Q8TQT 256
4A833 632
5499J 812
44222 176
6QQ6Q 317
TJT2T 206
A862Q 468
36663 464
54JK9 302
8J828 103
32QQ2 38
66675 595
2J8TQ 50
2QQQQ 783
333QQ 282
67KKK 511
2996J 518
J824K 44
K6656 726
Q7Q5T 793
KQ27T 494
T2KQA 308
AAAA2 441
24J49 716
K58TT 873
7TA49 39
6KQ7T 298
6Q555 455
66AJA 819
5A9A3 922
AAA88 170
42324 962
22Q22 616
44QJQ 399
9J3TA 342
56K3A 588
99T9A 224
56T66 869
77997 671
53222 161
8KKJT 384
37777 567
TKTK5 42
6J622 127
387Q5 417
T3A73 360
28AKA 868
K26Q5 288
J6J88 692
KKKK9 690
2A5QA 435
K83T4 158
QAA3A 104
T7Q66 914
A3A6A 270
J888J 838
3JTKQ 867
7KKKK 451
K7766 824
Q4Q9Q 620
65A33 957
99A9A 781
A9AAA 344
44744 935
6666J 804
A8QJ9 155
AQKAA 681
6K7KJ 853
A99JA 366
65JJ5 47
4TQ8T 769
66555 457
TJ226 222
78777 758
5K488 999
Q65T4 362
4Q738 80
5JJ55 323
8Q65A 918
A5TT5 353
294J3 471
33Q44 102
66668 254
7663Q 516
AAAJJ 798
3344J 10
85888 507
68868 144
588T5 124
TT4TT 834
QQ7QK 168
75555 593
849KA 446
9QT7A 165
5AA7A 697
J99J9 213
6834K 5
TQQQT 292
7A655 403
982AQ 143
A6237 334
QK5T6 963
99895 232
56366 376
34J35 231
AAQAQ 150
78887 485
QQQQJ 263
TAQ98 197
425J5 895
JQ7QQ 992
J9JJ9 61
5888J 665
6J6K6 496
78J82 293
22292 73
TT2TT 911
ATAAT 322
339AA 953
A7465 413
AA4AA 283
QT3TQ 84
QQA5Q 66
J472J 784
T3JTT 131
333A4 210
79299 550
88A8J 594
J9749 584
J735K 902
933JQ 109
5T926 481
4T4T4 561
87TK6 247
98964 159
78997 354
36JT4 29
59464 771
2AA5A 33
77J43 244
37T7T 448
23QJ3 925
K7K5Q 792
QQQQ9 411
KK568 278
49TK7 961
55TAA 817
33J4Q 984
5QJK9 105
9A9J9 623
AK62Q 842
38333 735
9A8J8 333
9T243 204
6K2J3 547
78JKQ 959
AA3A9 634
KJJKT 13
KJKKJ 921
99934 310
4J929 431
55559 445
TT62T 355
32K25 825
622A6 480
334Q9 412
26922 114
638KJ 900
364T8 462
QQJT7 234
TK586 525
K342K 816
TTT99 699
JT658 315
36388 24
2666J 185
53455 592
4AJAA 304
J3QQ8 228
22J2A 416
99768 927
TKJ9A 487
5A55J 744
QKQ44 613
336QA 81
66622 200
JTTTK 717
59ATT 513
33938 813
66AKJ 466
3976Q 941
8888T 491
JJK47 836
99Q7Q 654
Q896K 633
Q8JKQ 553
J6K6K 811
2T323 750
KKAKK 952
Q6JJ4 929
77J77 993
9KQJT 989
44254 857
4AA5A 514
TATJA 715
74422 145
33332 544
5T5QT 311
78JT8 913
JKKT2 94
26QK7 71
444JJ 287
99979 133
Q999Q 314
48888 649
33T8K 368
77T57 711
4T42Q 351
89Q99 89
69666 846
3A33A 890
8Q8A3 636
4A888 603
9TQTA 747
9AAA9 52
TJ4TT 267
J76J7 72
K773Q 370
77Q77 329
636QQ 575
ATQAA 917
2743Q 932
2KKKJ 452
93929 686
4ATTA 458
42222 252
35225 402
45JKA 160
4TAT6 201
7A278 839
4A7Q5 543
Q33T6 641
JQ99Q 238
A793A 86
78575 187
49T9T 303
8542K 198
25A82 786
77A77 363
244KK 397
87877 689
T6T6T 778
KKKK4 392
22T2J 171
T77A7 174
99KJK 180
2444J 761
QAQQA 508
3373T 121
222TT 137
736T2 8
4444J 12
33555 566
487A4 230
22626 439
QQQQ8 336
5T552 521
QTQQQ 872
63836 614
66695 450
AKAAA 361
95A95 111
644JK 701
ATAAA 840
9J99T 35
3333A 664
99992 99
5A5A5 680
Q7J5J 405
59999 954
2KTQ9 255
6QQ96 149
37333 67
QJ6Q3 425
Q6K29 415
J7277 126
AA29Q 220
AAKJK 831
27QQ2 986
AJ367 891
33292 666
Q8786 933
TAJ28 554
K4448 585
Q8225 931
46242 598
7AT98 693
78J56 369
TTTTJ 371
TKJKK 990
66767 802
56956 789
544K4 275
46699 215
26666 710
AQQQQ 116
6A858 757
55757 142
J2KA4 723
6229K 906
6K366 179
4378K 527
AA664 832
72242 499
2TT2Q 998
5QQQ5 647
5858J 856
555KJ 655
7788J 524
36J5J 82
99666 2
9AKK3 177
47447 596
9266J 572
4TTQ4 946
999J9 110
T74K4 899
Q27J8 156
98AK5 754
3TJ6T 396
75QK7 517
K22KJ 741
9699T 916
66QAQ 202
7329Q 32
89JAT 708
444Q4 841
73366 880
677QK 683
48J84 394
2966T 6
9KT9K 531
8544T 746
2222A 934
T2QKT 615
8J282 430
K9K9K 214
336TJ 904
9JTJ9 777
QKAKK 68
62A66 48
49499 280
97967 46
8T66T 273
94349 379
57777 719
2QT5K 827
4TTT2 40
J2252 859
A3TQA 426
468JA 611
57745 662
424AA 938
J33AT 309
99339 610
872KJ 570
K2395 571
77A5Q 996
JQ7Q6 340
973J9 776
J6K92 14
5J5Q9 191
Q5555 773
A7KA7 11
54545 851
AJ9A8 968
QQAJ7 821
T6JTT 670
3T2TT 151
TTTT3 886
33933 850
KKKQQ 656
T2TT2 54
QA44J 995
89J27 335
3742A 212
T7Q88 260
TT666 75
JKQ28 724
548T3 698
3883K 148
39966 864
69424 320
4QJ5J 332
J4297 346
78A66 605
82333 809
4K777 644
9739T 936
JJ433 755
88688 43
3TJ33 988
J37K3 628
3KK3T 583
A433J 195
89K46 262
JKKQK 545
7AA27 437
977T8 828
757Q7 759
7T7A8 805
33336 19
KJKKK 118
44445 586
84Q8K 205
439K3 909
6J663 762
33777 975
9AAQA 564
JJ8JJ 91
24555 696
62644 707
AA3J5 31
6T2KQ 135
24244 34
3QK3K 560
9J3T9 787
7QTA8 705
A22JA 528
84844 537
87667 937
QJ5K4 90
2K326 239
59878 421
7J377 536
857K7 350
2K2A2 704
39T9T 493
QKT86 829
3AQJT 714
7AAAJ 600
9QK56 983
35K33 193
89888 589
TQ477 432
777K7 59
86AQJ 17
QQQJ3 407
68K25 166
32288 748
TKTQK 65
J9K56 530
AA323 960
27266 112
22722 675
73367 497
Q7JJ3 16
444T4 438
22323 74
3QQ6K 348
A68J8 454
42K64 367
3AA7J 889
AT492 398
AAA6A 673
2Q9QQ 95
A7477 815
4A8KA 444
6JJ66 893
84445 429
7997J 101
A5A6A 958
K27A2 486
4A4J4 327
464TJ 434
5554J 766
KTKT8 801
573K5 64
JKK88 522
A9999 291
T787T 338
39648 502
46464 733
AQAAA 357
8TTTT 797
64444 515
8588T 53
AKAKK 617
8AJ99 888
3TAAJ 874
338Q3 694
TT443 578
86227 419
9J9JQ 736
22522 943
823J3 866
24444 519
A7A7A 207
5JJ99 36
K2896 250
66A5J 129
JJJJJ 668
8J548 721
J8J63 385
3Q442 79
8K868 141
AAA67 767
T968K 289
5QJ5K 245
TKQK5 96
54774 122
89666 568
95596 538
9K3J4 380
66665 20
7759A 209
6JTA6 702
29574 88
AA6A4 181
Q28T4 152
777KQ 386
47888 271
K8KKQ 738
J7337 162
JQA88 820
QQ4QQ 276
TKKTT 728
JTKTK 316
3J334 684
9944Q 830
8485A 753
JKKJ8 221
A9QJ6 948
KJ3KQ 727
Q5QQQ 695
Q8QTQ 542
2QQQ8 119
JJ55Q 845
52725 950
QAJ33 808
JAA7J 557
Q22AA 183
Q8Q8Q 661
J55JT 410
KKQJJ 901
Q5455 539
AQJJ9 956
7QJ7T 896
K5KKJ 994
388KK 822
2QQ2K 218
3J4K3 285
256K7 923
K2KKA 157
QQTKQ 139
48TTT 1
TTT44 770
JJ777 898
Q466K 117
TQ4QQ 172
43333 883
855T3 324
8T933 645
579K9 347
A76Q4 729
3TTT3 115
QJAQA 928
65T65 541
77A7A 625
29J9J 472
TKT74 926
A934K 643
JT533 199
TT4AJ 216
KKKK6 55
6J3K5 676
398J3 18
778K8 653
79773 406
25446 606
54323 76
2T992 601
8A888 241
9AJQK 509
3Q3QK 739
KKKK8 667
JJ494 590
83JKT 203
J9957 751
JJAQQ 296
4835Q 301
333T3 722
KKK2K 535
8Q2QJ 378
5J396 652
TQ7J8 624
5JJ22 447
TT777 62
TTJT7 60
TA2QT 626
T3Q79 791
K6QQ8 294
28K52 967
6K374 663
7877A 495
24226 352
88KAK 907
J242T 546
K77JT 465
Q77Q5 863
TQTQT 284
49K62 26
6TTT8 569
Q77QQ 779
99T6T 70
K4AKA 130
J5TT5 979
KQJT8 175
96K99 648
A56J3 422
53585 58
6QJTQ 794
9QJ77 388
88944 235
55A2Q 780
9Q992 297
96699 660
682QJ 865
6TTTK 799
Q47QQ 358
2929K 920
J5535 752
T3383 631
6737Q 894
9QT72 440
844J9 470
6AA6A 211
5AA5A 981
8KJ88 49
55855 93
5J495 261
8QQQ5 629
J4493 860
ATTKA 818
77264 877
55K58 365
QQ666 106
238T6 459
77QQK 848
5757A 233
84AT3 951
TT7TT 642
72236 345
TQ333 760
77744 720
QQ4QK 478
Q82A2 506
AJ3AA 942
JJ958 526
AJ4A4 341
A26J8 742
5TK28 871
865J3 136
66A6A 556
Q4A55 552
K8429 37
7QQ9Q 442
323J5 375
6J456 608
73Q6A 424
8QQ68 976
J9KA7 286
Q5Q5J 418
74472 154
KKQT9 637
Q8Q88 574
7543A 190
KA87J 456
2877K 635
J76A4 330
83Q69 128
A88A8 377
9999K 630
J698Q 878
67777 243
A232A 844
8K66J 835
QJ36A 420
22QQ6 782
3339K 677
K72QK 563
86777 307
323JJ 972
955KQ 826
33443 259
88Q88 897
85778 939
7T268 356
5T85J 861
833J8 387
4AA4A 7
QTQJJ 725
TT36T 395
6KJAJ 520
5J525 473
T88JT 182
44T66 173
Q75A8 251
K777A 985
88T33 905
99575 949
62222 186
22923 492
J4Q42 706
AA872 500
JA895 153
TT562 295
34434 854
2222J 881
69K46 882
TK74J 274
T46TT 548
K54KJ 164
9999Q 184
3QTJJ 400
8QK59 41
994Q9 1000
347J4 581
Q7289 138"""
val ins = Day7()
println(ins.two(inputReal))
}
data class Hand(val hand: List<Card>, val bid: Int) : Comparable<Hand> {
var counts: Map<Card, Int> = emptyMap()
fun getRank(): Int {
return when (counts.values.max()) {
5 -> 7
4 -> 6
3 -> if (counts.values.contains(2)) 5 else 4
2 -> if (counts.values.count { it == 2 } == 2) 3 else 2
1 -> 1
else -> 0
}
}
override fun toString(): String {
return getRank().toString() + ": " + hand.toString()
}
override fun compareTo(other: Hand): Int {
val left = other.getRank()
val right = this.getRank()
return if (left == right) {
for (i in 0..<other.hand.size) {
val comp = this.hand[i].value.compareTo(other.hand[i].value)
if (comp != 0) {
return comp
}
}
return 0
} else {
compareValues(right, left)
}
}
}
enum class Card(val value: Int) {
_2(1),
_3(2),
_4(3),
_5(4),
_6(5),
_7(6),
_8(7),
_9(8),
T(9),
J(0),
Q(11),
K(12),
A(13);
companion object {
fun getCard(c: String) = run {
try {
Card.valueOf(c)
} catch (e: IllegalArgumentException) {
Card.valueOf("_$c")
}
}
}
override fun toString(): String {
return this.name.replace("_", "")
}
} | 0 | Kotlin | 0 | 0 | a36addef07f61072cbf4c7c71adf2236a53959a5 | 12,865 | advent-code | MIT License |
src/main/kotlin/biodivine/algebra/rootisolation/DescartWithPolyFactorisationRootIsolation.kt | daemontus | 160,796,526 | false | null | package biodivine.algebra.rootisolation
import biodivine.algebra.UPoly
import cc.redberry.rings.bigint.BigInteger
import cc.redberry.rings.poly.univar.UnivariateFactorization
import cc.redberry.rings.poly.univar.UnivariatePolynomial
import biodivine.algebra.getDefaultBoundForDescartMethod
import biodivine.algebra.getNumberOfSignChanges
import biodivine.algebra.ia.Interval
import biodivine.algebra.transformPolyToInterval
import cc.redberry.rings.poly.PolynomialMethods.Factor
object DescartWithPolyFactorisationRootIsolation : RootIsolation {
override fun isolateInBounds(
polynomial: UnivariatePolynomial<NumQ>,
bounds: Interval,
precision: NumQ
): List<Interval> {
val computedRoots = mutableListOf<Interval>()
for (poly in UnivariateFactorization.Factor(polynomial)) {
if (poly.isLinearExactly) {
val root = poly[0].negate().divide(poly[1])
//println("Poly $poly is linear and root is $root")
if (root in bounds) {
computedRoots += Interval(root, root)
}
} else {
computedRoots += isolateIrracionalRootsRecursively(poly, bounds, precision)
}
}
return computedRoots
}
override fun isolateRoots(polynomial: UnivariatePolynomial<NumQ>, precision: NumQ): List<Interval> {
val defaultBound = Interval(polynomial.getDefaultBoundForDescartMethod().negate(), polynomial.getDefaultBoundForDescartMethod())
return isolateInBounds(polynomial, defaultBound, precision)
}
private fun isolateIrracionalRootsRecursively(polynomial: UnivariatePolynomial<NumQ>, bounds: Interval, precision: NumQ): List<Interval> {
val result = ArrayList<Interval>()
val workQueue = ArrayList<Interval>()
workQueue.add(bounds)
while (workQueue.isNotEmpty()) {
val (lowerBound, upperBound) = workQueue.removeAt(workQueue.lastIndex)
val numberOfSignChangesInInterval = polynomial.transformPolyToInterval(lowerBound, upperBound).getNumberOfSignChanges()
val middleValue = (upperBound.add(lowerBound)).divide(BigInteger.TWO)
val actualPrecision = (upperBound.subtract(lowerBound)).divide(BigInteger.TWO)
if (polynomial.evaluate(middleValue).isZero) {
result.add(Interval(middleValue, middleValue))
}
when {
numberOfSignChangesInInterval == 0 -> Unit
numberOfSignChangesInInterval == 1 && precision > actualPrecision && lowerBound != bounds.low && upperBound != bounds.high -> {
result.add(Interval(lowerBound, upperBound))
}
else -> {
workQueue.add(Interval(lowerBound, middleValue))
workQueue.add(Interval(middleValue, upperBound))
}
}
}
return result
}
override fun isolateRootsInBounds(
polynomials: Collection<UnivariatePolynomial<NumQ>>,
bounds: Interval,
precision: NumQ
): List<Interval> {
val factors = polynomials.flatMapTo(HashSet()) { Factor(it) }
val linearRoots = factors.filter { it.isLinearExactly }.mapNotNull { poly ->
val root = poly[0].negate().divide(poly[1])
if (root !in bounds) null else Interval(root, root)
}
//val nonLinearCombination = factors.filter { !it.isLinearExactly }
//.fold(UnivariatePolynomial.one(polynomials.first().ring)) { a, b -> a.multiply(b) }
val nonLinearRoots = factors.filter { !it.isLinearExactly }.flatMap {
isolateIrracionalRootsRecursively(it, bounds, precision)
}.toHashSet()
return linearRoots + nonLinearRoots
}
} | 0 | Kotlin | 0 | 0 | ed4fd35015b73ea3ac36aecb1c5a568f6be7f14c | 3,820 | biodivine-algebraic-toolkit | MIT License |
src/main/kotlin/com/kishor/kotlin/ds/BinarySearchTree.kt | kishorsutar | 276,212,164 | false | null | package com.kishor.kotlin.ds
import kotlin.math.abs
class BinarySearchTree<T : Comparable<T>> {
var root: Node<T>? = null
var nodeCount = 0
data class Node<T>(var data: T, var left: Node<T>? = null, var right: Node<T>? = null)
fun isEmpty(): Boolean {
return size() == 0
}
fun size(): Int {
return nodeCount
}
fun add(elem: T): Boolean {
return if (contains(root, elem)) { // add contains method
false
} else {
root = root?.let { add(it, elem) }
nodeCount++
true
}
}
fun add(node: Node<T>, elem: T): Node<T>? {
var nodeToReturn: Node<T>? = null
if (node == null) {
nodeToReturn = Node(elem, null, null)
} else {
if (elem.compareTo(node.data) < 0) {
node.left = node.left?.let { add(it, elem) }
} else {
node.right = node.right?.let { add(it, elem) }
}
}
return nodeToReturn
}
// private recursive method to find an element in the tree
private fun contains(node: Node<T>?, elem: T): Boolean {
// Base case: reached bottom, value not found
if (node == null) return false
val cmp = elem.compareTo(node.data)
// Dig into the left subtree because the value we're
// looking for is smaller than the current value
return if (cmp < 0) contains(node.left, elem) else if (cmp > 0) contains(node.right, elem) else true
}
/**
find the element if it's exists
- apply technique if it's leaf node is removed. -> check if left and right is null
- if it has only left child - get the successor and add replace it with current node-> righis null
- if it has only right childe - get the right successor and replace with current -> left is null
- if it has both then go to smallest on right or largest on left and make the successor - take left first
*/
fun removeElement(elem: T): Boolean {
if (contains(root, elem)) {
root = remove(elem, root)
nodeCount--
return true
}
return false
}
fun remove(elem: T, node: Node<T>?): Node<T>? {
if (node == null) return null
val cmp = elem.compareTo(node.data)
if (cmp < 0) {
node.left = remove(elem, node.left)
} else if (cmp > 0) {
node.right = remove(elem, node.right)
} else {
if (node.left == null) {
return node.right
} else if (node.right == null) {
return node.left
} else {
val temp = findMin(node.right!!)
node.data = temp!!.data
node.right = remove(temp.data, node.right)
}
}
return node
}
fun findMin(node: Node<T>): Node<T>? {
var temp: Node<T>? = node
while (node.left == null) temp = node.left
return temp
}
}
fun findTheClosestValue(root: BinarySearchTree.Node<Int>, target: Int): Int {
var minValue = Int.MAX_VALUE
return findTheClosest(minValue, root, target)
}
fun findTheClosest(closest: Int, node: BinarySearchTree.Node<Int>?, target: Int): Int {
if (node == null) return closest
var newClosest = closest
val curr = kotlin.math.abs(node.data - target)
val prev = kotlin.math.abs(target - newClosest)
if (curr < prev) {
newClosest = node.data
if (curr == 0) {
return newClosest
}
}
if (target < node.data) {
return findTheClosest(newClosest, node.left, target)
} else if (target > node.data){
return findTheClosest(newClosest, node.right, target)
} else {
return newClosest
}
}
fun findClosestIterative(tree: BinarySearchTree.Node<Int>, target: Int): Int {
var currentNode = tree
var closest = tree.data
while (currentNode != null) {
if (abs(target - currentNode.data) < abs(target - closest)) {
closest = currentNode.data
}
if (target < currentNode.data) {
currentNode = currentNode.left!!
} else if (target > currentNode.data) {
currentNode = currentNode.right!!
} else {
return currentNode.data
}
}
return closest
}
open class BST(value: Int) {
var value = value
var left: BST? = null
var right: BST? = null
fun insert(value: Int) {
if (value < this.value) {
if (this.left == null) {
this.left = BST(value)
} else {
this.left!!.insert(value)
}
} else {
if (this.right == null) {
this.right = BST(value)
} else {
this.right!!.insert(value)
}
}
}
}
fun validateBst(tree: BST): Boolean {
// Write your code here.
return validateBST(tree, Int.MIN_VALUE, Int.MAX_VALUE)
}
fun validateBST (tree: BST?, minValue: Int, maxValue: Int): Boolean{
if (tree == null) return true
if (tree.value < minValue || tree.value >= minValue) return false
val isLeftValid = validateBST(tree.left, minValue, tree.value)
val isRightValid = validateBST(tree.right, tree.value, maxValue)
return isLeftValid && isRightValid
}
fun minHeightBST(array: List<Int>): BST {
return constructBST(array, 0, array.size-1)!!
}
fun constructBST(array: List<Int>, startIdx: Int, endIdx: Int): BST? {
if (startIdx < endIdx) return null
val mid = (startIdx + endIdx) / 2
val bst = BST(array[mid])
bst.left = constructBST(array, startIdx, mid - 1)
bst.right = constructBST(array, mid + 1, endIdx)
return bst
}
// Same BSTS problem
fun sameBsts(arrayOne: List<Int>, arrayTwo: List<Int>): Boolean {
if (arrayOne.size != arrayTwo.size) return false
if (arrayOne.size == 0 && arrayTwo.size == 0) return true
if (arrayOne[0] != arrayTwo[0]) return false
val leftOne = getSmaller(arrayOne)
val leftTwo = getSmaller(arrayTwo)
val rightOne = getBiggerOrEqual(arrayOne)
val rightTwo = getBiggerOrEqual(arrayTwo)
return sameBsts(leftOne, leftTwo) && sameBsts(rightOne, rightTwo)
}
fun getSmaller(array: List<Int>): List<Int> {
val smallerList = mutableListOf<Int>()
for (i in 1 until array.size) {
if (array[i] < array[0]) {
smallerList.add(array[i])
}
}
return smallerList
}
fun getBiggerOrEqual(array: List<Int>): List<Int> {
val biggerOrEqual = mutableListOf<Int>()
for (i in 1 until array.size) {
if (array[i] >= array[0]) {
biggerOrEqual.add(array[i])
}
}
return biggerOrEqual
}
// O(n^2) O(n)
fun rightSmallerThan(array: List<Int>): List<Int> {
// val map = mutableMapOf<Int, Int>()
val list = mutableListOf<Int>()
for (i in 0 until array.size) {
var currentCount = 0
for (j in i + 1 until array.size) {
if (array[j] < array[i]) {
currentCount++
}
}
// map[i] = currentCount
list.add(currentCount)
}
// for (i in array.indices) {
// list.add(map[i]!!)
// }
return list
}
| 0 | Kotlin | 0 | 0 | 6672d7738b035202ece6f148fde05867f6d4d94c | 7,271 | DS_Algo_Kotlin | MIT License |
src/main/kotlin/Excercise17.kt | underwindfall | 433,989,850 | false | {"Kotlin": 55774} | private fun part1() {
val input = getInputAsTest("17")
val (xr, yr) = input[0].removePrefix("target area: ").split(", ")
val (x1, x2) = xr.removePrefix("x=").split("..").map { it.toInt() }
val (y1, y2) = yr.removePrefix("y=").split("..").map { it.toInt() }
var ans = 0
for (vx0 in 1..1000) {
for (vy0 in 0..1000) {
var vx = vx0
var vy = vy0
var x = 0
var y = 0
var maxY = 0
var ok = false
while (x <= x2 && y >= y1) {
x += vx
y += vy
maxY = maxOf(maxY, y)
if (x in x1..x2 && y in y1..y2) {
ok = true
break
}
if (vx > 0) vx--
vy--
}
if (ok) ans = maxOf(ans, maxY)
}
}
println("Part1 $ans")
}
private fun part2() {
val input = getInputAsTest("17")
val (xr, yr) = input[0].removePrefix("target area: ").split(", ")
val (x1, x2) = xr.removePrefix("x=").split("..").map { it.toInt() }
val (y1, y2) = yr.removePrefix("y=").split("..").map { it.toInt() }
var ans = 0
for (vx0 in 1..1000) for (vy0 in -1000..1000) {
var vx = vx0
var vy = vy0
var x = 0
var y = 0
var ok = false
while (x <= x2 && y >= y1) {
x += vx
y += vy
if (x in x1..x2 && y in y1..y2) {
ok = true
break
}
if (vx > 0) vx--
vy--
}
if (ok) ans++
}
println("Part2 $ans")
}
fun main() {
part1()
part2()
}
| 0 | Kotlin | 0 | 0 | 4fbee48352577f3356e9b9b57d215298cdfca1ed | 1,421 | advent-of-code-2021 | MIT License |
domain/src/main/kotlin/com/seanshubin/condorcet/domain/Matrix.kt | SeanShubin | 126,547,543 | false | null | package com.seanshubin.condorcet.domain
import kotlin.math.max
import kotlin.math.min
class Matrix(val rows: List<List<Int>>) {
private var rowCount: Int = 0
private var columnCount: Int = 0
init {
for (row in rows) {
rowCount += 1
if (columnCount == 0) {
columnCount = row.size
} else if (columnCount != row.size) {
throw RuntimeException("all rows must be the same size")
}
}
}
fun rowCount(): Int = rowCount
fun columnCount(): Int = columnCount
operator fun get(rowIndex: Int, columnIndex: Int): Int {
return rows[rowIndex][columnIndex]
}
fun schulzeStrongestPaths(): Matrix {
val size = squareSize()
val strongestPaths = createEmptyMutableMatrixData(rowCount, columnCount)
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 Matrix(strongestPaths)
}
fun schulzeTally(): List<List<Int>> = schulzeTally(emptyList(), emptyList())
private fun schulzeTally(soFar: List<List<Int>>, indices: List<Int>): List<List<Int>> {
val size = squareSize()
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) || get(i, j) >= get(j, i)
}
}
schulzeTally(soFar + listOf(undefeated), indices + undefeated)
}
}
private fun squareSize(): Int =
if (rowCount == columnCount)
rowCount
else
throw UnsupportedOperationException(
"This method is only valid for square matrices," +
" this matrix has $rowCount rows and $columnCount columns")
private fun createEmptyMutableMatrixData(rowCount: Int, columnCount: Int): MutableList<MutableList<Int>> =
mutableListOf(*(0 until rowCount).map { mutableListOf(*(0 until columnCount).map { 0 }.toTypedArray()) }.toTypedArray())
}
fun matrixOfSizeWithDefault(rowCount: Int, columnCount: Int, default: Int): Matrix =
Matrix(listOf(*(0 until rowCount).map { listOf(*(0 until columnCount).map { default }.toTypedArray()) }.toTypedArray()))
fun matrixOfSizeWithGenerator(rowCount: Int, columnCount: Int, generate: (Int, Int) -> Int): Matrix {
val rows = mutableListOf<List<Int>>()
for (i in 0 until rowCount) {
val cells = mutableListOf<Int>()
for (j in 0 until columnCount) {
cells.add(generate(i, j))
}
rows.add(cells)
}
return Matrix(rows)
}
operator fun Matrix.plus(that: Matrix): Matrix {
if (this.rowCount() != that.rowCount())
throw RuntimeException("Attempting to add a matrix with ${this.rowCount()} rows to matrix with ${that.rowCount()} rows")
return matrixOfSizeWithGenerator(this.rowCount(), this.columnCount(), { i, j -> this[i, j] + that[i, j] })
}
| 0 | Kotlin | 0 | 0 | a5f887e9ab2281a9c15240a314a6de489ce42f76 | 3,562 | condorcet | The Unlicense |
2023/src/main/kotlin/Day20.kt | dlew | 498,498,097 | false | {"Kotlin": 331659, "TypeScript": 60083, "JavaScript": 262} | object Day20 {
fun part1(input: String): Long {
var modules = parse(input)
var low = 0L
var high = 0L
repeat(1000) {
val (nextModules, pulseCount) = pushButton(modules)
low += pulseCount.low
high += pulseCount.high
modules = nextModules
}
return low * high
}
fun part2(input: String): Long {
var modules = parse(input)
// Find the module leading to rx
val moduleLeadingToRx = modules.find { "rx" in it.destinations }!!
// Find all conjunctions leading to the key
val conjunctionsLeadingToRx = modules.filter { moduleLeadingToRx.name in it.destinations }.map { it.name }
// It just so happens that the conjunctions leading to rx cycle, so detect their cycles
var buttonCount = 0
val cycles = mutableMapOf<String, Int>()
while (true) {
val (nextModules, _, conjunctionsThatPulsedHigh) = pushButton(modules)
modules = nextModules
buttonCount++
// Add to cycles if we found another
conjunctionsThatPulsedHigh
.filter { name -> name in conjunctionsLeadingToRx }
.forEach { name -> cycles[name] = buttonCount }
// If we have all cycles, finish
if (cycles.size == conjunctionsLeadingToRx.size) {
return leastCommonMultiple(cycles.values.map { it.toLong() })
}
}
}
private fun pushButton(modules: List<Module>): Result {
var low = 0L
var high = 0L
val queue = mutableListOf(Pulse("button", "broadcaster", false))
val moduleMap = modules.associateBy { it.name }.toMutableMap()
val conjunctionsThatPulsedHigh = mutableSetOf<String>()
while (queue.isNotEmpty()) {
val pulse = queue.removeFirst()
if (pulse.isHigh) high++ else low++
when (val module = moduleMap[pulse.destination]) {
is Module.Broadcaster -> queue.addAll(module.destinations.map { Pulse(module.name, it, pulse.isHigh) })
is Module.Conjunction -> {
val newModuleState = module.copy(memory = module.memory + mapOf(pulse.source to pulse.isHigh))
moduleMap[module.name] = newModuleState
val sendHigh = !newModuleState.memory.values.all { it }
if (sendHigh) {
conjunctionsThatPulsedHigh.add(module.name)
}
queue.addAll(module.destinations.map { Pulse(module.name, it, sendHigh) })
}
is Module.FlipFlop -> {
if (!pulse.isHigh) {
moduleMap[module.name] = module.copy(on = !module.on)
queue.addAll(module.destinations.map { Pulse(module.name, it, !module.on) })
}
}
null -> {
// Theoretically, this is the pulse to rx, but the number is so high as to be unrealistic to ever hit
}
}
}
return Result(moduleMap.values.toList(), PulseCount(low, high), conjunctionsThatPulsedHigh)
}
private fun leastCommonMultiple(numbers: List<Long>) = numbers.reduce { a, b -> leastCommonMultiple(a, b) }
private fun leastCommonMultiple(a: Long, b: Long) = a * (b / greatestCommonDivisor(a, b))
// Euclid's algorithm
private fun greatestCommonDivisor(a: Long, b: Long): Long = if (b == 0L) a else greatestCommonDivisor(b, a % b)
private sealed class Module {
abstract val name: String
abstract val destinations: List<String>
data class Broadcaster(override val destinations: List<String>) : Module() {
override val name = "broadcaster"
}
data class FlipFlop(override val name: String, override val destinations: List<String>, val on: Boolean = false) :
Module()
data class Conjunction(
override val name: String,
override val destinations: List<String>,
val memory: Map<String, Boolean> = emptyMap()
) : Module()
}
private data class Pulse(val source: String, val destination: String, val isHigh: Boolean)
private data class PulseCount(val low: Long, val high: Long)
private data class Result(
val modules: List<Module>,
val pulseCount: PulseCount,
val conjunctionsThatPulsedHigh: Set<String>
)
private fun parse(input: String): List<Module> {
val inputs = mutableMapOf<String, MutableList<String>>()
val modules = input.splitNewlines().map {
val (nameAndFunction, destinationsStr) = it.split(" -> ")
val destinations = destinationsStr.splitCommas()
val module = when {
nameAndFunction == "broadcaster" -> Module.Broadcaster(destinations)
nameAndFunction.startsWith("%") -> Module.FlipFlop(nameAndFunction.drop(1), destinations)
else -> Module.Conjunction(nameAndFunction.drop(1), destinations)
}
module.destinations.forEach { destination ->
val inputList = inputs.getOrPut(destination) { mutableListOf() }
inputList.add(module.name)
}
return@map module
}.toMutableList()
// Set the memory for every conjunction module
modules.indices.forEach { index ->
val module = modules[index]
if (module is Module.Conjunction) {
modules[index] = module.copy(memory = inputs[module.name].orEmpty().associateWith { false })
}
}
return modules
}
} | 0 | Kotlin | 0 | 0 | 6972f6e3addae03ec1090b64fa1dcecac3bc275c | 5,135 | advent-of-code | MIT License |
kotlin/src/com/codeforces/round626/B.kt | programmerr47 | 248,502,040 | false | null | package com.codeforces.round626
import java.util.*
import kotlin.math.max
import kotlin.math.sqrt
fun main(args: Array<String>) {
// Creates an instance which takes input from standard input (keyboard)
val reader = Scanner(System.`in`)
rectCount(reader)
}
private fun rectCount(input: Scanner) {
val rowCount = input.nextInt()
val columnCount = input.nextInt()
val k = input.nextInt()
val delMax = sqrt(k.toFloat()).toInt()
val delimiters = mutableListOf<Int>()
for (i in 1..delMax) {
if (k % i == 0) {
delimiters.add(i)
if (k / i != i) {
delimiters.add(k / i)
}
}
}
val conRowCounts = conRow(input, rowCount)
val conColCounts = conRow(input, columnCount)
var result = 0L
for (i in delimiters.indices) {
val del1 = delimiters[i]
val del2 = k / del1
var horizRects = 0L
conRowCounts.forEach { conRowCount ->
horizRects += max(conRowCount - del1 + 1, 0)
}
var vertRects = 0L
conColCounts.forEach { conColCount ->
vertRects += max(conColCount - del2 + 1, 0)
}
result += horizRects * vertRects
}
println(result)
}
private fun conRow(input: Scanner, rowCount: Int): List<Int> {
val result = mutableListOf<Int>()
var conRow = 0
repeat(rowCount) {
val row = input.nextInt()
if (row == 1) {
conRow++
} else if (conRow > 0) {
result.add(conRow)
conRow = 0
}
}
if (conRow > 0) {
result.add(conRow)
}
return result
}
| 0 | Kotlin | 0 | 0 | 0b5fbb3143ece02bb60d7c61fea56021fcc0f069 | 1,650 | problemsolving | Apache License 2.0 |
2015/kotlin/src/main/kotlin/nl/sanderp/aoc/aoc2015/day18/Day18.kt | sanderploegsma | 224,286,922 | false | {"C#": 233770, "Kotlin": 126791, "F#": 110333, "Go": 70654, "Python": 64250, "Scala": 11381, "Swift": 5153, "Elixir": 2770, "Jinja": 1263, "Ruby": 1171} | package nl.sanderp.aoc.aoc2015.day18
import nl.sanderp.aoc.common.Point2D
import nl.sanderp.aoc.common.bounds
import nl.sanderp.aoc.common.pointsAround
import nl.sanderp.aoc.common.readResource
fun simulate(grid: Map<Point2D, Int>, alwaysOn: Collection<Point2D> = emptyList()) = buildMap {
alwaysOn.forEach { point ->
put(point, 1)
}
grid.entries
.filterNot { alwaysOn.contains(it.key) }
.forEach { (point, isOn) ->
val neighborsOn = point.pointsAround().mapNotNull { grid[it] }.sum()
val newState = when (neighborsOn) {
3 -> 1
2 -> isOn
else -> 0
}
put(point, newState)
}
}
fun main() {
val grid = buildMap {
readResource("18.txt").lines().forEachIndexed { y, row ->
row.forEachIndexed { x, cell ->
put(Pair(x, y), if (cell == '#') 1 else 0)
}
}
}
val simulation = generateSequence(grid, ::simulate)
println("Part one: ${simulation.elementAt(100).values.sum()}")
val corners = grid.keys.bounds()
val gridWithCornersOn = grid + corners.associateWith { 1 }
val simulation2 = generateSequence(gridWithCornersOn) { simulate(it, alwaysOn = corners) }
println("Part two: ${simulation2.elementAt(100).values.sum()}")
}
| 0 | C# | 0 | 6 | 8e96dff21c23f08dcf665c68e9f3e60db821c1e5 | 1,347 | advent-of-code | MIT License |
src/main/kotlin/biz/koziolek/adventofcode/year2023/day14/day14.kt | pkoziol | 434,913,366 | false | {"Kotlin": 715025, "Shell": 1892} | package biz.koziolek.adventofcode.year2023.day14
import biz.koziolek.adventofcode.*
fun main() {
val inputFile = findInput(object {})
val platform = parsePlatform(inputFile.bufferedReader().readLines())
println("Total load after sliding north: ${platform.slideNorth().totalLoad}")
println("Total load after 1 000 000 000 cycles: ${platform.cycle(n = 1_000_000_000).totalLoad}")
}
const val ROUND_ROCK = 'O'
const val CUBE_ROCK = '#'
const val EMPTY_SPACE = '.'
data class Platform(val rocks: Map<Coord, Char>) {
val width = rocks.getWidth()
val height = rocks.getHeight()
val totalLoad: Int by lazy {
rocks
.filter { it.value == ROUND_ROCK }
.map { height - it.key.y }
.sum()
}
override fun toString() = toString(color = false)
fun toString(color: Boolean = false) =
buildString {
for (y in 0 until height) {
for (x in 0 until width) {
val coord = Coord(x, y)
val symbol = rocks[coord] ?: EMPTY_SPACE
if (color) {
when (symbol) {
ROUND_ROCK -> append(AsciiColor.BRIGHT_WHITE.format(symbol))
CUBE_ROCK -> append(AsciiColor.WHITE.format(symbol))
EMPTY_SPACE -> append(AsciiColor.BLACK.format(symbol))
}
} else {
append(symbol)
}
}
if (y != height - 1) {
append("\n")
}
}
}
fun cycle(n: Int): Platform {
val seenPlatforms = mutableMapOf<Platform, MutableList<Int>>()
var newPlatform = this
var startOffset: Int? = null
var cyclePeriod: Int? = null
for (cycle in 1..n) {
newPlatform = cycleInternal(newPlatform, cycle)
if (newPlatform in seenPlatforms) {
val seenCycles = seenPlatforms[newPlatform]!!
seenCycles.add(cycle)
println(seenCycles)
if (seenCycles.size == 2) {
startOffset = seenCycles[0]
cyclePeriod = seenCycles[1] - seenCycles[0]
break
}
} else {
seenPlatforms[newPlatform] = mutableListOf(cycle)
}
}
if (startOffset == null || cyclePeriod == null) {
println("Warning: finished without finding startOffset or cyclePeriod")
return newPlatform
}
val wholePeriods = (n - startOffset) / cyclePeriod
val endRemainder = (n - startOffset) % cyclePeriod
println("Start offset: $startOffset")
println("Cycle period: $cyclePeriod")
println("Whole periods: $wholePeriods")
println("End remainder: $endRemainder")
for (cycle in (startOffset + wholePeriods * cyclePeriod + 1)..(startOffset + wholePeriods * cyclePeriod + endRemainder)) {
// println("Cycle $cycle")
newPlatform = cycleInternal(newPlatform, cycle)
}
return newPlatform
}
private fun cycleInternal(newPlatform: Platform, cycle: Int) =
newPlatform
// .also { println("Cycle $cycle:\n${it.toString(color = true)}\n") }
.slideNorth()
// .also { println("North:\n${it.toString(color = true)}\n") }
.slideWest()
// .also { println("West:\n${it.toString(color = true)}\n") }
.slideSouth()
// .also { println("South:\n${it.toString(color = true)}\n") }
.slideEast()
// .also { println("East:\n${it.toString(color = true)}\n") }
fun slideNorth(): Platform =
slide(
allCoordsToBrowse = rocks.walkSouth(),
coordsToFallAt = { it.walkNorthTo(0, includeCurrent = false) }
)
fun slideWest(): Platform =
slide(
allCoordsToBrowse = rocks.walkEast(),
coordsToFallAt = { it.walkWestTo(0, includeCurrent = false) }
)
fun slideSouth(): Platform =
slide(
allCoordsToBrowse = rocks.walkNorth(),
coordsToFallAt = { it.walkSouthTo(height - 1, includeCurrent = false) }
)
fun slideEast(): Platform =
slide(
allCoordsToBrowse = rocks.walkWest(),
coordsToFallAt = { it.walkEastTo(width - 1, includeCurrent = false) }
)
private fun slide(allCoordsToBrowse: Sequence<Coord>,
coordsToFallAt: (Coord) -> Sequence<Coord>): Platform {
val newRocks = rocks.toMutableMap()
for (coord in allCoordsToBrowse) {
if (newRocks[coord] == ROUND_ROCK) {
var lastFreeCoord = coord
for (coordToFallAt in coordsToFallAt(coord)) {
if (newRocks[coordToFallAt] == null) {
lastFreeCoord = coordToFallAt
} else {
break
}
}
newRocks.remove(coord)
newRocks[lastFreeCoord] = ROUND_ROCK
}
}
return Platform(newRocks)
}
}
fun parsePlatform(lines: Iterable<String>): Platform =
Platform(lines.parse2DMap { if (it != EMPTY_SPACE) it else null }.toMap())
| 0 | Kotlin | 0 | 0 | 1b1c6971bf45b89fd76bbcc503444d0d86617e95 | 5,409 | advent-of-code | MIT License |
src/Day02.kt | floblaf | 572,892,347 | false | {"Kotlin": 28107} | fun main() {
val part1Scoring = mapOf(
"A X" to 1+3,
"A Y" to 2+6,
"A Z" to 3+0,
"B X" to 1+0,
"B Y" to 2+3,
"B Z" to 3+6,
"C X" to 1+6,
"C Y" to 2+0,
"C Z" to 3+3,
)
val part2Scoring = mapOf(
"A X" to 3+0,
"A Y" to 1+3,
"A Z" to 2+6,
"B X" to 1+0,
"B Y" to 2+3,
"B Z" to 3+6,
"C X" to 2+0,
"C Y" to 3+3,
"C Z" to 1+6,
)
fun part1(input: List<String>): Int {
return input.sumOf { part1Scoring[it] ?: throw IllegalStateException() }
}
fun part2(input: List<String>): Int {
return input.sumOf { part2Scoring[it] ?: throw IllegalStateException() }
}
val input = readInput("Day02")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | a541b14e8cb401390ebdf575a057e19c6caa7c2a | 831 | advent-of-code-2022 | Apache License 2.0 |
2023/day04-25/src/main/kotlin/Day16.kt | CakeOrRiot | 317,423,901 | false | {"Kotlin": 62169, "Python": 56994, "C#": 20675, "Rust": 10417} | import java.io.File
class Day16 {
fun solve1() {
val grid = File("inputs/16.txt").inputStream().bufferedReader().lineSequence().map { it.toList() }.toList()
println(calcEnergy(grid, Point(0, 0), Point(0, 1)))
}
fun solve2() {
val grid = File("inputs/16.txt").inputStream().bufferedReader().lineSequence().map { it.toList() }.toList()
val starts = emptyList<Pair<Point, Point>>().toMutableList()
for (i in grid.indices) {
starts.add(Pair(Point(i, 0), Point(0, 1)))
starts.add(Pair(Point(i, grid[0].size - 1), Point(0, -1)))
}
for (i in grid[0].indices) {
starts.add(Pair(Point(0, i), Point(1, 0)))
starts.add(Pair(Point(grid.size - 1, i), Point(-1, 0)))
}
println(starts.maxOf { calcEnergy(grid, it.first, it.second) })
}
data class Point(val x: Int, val y: Int) {
operator fun plus(other: Point): Point {
return Point(x + other.x, y + other.y)
}
}
operator fun List<List<Char>>.get(p: Point): Char {
return this[p.x][p.y]
}
fun calcEnergy(grid: List<List<Char>>, initialPos: Point, initialDirection: Point): Int {
val energized = emptySet<Point>().toMutableSet()
val memo = emptySet<Pair<Point, Point>>().toMutableSet()
fun moveBeam(grid: List<List<Char>>, pos: Point, direction: Point) {
if (memo.contains(Pair(pos, direction)))
return
memo.add(Pair(pos, direction))
var curPos = pos
var curDirection = direction
while (curPos.x >= 0 && curPos.y >= 0 && curPos.x < grid.size && curPos.y < grid[0].size) {
energized.add(curPos)
if (grid[curPos] == '/') {
curDirection = Point(curDirection.y * -1, curDirection.x * -1)
} else if (grid[curPos] == '\\') {
curDirection = Point(curDirection.y, curDirection.x)
} else if (grid[curPos] == '|') {
if (curDirection.y != 0) {
moveBeam(grid, curPos + Point(-1, 0), Point(-1, 0))
moveBeam(grid, curPos + Point(1, 0), Point(1, 0))
break
}
} else if (grid[curPos] == '-') {
if (curDirection.x != 0) {
moveBeam(grid, curPos + Point(0, 1), Point(0, 1))
moveBeam(grid, curPos + Point(0, -1), Point(0, -1))
break
}
}
curPos += curDirection
}
}
moveBeam(grid, initialPos, initialDirection)
return energized.size
}
} | 0 | Kotlin | 0 | 0 | 8fda713192b6278b69816cd413de062bb2d0e400 | 2,763 | AdventOfCode | MIT License |
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[48]旋转图像.kt | maoqitian | 175,940,000 | false | {"Kotlin": 354268, "Java": 297740, "C++": 634} | //给定一个 n × n 的二维矩阵表示一个图像。
//
// 将图像顺时针旋转 90 度。
//
// 说明:
//
// 你必须在原地旋转图像,这意味着你需要直接修改输入的二维矩阵。请不要使用另一个矩阵来旋转图像。
//
// 示例 1:
//
// 给定 matrix =
//[
// [1,2,3],
// [4,5,6],
// [7,8,9]
//],
//
//原地旋转输入矩阵,使其变为:
//[
// [7,4,1],
// [8,5,2],
// [9,6,3]
//]
//
//
// 示例 2:
//
// 给定 matrix =
//[
// [ 5, 1, 9,11],
// [ 2, 4, 8,10],
// [13, 3, 6, 7],
// [15,14,12,16]
//],
//
//原地旋转输入矩阵,使其变为:
//[
// [15,13, 2, 5],
// [14, 3, 4, 1],
// [12, 6, 8, 9],
// [16, 7,10,11]
//]
//
// Related Topics 数组
// 👍 691 👎 0
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
fun rotate(matrix: Array<IntArray>): Unit {
//时间复杂度 O(n)
val len = matrix.size
//水平翻转
for (i in 0 until len/2){
for (j in 0 until len){
val temp = matrix[i][j]
matrix[i][j] = matrix[len - i -1][j]
matrix[len - i -1][j] = temp
}
}
//对折翻转
for (i in 0 until len){
for (j in 0 until i){
val temp = matrix[i][j]
matrix[i][j] = matrix[j][i]
matrix[j][i] = temp
}
}
}
}
//leetcode submit region end(Prohibit modification and deletion)
| 0 | Kotlin | 0 | 1 | 8a85996352a88bb9a8a6a2712dce3eac2e1c3463 | 1,510 | MyLeetCode | Apache License 2.0 |
src/main/kotlin/Day10_2.kt | vincent-mercier | 726,287,758 | false | {"Kotlin": 37963} | import java.io.File
import java.io.InputStream
import java.lang.Integer.max
import java.lang.Integer.min
enum class Direction2(val deltaY: Int, val deltaX: Int, val nextDirection: Map<Char, () -> Direction2?>) {
S(
0,
0,
mapOf(
'S' to { S }
)
),
UP(
-1,
0,
mapOf(
'|' to { UP },
'F' to { RIGHT },
'7' to { LEFT },
'.' to { null },
'-' to { null },
'L' to { null },
'J' to { null },
'S' to { S }
)
),
DOWN(
1,
0,
mapOf(
'|' to { DOWN },
'J' to { LEFT },
'L' to { RIGHT },
'.' to { null },
'-' to { null },
'7' to { null },
'F' to { null },
'S' to { S }
)
),
LEFT(
0,
-1,
mapOf(
'-' to { LEFT },
'L' to { UP },
'F' to { DOWN },
'.' to { null },
'|' to { null },
'7' to { null },
'J' to { null },
'S' to { S }
)
),
RIGHT(
0,
1,
mapOf(
'-' to { RIGHT },
'J' to { UP },
'7' to { DOWN },
'.' to { null },
'|' to { null },
'L' to { null },
'F' to { null },
'S' to { S }
)
)
}
data class Point2(val y: Int, val x: Int) {
fun moveIn(direction: Direction, matrix: List<String>): Pair<Point2, Direction?>? {
val newPoint = Point2(
y + direction.deltaY,
x + direction.deltaX
)
return newPoint to direction.nextDirection[matrix[newPoint.y][newPoint.x]]?.invoke()
}
companion object {
fun fromCoords(coords: Pair<Int, Int>): Point2 {
return Point2(coords.first, coords.second)
}
}
}
fun main() {
val inputStream: InputStream = File("./src/main/resources/day10.txt").inputStream()
val matrix = inputStream.bufferedReader().readLines().toMutableList()
val s = Point2.fromCoords(
matrix.mapIndexed {lineIndex, line ->
val sIndex = line.mapIndexed { charIndex, char ->
if (char == 'S') {
charIndex
} else {
null
}
}.firstOrNull { it != null }
if (sIndex != null) {
lineIndex to sIndex
} else {
null
}
}.first { it != null }!!
)
var steps = 0
var currentPosition = s
val directions = listOf(Direction.UP, Direction.DOWN, Direction.LEFT, Direction.RIGHT)
.filter { s.moveIn(it, matrix)?.second != null }
val replacement = if (directions.contains(Direction.UP) && directions.contains(Direction.RIGHT)) {
'L'
} else if (directions.contains(Direction.UP) && directions.contains(Direction.LEFT)) {
'J'
} else if (directions.contains(Direction.DOWN) && directions.contains(Direction.LEFT)) {
'7'
} else if (directions.contains(Direction.DOWN) && directions.contains(Direction.RIGHT)) {
'F'
} else if (directions.contains(Direction.UP) && directions.contains(Direction.DOWN)) {
'|'
} else {
'-'
}
matrix[s.y] = matrix[s.y].replaceRange(s.x until s.x+1, "$replacement")
var nextDirection = directions.first()
val points = mutableSetOf(s)
var minY = matrix.size
var minX = matrix[0].length
var maxY = 0
var maxX = 0
do {
steps++
val next = currentPosition.moveIn(nextDirection, matrix)
currentPosition = next!!.first
nextDirection = next.second!!
points.add(currentPosition)
maxX = max(maxX, currentPosition.x)
maxY = max(maxY, currentPosition.y)
minX = min(minX, currentPosition.x)
minY = min(minY, currentPosition.y)
} while (currentPosition != s)
var countInLoop = 0
for (y in minY..maxY) {
var inLoop = false
var lastBarrier: Char? = null
for (x in minX .. maxX) {
val char = matrix[y][x]
if (points.contains(Point2(y, x))) {
when (char) {
'|' -> {
inLoop = !inLoop
}
'L', 'F' -> {
lastBarrier = char
}
'J' -> {
if (lastBarrier == 'F') {
inLoop = !inLoop
}
}
'7' -> {
if (lastBarrier == 'L') {
inLoop = !inLoop
}
}
}
} else {
countInLoop += if (inLoop) 1 else 0
}
}
}
print(countInLoop)
}
| 0 | Kotlin | 0 | 0 | 53b5d0a0bb65a77deb5153c8a912d292c628e048 | 5,000 | advent-of-code-2023 | MIT License |
kotlin/14_Longest_Common_Prefix/solution.kt | giovanniPepi | 607,763,568 | false | null | // Solution for LeetCode problem #14, Longest Common Prefix
// Problem description found on:
// https://leetcode.com/problems/longest-common-prefix/
class Solution {
fun longestCommonPrefix(strs: Array<String>): String {
// finds the length of the shortest word in strs
var shortestLen: Int = 200 // 200 is maximum, given by problem
strs.forEach{
if (it.length < shortestLen) shortestLen = it.length
}
var output: String = "" // output string, starts empty
// 1st loop, for every char
for (charPosition in 0 until shortestLen){
var auxChar: Char = strs[0][charPosition] // char for comparison, taken from 1st word
// 2nd loop, for every word in strs
for (word in strs){
if (word[charPosition] != auxChar) return output
}
output += auxChar // if true adds char to the output
}
return output
}
}
| 0 | Kotlin | 1 | 0 | ccb853bce41206f30cbfb1ff4ca8e8f22feb0ee2 | 980 | bastterCode | MIT License |
src/search/TernarySearch.kt | daolq3012 | 143,137,563 | false | null | package search
import sort.HeapSort
import java.io.IOException
import java.util.*
import kotlin.collections.ArrayList
class TernarySearch : SearchAlgorithms<Int> {
override fun findIndexOf(arr: ArrayList<Int>, value: Int): Int {
return ternarySearch(arr, value, 0, arr.size - 1)
}
/**
* @param arr The **Sorted** array in which we will search the element.
* @param key The value that we want to search for.
* @param left The starting index from which we will left Searching.
* @param right The ending index till which we will Search.
* @return Returns the index of the Element if found.
* Else returns -1.
*/
private fun ternarySearch(arr: ArrayList<Int>, key: Int, left: Int, right: Int): Int {
if (left > right) {
return -1
}
/* First boundary: add 1/3 of length to left */
var mid1 = left + (right - left) / 3
/* Second boundary: add 2/3 of length to left */
var mid2 = left + 2 * (right - left) / 3
return when {
key == arr[mid1] -> mid1
key == arr[mid2] -> mid2
/* Search the first (1/3) rd part of the array.*/
key < arr[mid1] -> ternarySearch(arr, key, left, --mid1)
/* Search 3rd (1/3)rd part of the array */
key > arr[mid2] -> ternarySearch(arr, key, ++mid2, right)
/* Search middle (1/3)rd part of the array */
else -> ternarySearch(arr, key, mid1, mid2)
}
}
object Run {
@Throws(IOException::class)
@JvmStatic
fun main(args: Array<String>) {
val dataInputs = arrayListOf(6, 5, 3, 1, 8, 7, 2, 4)
// sort data inputs
HeapSort().sort(dataInputs)
System.out.print("---------Input---------\n$dataInputs\n")
val searchAlgorithms: SearchAlgorithms<Int> = TernarySearch()
val randomInput = Random().nextInt(10)
val result = searchAlgorithms.findIndexOf(dataInputs, randomInput)
System.out.print("---------Result---------\n")
if (result != -1) {
System.out.print("Found $randomInput at index $result")
} else {
System.out.print("$randomInput not found in dataInputs!")
}
}
}
}
| 1 | Kotlin | 11 | 74 | 40e00d0d3f1c7cbb93ad28f4197e7ffa5ea36ef9 | 2,313 | Kotlin-Algorithms | Apache License 2.0 |
src/Day06.kt | Jaavv | 571,865,629 | false | {"Kotlin": 14896} | // https://adventofcode.com/2022/day/6
fun main() {
val testInput = readInput("Day06_test")
val input = readInput("Day06")
check(day06Part1and2("mjqjpqmgbljsphdztnvjfqwrcgsmlb", 4) == 7)
check(day06Part1and2("bvwbjplbgvbhsrlpgdmjqwftvncz", 4) == 5)
check(day06Part1and2("nppdvjthqldpwncqszvftbrmjlhg", 4) == 6)
check(day06Part1and2("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg", 4) == 10)
check(day06Part1and2("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw", 4) == 11)
check(day06Part1and2("mjqjpqmgbljsphdztnvjfqwrcgsmlb", 14) == 19)
check(day06Part1and2("bvwbjplbgvbhsrlpgdmjqwftvncz", 14) == 23)
check(day06Part1and2("nppdvjthqldpwncqszvftbrmjlhg", 14) == 23)
check(day06Part1and2("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg", 14) == 29)
check(day06Part1and2("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw", 14) == 26)
println(day06Part1and2(input[0], 4)) //1538
println(day06Part1and2(input[0], 14)) //2315
}
fun day06Part1and2(input: String, characters: Int): Int {
val marker = input.windowed(characters).map { it.toSet() }.first { it.size == characters }.joinToString("")
return input.indexOf(marker) + characters
}
| 0 | Kotlin | 0 | 0 | 5ef23a16d13218cb1169e969f1633f548fdf5b3b | 1,146 | advent-of-code-2022 | Apache License 2.0 |
src/Day19.kt | l8nite | 573,298,097 | false | {"Kotlin": 105683} | import kotlin.math.max
const val ORE = 0
const val CLAY = 1
const val OBSIDIAN = 2
const val GEODE = 3
val resourceNames = listOf("ore", "clay", "obsidian", "geode")
val blueprintRegex =
("^Blueprint (\\d+): Each ore robot costs (\\d+) ore. " +
"Each clay robot costs (\\d+) ore. " +
"Each obsidian robot costs (\\d+) ore and (\\d+) clay. " +
"Each geode robot costs (\\d+) ore and (\\d+) obsidian.$").toRegex()
data class Blueprint(val id: Int, val costs: List<List<Int>>) {
val maxResourceCost = listOf(
costs.maxOf { it[ORE] },
costs.maxOf { it[CLAY] },
costs.maxOf { it[OBSIDIAN] },
Int.MAX_VALUE
)
fun printInfo() {
println("== Blueprint ${id} ==")
for (robotType in listOf(ORE, CLAY, OBSIDIAN, GEODE)) {
val costs = costs[robotType].mapIndexedNotNull { resourceType, resourceCost ->
if (resourceCost > 0) { "$resourceCost ${resourceNames[resourceType]}" } else { null }
}
println(" Each ${resourceNames[robotType]} robot costs ${costs.joinToString(" and ")}")
}
}
companion object {
fun parse(input: String): Blueprint {
val (id, oreOre, clayOre, obsidianOre, obsidianClay, geodeOre, geodeObsidian) =
blueprintRegex.matchEntire(input)!!.destructured
return Blueprint(id.toInt(), ArrayList<List<Int>>(4).also {
it.add(ORE, listOf(oreOre.toInt(), 0, 0, 0))
it.add(CLAY,listOf(clayOre.toInt(), 0, 0, 0))
it.add(OBSIDIAN, listOf(obsidianOre.toInt(), obsidianClay.toInt(), 0, 0))
it.add(GEODE, listOf(geodeOre.toInt(), 0, geodeObsidian.toInt(), 0))
})
}
}
}
data class State(var blueprint: Blueprint, var minute: Int = 0, val resources: MutableList<Int> = arrayListOf(0, 0, 0, 0), val robots: MutableList<Int> = arrayListOf(1, 0, 0, 0), var robotToBuild: Int = -1, val history: MutableList<Int> = mutableListOf()) {
fun operate(operation: Int, debug: Boolean = false) {
robotToBuild = operation // shortcut for replaying history to set robotToBuild
minute++
if (debug) { println("== Minute $minute ==") }
spendResources(debug)
harvestResources(debug)
buildRobot(debug)
if (debug) { println() }
history.add(robotToBuild)
}
private fun spendResources(debug: Boolean) {
if (robotToBuild < 0) {
if (debug) {
println("You are not constructing a robot this time.")
}
return
}
blueprint.costs[robotToBuild].forEachIndexed { resourceType, resourceCost ->
resources[resourceType] -= resourceCost
}
if (debug) {
print("Spend ")
val costs = blueprint.costs[robotToBuild].mapIndexedNotNull { resourceType, resourceCost ->
if (resourceCost > 0) {
"$resourceCost ${resourceNames[resourceType]}"
} else {
null
}
}
print(costs.joinToString(" and "))
println(" to start building an ${resourceNames[robotToBuild]}-collecting robot.")
}
}
private fun harvestResources(debug: Boolean) {
robots.forEachIndexed { robotType, robotCount ->
resources[robotType] += robotCount
if (debug && robotCount > 0) {
println("$robotCount ${resourceNames[robotType]}-collecting robot(s) collects $robotCount ${resourceNames[robotType]}; you now have ${resources[robotType]} ${resourceNames[robotType]}")
}
}
}
private fun buildRobot(debug: Boolean) {
if (robotToBuild < 0) {
return
}
robots[robotToBuild]++
if (debug) {
println("The new ${resourceNames[robotToBuild]}-collecting robot is ready; you now have ${robots[robotToBuild]} of them.")
}
}
fun canBuildRobot(robotType: Int): Boolean {
blueprint.costs[robotType].forEachIndexed { resourceType, resourceCost ->
if (resources[resourceType] < resourceCost) {
return false
}
}
return true
}
fun clone(): State {
return State(blueprint, minute, resources.toMutableList(), robots.toMutableList(), robotToBuild, history.toMutableList())
}
}
var statesExplored = 0
var statesExploredFully = 0
var statesPrunedByTriangularNumber = 0
var bestState = mutableMapOf<Int, State>()
var bestCount = mutableMapOf<Int, Int>()
var maxMinutes = 24
fun quality(currentState: State): Int {
val currentBestCount = bestCount[currentState.blueprint.id] ?: Int.MIN_VALUE
// increase time, spend the resources for a robot build (if any), harvest resources, build the robot (if any)
currentState.operate(currentState.robotToBuild)
// if we've advanced to the end...
if (currentState.minute == maxMinutes) {
statesExploredFully++
if (currentState.resources[GEODE] > currentBestCount) {
bestCount[currentState.blueprint.id] = currentState.resources[GEODE]
bestState[currentState.blueprint.id] = currentState.clone()
}
return currentState.resources[GEODE]
}
// determine if this particular state will ever be able to compete with the best state we've seen
val timeRemaining = maxMinutes - currentState.minute
val upperBoundGeodes = currentState.resources[GEODE] + // the existing resources
(1 until timeRemaining).sum() + // if we made 1 geode-bot on every tick
(currentState.robots[GEODE] * timeRemaining) // the ones we will harvest in future rounds
if (currentBestCount >= upperBoundGeodes) {
statesPrunedByTriangularNumber++
return Int.MIN_VALUE // abandon this path...
}
val statesToExplore = mutableListOf(
currentState.clone().apply { robotToBuild = -1 }
)
for (robotType in listOf(ORE, CLAY, OBSIDIAN, GEODE)) {
// TODO: optimize by calculating maximum demand for remaining minutes and see if we already have it covered
if (currentState.canBuildRobot(robotType) && currentState.robots[robotType] < currentState.blueprint.maxResourceCost[robotType]) {
statesToExplore.add(currentState.clone().apply { robotToBuild = robotType })
}
}
statesExplored += statesToExplore.size
// reverse so we try things in order: geode bots, obsidian bots, clay bots, ore bots, no bots
return statesToExplore.reversed().maxOf {
quality(it)
}
}
fun main() {
fun part1(input: List<String>): Int {
val blueprints = input.map { Blueprint.parse(it) }
val quality = blueprints.sumOf {
it.printInfo()
val x = max(0, quality(State(it))) * it.id
println("QUALITY SCORE: $x")
println("Explored $statesExploredFully states fully out of $statesExplored total (pruned $statesPrunedByTriangularNumber by triangular number)")
x
}
return quality
}
fun part2(input: List<String>): Int {
val blueprints = input.map { Blueprint.parse(it) }.take(3)
maxMinutes = 32
val qualities = blueprints.map {
it.printInfo()
val x = max(0, quality(State(it)))
println("QUALITY SCORE: $x")
println("Explored $statesExploredFully states fully out of $statesExplored total (pruned $statesPrunedByTriangularNumber by triangular number)")
x
}
return qualities.reduce { acc, q -> q * acc }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day19_test")
check(part1(testInput) == 33)
println("Part 1 checked out ok!")
check(part2(testInput) == 3472)
println("Part 2 checked out ok!")
val input = readInput("Day19")
// println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f74331778fdd5a563ee43cf7fff042e69de72272 | 8,043 | advent-of-code-2022 | Apache License 2.0 |
src/Day11.kt | laricchia | 434,141,174 | false | {"Kotlin": 38143} | import org.jetbrains.kotlinx.multik.api.toNDArray
import org.jetbrains.kotlinx.multik.ndarray.data.D2Array
import org.jetbrains.kotlinx.multik.ndarray.data.get
import org.jetbrains.kotlinx.multik.ndarray.data.set
import org.jetbrains.kotlinx.multik.ndarray.operations.all
import org.jetbrains.kotlinx.multik.ndarray.operations.plus
fun firstPart11(list : List<List<Int>>) {
val steps = 100
var dumboMap = list.toNDArray()
var flashCounter = 0
for (i in 0 .. steps) {
val setOfAdd = mutableSetOf<IntArray>()
val setOfNeigh = mutableSetOf<IntArray>()
while (dumboMap.find { it > 9 }.isNotEmpty()) {
val currentNine = dumboMap.find { it > 9 }.first { it !in setOfAdd }
setOfAdd.add(currentNine)
val neigh = dumboMap.findNeigh(currentNine).filterNot { dumboMap[it[0], it[1]] == 0 }
neigh.map { dumboMap[it[0], it[1]] = dumboMap[it[0], it[1]] + 1 }
setOfNeigh.addAll(neigh)
dumboMap[currentNine[0], currentNine[1]] = 0
flashCounter++
}
// println(dumboMap)
dumboMap = dumboMap.plus(1)
if (steps == i) println("Flash counter at step $i: $flashCounter")
}
}
fun secondPart11(list : List<List<Int>>) {
var dumboMap = list.toNDArray()
var stepCounter = 0
while (true) {
val setOfAdd = mutableSetOf<IntArray>()
val setOfNeigh = mutableSetOf<IntArray>()
while (dumboMap.find { it > 9 }.isNotEmpty()) {
val currentNine = dumboMap.find { it > 9 }.first { it !in setOfAdd }
setOfAdd.add(currentNine)
val neigh = dumboMap.findNeigh(currentNine).filterNot { dumboMap[it[0], it[1]] == 0 }
neigh.map { dumboMap[it[0], it[1]] = dumboMap[it[0], it[1]] + 1 }
setOfNeigh.addAll(neigh)
dumboMap[currentNine[0], currentNine[1]] = 0
}
if (dumboMap.all { it == 0 }) break
dumboMap = dumboMap.plus(1)
stepCounter++
}
println("All 0 at step $stepCounter")
}
fun main() {
val input : List<String> = readInput("Day11")
val list = input.filter { it.isNotBlank() }.map { it.split("").filterNot { it.isBlank() }.map { it.toInt() } }
firstPart11(list)
secondPart11(list)
}
fun D2Array<Int>.find(condition : (Int) -> Boolean) : List<IntArray> {
val eightMap = mutableListOf<IntArray>()
for (j in multiIndices) {
if (condition(this[j[0], j[1]])) { eightMap.add(j.copyOf()) }
}
return eightMap.toList()
}
fun D2Array<Int>.findNeigh(seed : IntArray) : List<IntArray> {
val neigh = mutableListOf<IntArray>()
val x = seed[0]
val y = seed[1]
neigh.add(intArrayOf(x-1, y-1))
neigh.add(intArrayOf(x-1, y))
neigh.add(intArrayOf(x-1, y+1))
neigh.add(intArrayOf(x, y-1))
neigh.add(intArrayOf(x+1, y-1))
neigh.add(intArrayOf(x+1, y+1))
neigh.add(intArrayOf(x+1, y))
neigh.add(intArrayOf(x, y+1))
neigh.removeAll { it[0] < 0 || it[1] < 0 || it[0] >= this.shape[0] || it[1] >= this.shape[1] }
return neigh.toList()
}
| 0 | Kotlin | 0 | 0 | 7041d15fafa7256628df5c52fea2a137bdc60727 | 3,084 | Advent_of_Code_2021_Kotlin | Apache License 2.0 |
kotlin/src/com/s13g/aoc/aoc2022/Day20.kt | shaeberling | 50,704,971 | false | {"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245} | package com.s13g.aoc.aoc2022
import com.s13g.aoc.Result
import com.s13g.aoc.Solver
import com.s13g.aoc.resultFrom
import kotlin.math.abs
/**
* --- Day 20: Grove Positioning System ---
* https://adventofcode.com/2022/day/20
*/
class Day20 : Solver {
override fun solve(lines: List<String>): Result {
val inputA = lines.map { Node(it.toLong()) }
val inputB = lines.map { Node(it.toLong() * 811589153) }
// Build the doubly linked list(s).
val connect = { input: List<Node> ->
for ((n1, n2) in input.windowed(2, 1)) {
n1.next = n2
n2.prev = n1
}
input.first().prev = input.last()
input.last().next = input.first()
}
connect(inputA)
connect(inputB)
return resultFrom(mix(inputA, 1), mix(inputB, 10))
}
private fun mix(input: List<Node>, rounds: Int): Long {
for (r in 1..rounds) {
for (toPlace in input) {
val num = abs(toPlace.value) % (input.size - 1)
if (num == 0L) continue
// Remove node from list first (important!).
val oldPrev = toPlace.prev!!
val oldNext = toPlace.next!!
oldPrev.next = oldNext
oldNext.prev = oldPrev
// Find place to insert.
var newPrev = toPlace
if (toPlace.value > 0) for (n in 1..num) newPrev = newPrev.next!!
else for (n in 1..num + 1) newPrev = newPrev.prev!!
val newNext = newPrev.next!!
// Insert into new place.
newPrev.next = toPlace
newNext.prev = toPlace
toPlace.prev = newPrev
toPlace.next = newNext
}
}
val thousands = mutableListOf<Long>()
var curr = input.first { it.value == 0L }
for (i in 1..3000) {
curr = curr.next!!
if (i % 1000 == 0) thousands.add(curr.value)
}
return thousands.sum()
}
data class Node(
val value: Long, var prev: Node? = null, var next: Node? = null
) {
override fun toString() = "${prev!!.value}<[$value]>${next!!.value}"
}
} | 0 | Kotlin | 1 | 2 | 7e5806f288e87d26cd22eca44e5c695faf62a0d7 | 1,981 | euler | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/LargestPalindromicNumber.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
/**
* 2384. Largest Palindromic Number
* @see <a href="https://leetcode.com/problems/largest-palindromic-number/">Source</a>
*/
fun interface LargestPalindromicNumber {
operator fun invoke(num: String): String
}
class LargestPalindromicNumberGreedy : LargestPalindromicNumber {
override operator fun invoke(num: String): String {
val count = IntArray(10)
for (c in num.toCharArray()) {
count[c.code - '0'.code]++
}
var odd = false
val sb = StringBuilder()
var middle = ' '
for (i in 9 downTo 0) {
if (i == 0 && sb.isEmpty() && !odd) {
return "0"
}
val c = (i + '0'.code).toChar()
if (!odd) {
odd = count[i] % 2 == 1
if (odd) {
middle = c
}
}
// no leading zero
if (i == 0 && sb.isEmpty()) {
continue
}
for (j in 0 until count[i] / 2) {
sb.append(c)
}
}
val reverse = StringBuilder(sb).reverse()
if (odd) {
sb.append(middle)
}
sb.append(reverse)
return sb.toString()
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,895 | kotlab | Apache License 2.0 |
common/src/main/kotlin/combo/math/Estimators.kt | rasros | 148,620,275 | false | null | package combo.math
import combo.util.FloatCircleBuffer
import kotlin.math.min
import kotlin.math.sqrt
interface VarianceEstimator : DataSample {
override fun accept(value: Float) = accept(value, 1.0f)
/**
* @param value include value in estimate
* @param weight frequency weight
*/
override fun accept(value: Float, weight: Float)
override val nbrSamples: Long get() = nbrWeightedSamples.toLong()
val nbrWeightedSamples: Float
val mean: Float
val sum: Float get() = mean * nbrWeightedSamples
override fun values() = floatArrayOf(mean)
override fun labels() = longArrayOf(0L)
fun combine(vs: VarianceEstimator): VarianceEstimator
val squaredDeviations: Float get() = variance * nbrWeightedSamples
val variance: Float get() = squaredDeviations / nbrWeightedSamples
val standardDeviation: Float get() = sqrt(variance)
fun updateSampleSize(newN: Float)
override fun copy(): VarianceEstimator
}
fun combineMean(m1: Float, m2: Float, n1: Float, n2: Float): Float {
val n = n1 + n2
return if (n == 0f) 0f
else (m1 * n1 + m2 * n2) / n
}
fun combineVariance(v1: Float, v2: Float, m1: Float, m2: Float, n1: Float, n2: Float): Float {
val n = n1 + n2
return if (n == 0f) 0f
else (v1 * n1 + v2 * n2) / n + (m1 - m2) * (m1 - m2) * n1 * n2 / n / n
}
fun combinePrecision(p1: Float, p2: Float, m1: Float, m2: Float, n1: Float, n2: Float): Float {
val n = n1 + n2
return if (p1 == 0f || p2 == 0f) 0f
else n * n / (n1 * n2 * (m1 - m2) * (m1 - m2) + n * (n1 / p1 + n2 / p2))
}
interface RemovableEstimator : VarianceEstimator {
fun remove(value: Float, weight: Float = 1.0f)
override fun combine(vs: VarianceEstimator): RemovableEstimator
override fun copy(): RemovableEstimator
}
/**
* This estimator is only used with poisson data, hence the variance is the mean.
*/
interface MeanEstimator : VarianceEstimator {
override val variance: Float
get() = mean
override fun copy(): MeanEstimator
}
/**
* This estimator is only used with binomial count data, hence the variance is a function of the mean.
*/
interface BinaryEstimator : VarianceEstimator {
override val variance: Float
get() = mean * (1 - mean)
override fun copy(): BinaryEstimator
}
/**
* This estimator is used for UCB1Tuned and UCB1Normal
*/
interface SquaredEstimator : VarianceEstimator {
val meanOfSquares: Float
override fun copy(): SquaredEstimator
}
/**
* Calculates incremental mean and variance according to the Welford's online algorithm.
*/
class RunningVariance(mean: Float = 0.0f, squaredDeviations: Float = 0.0f, nbrWeightedSamples: Float = 0.0f)
: RemovableEstimator {
override var mean = mean
private set
override var squaredDeviations = squaredDeviations
private set
override var nbrWeightedSamples = nbrWeightedSamples
private set
override fun accept(value: Float, weight: Float) {
require(weight >= 0.0f)
nbrWeightedSamples += weight
val oldM = mean
mean = oldM + (value - oldM) * (weight / nbrWeightedSamples)
squaredDeviations += weight * (value - oldM) * (value - mean)
}
override fun remove(value: Float, weight: Float) {
require(nbrWeightedSamples > weight)
nbrWeightedSamples -= weight
val oldM = mean
mean = oldM - (value - oldM) * (weight / (nbrWeightedSamples))
squaredDeviations -= weight * (value - oldM) * (value - mean)
}
override fun updateSampleSize(newN: Float) {
squaredDeviations *= newN / nbrWeightedSamples
nbrWeightedSamples = newN
}
override fun toString() = "RunningVariance(mean=$mean, variance=$variance, nbrSamples=$nbrSamples)"
override fun copy() = RunningVariance(mean, squaredDeviations, nbrWeightedSamples)
override fun combine(vs: VarianceEstimator): RunningVariance {
val n1 = nbrWeightedSamples
val n2 = vs.nbrWeightedSamples
val v1 = variance
val v2 = vs.variance
val m1 = mean
val m2 = vs.mean
val n = n1 + n2
val m = combineMean(m1, m2, n1, n2)
val v = combineVariance(v1, v2, m1, m2, n1, n2)
return RunningVariance(m, v * n, n)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is RunningVariance) return false
return mean == other.mean &&
squaredDeviations == other.squaredDeviations &&
nbrWeightedSamples == other.nbrWeightedSamples
}
override fun hashCode(): Int {
var result = mean.hashCode()
result = 31 * result + squaredDeviations.hashCode()
result = 31 * result + nbrWeightedSamples.hashCode()
return result
}
}
/**
* This calculates a moving average and variance by assigning old values an exponentially decaying weight. The storage
* requirement is constant and does not depend on the size of the window of the moving average. The [nbrSamples] is
* capped to the window size.
* @param beta strength of the update. For finite samples n the optimal parameter can be set to: beta = 2/n+1.
* Default n is 99.
*/
class ExponentialDecayVariance(val beta: Float = 0.02f, mean: Float = 0.0f, variance: Float = 0.0f, nbrWeightedSamples: Float = 0.0f)
: VarianceEstimator {
constructor(window: Int) : this(2.0f / (window + 1.0f))
override var mean = mean
private set
override var variance = variance
private set
override var nbrWeightedSamples = nbrWeightedSamples
private set
private val maxSize: Float = 2 / beta - 1
init {
require(beta < 1.0f && beta > 0.0f) { "Beta (decay parameter) must be within 0 to 1 range, got $beta." }
}
override fun accept(value: Float, weight: Float) {
nbrWeightedSamples = min(maxSize, nbrWeightedSamples + weight)
if (nbrWeightedSamples == weight) {
mean = value
} else {
val adjustedBeta = if (weight == 1.0f) beta
else weight * beta / (1 - beta + weight * beta)
val diff = value - mean
val inc = adjustedBeta * diff
mean += inc
variance = (1 - adjustedBeta) * (variance + inc * diff)
}
}
override fun updateSampleSize(newN: Float) {
nbrWeightedSamples = newN
}
override fun toString() = "ExponentialDecayVariance(mean=$mean, variance=$variance, nbrSamples=$nbrSamples)"
override fun copy() = ExponentialDecayVariance(beta, mean, variance, nbrWeightedSamples)
override fun combine(vs: VarianceEstimator): ExponentialDecayVariance {
val n1 = nbrWeightedSamples
val n2 = vs.nbrWeightedSamples
val v1 = variance
val v2 = vs.variance
val m1 = mean
val m2 = vs.mean
val n = n1 + n2
val m = combineMean(m1, m2, n1, n2)
val v = combineVariance(v1, v2, m1, m2, n1, n2)
return ExponentialDecayVariance(beta, m, v, min(maxSize, n))
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is ExponentialDecayVariance) return false
return mean == other.mean &&
variance == other.variance &&
nbrWeightedSamples == other.nbrWeightedSamples
}
override fun hashCode(): Int {
var result = mean.hashCode()
result = 31 * result + variance.hashCode()
result = 31 * result + nbrWeightedSamples.hashCode()
return result
}
}
class BinarySum(sum: Float = 0.0f, nbrWeightedSamples: Float = 0.0f) : BinaryEstimator, RemovableEstimator {
override fun accept(value: Float, weight: Float) {
require(value in 0.0f..1.0f) { "BinarySum can only be used with Binomial data." }
sum += value * weight
nbrWeightedSamples += weight
}
override fun remove(value: Float, weight: Float) {
require(value in 0.0f..1.0f) { "BinarySum can only be used with Binomial data." }
require(nbrWeightedSamples >= weight)
sum -= value * weight
nbrWeightedSamples -= weight
}
override var sum = sum
private set
override var nbrWeightedSamples: Float = nbrWeightedSamples
private set
override val mean: Float
get() = sum / nbrWeightedSamples
override val variance: Float
get() = mean * (1 - mean)
override fun updateSampleSize(newN: Float) {
sum *= newN / nbrWeightedSamples
nbrWeightedSamples = newN
}
override fun toString() = "BinarySum(sum=$sum, nbrSamples=$nbrSamples, mean=$mean)"
override fun copy() = BinarySum(sum, nbrWeightedSamples)
override fun combine(vs: VarianceEstimator) = BinarySum(sum + vs.sum, nbrWeightedSamples + vs.nbrWeightedSamples)
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is BinarySum) return false
return sum == other.sum && nbrWeightedSamples == other.nbrWeightedSamples
}
override fun hashCode(): Int {
var result = sum.hashCode()
result = 31 * result + nbrWeightedSamples.hashCode()
return result
}
}
class RunningMean(mean: Float = 0.0f, nbrWeightedSamples: Float = 0.0f) : MeanEstimator, RemovableEstimator {
override var mean = mean
private set
override var nbrWeightedSamples = nbrWeightedSamples
private set
override fun accept(value: Float, weight: Float) {
nbrWeightedSamples += weight
val oldM = mean
mean = oldM + (value - oldM) * (weight / nbrWeightedSamples)
}
override fun remove(value: Float, weight: Float) {
require(nbrWeightedSamples >= weight)
nbrWeightedSamples -= weight
val oldM = mean
mean = oldM - (value - oldM) * (weight / nbrWeightedSamples)
}
override fun updateSampleSize(newN: Float) {
mean *= newN / nbrWeightedSamples
nbrWeightedSamples = newN
}
override fun toString() = "RunningMean(mean=$mean, nbrSamples=$nbrSamples)"
override fun copy() = RunningMean(mean, nbrWeightedSamples)
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is RunningMean) return false
return mean == other.mean && nbrWeightedSamples == other.nbrWeightedSamples
}
override fun combine(vs: VarianceEstimator): RunningMean {
val n1 = nbrWeightedSamples
val n2 = vs.nbrWeightedSamples
val m1 = mean
val m2 = vs.mean
val m = combineMean(m1, m2, n1, n2)
return RunningMean(m, n1 + n2)
}
override fun hashCode(): Int {
var result = mean.hashCode()
result = 31 * result + nbrWeightedSamples.hashCode()
return result
}
}
class RunningSquaredMeans private constructor(private val base: RunningVariance, meanOfSquares: Float)
: RemovableEstimator by base, SquaredEstimator {
constructor(mean: Float = 0.0f,
meanOfSquares: Float = 0.0f,
squaredDeviations: Float = 0.0f,
nbrWeightedSamples: Float = 0.0f) : this(RunningVariance(mean, squaredDeviations, nbrWeightedSamples), meanOfSquares)
override var meanOfSquares: Float = meanOfSquares
private set
override fun accept(value: Float) = accept(value, 1.0f)
override fun accept(value: Float, weight: Float) {
base.accept(value, weight)
val oldMS = meanOfSquares
meanOfSquares = oldMS + (value * value - oldMS) * (weight / nbrWeightedSamples)
}
override fun remove(value: Float, weight: Float) {
base.remove(value, weight)
val oldMS = meanOfSquares
meanOfSquares = oldMS - (value * value - oldMS) * (weight / nbrWeightedSamples)
}
override fun combine(vs: VarianceEstimator): RunningSquaredMeans {
vs as SquaredEstimator
val ms1 = meanOfSquares
val ms2 = vs.meanOfSquares
val n1 = nbrWeightedSamples
val n2 = vs.nbrWeightedSamples
val ms = combineMean(ms1, ms2, n1, n2)
return RunningSquaredMeans(base.combine(vs), ms)
}
override fun copy() = RunningSquaredMeans(mean, meanOfSquares, squaredDeviations, nbrWeightedSamples)
override fun toString() = "RunningSquaredMeans(mean=$mean, meanOfSquares=$meanOfSquares, squaredDeviations=$squaredDeviations, nbrSamples=$nbrSamples)"
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is RunningSquaredMeans) return false
return base == other.base && meanOfSquares == other.meanOfSquares
}
override fun hashCode(): Int {
var result = base.hashCode()
result = 31 * result + meanOfSquares.hashCode()
return result
}
}
class WindowedEstimator(val windowSize: Int, val base: RemovableEstimator) : BinaryEstimator, MeanEstimator, VarianceEstimator by base {
private val values = FloatCircleBuffer(windowSize)
private val weights = FloatCircleBuffer(windowSize)
override val variance: Float get() = base.variance
override fun accept(value: Float, weight: Float) {
val oldV = values.add(value)
val oldW = weights.add(weight)
if (oldW > 0.0f) base.remove(oldV, oldW)
base.accept(value, weight)
}
override fun combine(vs: VarianceEstimator) = WindowedEstimator(windowSize, base.combine(vs))
override fun copy() = WindowedEstimator(windowSize, base.copy())
override fun toString() = "WindowedEstimator(mean=$mean, variance=$variance, nbrSamples=$nbrSamples)"
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is WindowedEstimator) return false
return base == other.base
}
override fun hashCode() = base.hashCode()
}
class WindowedSquaredEstimator(val windowSize: Int, val base: RunningSquaredMeans = RunningSquaredMeans()) : SquaredEstimator by base {
private val values = FloatCircleBuffer(windowSize)
private val weights = FloatCircleBuffer(windowSize)
override val variance: Float get() = base.variance
override fun accept(value: Float, weight: Float) {
val oldV = values.add(value)
val oldW = weights.add(weight)
if (oldW > 0.0f) base.remove(oldV, oldW)
base.accept(value, weight)
}
override fun combine(vs: VarianceEstimator) = WindowedSquaredEstimator(windowSize, base.combine(vs))
override fun copy() = WindowedSquaredEstimator(windowSize, base.copy())
override fun toString() = "WindowedSquaredEstimator(mean=$mean, meanOfSquares=$meanOfSquares, variance=$variance, nbrSamples=$nbrSamples)"
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is WindowedSquaredEstimator) return false
return base == other.base
}
override fun hashCode() = base.hashCode()
}
| 0 | Kotlin | 1 | 2 | 2f4aab86e1b274c37d0798081bc5500d77f8cd6f | 14,974 | combo | Apache License 2.0 |
src/main/kotlin/days/Day13.kt | MaciejLipinski | 317,582,924 | true | {"Kotlin": 60261} | package days
import java.time.Duration
import java.time.Instant
import kotlin.math.ceil
class Day13 : Day(13) {
override fun partOne(): Any {
val timestamp = inputList[0].toInt()
return inputList[1]
.split(",")
.filter { it != "x" }
.map { it.toInt() }
.map { it to findLowestMultipleGte(it, timestamp) }
.minByOrNull { it.second }
?.let { (it.second - timestamp) * it.first }
?: throw RuntimeException()
}
override fun partTwo(): Any {
val buses = getBuses()
val nums = buses.map { it.first.toLong() }
val maxOffset = buses.maxByOrNull { it.second }?.second!! + 1
val offsets = buses.map { it.second }.map { maxOffset - it }
return chineseRemainder(nums, offsets) - maxOffset
}
private fun partTwoIterative(): Long {
val busesWithOffsets = getBuses()
var multiplier = 1L//210000000000000L
val timeAtStart = Instant.now()
outer@ while (true) {
if (multiplier % 1000000000 == 0L) println("${Duration.between(timeAtStart, Instant.now())} $multiplier")
for (i in 1..busesWithOffsets.lastIndex) {
if ((multiplier * busesWithOffsets[0].first + busesWithOffsets[i].second) % busesWithOffsets[i].first != 0L) {
if (i == 1) {
multiplier++
} else {
multiplier += busesWithOffsets[i - 1].first
}
continue@outer
}
}
return multiplier * busesWithOffsets[0].first
}
}
private fun getBuses(): List<Pair<Int, Int>> {
val tokens = inputList[1].split(",")
val busesWithOffsets = mutableListOf<Pair<Int, Int>>()
var offset = 0
for (i in tokens.indices) {
if (tokens[i] == "x") {
offset++
} else {
busesWithOffsets.add(Pair(
tokens[i].toInt(),
(if (busesWithOffsets.isEmpty()) 0 else busesWithOffsets.last().second + 1) + offset
))
offset = 0
}
}
return busesWithOffsets
}
private fun findLowestMultipleGte(number: Int, other: Int): Int {
return ceil(other.toDouble() / number).toInt() * number
}
/**
* This function was copied from https://rosettacode.org/wiki/Chinese_remainder_theorem#Kotlin and then modified.
* It is licensed under GNU Free Documentation License 1.2.
* See the file resources/fdl-1.2.txt for copying conditions.
*/
private fun chineseRemainder(n: List<Long>, a: List<Int>): Long {
val product = n.fold(1L) { acc, i -> acc * i }
var sum = 0L
for (i in n.indices) {
val p = product / n[i]
sum += a[i] * p *
(if (n[i] == 1L) 1 else {
var a1 = p
var b1 = n[i]
var x0 = 0L
var x1 = 1L
while (a1 > 1) {
val q = a1 / b1
var t = b1
b1 = a1 % b1
a1 = t
t = x0
x0 = x1 - q * x0
x1 = t
}
if (x1 < 0) x1 += n[i]
x1
})
}
return sum % product
}
} | 0 | Kotlin | 0 | 0 | 1c3881e602e2f8b11999fa12b82204bc5c7c5b51 | 3,626 | aoc-2020 | Creative Commons Zero v1.0 Universal |
backend.native/tests/external/stdlib/collections/ArraysTest/sortedWith.kt | acidburn0zzz | 110,847,830 | true | {"Kotlin": 3712759, "C++": 728274, "C": 132862, "Groovy": 52992, "JavaScript": 7780, "Shell": 6563, "Batchfile": 6379, "Objective-C++": 5203, "Objective-C": 1891, "Python": 1870, "Pascal": 1698, "Java": 782, "HTML": 185} | import kotlin.test.*
private class ArraySortedChecker<A, T>(val array: A, val comparator: Comparator<in T>) {
public fun <R> checkSorted(sorted: A.() -> R, sortedDescending: A.() -> R, iterator: R.() -> Iterator<T>) {
array.sorted().iterator().assertSorted { a, b -> comparator.compare(a, b) <= 0 }
array.sortedDescending().iterator().assertSorted { a, b -> comparator.compare(a, b) >= 0 }
}
}
fun box() {
val comparator = compareBy { it: Int -> it % 3 }.thenByDescending { it }
fun <A, T> arrayData(array: A, comparator: Comparator<T>) = ArraySortedChecker<A, T>(array, comparator)
arrayData(intArrayOf(0, 1, 2, 3, 4, 5), comparator)
.checkSorted<List<Int>>({ sortedWith(comparator) }, { sortedWith(comparator.reversed()) }, { iterator() })
arrayData(arrayOf(0, 1, 2, 3, 4, 5), comparator)
.checkSorted<Array<out Int>>({ sortedArrayWith(comparator) }, { sortedArrayWith(comparator.reversed()) }, { iterator() })
// in-place
val array = Array(6) { it }
array.sortWith(comparator)
array.iterator().assertSorted { a, b -> comparator.compare(a, b) <= 0 }
}
| 1 | Kotlin | 0 | 1 | 7b9cd6c9f4f3f3218d48acc9ba3b9a1dd62cc57f | 1,139 | kotlin-native | Apache License 2.0 |
src/main/kotlin/nl/dirkgroot/adventofcode/year2019/Day02.kt | dirkgroot | 317,968,017 | false | {"Kotlin": 187862} | package nl.dirkgroot.adventofcode.year2019
import kotlinx.collections.immutable.PersistentList
import kotlinx.collections.immutable.toPersistentList
import nl.dirkgroot.adventofcode.util.Input
import nl.dirkgroot.adventofcode.util.Puzzle
class Day02(input: Input, private val replaceInput: Boolean = true) : Puzzle() {
private val program = input.string()
.split(",")
.map(String::toInt)
override fun part1() = if (replaceInput)
exec(program, 12, 2)
else
exec(program, program[1], program[2])
override fun part2() =
allNounVerbCombos()
.first { (noun, verb) -> exec(program, noun, verb) == 19690720 }
.let { (noun, verb) -> 100 * noun + verb }
private fun exec(program: List<Int>, noun: Int, verb: Int): Int {
tailrec fun exec(memory: PersistentList<Int>, ip: Int = 0): Int =
when (memory[ip]) {
1 -> exec(memory.set(memory[ip + 3], memory[memory[ip + 1]] + memory[memory[ip + 2]]), ip + 4)
2 -> exec(memory.set(memory[ip + 3], memory[memory[ip + 1]] * memory[memory[ip + 2]]), ip + 4)
else -> memory[0]
}
return exec(program.toPersistentList().set(1, noun).set(2, verb))
}
private fun allNounVerbCombos() = generateSequence(0 to 0) { (noun, verb) ->
when {
noun == 100 -> null
verb == 99 -> noun + 1 to 0
else -> noun to verb + 1
}
}
}
| 1 | Kotlin | 1 | 1 | ffdffedc8659aa3deea3216d6a9a1fd4e02ec128 | 1,480 | adventofcode-kotlin | MIT License |
src/main/kotlin/d17/D17_2.kt | MTender | 734,007,442 | false | {"Kotlin": 108628} | package d17
import d16.Direction
import input.Input
data class Part1Location(
override val row: Int,
override val col: Int,
val from: Direction,
val straight: Int
) : Location(row, col) {
override fun getNeighbors(): List<Location> {
when (from) {
Direction.LEFT -> {
val neighbors = mutableListOf(
Part1Location(row - 1, col, Direction.BELOW, 1),
Part1Location(row + 1, col, Direction.ABOVE, 1)
)
if (straight < 3) neighbors.add(Part1Location(row, col + 1, from, straight + 1))
return neighbors
}
Direction.RIGHT -> {
val neighbors = mutableListOf(
Part1Location(row - 1, col, Direction.BELOW, 1),
Part1Location(row + 1, col, Direction.ABOVE, 1)
)
if (straight < 3) neighbors.add(Part1Location(row, col - 1, from, straight + 1))
return neighbors
}
Direction.BELOW -> {
val neighbors = mutableListOf(
Part1Location(row, col - 1, Direction.RIGHT, 1),
Part1Location(row, col + 1, Direction.LEFT, 1)
)
if (straight < 3) neighbors.add(Part1Location(row - 1, col, from, straight + 1))
return neighbors
}
Direction.ABOVE -> {
val neighbors = mutableListOf(
Part1Location(row, col - 1, Direction.RIGHT, 1),
Part1Location(row, col + 1, Direction.LEFT, 1)
)
if (straight < 3) neighbors.add(Part1Location(row + 1, col, from, straight + 1))
return neighbors
}
}
}
override fun isValidTarget(target: Pair<Int, Int>): Boolean {
return target == Pair(row, col)
}
}
fun main() {
val lines = Input.read("input.txt")
val weights = parseInput(lines)
val distance = dijkstra(
weights,
Part1Location(0, 0, Direction.LEFT, 0),
Pair(weights.lastIndex, weights[0].lastIndex)
)
println(distance)
} | 0 | Kotlin | 0 | 0 | a6eec4168b4a98b73d4496c9d610854a0165dbeb | 2,194 | aoc2023-kotlin | MIT License |
2023/15/solve-2.kts | gugod | 48,180,404 | false | {"Raku": 170466, "Perl": 121272, "Kotlin": 58674, "Rust": 3189, "C": 2934, "Zig": 850, "Clojure": 734, "Janet": 703, "Go": 595} | import java.io.File
fun main () {
val boxes = (0..255).map { mutableListOf<Pair<String,Int>>() }.toList()
val steps = File(args.getOrNull(0) ?: "input").readLines().joinToString("").split(",")
steps.forEach {
val l = labelFrom(it)
val op = opFrom(it)
val focal = focalFrom(it)
val h = runHASH(l)
when (op) {
"=" -> upsert(boxes[h], l, focal!!)
"-" -> remove(boxes[h], l)
else -> throw IllegalStateException("not possible")
}
}
val y = boxes.mapIndexed { i,lenses ->
lenses.mapIndexed { j,lens -> (i+1) * (j+1) * lens.second }.sum()
}.sum()
println(y)
}
fun upsert (box: MutableList<Pair<String,Int>>, label: String, focalLength: Int) {
val o = Pair(label, focalLength)
val i = box.indices.firstOrNull { box[it].first == label }
if (i == null) {
box.add(o)
} else {
box[i] = o
}
}
fun remove (box: MutableList<Pair<String,Int>>, label: String) {
box.indices.firstOrNull { box[it].first == label }?.let {
box.removeAt(it)
}
}
fun labelFrom(x: String) = Regex("^[a-z]+").find(x)!!.value
fun opFrom(x: String) = Regex("[-=]").find(x)!!.value
fun focalFrom(x: String) = Regex("[0-9]$").find(x)?.value?.toInt()
fun runHASH (x: String): Int {
var h: Int = 0
x.forEach {
h = ((h + it.code) * 17) % 256
}
return h
}
main()
| 0 | Raku | 1 | 5 | ca0555efc60176938a857990b4d95a298e32f48a | 1,419 | advent-of-code | Creative Commons Zero v1.0 Universal |
算法/一维数组的动态和1480.kt | Simplation | 506,160,986 | false | {"Kotlin": 10116} | 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]
} | 0 | Kotlin | 0 | 0 | d45feaa4c8ea2a08ce7357ee609a2df5b0639b68 | 1,160 | OpenSourceRepository | Apache License 2.0 |
2021/src/main/kotlin/com/trikzon/aoc2021/Day10.kt | Trikzon | 317,622,840 | false | {"Kotlin": 43720, "Rust": 21648, "C#": 12576, "C++": 4114, "CMake": 397} | package com.trikzon.aoc2021
import java.util.*
import kotlin.collections.ArrayList
fun main() {
val input = getInputStringFromFile("/day10.txt")
benchmark(Part.One, ::day10Part1, input, 436497, 50000)
benchmark(Part.One, ::day10Part2, input, 2377613374, 50000)
}
fun day10Part1(input: String): Int {
var errorScore = 0
input.lines().forEach { line ->
val stack = Stack<Char>()
for (i in line.indices) {
when (line[i]) {
'(' -> stack.push(line[i])
'[' -> stack.push(line[i])
'{' -> stack.push(line[i])
'<' -> stack.push(line[i])
')' -> if (stack.pop() != '(') { errorScore += 3; break }
']' -> if (stack.pop() != '[') { errorScore += 57; break }
'}' -> if (stack.pop() != '{') { errorScore += 1197; break }
'>' -> if (stack.pop() != '<') { errorScore += 25137; break }
}
}
}
return errorScore
}
fun day10Part2(input: String): Long {
val scores = ArrayList<Long>()
input.lines().forEach { line ->
val stack = Stack<Char>()
var isCorrupt = false
for (i in line.indices) {
when (line[i]) {
'(' -> stack.push(line[i])
'[' -> stack.push(line[i])
'{' -> stack.push(line[i])
'<' -> stack.push(line[i])
')' -> if (stack.pop() != '(') { isCorrupt = true; break }
']' -> if (stack.pop() != '[') { isCorrupt = true; break }
'}' -> if (stack.pop() != '{') { isCorrupt = true; break }
'>' -> if (stack.pop() != '<') { isCorrupt = true; break }
}
}
if (!isCorrupt) {
var score = 0L
while (!stack.isEmpty()) {
when (stack.pop()) {
'(' -> score = (score * 5) + 1
'[' -> score = (score * 5) + 2
'{' -> score = (score * 5) + 3
'<' -> score = (score * 5) + 4
}
}
scores.add(score)
}
}
scores.sort()
return scores[scores.size / 2]
}
| 0 | Kotlin | 1 | 0 | d4dea9f0c1b56dc698b716bb03fc2ad62619ca08 | 2,202 | advent-of-code | MIT License |
src/main/kotlin/Day13.kt | dlew | 75,886,947 | false | null | import java.util.*
class Day13 {
data class Coord(val x: Int, val y: Int)
companion object {
private val ADJACENT = arrayOf(
Coord(-1, 0),
Coord(0, -1),
Coord(1, 0),
Coord(0, 1)
)
fun bfs(startX: Int, startY: Int, targetX: Int, targetY: Int, favorite: Int): Array<IntArray> {
// Try an array 2x the size we need, just for simplicity
val width = targetX * 2
val height = targetY * 2
val maze = generateMaze(width, height, favorite)
val bfs = Array<IntArray>(height, { IntArray(width) })
bfs[startY][startX] = 1
var distance = 1
val stack = ArrayList<Coord>()
stack.add(Coord(startX, startY))
while (stack.isNotEmpty()) {
val nextStack = ArrayList<Coord>()
stack.forEach { coord ->
ADJACENT.forEach { rel ->
val x = coord.x + rel.x
val y = coord.y + rel.y
if (x >= 0 && y >= 0 && x < width && y < height && !maze[y][x] && bfs[y][x] == 0) {
bfs[y][x] = distance
nextStack.add(Coord(x, y))
}
}
}
stack.clear()
stack.addAll(nextStack)
distance++
}
return bfs
}
fun maxSteps(bfs: Array<IntArray>, max: Int) =
bfs.fold(0, { count, row ->
count + row.fold(0, { subCount, item ->
if (item != 0 && item <= max) subCount + 1 else subCount
})
})
fun generateMaze(width: Int, height: Int, favorite: Int): Array<BooleanArray> {
val maze = Array<BooleanArray>(height, { BooleanArray(width) })
(0..width - 1).forEach { x ->
(0..height - 1).forEach { y ->
maze[y][x] = isWall(x, y, favorite)
}
}
return maze
}
fun printMaze(maze: Array<BooleanArray>): String {
val sb = StringBuilder()
maze.forEach { row ->
row.forEach { sb.append(if (it) "#" else ".") }
sb.appendln()
}
return sb.toString().trim()
}
fun isWall(x: Int, y: Int, favorite: Int) = hammingWeight(math(x.toLong(), y.toLong(), favorite.toLong())) % 2 == 1
private fun math(x: Long, y: Long, favorite: Long) = (x * x) + (3 * x) + (2 * x * y) + y + (y * y) + favorite
private fun hammingWeight(num: Long): Int {
var curr = num
var count = 0
while (curr != 0L) {
if (curr.and(1L) != 0L) {
count++
}
curr = curr.ushr(1)
}
return count
}
}
} | 0 | Kotlin | 2 | 12 | 527e6f509e677520d7a8b8ee99f2ae74fc2e3ecd | 2,506 | aoc-2016 | MIT License |
src/main/kotlin/days/aoc2023/Day19.kt | bjdupuis | 435,570,912 | false | {"Kotlin": 537037} | package days.aoc2023
import days.Day
import java.lang.IllegalStateException
class Day19 : Day(2023, 19) {
override fun partOne(): Any {
return calculatePartOne(inputList)
}
override fun partTwo(): Any {
return calculatePartTwo(inputList)
}
internal data class Part(val map: Map<String,Int>)
internal class Rule(val condition: (Part) -> Boolean)
internal class Workflow(val name: String, private val rules: List<Rule>) {
fun invoke(part: Part) {
rules.takeWhile { rule -> rule.condition.invoke(part) }
}
}
fun calculatePartOne(input: List<String>): Int {
val accepted = mutableListOf<Part>()
val workflows = mutableMapOf<String, Workflow>()
input.takeWhile { it.isNotEmpty() }.forEach { line ->
val rules = mutableListOf<Rule>()
Regex("(\\w+)\\{(.*)\\}").matchEntire(line)?.destructured?.let { (name, ruleDescription) ->
ruleDescription.split(",").forEach { step ->
if (step == "R") {
rules.add(Rule { _ ->
false
})
} else if (step == "A") {
rules.add(Rule { part ->
accepted.add(part)
false
})
} else if (step.contains(":")) {
Regex("([xmas])([<>])(\\d+):(\\w+)").matchEntire(step)?.destructured?.let { (register, comparison, value, destination) ->
rules.add(Rule { part ->
val other = value.toInt()
if (comparison == ">" && (part.map[register]!! > other) || comparison == "<" && (part.map[register]!! < other)) {
if (destination == "A") {
accepted.add(part)
} else if (destination == "R") {
} else {
workflows[destination]!!.invoke(part)
}
false
} else {
true
}
})
}
} else {
// it's a direct transfer
rules.add(Rule { part ->
workflows[step]?.invoke(part)
false
})
}
}
workflows[name] = Workflow(name, rules)
}
}
input.dropWhile { it.isNotEmpty() }.drop(1).forEach { line ->
val map = mutableMapOf<String,Int>()
line.drop(1).dropLast(1).split(",").forEach { registerAndValue ->
val (register, value) = registerAndValue.split("=")
map[register] = value.toInt()
}
workflows["in"]!!.invoke(Part(map))
}
return accepted.sumOf { it.map.values.sum() }
}
fun calculatePartTwo(input: List<String>): Long {
val ruleMap = mutableMapOf<String, String>()
input.takeWhile { it.isNotEmpty() }.forEach { line ->
Regex("(\\w+)\\{(.*)\\}").matchEntire(line)?.destructured?.let { (name, ruleDescription) ->
ruleMap[name] = ruleDescription
}
}
fun mergeMap(first: Map<String, Set<Int>>, second: Map<String, Set<Int>>): Map<String, Set<Int>> {
val result = mutableMapOf<String, Set<Int>>()
first.keys.plus(second.keys).distinct().forEach { key ->
val s1 = first[key] ?: emptySet()
val s2 = second[key] ?: emptySet()
result[key] = s1 + s2
}
return result
}
var acceptedSoFar = 0L
fun traverseRule(name: String, current: Map<String, Set<Int>>) {
var steps = ruleMap[name]!!.split(",").toMutableList()
fun permutations(values: Collection<Set<Int>>): Long {
values.forEach { set ->
print("(${set.min()} .. ${set.max()}) ")
}
println()
return values.fold(1L) { acc, ints -> acc * if (ints.isEmpty()) 1L else ints.size.toLong() }
}
fun processSteps(steps: List<String>, current: Map<String, Set<Int>>) {
val step = steps.first()
if (step == "R") {
return
} else if (step == "A") {
acceptedSoFar += permutations((current.values))
return
} else if (step.contains(":")) {
Regex("([xmas])([<>])(\\d+):(\\w+)").matchEntire(step)?.destructured?.let { (register, comparison, valueString, destination) ->
val value = valueString.toInt()
if (comparison == ">") {
val mySet = current[register]!!.toSet().filter { it > value }.toSet()
val otherSet = current[register]!!.toSet().filter { it <= value }.toSet()
if (destination == "A") {
acceptedSoFar += permutations(current.plus(register to mySet).values)
return processSteps(steps.drop(1), current.plus(register to otherSet))
} else if (destination == "R") {
return processSteps(steps.drop(1), current.plus(register to otherSet))
} else {
traverseRule(destination, current.plus(register to mySet))
processSteps(steps.drop(1), current.plus(register to otherSet))
return
}
} else {
val mySet = current[register]!!.toSet().filter { it < value }.toSet()
val otherSet = current[register]!!.toSet().filter { it >= value }.toSet()
if (destination == "A") {
acceptedSoFar += permutations(current.plus(register to mySet).values)
return processSteps(steps.drop(1), current.plus(register to otherSet))
} else if (destination == "R") {
return processSteps(steps.drop(1), current.plus(register to otherSet))
} else {
traverseRule(destination, current.plus(register to mySet))
processSteps(steps.drop(1), current.plus(register to otherSet))
return
}
}
} ?: throw IllegalStateException("how are we here?")
} else {
// it's a direct transfer
return traverseRule(step, current)
}
}
return processSteps(steps, current)
}
val maps = mapOf(
"x" to (1..4000).toSet(),
"m" to (1..4000).toSet(),
"a" to (1..4000).toSet(),
"s" to (1..4000).toSet()
)
traverseRule("in", maps)
return acceptedSoFar
}
} | 0 | Kotlin | 0 | 1 | c692fb71811055c79d53f9b510fe58a6153a1397 | 7,544 | Advent-Of-Code | Creative Commons Zero v1.0 Universal |
src/main/kotlin/com/chriswk/aoc/advent2018/Day16.kt | chriswk | 317,863,220 | false | {"Kotlin": 481061} | package com.chriswk.aoc.advent2018
object Day16 {
val instructionPattern = """.*?(\d+),? (\d+),? (\d+),? (\d+).*""".toRegex()
fun partOne(input: List<String>, matchingOpCodeCount: Int): Int {
val sampleRuns = parseInput(input)
return sampleRuns.count { sample ->
findOpCodesWithMatchingOutput(sample) >= matchingOpCodeCount
}
}
fun partTwo(input: List<String>): Register {
val program = input.map { parseInstruction(it) }
return program.fold(Register(0, 0, 0, 0)) { currentRegister, instruction ->
OpCode.get(instruction.opCode).run(instruction, currentRegister)
}
}
fun parseInstruction(instruction: String): Instruction {
val (opCode, a, b, c) = instructionPattern.find(instruction)!!.groupValues.drop(1).map { it.toInt() }
return Instruction(opCode, a, b, c)
}
fun findOpCodesWithMatchingOutput(sampleRun: SampleRun): Int {
return OpCode.values().count { it.run(sampleRun.instruction, sampleRun.before) == sampleRun.after }
}
fun findOpCode(sampleRun: SampleRun) {
val codesWithMatch = OpCode.values().filter { it.opCode == -1 }.mapNotNull { opCode ->
if (opCode.run(sampleRun.instruction, sampleRun.before) == sampleRun.after) {
opCode
} else {
null
}
}
if(codesWithMatch.size == 1) {
println(codesWithMatch.first() to sampleRun.instruction.opCode)
}
}
data class SampleRun(val instruction: Instruction, val before: Register, val after: Register)
fun parseInput(input: List<String>) : List<SampleRun> {
return input.chunked(4).map { parseSingleSample(it) }
}
fun parseSingleSample(input: List<String>): SampleRun {
val (r0, r1, r2, r3) = instructionPattern.find(input[0])!!.groupValues.drop(1).map { it.toInt() }
val (opCode, a, b, c) = instructionPattern.find(input[1])!!.groupValues.drop(1).map { it.toInt() }
val (r_0, r_1, r_2, r_3) = instructionPattern.find(input[2])!!.groupValues.drop(1).map { it.toInt() }
return SampleRun(before = Register(r0, r1, r2, r3), instruction = Instruction(opCode, a, b, c), after = Register(r_0, r_1, r_2, r_3))
}
data class Instruction(val opCode: Int, val A: Int, val B: Int, val C: Int)
data class Register(val r0: Int, val r1: Int, val r2: Int, val r3: Int) {
operator fun get(idx: Int): Int = when(idx) {
0 -> r0
1 -> r1
2 -> r2
3 -> r3
else -> throw IllegalArgumentException("Non existent registry accessed")
}
operator fun set(idx: Int, value: Int): Register = when(idx) {
0 -> copy(r0 = value)
1 -> copy(r1 = value)
2 -> copy(r2 = value)
3 -> copy(r3 = value)
else -> throw java.lang.IllegalArgumentException("Non existent registry accessed")
}
fun copy(idx: Int, value: Int): Register {
return set(idx, value)
}
}
enum class OpCode(val opCode: Int) {
ADDR(11), ADDI(4), MULR(13), MULI(1), BANR(0),
BANI(10), BORR(8), BORI(2), SETR(3), SETI(14),
GTIR(7), GTRI(6), GTRR(15),
EQIR(12), EQRI(9), EQRR(5);
fun run(instruction: Instruction, register: Register): Register {
return when (this) {
ADDR -> {
val newValue = register[instruction.A] + register[instruction.B]
register.copy(instruction.C, newValue)
}
ADDI -> {
val newValue = register[instruction.A] + instruction.B
register.copy(instruction.C, newValue)
}
MULR -> {
val newValue = register[instruction.A] * register[instruction.B]
register.copy(instruction.C, newValue)
}
MULI -> {
val newValue = register[instruction.A] * instruction.B
register.copy(instruction.C, newValue)
}
BANR -> {
val newValue = register[instruction.A] and register[instruction.B]
register.copy(instruction.C, newValue)
}
BANI -> {
val newValue = register[instruction.A] and instruction.B
register.copy(instruction.C, newValue)
}
BORR -> {
val newValue = register[instruction.A] or register[instruction.B]
register.copy(instruction.C, newValue)
}
BORI -> {
val newValue = register[instruction.A] or instruction.B
register.copy(instruction.C, newValue)
}
SETR -> {
register.copy(instruction.C, register[instruction.A])
}
SETI -> {
register.copy(instruction.C, instruction.A)
}
GTIR -> {
if(instruction.A > register[instruction.B]) {
register.copy(instruction.C, 1)
} else {
register.copy(instruction.C, 0)
}
}
GTRI -> {
if (register[instruction.A] > instruction.B) {
register.copy(instruction.C, 1)
} else {
register.copy(instruction.C, 0)
}
}
GTRR -> {
if (register[instruction.A] > register[instruction.B]) {
register.copy(instruction.C, 1)
} else {
register.copy(instruction.C, 0)
}
}
EQIR -> {
if (instruction.A == register[instruction.B]) {
register.copy(instruction.C, 1)
} else {
register.copy(instruction.C, 0)
}
}
EQRI -> {
if (register[instruction.A] == instruction.B) {
register.copy(instruction.C, 1)
} else {
register.copy(instruction.C, 0)
}
}
EQRR -> {
if (register[instruction.A] == register[instruction.B]) {
register.copy(instruction.C, 1)
} else {
register.copy(instruction.C, 0)
}
}
}
}
companion object {
private val opCodes: Map<Int, OpCode> = OpCode.values().groupBy { it.opCode }.mapValues { it.value.first() }
fun get(opCode: Int): OpCode = opCodes[opCode]!!
}
}
} | 116 | Kotlin | 0 | 0 | 69fa3dfed62d5cb7d961fe16924066cb7f9f5985 | 7,043 | adventofcode | MIT License |
core/matchers/src/main/kotlin/au/com/dius/pact/core/matchers/RequestMatching.kt | ryanlevell | 342,718,513 | true | {"Groovy": 1072122, "Kotlin": 1065230, "Java": 610165, "Scala": 100906, "Clojure": 7519, "ANTLR": 7426, "Dockerfile": 582} | package au.com.dius.pact.core.matchers
import au.com.dius.pact.core.model.Interaction
import au.com.dius.pact.core.model.Request
import au.com.dius.pact.core.model.RequestResponseInteraction
import au.com.dius.pact.core.model.Response
import mu.KLogging
sealed class RequestMatch {
private val score: Int
get() {
return when (this) {
is FullRequestMatch -> this.calculateScore()
is PartialRequestMatch -> this.calculateScore()
else -> 0
}
}
/**
* Take the first total match, or merge partial matches, or take the best available.
*/
fun merge(other: RequestMatch): RequestMatch = when {
this is FullRequestMatch && other is FullRequestMatch -> if (this.score >= other.score) this
else other
this is FullRequestMatch -> this
other is FullRequestMatch -> other
this is PartialRequestMatch && other is PartialRequestMatch -> if (this.score >= other.score) this
else other
this is PartialRequestMatch -> this
else -> other
}
}
data class FullRequestMatch(val interaction: Interaction, val result: RequestMatchResult) : RequestMatch() {
fun calculateScore() = result.calculateScore()
}
data class PartialRequestMatch(val problems: Map<Interaction, RequestMatchResult>) : RequestMatch() {
fun description(): String {
var s = ""
for (problem in problems) {
s += problem.key.description + ":\n"
for (mismatch in problem.value.mismatches) {
s += " " + mismatch.description() + "\n"
}
}
return s
}
fun calculateScore() = problems.values.map { it.calculateScore() }.max() ?: 0
}
object RequestMismatch : RequestMatch()
class RequestMatching(private val expectedInteractions: List<RequestResponseInteraction>) {
fun matchInteraction(actual: Request): RequestMatch {
val matches = expectedInteractions.map { compareRequest(it, actual) }
return if (matches.isEmpty())
RequestMismatch
else
matches.reduce { acc, match -> acc.merge(match) }
}
fun findResponse(actual: Request): Response? {
val match = matchInteraction(actual)
return when (match) {
is FullRequestMatch -> (match.interaction as RequestResponseInteraction).response
else -> null
}
}
companion object : KLogging() {
private fun decideRequestMatch(expected: RequestResponseInteraction, result: RequestMatchResult) =
when {
result.matchedOk() -> FullRequestMatch(expected, result)
result.matchedMethodAndPath() -> PartialRequestMatch(mapOf(expected to result))
else -> RequestMismatch
}
fun compareRequest(expected: RequestResponseInteraction, actual: Request): RequestMatch {
val mismatches = requestMismatches(expected.request, actual)
logger.debug { "Request mismatch: $mismatches" }
return decideRequestMatch(expected, mismatches)
}
@JvmStatic
fun requestMismatches(expected: Request, actual: Request): RequestMatchResult {
logger.debug { "comparing to expected request: \n$expected" }
val pathContext = MatchingContext(expected.matchingRules.rulesForCategory("path"), false)
val bodyContext = MatchingContext(expected.matchingRules.rulesForCategory("body"), false)
val queryContext = MatchingContext(expected.matchingRules.rulesForCategory("query"), false)
val headerContext = MatchingContext(expected.matchingRules.rulesForCategory("header"), false)
return RequestMatchResult(Matching.matchMethod(expected.method, actual.method),
Matching.matchPath(expected, actual, pathContext),
Matching.matchQuery(expected, actual, queryContext),
Matching.matchCookies(expected.cookie(), actual.cookie(), headerContext),
Matching.matchRequestHeaders(expected, actual, headerContext),
Matching.matchBody(expected, actual, bodyContext))
}
}
}
| 0 | Groovy | 0 | 0 | c91f44d2a523240b69899d2c705937ae9cbb5448 | 3,889 | pact-jvm | Apache License 2.0 |
src/main/kotlin/com/sk/topicWise/tree/543. Diameter of Binary Tree.kt | sandeep549 | 262,513,267 | false | {"Kotlin": 530613} | package com.sk.topicWise.tree
import java.util.Stack
// backtracking
/**
* Traverse the tree in dfs, and while backtrack, keep track of 2 things
* 1. Farthest leaf node distance from current node, return it to caller adding 1 more edge
* 2. Max diameter under this node
*
* Every node will return max length path available under it.
* For every node calculate max distance by adding max length on left and right side of it,
* and keep track'of max found so far.
*/
private fun diameterOfBinaryTree2(root: TreeNode?): Int {
var ans = 0
fun dfs(root: TreeNode?): Int {
if (root == null) return 0
var l = dfs(root.left)
var r = dfs(root.right)
ans = maxOf(ans, l + r)
return maxOf(l, r) + 1
}
dfs(root)
return ans
}
fun diameterOfBinaryTree(root: TreeNode?): Int {
if (root == null) {
return 0
}
var maxSoFar = 0
val s = Stack<TreeNode>()
val map = mutableMapOf<TreeNode, Int>()
s.push(root)
while (!s.isEmpty()) {
val node = s.peek() // kotlin ArrayDeque doesn't have peek yet, so experimental
if (node.left != null && !map.containsKey(node.left!!)) {
s.push(node.left)
} else if (node.right != null && !map.containsKey(node.right!!)) {
s.push(node.right)
} else {
val cur = s.pop()
val lmax = if (cur.left != null) map.getOrDefault(cur.left!!, 0) else 0
val rmax = if (cur.right != null) map.getOrDefault(cur.right!!, 0) else 0
val nodeMax = maxOf(lmax, rmax) + 1
map[cur] = nodeMax
maxSoFar = maxOf(maxSoFar, lmax + rmax)
}
}
return maxSoFar
}
| 1 | Kotlin | 0 | 0 | cf357cdaaab2609de64a0e8ee9d9b5168c69ac12 | 1,695 | leetcode-kotlin | Apache License 2.0 |
src/main/kotlin/fijb/leetcode/algorithms/A2AddTwoNumbers.kt | fi-jb | 552,324,917 | false | {"Kotlin": 22836} | package fijb.leetcode.algorithms
//https://leetcode.com/problems/add-two-numbers/
object A2AddTwoNumbers {
fun addTwoNumbers(l1: ListNode?, l2: ListNode?): ListNode? {
var result : ListNode? = null
var it: ListNode? = null
var it1 = l1
var it2 = l2
var dev = 0
while (it1 != null) {
var sum =
if (it2 == null) it1.`val` + dev
else it1.`val` + it2.`val` + dev
dev = sum / 10
sum %= 10
if (result == null) {
result = ListNode(sum)
it = result
}
else {
it?.next = ListNode(sum)
it = it?.next
}
it1 = it1.next
it2 = it2?.next
}
while (it2 != null) {
var sum = it2.`val` + dev
dev = sum / 10
sum %= 10
it?.next = ListNode(sum)
it = it?.next
it2 = it2.next
}
if (dev != 0) it?.next = ListNode(dev)
return result
}
class ListNode(var `val`: Int) {
var next: ListNode? = null
override fun toString(): String {
val result = StringBuilder()
var it : ListNode? = this
while (it != null) {
result.append("${it.`val`} ")
it = it.next
}
return "[" + result.toString().trim().replace(" ", ",") + "]"
}
override fun equals(other: Any?): Boolean {
var it1: ListNode? = this
var it2: ListNode? = other as ListNode
while (it1 != null) {
if (it1.`val` != it2?.`val`) return false
it1 = it1.next
it2 = it2.next
}
if (it2 != null) return false
return true
}
override fun hashCode(): Int {
var result = `val`
result = 31 * result + (next?.hashCode() ?: 0)
return result
}
}
}
| 0 | Kotlin | 0 | 0 | f0d59da5bcffaa7a008fe6b83853306d40ac4b90 | 2,046 | leetcode | MIT License |
src/main/kotlin/aoc/utils/CustomListExtensions.kt | Arch-vile | 572,557,390 | false | {"Kotlin": 132454} | package aoc.utils
import kotlin.math.min
fun <T> List<T>.indexesOf(predicate: (T) -> Boolean): List<Int> {
val indexes = mutableListOf<Int>()
for (i in indices) {
if (predicate(this[i])) {
indexes.add(i)
}
}
return indexes
}
/**
* Identical to takeWhile but also includes the first element that did not match.
* listOf(1,2,3,4).takeUntil { it < 2 } --> [1,2,3]
*/
fun <T> List<T>.takeUntil(predicate: (T) -> Boolean): List<T> {
val delimeterIndex = indexOfFirst { !predicate(it) }
return if (delimeterIndex != -1) {
subList(0, delimeterIndex + 1)
} else {
this
}
}
/**
* Like takeWhile but only stop at the second matching element
*/
fun <T> List<T>.takeWhileSecond(predicate: (T) -> Boolean): List<T> {
val first = indexOfFirst { !predicate(it) }
return if (first != -1) {
val indexOfNext = subList(first + 1, size).indexOfFirst { !predicate(it) }
if (indexOfNext != -1) {
subList(0, first + 1 + indexOfNext)
} else {
this
}
} else {
this;
}
}
/**
* Split just before the first element matching the predicate. The matching element is included
* in the latter Pair element
*/
fun <T> List<T>.breakBeforeFirst(predicate: (T) -> Boolean): Pair<List<T>, List<T>> {
val firstIndex = indexOfFirst(predicate)
if(firstIndex == -1) {
return Pair(this, listOf())
}
return Pair(subList(0,firstIndex),subList(firstIndex,size))
}
/**
* Break the list to parts before each matching element. Separator is included in parts.
*
*/
fun <T> List<T>.breakBefore(predicate: (T) -> Boolean): List<List<T>> {
if(this.isEmpty()) return listOf()
val matches = indexesOf(predicate)
if(matches.isEmpty()) {
return listOf(this)
}
return listOf(0).plus(matches).plus(size)
.windowed(2, 1)
.map {
subList(it[0], it[1])
}
}
/**
* Break the list to parts after each matching element. Separator is included in parts.
*
*/
fun <T> List<T>.breakAfter(predicate: (T) -> Boolean): List<List<T>> {
if(this.isEmpty()) return listOf()
val matches = indexesOf(predicate).map { it+1 }
if(matches.isEmpty()) {
return listOf(this)
}
return listOf(0).plus(matches).plus(size)
.windowed(2, 1)
.map {
subList(it[0], min(it[1],size))
}
}
/**
* Split to sublists on given delimeter. Delimeter is not included on lists.
*/
fun <T> List<T>.splitOn(predicate: (T) -> Boolean): List<List<T>> {
if(this.isEmpty()) return listOf()
val matches = indexesOf(predicate).map { it }
if(matches.isEmpty()) {
return listOf(this)
}
val parts = matches.plus(size)
.windowed(2, 1)
.map {
subList(it[0]+1, it[1])
}
return listOf(subList(0,matches.first())).plus(parts)
}
fun <T> intersect(data: Collection<Collection<T>>): Collection<T> {
return data.reduce { acc, list -> acc.intersect(list).toList() }
}
/**
* Returns all the possible combinations (order does not matter) formed from given values.
* Each combination will have at least one element.
*
* combinations([1,2,3]) => [[1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]
*
* Duplicates are allowed if you feed in duplicates:
* combinations([1,2,2]) => [[1], [2], [1, 2], [2, 2], [1, 2, 2]]
*/
fun <T> List<T>.combinations(): Set<List<T>> {
val subsets = mutableSetOf<List<T>>()
val n: Int = size
for (i in 0 until (1 shl n)) {
val subset = mutableListOf<T>()
for (j in 0 until n) {
if (i and (1 shl j) > 0) {
subset.add(this[j])
}
}
subsets.add(subset)
}
return subsets.filter { it.isNotEmpty() }.toSet()
}
/**
* All order permutations of given values. Contains all given values
* e.g. 1,2,3 -> 1,2,3 2,3,1 3,1,2 ...
*/
fun <T> permutations(set: Set<T>): Set<List<T>> {
if (set.isEmpty()) return emptySet()
fun <T> allPermutations(list: List<T>): Set<List<T>> {
if (list.isEmpty()) return setOf(emptyList())
val result: MutableSet<List<T>> = mutableSetOf()
for (i in list.indices) {
allPermutations(list - list[i]).forEach { item ->
result.add(item + list[i])
}
}
return result
}
return allPermutations(set.toList())
}
data class SectionCandidate<T>(val section: List<T>, val before: List<T>, val after: List<T>)
/**
* Find sections within given size limits that satisfy the condition matcher
*/
fun <T> List<T>.findSections(sectionSize: ClosedRange<Int>, matcher: (SectionCandidate<T>) -> Boolean): List<List<T>> {
val sections = mutableListOf<List<T>>()
for (i in indices) {
var sliceSize = sectionSize.start
while (sectionSize.contains(sliceSize) && i + sliceSize < size) {
val section = subList(i, i + sliceSize)
val before = subList(0, i)
val after = subList(i + sliceSize, size)
if (matcher(SectionCandidate(section, before, after)))
sections.add(section)
sliceSize++
}
}
return sections
}
| 0 | Kotlin | 0 | 0 | e737bf3112e97b2221403fef6f77e994f331b7e9 | 5,236 | adventOfCode2022 | Apache License 2.0 |
kotlin/src/katas/kotlin/leetcode/jump_game/JumpGame.kt | dkandalov | 2,517,870 | false | {"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221} | package katas.kotlin.leetcode.jump_game
import datsok.*
import org.junit.*
/**
* https://leetcode.com/problems/jump-game-ii/
*
* Given an array of non-negative integers, you are initially positioned at the first index of the array.
* Each element in the array represents your maximum jump length at that position.
* Your goal is to reach the last index in the minimum number of jumps.
*/
class JumpGame {
@Test fun `some examples`() {
jump() shouldEqual emptyList()
jump(1) shouldEqual emptyList()
jump(1, 1) shouldEqual listOf(1)
jump(1, 1, 1) shouldEqual listOf(1, 1)
jump(2, 1, 1) shouldEqual listOf(2)
jump(2, 3, 1, 1, 4) shouldEqual listOf(1, 3)
jump(10, 3, 1, 1, 4) shouldEqual listOf(4)
}
private fun jump(vararg nums: Int): List<Int> = jump(nums.toTypedArray())
private fun jump(nums: Array<Int>): List<Int> {
if (nums.size <= 1) return emptyList()
val jumps = ArrayList<Int>()
var i = 0
var lastRangeEnd = 1
while (true) {
val range = lastRangeEnd..(i + nums[i])
lastRangeEnd = range.last
if (nums.lastIndex in range) break
val max = range.maxByOrNull { it: Int -> it + nums[it] }!!
jumps.add(max - i)
i = max
}
jumps.add(nums.lastIndex - i)
return jumps
}
private fun allJumps(nums: List<Int>, i: Int = 0): List<List<Int>> {
if (i >= nums.size - 1) return listOf(emptyList())
return (1..nums[i]).flatMap { jumpSize ->
allJumps(nums, i + jumpSize).map { listOf(jumpSize) + it }
}
}
} | 7 | Roff | 3 | 5 | 0f169804fae2984b1a78fc25da2d7157a8c7a7be | 1,664 | katas | The Unlicense |
src/main/kotlin/com/misterpemodder/aoc2022/solutions/Day02.kt | MisterPeModder | 573,061,300 | false | {"Kotlin": 87294} | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.misterpemodder.aoc2022.solutions
import com.misterpemodder.aoc2022.RegisterSolution
import com.misterpemodder.aoc2022.Solution
import com.misterpemodder.aoc2022.utf8Lines
import io.ktor.utils.io.*
@RegisterSolution(year = 2022, day = 2)
internal object Day02 : Solution<StrategyGuide> {
override suspend fun setup(input: ByteReadChannel): StrategyGuide {
// initialize strengths and weaknesses of each shape
// we cannot put this inside the 'Shape' class because it would reference itself.
val shapes = Shape.values()
for (shape in shapes) {
shape.strongAgainst = shapes[(shape.ordinal - 1).mod(shapes.size)]
shape.weakAgainst = shapes[(shape.ordinal + 1).mod(shapes.size)]
}
val opponentShapes = mutableListOf<Shape>()
val ownShapes = mutableListOf<Shape>()
input.utf8Lines().collect { line ->
// input line is two letters separated by a single space
opponentShapes += when (val opponentShape = line[0]) {
'A' -> Shape.ROCK
'B' -> Shape.PAPER
'C' -> Shape.SCISSORS
else -> throw RuntimeException("Unexpected opponent shape: $opponentShape")
}
ownShapes += when (val ownShape = line[2]) {
'X' -> Shape.ROCK
'Y' -> Shape.PAPER
'Z' -> Shape.SCISSORS
else -> throw RuntimeException("Unexpected own shape: $ownShape")
}
}
return StrategyGuide(opponentShapes, ownShapes)
}
/** Computes the sum of all round results by following the guide exactly. */
override fun part1(data: StrategyGuide): Long = data.opponentShapes.asSequence()
.zip(data.ownShapes.asSequence())
.map { (opponentShape, ownShape) ->
ownShape.score + ownShape.round(opponentShape).score
}
.sum()
/** Computes the sum of all round results by treating second column of the guide as the outcome to get. */
override fun part2(data: StrategyGuide): Long = data.opponentShapes.asSequence()
.zip(data.ownShapes.asSequence().map(Shape::toOutcome))
.map { (opponentShape, outcome) ->
outcome.score + when (outcome) {
Outcome.WIN -> opponentShape.weakAgainst.score
Outcome.LOSS -> opponentShape.strongAgainst.score
Outcome.DRAW -> opponentShape.score
}
}
.sum()
}
/** @param score The points to award as a result of this outcome. */
enum class Outcome(val score: Long) {
WIN(6L), LOSS(0L), DRAW(3L)
}
enum class Shape {
ROCK, PAPER, SCISSORS;
/** The points to award when this shape is chosen by the player. */
val score: Long = ordinal + 1L
/** The shape that this instance will always win against. */
lateinit var strongAgainst: Shape
/** The shape that this instance will always lose against. */
lateinit var weakAgainst: Shape
/** Plays a round of rock-paper-scissors */
fun round(other: Shape): Outcome = if (other === this.strongAgainst) {
Outcome.WIN
} else if (other === this.weakAgainst) {
Outcome.LOSS
} else {
Outcome.DRAW
}
/** @return The outcome that needs to happen if this shape is selected by the opposing player. */
fun toOutcome(): Outcome = when (this) {
ROCK -> Outcome.LOSS
PAPER -> Outcome.DRAW
SCISSORS -> Outcome.WIN
}
}
/** The parsed input data of day 2. */
data class StrategyGuide(val opponentShapes: List<Shape>, val ownShapes: List<Shape>)
| 0 | Kotlin | 0 | 0 | af1b258325a7bd036a47b5395c90bbac42bbd337 | 4,223 | AdventOfCode2022 | Apache License 2.0 |
core-types/src/main/java/lang/taxi/policies/Policy.kt | adarro | 458,750,628 | false | {"Kotlin": 519316, "TypeScript": 56768, "ANTLR": 38921, "JavaScript": 4324, "Python": 2009, "Java": 754, "Batchfile": 133, "Shell": 129, "Dockerfile": 123} | package lang.taxi.policies
import lang.taxi.Operator
import lang.taxi.types.*
import lang.taxi.types.Annotation
data class Policy(
override val qualifiedName: String,
val targetType: Type,
val ruleSets: List<RuleSet>,
override val annotations: List<Annotation>,
override val compilationUnits: List<CompilationUnit>
) : Annotatable, Named, Compiled
data class RuleSet(
val scope: PolicyScope,
val statements: List<PolicyStatement>
)
/**
* operationType is a user-defined value, that descrbbes the behaviour of the operation.
* Common values would be read,write - but it;s up too the user to ddefine.
* These then need to be applied to operations, for the policy to apply.
*
* Alternatively, a wildcard operationType of '*' may be defined, which matches all
* operation
*
*/
data class PolicyScope(val operationType: String = WILDCARD_OPERATION_TYPE, val operationScope: OperationScope = DEFAULT_OPERATION_SCOPE) {
fun appliesTo(operationType: String?, operationScope: OperationScope): Boolean {
val operationTypeMatches = operationTypeMatches(this.operationType, operationType)
val scopeMatches = operationScopeMatches(this.operationScope, operationScope)
return operationTypeMatches && scopeMatches
}
override fun toString(): String {
return "Policy scope $operationType ${operationScope.symbol}"
}
private fun operationScopeMatches(policyScope: OperationScope, operationScope: OperationScope): Boolean {
// TODO : Haven't given this much thought, so this needs revisiting.
// In theory, if one of the scopes covers both internal & external, then it's a match,
// But this is a quick impl, and that thought might be wrong.
return when {
policyScope == operationScope -> true
policyScope == OperationScope.INTERNAL_AND_EXTERNAL -> true
operationScope == OperationScope.INTERNAL_AND_EXTERNAL -> true
else -> false
}
}
private fun operationTypeMatches(policyOperationType: String, operationType: String?): Boolean {
// The idea here is that if a policy is defined as wildcard, it always matches.
// If an operation hasn't defined a scope, then no policies with defined scopes (other than wildcard) match
return when {
policyOperationType == WILDCARD_OPERATION_TYPE -> true
operationType == null -> false
policyOperationType == operationType -> true
else -> false
}
}
companion object {
const val WILDCARD_OPERATION_TYPE = "*"
val DEFAULT_OPERATION_SCOPE = OperationScope.INTERNAL_AND_EXTERNAL
val DEFAULT_POLICY_SCOPE = PolicyScope()
fun from(operationType: String?, operationScope: OperationScope?): PolicyScope {
return PolicyScope(operationType ?: WILDCARD_OPERATION_TYPE, operationScope ?: DEFAULT_OPERATION_SCOPE)
}
}
}
/**
* Differentiates between data returned to a caller (External),
* and data collected by Vyne as part of a query plan (Internal).
* The idea being you can write more relaxed rules for Vyne to collect data,
* and then strict rules about what is actually returned back out to the caller.
*/
enum class OperationScope(val symbol: String) {
INTERNAL_AND_EXTERNAL("internal"),
EXTERNAL("external");
companion object {
private val bySymbol = OperationScope.values().associateBy { it.symbol }
fun parse(input: String?): OperationScope? {
return if (input == null) null else
bySymbol[input] ?: error("Unknown scope - $input")
}
}
}
data class PolicyStatement(
val condition: Condition,
val instruction: Instruction,
val source: CompilationUnit
) {
}
interface Condition {
}
class ElseCondition : Condition {
// override fun matches(any: Any) = true
}
sealed class Subject {
}
class CaseCondition(val lhSubject: Subject, val operator: Operator, val rhSubject: Subject) : Condition {
}
data class RelativeSubject(val source: RelativeSubjectSource, val targetType: Type) : Subject() {
enum class RelativeSubjectSource {
CALLER, THIS;
}
}
data class LiteralArraySubject(val values: List<Any>) : Subject()
data class LiteralSubject(val value: Any?) : Subject()
data class InstructionProcessor(
val name: String,
val args: List<Any> = emptyList()
)
interface Instruction {
val type: Instruction.InstructionType
val description: String
// Processors commend out for now.
// https://gitlab.com/vyne/vyne/issues/52
enum class InstructionType(val symbol: String /*, val requiresProcessor: Boolean = false */) {
PERMIT("permit"),
// PROCESS("process", true),
// DEFER("defer"),
FILTER("filter");
companion object {
private val bySymbol = InstructionType.values().associateBy { it.symbol }
fun parse(symbol: String) = bySymbol[symbol] ?: error("Invalid instruction with symbol $symbol")
}
}
}
object PermitInstruction : Instruction {
override val type = Instruction.InstructionType.PERMIT
override val description: String = type.symbol
override fun toString(): String {
return "Instruction permit"
}
}
data class FilterInstruction(val fieldNames: List<String> = emptyList()) : Instruction {
override val type = Instruction.InstructionType.FILTER
override val description: String
get() = this.toString()
val isFilterAll = fieldNames.isEmpty()
override fun toString(): String {
val fieldNameList = if (isFilterAll) "all" else fieldNames.joinToString(",")
return "Instruction filter $fieldNameList"
}
}
// TODO : Simplifying instructions at the moment to either Permit, or Filter xxx.
// Re-introduce processors later.
// https://gitlab.com/vyne/vyne/issues/52
//
//data class Instruction(
// val type: InstructionType,
// val filteredFields: List<String>?,
// val processor: InstructionProcessor?
//) {
// init {
// if (this.type.requiresProcessor && this.processor == null) {
// error("A processor must be specified if using instruction of type ${type.symbol}")
// }
// }
//
// override fun toString(): String {
// val processorString = if (processor != null) " with processor ${processor.name}" else ""
// return "Instruction ${type.symbol}$processorString"
// }
//
// companion object {
// fun parse(instruction: TaxiParser.PolicyInstructionContext): Instruction {
// return when {
// instruction.policyInstructionEnum() != null -> Instruction(InstructionType.parse(instruction.policyInstructionEnum().text), null)
// instruction.policyFilterDeclaration() != null -> {
// val filterDeclaration = instruction.policyFilterDeclaration()
//
// }
//
// instruction.policyProcessorDeclaration() != null -> {
// val processor = instruction.policyProcessorDeclaration()
// val processorName = processor.qualifiedName().text
// val params = processor.policyProcessorParameterList().policyParameter().map { parameter ->
// when {
// parameter.literal() != null -> parameter.literal().value()
// parameter.literalArray() != null -> parameter.literalArray().value()
// else -> error("Unhandled param type")
// }
// }
// Instruction(InstructionType.PROCESS, InstructionProcessor(processorName, params))
// }
// else -> error("Unhandled policy type")
// }
// }
// }
//}
| 0 | Kotlin | 0 | 0 | 4e63dc633ef4dd28f6c92f1546640d9b67fa0826 | 7,898 | quarkus-taxi-poc | Apache License 2.0 |
leetcode2/src/leetcode/PascalsTriangle.kt | hewking | 68,515,222 | false | null | package leetcode
/**
* 118. 杨辉三角
* https://leetcode-cn.com/problems/pascals-triangle/
* Created by test
* Date 2019/6/7 1:05
* Description
* 给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。
在杨辉三角中,每个数是它左上方和右上方的数的和。
示例:
输入: 5
输出:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/pascals-triangle
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
object PascalsTriangle {
class Solution {
/**
* 思路:
*秒过题目
* 1.主要下一层需要上一层的数据,所幸是一个List<List>
*/
fun generate(numRows: Int): List<List<Int>> {
val rows = mutableListOf<List<Int>>()
for (i in 0 until numRows) {
val row = mutableListOf<Int>()
rows.add(row)
for (j in 0 until i + 1) {
if (i == 0) {
row.add(1)
} else {
if (j == 0 || j == i) {
row.add(1)
} else {
row.add(rows[i-1][j-1] + rows[i-1][j])
}
}
}
}
return rows
}
}
} | 0 | Kotlin | 0 | 0 | a00a7aeff74e6beb67483d9a8ece9c1deae0267d | 1,451 | leetcode | MIT License |
src/main/kotlin/ch/uzh/ifi/seal/bencher/Comparators.kt | chrstphlbr | 227,602,878 | false | {"Kotlin": 918163, "Java": 29153} | package ch.uzh.ifi.seal.bencher
private const val equal = 0
object MethodComparator : Comparator<Method> {
private val c = compareBy(Method::clazz)
.thenBy(Method::name)
.thenComparing(ParameterComparator)
.thenComparing(JmhParameterComparator)
override fun compare(m1: Method, m2: Method): Int = c.compare(m1, m2)
}
private object ParameterComparator : Comparator<Method> {
override fun compare(m1: Method, m2: Method): Int {
val sizes = m1.params.size.compareTo(m2.params.size)
if (sizes != equal) {
return sizes
}
return m1.params.asSequence()
.zip(m2.params.asSequence())
.map { comparePair(it) }
.find { it != equal }
?: equal
}
}
private object JmhParameterComparator : Comparator<Method> {
override fun compare(m1: Method, m2: Method): Int =
if (m1 is Benchmark && m2 is Benchmark) {
compare(m1, m2)
} else {
0
}
private fun compare(m1: Benchmark, m2: Benchmark): Int {
val cs = m1.jmhParams.size.compareTo(m2.jmhParams.size)
if (cs != equal) {
return cs
}
val diff = m1.jmhParams.asSequence()
.zip(m2.jmhParams.asSequence())
.map { (m1p, m2p) ->
Pair(
m1p.first.compareTo(m2p.first),
m1p.second.compareTo(m2p.second)
)
}
.find { it.first != equal || it.second != equal }
?: return equal
return when {
diff.first != equal -> diff.first
diff.second != equal -> diff.second
else -> equal
}
}
}
object LineComparator : Comparator<Line> {
val c = compareBy(Line::file).thenBy(Line::number)
override fun compare(l1: Line, l2: Line): Int = c.compare(l1, l2)
}
private fun <T : Comparable<T>> comparePair(p: Pair<T, T>): Int = p.first.compareTo(p.second)
| 0 | Kotlin | 2 | 4 | 06601fb4dda3b2996c2ba9b2cd612e667420006f | 2,087 | bencher | Apache License 2.0 |
year2021/src/main/kotlin/net/olegg/aoc/year2021/day6/Day6.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2021.day6
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.utils.parseInts
import net.olegg.aoc.year2021.DayOf2021
/**
* See [Year 2021, Day 6](https://adventofcode.com/2021/day/6)
*/
object Day6 : DayOf2021(6) {
override fun first(): Any? {
return solve(80)
}
override fun second(): Any? {
return solve(256)
}
private fun solve(days: Int): Long {
val input = data.parseInts(",")
val counts = input
.groupingBy { it }
.eachCount()
val start = List(10) { counts.getOrDefault(it, 0).toLong() }
val end = (1..days).fold(start) { acc, _ ->
val reset = acc.first()
acc.drop(1).mapIndexed { index, value ->
when (index) {
6, 8 -> value + reset
else -> value
}
} + listOf(0L)
}
return end.sum()
}
}
fun main() = SomeDay.mainify(Day6)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 883 | adventofcode | MIT License |
Kotlin/src/main/kotlin/org/algorithm/problems/0048_all_nodes_distance_k_in_binary_tree.kt | raulhsant | 213,479,201 | true | {"C++": 1035543, "Kotlin": 114509, "Java": 27177, "Python": 16568, "Shell": 999, "Makefile": 187} | // Problem Statement
// We are given a binary tree (with root node root), a target node, and an integer value K.
//
// Return a list of the values of all nodes that have a distance K from the
// target node. The answer can be returned in any order.
/**
* Definition for a binary tree node.
* class TreeNode(var `val`: Int = 0) {
* var left: TreeNode? = null
* var right: TreeNode? = null
* }
*/
package org.algorithm.problems
import org.algorithm.shared.TreeNode
class `0048_all_nodes_distance_k_in_binary_tree` {
private val parents = HashMap<Int, TreeNode?>()
private var targetFound = false
private val result = mutableListOf<Int>()
private val visited = mutableSetOf<Int>()
fun distanceK(root: TreeNode?, target: TreeNode?, K: Int): List<Int> {
if (K != 0) {
parents.put(root!!.`val`, null)
findTarget(root, target);
populateResult(target, 0, K)
} else {
result.add(target!!.`val`)
}
return result
}
private fun populateResult(node: TreeNode?, currDist: Int, K: Int) {
if (node == null) {
return
}
visited.add(node.`val`)
if (currDist == K) {
result.add(node.`val`)
} else {
if (node.left != null && !visited.contains(node.left?.`val`)) {
populateResult(node.left, currDist + 1, K)
}
if (node.right != null && !visited.contains(node.right?.`val`)) {
populateResult(node.right, currDist + 1, K)
}
val parent = parents.get(node.`val`)
if (parent != null && !visited.contains(parent.`val`)) {
populateResult(parent, currDist + 1, K)
}
}
}
private fun findTarget(node: TreeNode?, target: TreeNode?) {
if (node != null) {
if (node != target) {
if (node.left != null) {
parents.put(node.left!!.`val`, node)
findTarget(node.left, target)
}
if (targetFound) {
return
}
if (node.right != null) {
parents.put(node.right!!.`val`, node)
findTarget(node.right, target)
}
} else {
targetFound = true
}
}
}
} | 0 | C++ | 0 | 0 | 1578a0dc0a34d63c74c28dd87b0873e0b725a0bd | 2,414 | algorithms | MIT License |
BackEnd/src/main/kotlin/com/sorbonne/daar/algorithms/automate/DFA.kt | MalickLSy | 622,912,085 | false | null | package com.sorbonne.daar.algorithms.automate
import java.util.*
class DFA(val root: DFAState, val acceptings: Set<DFAState?>) {
override fun toString(): String {
return root.toString()
}
companion object {
private var allDFAStates: MutableSet<DFAState> = HashSet()
/**
* convert NFA to DFA
* @param nfa is instance of NFA
* @return an instance of DFA, removing all epsilon transition
*/
fun fromNFAtoDFA(nfa: NFA): DFA {
val inputSymbols = nfa.inputSymbols
val root = nfa.root
val accepting = nfa.accepting
val start = DFAState(root.epsilonClosure())
val accepts: MutableSet<DFAState?> = HashSet()
allDFAStates.add(start)
val queue: Queue<DFAState> = LinkedList()
queue.offer(start)
while (!queue.isEmpty()) {
val current = queue.poll()
for (input in inputSymbols) {
val set = getNextSubStates(current, input)
if (set.isNotEmpty()) {
val next = DFAState(set)
if (!allDFAStates.add(next)) {
for (same in allDFAStates) {
if (same == next) {
current.addTransition(input, same)
break
}
}
DFAState.counter--
} else {
if (next.subset?.contains(accepting) == true) {
accepts.add(next)
}
queue.offer(next)
current.addTransition(input, next)
}
}
}
}
val wordlist: Queue<MutableSet<DFAState?>> = LinkedList()
val union1: MutableSet<DFAState?> = HashSet()
for (state in allDFAStates) {
if (!accepts.contains(state)) {
union1.add(state)
}
}
wordlist.add(union1)
wordlist.add(accepts)
while (!wordlist.isEmpty()) {
val current = wordlist.poll()
val union2: MutableSet<DFAState?> = HashSet()
for (input in inputSymbols) {
val inUnion: Set<DFAState?> = HashSet(current)
val tmp: MutableSet<DFAState?> = HashSet()
for (st in current) {
if (!inUnion.contains(st!!.getTransition(input))) {
union2.add(st)
tmp.add(st)
}
}
current.removeAll(tmp)
}
if (union2.size > 1) {
wordlist.add(union2)
}
if (current.size < 2) {
break
}
for (state in allDFAStates) {
for (input in inputSymbols) {
val next = state.transitions[input] ?: continue
if (current.contains(next)) {
state.transitions.remove(input)
val copy: MutableSet<DFAState?> = HashSet(current)
copy.remove(next)
state.transitions[input] = copy.iterator().next()
}
}
}
}
return DFA(start, accepts)
}
private fun getNextSubStates(state: DFAState, input: Int): Set<NFAState?> {
val subset: MutableSet<NFAState?> = HashSet()
val tmp: Set<NFAState> = NFAState.move(input, state.subset)
for (nfaState in tmp) {
subset.addAll(nfaState.epsilonClosure())
}
return subset
}
}
} | 0 | Kotlin | 0 | 0 | b22e9e4f1410a63cf689ed66fa88e0a84a20f2a0 | 4,067 | search-engine-book | MIT License |
src/Day01.kt | tsdenouden | 572,703,357 | false | {"Kotlin": 8295} | fun main() {
fun getInventories(input: List<String>): MutableList<Int> {
val calories: MutableList<Int> = mutableListOf()
var currentInventory = 0
input.forEach { line ->
if (line == "") {
calories.add(currentInventory)
currentInventory = 0
} else {
currentInventory += line.toInt()
}
}
if (currentInventory != 0) {
calories.add(currentInventory)
}
return calories
}
fun part1(input: List<String>): Int {
val calories = getInventories(input)
return calories.maxOrNull() ?: 0
}
fun part2(input: List<String>): Int {
val calories = getInventories(input)
calories.sortDescending()
return calories[0] + calories[1] + calories[2]
}
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 68982ebffc116f3b49a622d81e725c8ad2356fed | 1,061 | aoc-2022-kotlin | Apache License 2.0 |
src/test/kotlin/org/nield/kotlinstatistics/IntegerStatisticsTest.kt | thomasnield | 84,361,977 | false | null | package org.nield.kotlinstatistics
import org.junit.Assert
import org.junit.Test
class IntegerStatisticsTest {
val intVector = sequenceOf(1, 3, 5, 11)
val groups = sequenceOf("A","A","B", "B")
@Test
fun sumBy() {
val r = mapOf("A" to 4, "B" to 16)
groups.zip(intVector).sumBy().let { Assert.assertTrue(it == r) }
groups.zip(intVector).sumBy(
keySelector = {it.first},
intSelector = {it.second}
).let { Assert.assertTrue(it == r) }
}
@Test
fun averageBy() {
val r = mapOf("A" to 2.0, "B" to 8.0)
groups.zip(intVector).averageBy(
keySelector = {it.first},
intSelector = {it.second}
).let { Assert.assertTrue(it == r) }
}
@Test
fun binTest() {
val binned = sequenceOf(
intVector,
intVector.map { it + 100 },
intVector.map { it + 200 }
).flatMap { it }
.zip(groups.repeat())
.binByInt(
binSize = 100,
valueSelector = {it.first},
rangeStart = 0
)
Assert.assertTrue(binned.bins.size == 3)
Assert.assertTrue(binned[5]!!.range.let { it.lowerBound == 0 && it.upperBound == 99 })
Assert.assertTrue(binned[105]!!.range.let { it.lowerBound == 100 && it.upperBound == 199 })
Assert.assertTrue(binned[205]!!.range.let { it.lowerBound == 200 && it.upperBound == 299 })
}
private fun <T> Sequence<T>.repeat() : Sequence<T> = sequence {
while(true) yieldAll(this@repeat)
}
}
| 15 | Kotlin | 48 | 840 | 17f64bae2a3cea2e85f05c08172d19a290561e3b | 1,668 | kotlin-statistics | Apache License 2.0 |
codeforces/kotlinheroes3/e.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package codeforces.kotlinheroes3
private fun solve() {
val (n, k) = readInts()
val nei = List(n) { mutableSetOf<Int>() }
repeat(n - 1) {
val (u, v) = readInts().map { it - 1 }
nei[u].add(v); nei[v].add(u)
}
val leaves = nei.indices.filter { nei[it].size == 1 }.toMutableList()
if (k == 1) return println("Yes\n1\n1")
if (k > leaves.size) return println("No")
val ans = nei.indices.toMutableSet()
while (leaves.size > k) {
val v = leaves.last()
val u = nei[v].first()
ans.remove(v)
nei[u].remove(v)
leaves.removeAt(leaves.lastIndex)
if (nei[u].size == 1) leaves.add(u)
}
println("Yes\n${ans.size}\n${ans.map { it + 1 }.joinToString(" ")}")
}
fun main() = repeat(readInt()) { solve() }
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 897 | competitions | The Unlicense |
src/main/kotlin/krangl/util/Util.kt | stangls | 238,162,024 | true | {"Kotlin": 252665, "R": 1809, "Java": 1121} | package krangl.util
//
// Functional Helpers (missing in kotlin-stdlib)
//
// todo should they go into separate artifact?
// adopted from https://stackoverflow.com/questions/44429419/what-is-basic-difference-between-fold-and-reduce-in-kotlin-when-to-use-which
// desc from https://stackoverflow.com/questions/17408880/reduce-fold-or-scan-left-right
/** scanLeft and scanRight cumulate a collection of intermediate cumulative results using a start value. */
fun <T, R> Sequence<T>.scanLeft(initial: R, operation: (R, T) -> R) =
fold(listOf(initial), { list, curVal -> list + operation(list.last(), curVal) })
fun <T, R> Sequence<T>.foldWhile(initial: R, operation: (R, T) -> R, predicate: (R) -> Boolean): R =
scanLeft(initial, operation).takeWhile { predicate(it) }.last()
fun <T, R> Sequence<T>.foldUntil(initial: R, operation: (R, T) -> R, predicate: (R) -> Boolean): R? =
scanLeft(initial, operation).dropWhile { predicate(it) }.firstOrNull()
fun <T, R> Sequence<T>.reduceUntil(operation: (R?, T) -> R, predicate: (R) -> Boolean): R? =
drop(1).scanLeft(operation(null, first()), operation).dropWhile { predicate(it) }.firstOrNull()
// Misc helpers
internal fun Sequence<*>.joinToMaxLengthString(
maxLength: Int = 80,
separator: CharSequence = ", ",
truncated: CharSequence = "...",
transform: ((Any?) -> String) = { it?.toString() ?: "" }
): String =
reduceUntil({ a: String?, b -> (a?.let { it + separator } ?: "") + transform(b) }, { it.length < maxLength })?.let {
when {
it.length < maxLength -> it
else -> it.substring(0, maxLength) + truncated
}
} ?: joinToString(transform = { transform(it) })
//fun main(args: Array<String>) {
// // listOf(1,2,3, 4).asSequence().scanLeft(0, { a, b -> a+b}).also{print(it)}
//
// // listOf("foo", "haus", "baum", "lala").asSequence().scanLeft("", {a,b ->a+b}).also{print(it)}
// listOf("foo", "haus", "baum", "lala").asSequence().foldWhile("", { a, b -> a + b }, {
// it.length < 30
// }).also { print(it) }
//}
| 0 | Kotlin | 1 | 0 | dfa3a6ccbb6777f97840582076a8f2f1a3308d14 | 2,073 | krangl | MIT License |
src/main/kotlin/nl/tiemenschut/aoc/y2023/day20.kt | tschut | 723,391,380 | false | {"Kotlin": 61206} | package nl.tiemenschut.aoc.y2023
import nl.tiemenschut.aoc.lib.dsl.aoc
import nl.tiemenschut.aoc.lib.dsl.day
import nl.tiemenschut.aoc.lib.dsl.parser.InputParser
import nl.tiemenschut.aoc.y2023.PulseValue.HIGH
import nl.tiemenschut.aoc.y2023.PulseValue.LOW
sealed class Module(open val name: String, open val connections: MutableList<Module> = mutableListOf()) {
abstract fun handlePulse(pulse: Pulse): List<Pulse>
}
class Broadcast : Module("broadcaster") {
override fun handlePulse(pulse: Pulse) = connections.map { Pulse(this, it, LOW) }
}
data class FlipFlop(override val name: String) : Module(name) {
private var state: PulseValue = LOW
override fun handlePulse(pulse: Pulse): List<Pulse> {
if (pulse.value == LOW) {
state = if (state == LOW) HIGH else LOW
return connections.map { Pulse(this, it, state) }
}
return emptyList()
}
}
data class Conjunction(override val name: String) : Module(name) {
val memory: MutableMap<String, PulseValue> = mutableMapOf()
override fun handlePulse(pulse: Pulse): List<Pulse> {
memory[pulse.source.name] = pulse.value
val outgoingPulse = if (memory.values.all { it == HIGH }) LOW else HIGH
return connections.map { Pulse(this, it, outgoingPulse) }
}
}
data class EndPoint(override val name: String) : Module(name) {
override fun handlePulse(pulse: Pulse): List<Pulse> = emptyList()
}
data object Button : Module("button") {
override fun handlePulse(pulse: Pulse): List<Pulse> {
TODO("Not yet implemented")
}
}
enum class PulseValue { LOW, HIGH }
data class Pulse(val source: Module, val destination: Module?, val value: PulseValue)
object ModuleConfigurationParser : InputParser<Map<String, Module>> {
override fun parse(input: String): Map<String, Module> {
val moduleConnections = mutableMapOf<String, List<String>>()
val modules = input.split("\n").associate { line ->
val (left, right) = line.split(" -> ")
val module = when {
"%" in left -> FlipFlop(left.substring(1..2))
"&" in left -> Conjunction(left.substring(1..2))
else -> Broadcast()
}
moduleConnections[module.name] = right.split(",").map { it.trim() }
module.name to module
}
moduleConnections.forEach { (moduleName, connectionName) ->
modules[moduleName]?.connections?.addAll(connectionName.map { modules[it] ?: EndPoint(it) })
}
modules.forEach { (name, module) ->
module.connections.forEach { connection ->
val connected = modules[connection.name]
if (connected is Conjunction) connected.memory[name] = LOW
}
}
return modules
}
}
fun main() {
aoc(ModuleConfigurationParser) {
puzzle { 2023 day 20 }
fun Map<String, Module>.pushTheButton(): Pair<Long, Long> {
var countLow = 1L
var countHigh = 0L
val pulseQueue = ArrayDeque(listOf(Pulse(Button, get("broadcaster")!!, LOW)))
while (pulseQueue.isNotEmpty()) {
val pulse = pulseQueue.removeFirst()
val outgoingPulses = pulse.destination!!.handlePulse(pulse)
countLow += outgoingPulses.count { it.value == LOW }
countHigh += outgoingPulses.count { it.value == HIGH }
pulseQueue.addAll(outgoingPulses.filter { p -> p.destination != null })
}
return countLow to countHigh
}
part1 { input ->
(0 until 1000).fold(0L to 0L) { acc, _ ->
input.pushTheButton().let { acc.first + it.first to acc.second + it.second }
}.let { it.first * it.second }
}
val vdPulses = mutableSetOf<String>()
fun Map<String, Module>.pushTheButtonUntilRxReceivesLow(): Boolean {
var result = false
val pulseQueue = ArrayDeque(listOf(Pulse(Button, get("broadcaster"), LOW)))
while (pulseQueue.isNotEmpty()) {
val pulse = pulseQueue.removeFirst()
val outgoingPulses = pulse.destination!!.handlePulse(pulse)
outgoingPulses.find { it.destination?.name == "vd" && it.value == HIGH && vdPulses.add(it.source.name) }
?.let {
println("#### ${it.source.name}")
result = true
}
pulseQueue.addAll(outgoingPulses.filter { p -> p.destination != null })
}
return result
}
part2(submit = false) { input ->
var count = 1
while (true) {
if (input.pushTheButtonUntilRxReceivesLow()) {
println("found: $count")
}
count++
}
// manually submit lcm (= product, all are prime) of the found values.
// Brute forcing a general solution is too slow.
}
}
}
| 0 | Kotlin | 0 | 1 | a1ade43c29c7bbdbbf21ba7ddf163e9c4c9191b3 | 5,066 | aoc-2023 | The Unlicense |
kotlin/src/com/daily/algothrim/leetcode/NumIslands.kt | idisfkj | 291,855,545 | false | null | package com.daily.algothrim.leetcode
/**
* 200. 岛屿数量
* 给你一个由 '1'(陆地)和 '0'(水)组成的的二维网格,请你计算网格中岛屿的数量。
* 岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。
* 此外,你可以假设该网格的四条边均被水包围。
*/
class NumIslands {
companion object {
@JvmStatic
fun main(args: Array<String>) {
println(NumIslands().numIslands(
arrayOf(
charArrayOf('1', '1', '1', '1', '0'),
charArrayOf('1', '1', '0', '1', '0'),
charArrayOf('1', '1', '0', '0', '0'),
charArrayOf('0', '0', '0', '0', '0')
)
))
}
}
fun numIslands(grid: Array<CharArray>): Int {
if (grid.isNullOrEmpty() || grid[0].isEmpty()) return 0
var result = 0
val r = grid.size
val c = grid[0].size
for (ir in 0 until r) {
for (ic in 0 until c) {
if (grid[ir][ic] == '1') {
result++
dfs(r, c, ir, ic, grid)
}
}
}
return result
}
private fun dfs(r: Int, c: Int, ir: Int, ic: Int, grid: Array<CharArray>) {
if (ir < 0 || ic < 0 || ir >= r || ic >= c || grid[ir][ic] == '0') return
grid[ir][ic] = '0'
dfs(r, c, ir - 1, ic, grid)
dfs(r, c, ir + 1, ic, grid)
dfs(r, c, ir, ic - 1, grid)
dfs(r, c, ir, ic + 1, grid)
}
} | 0 | Kotlin | 9 | 59 | 9de2b21d3bcd41cd03f0f7dd19136db93824a0fa | 1,617 | daily_algorithm | Apache License 2.0 |
aoc_2023/src/main/kotlin/problems/day15/LensHashes.kt | Cavitedev | 725,682,393 | false | {"Kotlin": 228779} | package problems.day15
class LensHashes(lines: List<String>) {
val sequences = lines[0].split(",")
fun stepIntoValue(step: Char, value: Int): Int {
val charCode = step.code
return ((value + charCode) * 17) % 256
}
fun sequenceIntoValue(sequence: String, value: Int): Int {
var returnValue = value
for (char in sequence) {
returnValue = stepIntoValue(char, returnValue)
}
return returnValue
}
fun sumHashResults(): Long {
var total = 0L
for (sequence in sequences) {
val value = sequenceIntoValue(sequence, 0)
total += value
}
return total
}
fun focusingPower(): Long {
val boxes = calculatesBoxes()
return boxes.foldIndexed(0L) { index, acc, box ->
acc + box.foldIndexed(0L) { index2, acc2, elementBox ->
acc2 + (index + 1) * (index2 + 1) * elementBox.second
}
}
}
fun calculatesBoxes(): List<List<Pair<String, Int>>> {
val returnArray: MutableList<MutableList<Pair<String, Int>>> = MutableList(256) { mutableListOf() }
for (sequence in sequences) {
val splitSequence = sequence.split("-", "=")
val code = sequenceIntoValue(splitSequence[0], 0)
// -
if (splitSequence[1] == "") {
returnArray[code].removeIf { it.first == splitSequence[0] }
}
// =
else {
val boxToAdd = splitSequence[1].toInt()
val findIndex = returnArray[code].indexOfFirst { it.first == splitSequence[0] }
val updatePair = Pair(splitSequence[0], boxToAdd)
if (findIndex != -1) {
returnArray[code][findIndex] = updatePair
} else {
returnArray[code].add(updatePair)
}
}
}
return returnArray
}
} | 0 | Kotlin | 0 | 1 | aa7af2d5aa0eb30df4563c513956ed41f18791d5 | 1,975 | advent-of-code-2023 | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.